Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/transforms/run/__init__.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 Convert a run description into a task description.
6
7 Run descriptions are similar to task descriptions, but they specify how to run
8 the task at a higher level, using a "run" field that can be interpreted by
9 run-using handlers in `taskcluster/taskgraph/transforms/run`.
10 """
11
12 import copy
13 import logging
14
15 from voluptuous import Exclusive, Extra, Optional, Required
16
17 from taskgraph.transforms.base import TransformSequence
18 from taskgraph.transforms.cached_tasks import order_tasks
19 from taskgraph.transforms.task import task_description_schema
20 from taskgraph.util import json
21 from taskgraph.util import path as mozpath
22 from taskgraph.util.python_path import import_sibling_modules
23 from taskgraph.util.schema import Schema, validate_schema
24 from taskgraph.util.taskcluster import get_artifact_prefix
25 from taskgraph.util.workertypes import worker_type_implementation
26
27 logger = logging.getLogger(__name__)
28
29 # Fetches may be accepted in other transforms and eventually passed along
30 # to a `task` (eg: from_deps). Defining this here allows them to reuse
31 # the schema and avoid duplication.
32 fetches_schema = {
33 Required("artifact"): str,
34 Optional("dest"): str,
35 Optional("extract"): bool,
36 Optional("verify-hash"): bool,
37 }
38
39 # Schema for a build description
40 run_description_schema = Schema(
41 {
42 # The name of the task and the task's label. At least one must be specified,
43 # and the label will be generated from the name if necessary, by prepending
44 # the kind.
45 Optional("name"): str,
46 Optional("label"): str,
47 # the following fields are passed directly through to the task description,
48 # possibly modified by the run implementation. See
49 # taskcluster/taskgraph/transforms/task.py for the schema details.
50 Required("description"): task_description_schema["description"],
51 Optional("priority"): task_description_schema["priority"],
52 Optional("attributes"): task_description_schema["attributes"],
53 Optional("task-from"): task_description_schema["task-from"],
54 Optional("dependencies"): task_description_schema["dependencies"],
55 Optional("soft-dependencies"): task_description_schema["soft-dependencies"],
56 Optional("if-dependencies"): task_description_schema["if-dependencies"],
57 Optional("requires"): task_description_schema["requires"],
58 Optional("deadline-after"): task_description_schema["deadline-after"],
59 Optional("expires-after"): task_description_schema["expires-after"],
60 Optional("routes"): task_description_schema["routes"],
61 Optional("scopes"): task_description_schema["scopes"],
62 Optional("tags"): task_description_schema["tags"],
63 Optional("extra"): task_description_schema["extra"],
64 Optional("treeherder"): task_description_schema["treeherder"],
65 Optional("index"): task_description_schema["index"],
66 Optional("run-on-projects"): task_description_schema["run-on-projects"],
67 Optional("run-on-tasks-for"): task_description_schema["run-on-tasks-for"],
68 Optional("run-on-git-branches"): task_description_schema["run-on-git-branches"],
69 Optional("shipping-phase"): task_description_schema["shipping-phase"],
70 Optional("always-target"): task_description_schema["always-target"],
71 Exclusive("optimization", "optimization"): task_description_schema[
72 "optimization"
73 ],
74 Optional("needs-sccache"): task_description_schema["needs-sccache"],
75 # The "when" section contains descriptions of the circumstances under which
76 # this task should be included in the task graph. This will be converted
77 # into an optimization, so it cannot be specified in a run description that
78 # also gives 'optimization'.
79 Exclusive("when", "optimization"): {
80 # This task only needs to be run if a file matching one of the given
81 # patterns has changed in the push. The patterns use the mozpack
82 # match function (python/mozbuild/mozpack/path.py).
83 Optional("files-changed"): [str],
84 },
85 # A list of artifacts to install from 'fetch' tasks.
86 Optional("fetches"): {
87 str: [
88 str,
89 fetches_schema,
90 ],
91 },
92 # A description of how to run this task.
93 "run": {
94 # The key to a run implementation in a peer module to this one
95 "using": str,
96 # Base work directory used to set up the task.
97 Optional("workdir"): str,
98 # Any remaining content is verified against that run implementation's
99 # own schema.
100 Extra: object,
101 },
102 Required("worker-type"): task_description_schema["worker-type"],
103 # This object will be passed through to the task description, with additions
104 # provided by the task's run-using function
105 Optional("worker"): dict,
106 }
107 )
108
109 transforms = TransformSequence()
110 transforms.add_validate(run_description_schema)
111
112
113 @transforms.add
114 def rewrite_when_to_optimization(config, tasks):
115 for task in tasks:
116 when = task.pop("when", {})
117 if not when:
118 yield task
119 continue
120
121 files_changed = when.get("files-changed")
122
123 # implicitly add task config directory.
124 files_changed.append(f"{config.path}/kind.yml")
125 if task.get("task-from") and task["task-from"] != "kind.yml":
126 files_changed.append(f"{config.path}/{task['task-from']}")
127
128 # "only when files changed" implies "skip if files have not changed"
129 task["optimization"] = {"skip-unless-changed": files_changed}
130
131 assert "when" not in task
132 yield task
133
134
135 @transforms.add
136 def set_implementation(config, tasks):
137 for task in tasks:
138 impl, os = worker_type_implementation(config.graph_config, task["worker-type"])
139 if os:
140 task.setdefault("tags", {})["os"] = os
141 if impl:
142 task.setdefault("tags", {})["worker-implementation"] = impl
143 worker = task.setdefault("worker", {})
144 assert "implementation" not in worker
145 worker["implementation"] = impl
146 if os:
147 worker["os"] = os
148 yield task
149
150
151 @transforms.add
152 def set_label(config, tasks):
153 for task in tasks:
154 if "label" not in task:
155 if "name" not in task:
156 raise Exception("task has neither a name nor a label")
157 task["label"] = "{}-{}".format(config.kind, task["name"])
158 if task.get("name"):
159 del task["name"]
160 yield task
161
162
163 def get_attribute(dict, key, attributes, attribute_name):
164 """Get `attribute_name` from the given `attributes` dict, and if there
165 is a corresponding value, set `key` in `dict` to that value."""
166 value = attributes.get(attribute_name)
167 if value:
168 dict[key] = value
169
170
171 @transforms.add
172 def use_fetches(config, tasks):
173 artifact_names = {}
174 aliases = {}
175 extra_env = {}
176
177 if config.kind in ("toolchain", "fetch"):
178 tasks = list(tasks)
179 for task in tasks:
180 run = task.get("run", {})
181 label = task["label"]
182 get_attribute(artifact_names, label, run, "toolchain-artifact")
183 value = run.get(f"{config.kind}-alias")
184 if value:
185 aliases[f"{config.kind}-{value}"] = label
186
187 for task in config.kind_dependencies_tasks.values():
188 if task.kind in ("fetch", "toolchain"):
189 get_attribute(
190 artifact_names,
191 task.label,
192 task.attributes,
193 f"{task.kind}-artifact",
194 )
195 get_attribute(extra_env, task.label, task.attributes, f"{task.kind}-env")
196 value = task.attributes.get(f"{task.kind}-alias")
197 if value:
198 aliases[f"{task.kind}-{value}"] = task.label
199
200 artifact_prefixes = {}
201 for task in order_tasks(config, tasks):
202 artifact_prefixes[task["label"]] = get_artifact_prefix(task)
203
204 fetches = task.pop("fetches", None)
205 if not fetches:
206 yield task
207 continue
208
209 task_fetches = []
210 name = task.get("name", task.get("label"))
211 dependencies = task.setdefault("dependencies", {})
212 worker = task.setdefault("worker", {})
213 env = worker.setdefault("env", {})
214 prefix = get_artifact_prefix(task)
215 for kind in sorted(fetches):
216 artifacts = fetches[kind]
217 if kind in ("fetch", "toolchain"):
218 for artifact in sorted(
219 artifacts, key=lambda a: a if isinstance(a, str) else a["artifact"]
220 ):
221 # Convert name only fetch entries to full fledged ones for
222 # easier processing.
223 if isinstance(artifact, str):
224 artifact = {
225 "artifact": artifact,
226 }
227
228 fetch_name = artifact["artifact"]
229 label = f"{kind}-{fetch_name}"
230 label = aliases.get(label, label)
231 if label not in artifact_names:
232 raise Exception(
233 f"Missing fetch task for {config.kind}-{name}: {fetch_name}"
234 )
235 if label in extra_env:
236 env.update(extra_env[label])
237
238 path = artifact_names[label]
239 dest = artifact.get("dest", None)
240 extract = artifact.get("extract", True)
241 verify_hash = artifact.get("verify-hash", False)
242
243 dependencies[label] = label
244 fetch = {
245 "artifact": path,
246 "task": f"<{label}>",
247 "extract": extract,
248 }
249 if dest is not None:
250 fetch["dest"] = dest
251 if verify_hash:
252 fetch["verify-hash"] = verify_hash
253 task_fetches.append(fetch)
254 else:
255 if kind not in dependencies:
256 raise Exception(
257 f"{name} can't fetch {kind} artifacts because "
258 f"it has no {kind} dependencies!"
259 )
260 dep_label = dependencies[kind]
261 if dep_label in artifact_prefixes:
262 prefix = artifact_prefixes[dep_label]
263 else:
264 dep_tasks = [
265 task
266 for label, task in config.kind_dependencies_tasks.items()
267 if label == dep_label
268 ]
269 if len(dep_tasks) != 1:
270 raise Exception(
271 "{name} can't fetch {kind} artifacts because "
272 "there are {tasks} with label {label} in kind dependencies!\n"
273 "Available tasks:"
274 "\n - {labels}".format(
275 name=name,
276 kind=kind,
277 label=dependencies[kind],
278 tasks=(
279 "no tasks"
280 if len(dep_tasks) == 0
281 else "multiple tasks"
282 ),
283 labels="\n - ".join(
284 config.kind_dependencies_tasks.keys()
285 ),
286 )
287 )
288
289 prefix = get_artifact_prefix(dep_tasks[0])
290
291 def cmp_artifacts(a):
292 if isinstance(a, str):
293 return a
294 else:
295 return a["artifact"]
296
297 for artifact in sorted(artifacts, key=cmp_artifacts):
298 if isinstance(artifact, str):
299 path = artifact
300 dest = None
301 extract = True
302 verify_hash = False
303 else:
304 path = artifact["artifact"]
305 dest = artifact.get("dest")
306 extract = artifact.get("extract", True)
307 verify_hash = artifact.get("verify-hash", False)
308
309 fetch = {
310 "artifact": f"{prefix}/{path}",
311 "task": f"<{kind}>",
312 "extract": extract,
313 }
314 if dest is not None:
315 fetch["dest"] = dest
316 if verify_hash:
317 fetch["verify-hash"] = verify_hash
318 task_fetches.append(fetch)
319
320 task_artifact_prefixes = {
321 mozpath.dirname(fetch["artifact"])
322 for fetch in task_fetches
323 if not fetch["artifact"].startswith("public/")
324 }
325 if task_artifact_prefixes:
326 # Use taskcluster-proxy and request appropriate scope. For example, add
327 # 'scopes: [queue:get-artifact:path/to/*]' for 'path/to/artifact.tar.xz'.
328 worker["taskcluster-proxy"] = True
329 for prefix in sorted(task_artifact_prefixes):
330 scope = f"queue:get-artifact:{prefix}/*"
331 if scope not in task.setdefault("scopes", []):
332 task["scopes"].append(scope)
333
334 env["MOZ_FETCHES"] = {
335 "task-reference": json.dumps(task_fetches, sort_keys=True)
336 }
337
338 env.setdefault("MOZ_FETCHES_DIR", "fetches")
339
340 yield task
341
342
343 @transforms.add
344 def make_task_description(config, tasks):
345 """Given a build description, create a task description"""
346 # import plugin modules first, before iterating over tasks
347 import_sibling_modules(exceptions=("common.py",))
348
349 for task in tasks:
350 # always-optimized tasks never execute, so have no workdir
351 if task["worker"]["implementation"] in ("docker-worker", "generic-worker"):
352 task["run"].setdefault("workdir", "/builds/worker")
353
354 taskdesc = copy.deepcopy(task)
355
356 # fill in some empty defaults to make run implementations easier
357 taskdesc.setdefault("attributes", {})
358 taskdesc.setdefault("dependencies", {})
359 taskdesc.setdefault("soft-dependencies", [])
360 taskdesc.setdefault("routes", [])
361 taskdesc.setdefault("scopes", [])
362 taskdesc.setdefault("extra", {})
363
364 # give the function for task.run.using on this worker implementation a
365 # chance to set up the task description.
366 configure_taskdesc_for_run(
367 config, task, taskdesc, task["worker"]["implementation"]
368 )
369 del taskdesc["run"]
370
371 # yield only the task description, discarding the task description
372 yield taskdesc
373
374
375 # A registry of all functions decorated with run_task_using
376 registry = {}
377
378
379 def run_task_using(worker_implementation, run_using, schema=None, defaults={}):
380 """Register the decorated function as able to set up a task description for
381 tasks with the given worker implementation and `run.using` property. If
382 `schema` is given, the task's run field will be verified to match it.
383
384 The decorated function should have the signature `using_foo(config, task, taskdesc)`
385 and should modify the task description in-place. The skeleton of
386 the task description is already set up, but without a payload."""
387
388 def wrap(func):
389 for_run_using = registry.setdefault(run_using, {})
390 if worker_implementation in for_run_using:
391 raise Exception(
392 f"run_task_using({run_using!r}, {worker_implementation!r}) already exists: {for_run_using[worker_implementation]!r}"
393 )
394 for_run_using[worker_implementation] = (func, schema, defaults)
395 return func
396
397 return wrap
398
399
400 @run_task_using(
401 "always-optimized", "always-optimized", Schema({"using": "always-optimized"})
402 )
403 def always_optimized(config, task, taskdesc):
404 pass
405
406
407 def configure_taskdesc_for_run(config, task, taskdesc, worker_implementation):
408 """
409 Run the appropriate function for this task against the given task
410 description.
411
412 This will raise an appropriate error if no function exists, or if the task's
413 run is not valid according to the schema.
414 """
415 run_using = task["run"]["using"]
416 if run_using not in registry:
417 raise Exception(f"no functions for run.using {run_using!r}")
418
419 if worker_implementation not in registry[run_using]:
420 raise Exception(
421 f"no functions for run.using {run_using!r} on {worker_implementation!r}"
422 )
423
424 func, schema, defaults = registry[run_using][worker_implementation]
425 for k, v in defaults.items():
426 task["run"].setdefault(k, v)
427
428 if schema:
429 validate_schema(
430 schema,
431 task["run"],
432 "In task.run using {!r}/{!r} for task {!r}:".format(
433 task["run"]["using"], worker_implementation, task["label"]
434 ),
435 )
436 func(config, task, taskdesc)