Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/parameters.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import gzip
6 import hashlib
7 import os
8 import time
9 from datetime import datetime
10 from io import BytesIO
11 from pprint import pformat
12 from subprocess import CalledProcessError
13 from unittest.mock import Mock
14 from urllib.parse import urlparse
15 from urllib.request import urlopen
16
17 import mozilla_repo_urls
18 from voluptuous import ALLOW_EXTRA, Any, Optional, Required, Schema
19
20 from taskgraph.util import json, yaml
21 from taskgraph.util.readonlydict import ReadOnlyDict
22 from taskgraph.util.schema import validate_schema
23 from taskgraph.util.taskcluster import find_task_id, get_artifact_url
24 from taskgraph.util.vcs import get_repository
25
26
27 class ParameterMismatch(Exception):
28 """Raised when a parameters.yml has extra or missing parameters."""
29
30
31 # Please keep this list sorted and in sync with docs/reference/parameters.rst
32 base_schema = Schema(
33 {
34 Required("base_repository"): str,
35 Required("base_ref"): str,
36 Required("base_rev"): str,
37 Required("build_date"): int,
38 Required("build_number"): int,
39 Required("do_not_optimize"): [str],
40 Required("enable_always_target"): Any(bool, [str]),
41 Required("existing_tasks"): {str: str},
42 Required("files_changed"): [str],
43 Required("filters"): [str],
44 Required("head_ref"): str,
45 Required("head_repository"): str,
46 Required("head_rev"): str,
47 Required("head_tag"): str,
48 Required("level"): str,
49 Required("moz_build_date"): str,
50 Required("next_version"): Any(str, None),
51 Required("optimize_strategies"): Any(str, None),
52 Required("optimize_target_tasks"): bool,
53 Required("owner"): str,
54 Required("project"): str,
55 Required("pushdate"): int,
56 Required("pushlog_id"): str,
57 Required("repository_type"): str,
58 # target-kinds is not included, since it should never be
59 # used at run-time
60 Required("target_tasks_method"): str,
61 Required("tasks_for"): str,
62 Required("version"): Any(str, None),
63 Optional("code-review"): {
64 Required("phabricator-build-target"): str,
65 },
66 }
67 )
68
69
70 def get_contents(path):
71 with open(path) as fh:
72 contents = fh.readline().rstrip()
73 return contents
74
75
76 def get_version(repo_path):
77 version_path = os.path.join(repo_path, "version.txt")
78 return get_contents(version_path) if os.path.isfile(version_path) else None
79
80
81 def _get_defaults(repo_root=None):
82 repo_path = repo_root or os.getcwd()
83 try:
84 repo = get_repository(repo_path)
85 except RuntimeError:
86 # Use fake values if no repo is detected.
87 repo = Mock(branch="", head_rev="", tool="git")
88 repo.get_url.return_value = ""
89 repo.get_changed_files.return_value = []
90
91 try:
92 repo_url = repo.get_url()
93 parsed_url = mozilla_repo_urls.parse(repo_url)
94 project = parsed_url.repo_name
95 except (
96 CalledProcessError,
97 mozilla_repo_urls.InvalidRepoUrlError,
98 mozilla_repo_urls.UnsupportedPlatformError,
99 ):
100 repo_url = ""
101 project = ""
102
103 return {
104 "base_repository": repo_url,
105 "base_ref": "",
106 "base_rev": "",
107 "build_date": int(time.time()),
108 "build_number": 1,
109 "do_not_optimize": [],
110 "enable_always_target": True,
111 "existing_tasks": {},
112 "files_changed": lambda: repo.get_changed_files("AM"),
113 "filters": ["target_tasks_method"],
114 "head_ref": repo.branch or repo.head_rev,
115 "head_repository": repo_url,
116 "head_rev": repo.head_rev,
117 "head_tag": "",
118 "level": "3",
119 "moz_build_date": datetime.now().strftime("%Y%m%d%H%M%S"),
120 "next_version": None,
121 "optimize_strategies": None,
122 "optimize_target_tasks": True,
123 "owner": "[email protected]",
124 "project": project,
125 "pushdate": int(time.time()),
126 "pushlog_id": "0",
127 "repository_type": repo.tool,
128 "target_tasks_method": "default",
129 "tasks_for": "",
130 "version": get_version(repo_path),
131 }
132
133
134 defaults_functions = [_get_defaults]
135
136
137 def extend_parameters_schema(schema, defaults_fn=None):
138 """
139 Extend the schema for parameters to include per-project configuration.
140
141 This should be called by the `taskgraph.register` function in the
142 graph-configuration.
143
144 Args:
145 schema (Schema): The voluptuous.Schema object used to describe extended
146 parameters.
147 defaults_fn (function): A function which takes no arguments and returns a
148 dict mapping parameter name to default value in the
149 event strict=False (optional).
150 """
151 global base_schema
152 global defaults_functions
153 base_schema = base_schema.extend(schema)
154 if defaults_fn:
155 defaults_functions.append(defaults_fn)
156
157
158 class Parameters(ReadOnlyDict):
159 """An immutable dictionary with nicer KeyError messages on failure"""
160
161 def __init__(self, strict=True, repo_root=None, **kwargs):
162 self.strict = strict
163 self.spec = kwargs.pop("spec", None)
164 self._id = None
165
166 if not self.strict:
167 # apply defaults to missing parameters
168 kwargs = Parameters._fill_defaults(repo_root=repo_root, **kwargs)
169
170 ReadOnlyDict.__init__(self, **kwargs)
171
172 @property
173 def id(self):
174 if not self._id:
175 self._id = hashlib.sha256(
176 json.dumps(self, sort_keys=True).encode("utf-8")
177 ).hexdigest()[:12]
178
179 return self._id
180
181 @staticmethod
182 def format_spec(spec):
183 """
184 Get a friendly identifier from a parameters specifier.
185
186 Args:
187 spec (str): Parameters specifier.
188
189 Returns:
190 str: Name to identify parameters by.
191 """
192 if spec is None:
193 return "defaults"
194
195 if any(spec.startswith(s) for s in ("task-id=", "project=", "index=")):
196 return spec
197
198 result = urlparse(spec)
199 if result.scheme in ("http", "https"):
200 spec = result.path
201
202 return os.path.splitext(os.path.basename(spec))[0]
203
204 @staticmethod
205 def _fill_defaults(repo_root=None, **kwargs):
206 defaults = {}
207 for fn in defaults_functions:
208 defaults.update(fn(repo_root))
209
210 for name, default in defaults.items():
211 if name not in kwargs:
212 kwargs[name] = default() if callable(default) else default
213 return kwargs
214
215 def check(self):
216 schema = (
217 base_schema if self.strict else base_schema.extend({}, extra=ALLOW_EXTRA)
218 )
219 try:
220 validate_schema(schema, self.copy(), "Invalid parameters:")
221 except Exception as e:
222 raise ParameterMismatch(str(e))
223
224 def __getitem__(self, k):
225 try:
226 return super().__getitem__(k)
227 except KeyError:
228 raise KeyError(f"taskgraph parameter {k!r} not found")
229
230 def is_try(self):
231 """
232 Determine whether this graph is being built on a try project or for
233 `mach try fuzzy`.
234 """
235 return "try" in self["project"] or self["tasks_for"] == "github-pull-request"
236
237 @property
238 def moz_build_date(self):
239 # XXX self["moz_build_date"] is left as a string because:
240 # * of backward compatibility
241 # * parameters are output in a YAML file
242 return datetime.strptime(self["moz_build_date"], "%Y%m%d%H%M%S")
243
244 def file_url(self, path, pretty=False):
245 """
246 Determine the VCS URL for viewing a file in the tree, suitable for
247 viewing by a human.
248
249 :param str path: The path, relative to the root of the repository.
250 :param bool pretty: Whether to return a link to a formatted version of the
251 file, or the raw file version.
252
253 :return str: The URL displaying the given path.
254 """
255 if self["repository_type"] == "hg":
256 if "comm/" in path:
257 path = path.split("comm/")[1]
258 repo = self["comm_head_repository"]
259 rev = self["comm_head_rev"]
260 else:
261 repo = self["head_repository"]
262 rev = self["head_rev"]
263 endpoint = "file" if pretty else "raw-file"
264 return f"{repo}/{endpoint}/{rev}/{path}"
265 elif self["repository_type"] == "git":
266 # For getting the file URL for git repositories, we only support a Github HTTPS remote
267 repo = self["head_repository"]
268 if repo.startswith("https://github.com/"):
269 if repo.endswith("/"):
270 repo = repo[:-1]
271
272 rev = self["head_rev"]
273 endpoint = "blob" if pretty else "raw"
274 return f"{repo}/{endpoint}/{rev}/{path}"
275 elif repo.startswith("[email protected]:"):
276 if repo.endswith(".git"):
277 repo = repo[:-4]
278 rev = self["head_rev"]
279 endpoint = "blob" if pretty else "raw"
280 return "{}/{}/{}/{}".format(
281 repo.replace("[email protected]:", "https://github.com/"),
282 endpoint,
283 rev,
284 path,
285 )
286 else:
287 raise ParameterMismatch(
288 f"Don't know how to determine file URL for non-githubrepo: {repo}"
289 )
290 else:
291 raise RuntimeError(
292 'Only the "git" and "hg" repository types are supported for using file_url()'
293 )
294
295 def __str__(self):
296 return f"Parameters(id={self.id}) (from {self.format_spec(self.spec)})"
297
298 def __repr__(self):
299 return pformat(dict(self), indent=2)
300
301
302 def load_parameters_file(
303 spec, strict=True, overrides=None, trust_domain=None, repo_root=None
304 ):
305 """
306 Load parameters from a path, url, decision task-id or project.
307
308 Examples:
309 task-id=fdtgsD5DQUmAQZEaGMvQ4Q
310 project=mozilla-central
311 """
312
313 if overrides is None:
314 overrides = {}
315 overrides["spec"] = spec
316
317 if not spec:
318 return Parameters(strict=strict, repo_root=repo_root, **overrides)
319
320 try:
321 # reading parameters from a local parameters.yml file
322 f = open(spec)
323 except OSError:
324 # fetching parameters.yml using task task-id, project or supplied url
325 task_id = None
326 if spec.startswith("task-id="):
327 task_id = spec.split("=")[1]
328 elif spec.startswith("project=") or spec.startswith("index="):
329 if spec.startswith("project="):
330 if trust_domain is None:
331 raise ValueError(
332 "Can't specify parameters by project "
333 "if trust domain isn't supplied.",
334 )
335 index = "{trust_domain}.v2.{project}.latest.taskgraph.decision".format(
336 trust_domain=trust_domain,
337 project=spec.split("=")[1],
338 )
339 else:
340 index = spec.split("=")[1]
341 task_id = find_task_id(index)
342
343 if task_id:
344 spec = get_artifact_url(task_id, "public/parameters.yml")
345 f = urlopen(spec)
346
347 # Decompress gzipped parameters.
348 if f.info().get("Content-Encoding") == "gzip":
349 buf = BytesIO(f.read())
350 f = gzip.GzipFile(fileobj=buf)
351
352 if spec.endswith(".yml"):
353 kwargs = yaml.load_stream(f)
354 elif spec.endswith(".json"):
355 kwargs = json.load(f)
356 else:
357 raise TypeError(f"Parameters file `{spec}` is not JSON or YAML")
358
359 kwargs.update(overrides)
360 return Parameters(strict=strict, repo_root=repo_root, **kwargs)
361
362
363 def parameters_loader(spec, strict=True, overrides=None):
364 def get_parameters(graph_config):
365 try:
366 repo_root = graph_config.vcs_root
367 except Exception:
368 repo_root = None
369
370 parameters = load_parameters_file(
371 spec,
372 strict=strict,
373 overrides=overrides,
374 repo_root=repo_root,
375 trust_domain=graph_config["trust-domain"],
376 )
377 parameters.check()
378 return parameters
379
380 return get_parameters