from BuildDemos import demos import argparse, requests, json, subprocess, re, pickle parser = argparse.ArgumentParser() parser.add_argument("version", type=str, help="Vaadin version that was just built") parser.add_argument("deployUrl", type=str, help="Base url of the deployment server") parser.add_argument("teamcityUser", type=str, help="Teamcity username to use") parser.add_argument("teamcityPassword", type=str, help="Password for given teamcity username") parser.add_argument("teamcityUrl", type=str, help="Address to the teamcity server") parser.add_argument("buildTypeId", type=str, help="The ID of this build step") parser.add_argument("buildId", type=str, help="ID of the build to generate this report for") parser.add_argument("stagingRepoUrl", type=str, help="URL to the staging repository") args = parser.parse_args() buildResultUrl = "http://{}/viewLog.html?buildId={}&tab=buildResultsDiv&buildTypeId={}".format(args.teamcityUrl, args.buildId, args.buildTypeId) def createTableRow(*columns): html = "" for column in columns: html += "" + column + "" return html + "" def getHtmlList(array): html = "" def getBuildStatusHtml(): build_steps_request_string = "http://{}/app/rest/problemOccurrences?locator=build:{}".format(args.teamcityUrl, args.buildId) build_steps_request = requests.get(build_steps_request_string, auth=(args.teamcityUser, args.teamcityPassword), headers={'Accept':'application/json'}) if build_steps_request.status_code != 200: return createTableRow(traffic_light.format(color="black"), "Build status: unable to retrieve status of build") else: build_steps_json = build_steps_request.json() if build_steps_json["count"] == 0: return createTableRow(traffic_light.format(color="green"), "Build status: all build steps successful") else: return createTableRow(traffic_light.format(color="red"), "Build status: there are failing build steps, check the build report".format(buildResultUrl)) def getTestStatusHtml(): test_failures_request_string = "http://{}/app/rest/testOccurrences?locator=build:{},status:FAILURE".format(args.teamcityUrl, args.buildId) test_failures_request = requests.get(test_failures_request_string, auth=(args.teamcityUser, args.teamcityPassword), headers={'Accept':'application/json'}) if test_failures_request.status_code != 200: return createTableRow(traffic_light.format(color="black"), "Test status: unable to retrieve status of tests") else: test_failures_json = test_failures_request.json() if test_failures_json["count"] == 0: return createTableRow(traffic_light.format(color="green"), "Test status: all tests passing") else: return createTableRow(traffic_light.format(color="red"), "Test status: there are " + str(test_failures_json["count"]) + " failing tests, check the build report".format(buildResultUrl)) def getDemoValidationStatusHtml(): status = pickle.load(open("result/demo_validation_status.pickle", "rb")) if status["error"]: return createTableRow(traffic_light.format(color="red"), getHtmlList(status["messages"])) else: return createTableRow(traffic_light.format(color="green"), getHtmlList(status["messages"])) def getDemoLinksHtml(): demos_html = "Try demos" link_list = list(map(lambda demo: "{demoName}".format(url=args.deployUrl, demoName=demo, version=args.version), demos)) return demos_html + getHtmlList(link_list) + "Note that the deployed framework8-demo WARs have a suffix -0..-4." def getApiDiffHtml(): apidiff_html = "Check API diff" modules = [ "client", "client-compiler", "compatibility-client", "compatibility-server", "compatibility-shared", "server", "shared" ] link_list = list(map(lambda module: "{}".format(args.teamcityUrl, args.buildTypeId, args.buildId, module, module), modules)) return apidiff_html + getHtmlList(link_list) def getDirs(url): page = requests.get(url) files = re.findall('(.*)', page.text) dirs = filter(lambda x: x.endswith('/'), files) return list(map(lambda x: x.replace('/', ''), dirs)) def dirTree(url): dirs = getDirs(url) result = [] for d in dirs: result.append(d) subDirs = list(map(lambda x: d + '/' + x, dirTree(url + '/' + d))) result.extend(subDirs) return result def getAllowedArtifactPaths(allowedArtifacts): result = [] for artifact in allowedArtifacts: parts = artifact.split('/', 1) result.append(parts[0]) if len(parts) > 1: subart = getAllowedArtifactPaths([ parts[1] ]) subArtifacts = list(map(lambda x: parts[0] + '/' + x, subart)) result.extend(subArtifacts) return result def checkStagingContents(url, allowedArtifacts): dirs = dirTree(url) allowedDirs = getAllowedArtifactPaths(allowedArtifacts) return set(dirs) == set(allowedDirs) def getStagingContentsHtml(repoUrl, allowedArtifacts): if checkStagingContents(repoUrl, allowedArtifacts): return createTableRow(traffic_light.format(color="green"), "Expected artifacts found in the staging repository. Link to the repository.".format(repoUrl)) else: return createTableRow(traffic_light.format(color="red"), "Extraneous or missing artifacts in the staging repository. Link to the repository.".format(repoUrl)) def completeArtifactName(artifactId, version): return 'com/vaadin/' + artifactId + '/' + version def completeArtifactNames(artifactIds, version): return list(map(lambda x: completeArtifactName(x, version), artifactIds)) allowedArtifacts = completeArtifactNames([ 'vaadin-maven-plugin', 'vaadin-archetypes', 'vaadin-archetype-application', 'vaadin-archetype-application-multimodule', 'vaadin-archetype-application-example', 'vaadin-archetype-widget', 'vaadin-archetype-liferay-portlet', 'vaadin-root', 'vaadin-shared', 'vaadin-server', 'vaadin-client', 'vaadin-client-compiler', 'vaadin-client-compiled', 'vaadin-push', 'vaadin-themes', 'vaadin-compatibility-shared', 'vaadin-compatibility-server', 'vaadin-compatibility-client', 'vaadin-compatibility-client-compiled', 'vaadin-compatibility-themes', 'vaadin-testbench-api', 'vaadin-bom' ], args.version) content = "" traffic_light = "" # Build step status content += getBuildStatusHtml() # Test failures content += getTestStatusHtml() # Missing @since tags try: p1 = subprocess.Popen(['find', '.', '-name', '*.java'], stdout=subprocess.PIPE) p2 = subprocess.Popen(['xargs', 'egrep', '-n', '@since ?$'], stdin=p1.stdout, stdout=subprocess.PIPE) missing = subprocess.check_output(['egrep', '-v', '/(testbench|test|tests|target)/'], stdin=p2.stdout) content += createTableRow(traffic_light.format(color="red"), "Empty @since:
%s
" % (missing)) except subprocess.CalledProcessError as e: if e.returncode == 1: content += createTableRow(traffic_light.format(color="green"), "No empty @since") else: raise e # check staging repositories don't contain extra artifacts content += getStagingContentsHtml(args.stagingRepoUrl, allowedArtifacts) content += createTableRow("", "

Manual checks before publishing

") # try demos content += createTableRow("", getDemoLinksHtml()) # link to release notes content += createTableRow("", "Check release notes".format(args.teamcityUrl, args.buildTypeId, args.buildId)) # link to api diff content += createTableRow("", getApiDiffHtml()) # check that GitHub issues are in the correct status content += createTableRow("", "Check that closed GitHub issues have correct milestone") content += createTableRow("", "

Preparations before publishing

") # link to build dependencies tab to initiate publish step content += createTableRow("", "

Start Publish Release from dependencies tab

".format(args.teamcityUrl, args.buildId, args.buildTypeId)) content += "
" f = open("result/report.html", 'w') f.write(content) ogin_flow_v2_sessions_2'>artonge/fix/login_flow_v2_sessions_2 Nextcloud server, a safe home for all your data: https://github.com/nextcloud/serverwww-data
aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/LargeFileHelper.php
blob: 4d96e79ead4239e593b52d4efe15aa955c7b654e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
<?php
/**
 * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
 * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
 * SPDX-License-Identifier: AGPL-3.0-only
 */
namespace OC;

use bantu\IniGetWrapper\IniGetWrapper;

/**
 * Helper class for large files on 32-bit platforms.
 */
class LargeFileHelper {
	/**
	 * pow(2, 53) as a base-10 string.
	 * @var string
	 */
	public const POW_2_53 = '9007199254740992';

	/**
	 * pow(2, 53) - 1 as a base-10 string.
	 * @var string
	 */
	public const POW_2_53_MINUS_1 = '9007199254740991';

	/**
	 * @brief Checks whether our assumptions hold on the PHP platform we are on.
	 *
	 * @throws \RuntimeException if our assumptions do not hold on the current
	 *                           PHP platform.
	 */
	public function __construct() {
		$pow_2_53 = (float)self::POW_2_53_MINUS_1 + 1.0;
		if ($this->formatUnsignedInteger($pow_2_53) !== self::POW_2_53) {
			throw new \RuntimeException(
				'This class assumes floats to be double precision or "better".'
			);
		}
	}

	/**
	 * @brief Formats a signed integer or float as an unsigned integer base-10
	 *        string. Passed strings will be checked for being base-10.
	 *
	 * @param int|float|string $number Number containing unsigned integer data
	 *
	 * @throws \UnexpectedValueException if $number is not a float, not an int
	 *                                   and not a base-10 string.
	 *
	 * @return string Unsigned integer base-10 string
	 */
	public function formatUnsignedInteger(int|float|string $number): string {
		if (is_float($number)) {
			// Undo the effect of the php.ini setting 'precision'.
			return number_format($number, 0, '', '');
		} elseif (is_string($number) && ctype_digit($number)) {
			return $number;
		} elseif (is_int($number)) {
			// Interpret signed integer as unsigned integer.
			return sprintf('%u', $number);
		} else {
			throw new \UnexpectedValueException(
				'Expected int, float or base-10 string'
			);
		}
	}

	/**
	 * @brief Tries to get the size of a file via various workarounds that
	 *        even work for large files on 32-bit platforms.
	 *
	 * @param string $filename Path to the file.
	 *
	 * @return int|float Number of bytes as number (float or int)
	 */
	public function getFileSize(string $filename): int|float {
		$fileSize = $this->getFileSizeViaCurl($filename);
		if (!is_null($fileSize)) {
			return $fileSize;
		}
		$fileSize = $this->getFileSizeViaExec($filename);
		if (!is_null($fileSize)) {
			return $fileSize;
		}
		return $this->getFileSizeNative($filename);
	}

	/**
	 * @brief Tries to get the size of a file via a CURL HEAD request.
	 *
	 * @param string $fileName Path to the file.
	 *
	 * @return null|int|float Number of bytes as number (float or int) or
	 *                        null on failure.
	 */
	public function getFileSizeViaCurl(string $fileName): null|int|float {
		if (\OC::$server->get(IniGetWrapper::class)->getString('open_basedir') === '') {
			$encodedFileName = rawurlencode($fileName);
			$ch = curl_init("file:///$encodedFileName");
			curl_setopt($ch, CURLOPT_NOBODY, true);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HEADER, true);
			$data = curl_exec($ch);
			curl_close($ch);
			if ($data !== false) {
				$matches = [];
				preg_match('/Content-Length: (\d+)/', $data, $matches);
				if (isset($matches[1])) {
					return 0 + $matches[1];
				}
			}
		}
		return null;
	}

	/**
	 * @brief Tries to get the size of a file via an exec() call.
	 *
	 * @param string $filename Path to the file.
	 *
	 * @return null|int|float Number of bytes as number (float or int) or
	 *                        null on failure.
	 */
	public function getFileSizeViaExec(string $filename): null|int|float {
		if (\OCP\Util::isFunctionEnabled('exec')) {
			$os = strtolower(php_uname('s'));
			$arg = escapeshellarg($filename);
			$result = null;
			if (str_contains($os, 'linux')) {
				$result = $this->exec("stat -c %s $arg");
			} elseif (str_contains($os, 'bsd') || str_contains($os, 'darwin')) {
				$result = $this->exec("stat -f %z $arg");
			}
			return $result;
		}
		return null;
	}

	/**
	 * @brief Gets the size of a file via a filesize() call and converts
	 *        negative signed int to positive float. As the result of filesize()
	 *        will wrap around after a file size of 2^32 bytes = 4 GiB, this
	 *        should only be used as a last resort.
	 *
	 * @param string $filename Path to the file.
	 *
	 * @return int|float Number of bytes as number (float or int).
	 */
	public function getFileSizeNative(string $filename): int|float {
		$result = filesize($filename);
		if ($result < 0) {
			// For file sizes between 2 GiB and 4 GiB, filesize() will return a
			// negative int, as the PHP data type int is signed. Interpret the
			// returned int as an unsigned integer and put it into a float.
			return (float) sprintf('%u', $result);
		}
		return $result;
	}

	/**
	 * Returns the current mtime for $fullPath
	 */
	public function getFileMtime(string $fullPath): int {
		try {
			$result = filemtime($fullPath) ?: -1;
		} catch (\Exception $e) {
			$result = - 1;
		}
		if ($result < 0) {
			if (\OCP\Util::isFunctionEnabled('exec')) {
				$os = strtolower(php_uname('s'));
				if (str_contains($os, 'linux')) {
					return (int)($this->exec('stat -c %Y ' . escapeshellarg($fullPath)) ?? -1);
				}
			}
		}
		return $result;
	}

	protected function exec(string $cmd): null|int|float {
		$result = trim(exec($cmd));
		return ctype_digit($result) ? 0 + $result : null;
	}
}