Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/transforms/task.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 These transformations take a task description and turn it into a TaskCluster
6 task definition (along with attributes, label, etc.). The input to these
7 transformations is generic to any kind of task, but abstracts away some of the
8 complexities of worker implementations, scopes, and treeherder annotations.
9 """
10
11 import functools
12 import hashlib
13 import os
14 import re
15 import time
16 from copy import deepcopy
17 from dataclasses import dataclass
18 from typing import Callable
19
20 from voluptuous import All, Any, Extra, NotIn, Optional, Required
21
22 from taskgraph import MAX_DEPENDENCIES
23 from taskgraph.transforms.base import TransformSequence
24 from taskgraph.util.hash import hash_path
25 from taskgraph.util.keyed_by import evaluate_keyed_by
26 from taskgraph.util.schema import (
27 OptimizationSchema,
28 Schema,
29 optionally_keyed_by,
30 resolve_keyed_by,
31 taskref_or_string,
32 validate_schema,
33 )
34 from taskgraph.util.treeherder import split_symbol, treeherder_defaults
35 from taskgraph.util.workertypes import worker_type_implementation
36
37 from ..util import docker as dockerutil
38 from ..util.workertypes import get_worker_type
39
40 RUN_TASK = os.path.join(
41 os.path.dirname(os.path.dirname(__file__)), "run-task", "run-task"
42 )
43
44
45 @functools.lru_cache(maxsize=None)
46 def _run_task_suffix():
47 """String to append to cache names under control of run-task."""
48 return hash_path(RUN_TASK)[0:20]
49
50
51 # A task description is a general description of a TaskCluster task
52 task_description_schema = Schema(
53 {
54 # the label for this task
55 Required("label"): str,
56 # description of the task (for metadata)
57 Required("description"): str,
58 # attributes for this task
59 Optional("attributes"): {str: object},
60 # relative path (from config.path) to the file task was defined in
61 Optional("task-from"): str,
62 # dependencies of this task, keyed by name; these are passed through
63 # verbatim and subject to the interpretation of the Task's get_dependencies
64 # method.
65 Optional("dependencies"): {
66 All(
67 str,
68 NotIn(
69 ["self", "decision"],
70 "Can't use 'self` or 'decision' as dependency names.",
71 ),
72 ): object,
73 },
74 Optional("priority"): Any(
75 "highest",
76 "very-high",
77 "high",
78 "medium",
79 "low",
80 "very-low",
81 "lowest",
82 ),
83 # Soft dependencies of this task, as a list of tasks labels
84 Optional("soft-dependencies"): [str],
85 # Dependencies that must be scheduled in order for this task to run.
86 Optional("if-dependencies"): [str],
87 Optional("requires"): Any("all-completed", "all-resolved"),
88 # expiration and deadline times, relative to task creation, with units
89 # (e.g., "14 days"). Defaults are set based on the project.
90 Optional("expires-after"): str,
91 Optional("deadline-after"): str,
92 # custom routes for this task; the default treeherder routes will be added
93 # automatically
94 Optional("routes"): [str],
95 # custom scopes for this task; any scopes required for the worker will be
96 # added automatically. The following parameters will be substituted in each
97 # scope:
98 # {level} -- the scm level of this push
99 # {project} -- the project of this push
100 Optional("scopes"): [str],
101 # Tags
102 Optional("tags"): {str: str},
103 # custom "task.extra" content
104 Optional("extra"): {str: object},
105 # treeherder-related information; see
106 # https://schemas.taskcluster.net/taskcluster-treeherder/v1/task-treeherder-config.json
107 # This may be provided in one of two ways:
108 # 1) A simple `true` will cause taskgraph to generate the required information
109 # 2) A dictionary with one or more of the required keys. Any key not present
110 # will use a default as described below.
111 # If not specified, no treeherder extra information or routes will be
112 # added to the task
113 Optional("treeherder"): Any(
114 True,
115 {
116 # either a bare symbol, or "grp(sym)".
117 # The default symbol is the uppercased first letter of each
118 # section of the kind (delimited by "-") all smooshed together.
119 # Eg: "test" becomes "T", "docker-image" becomes "DI", etc.
120 "symbol": Optional(str),
121 # the task kind
122 # If "build" or "test" is found in the kind name, this defaults
123 # to the appropriate value. Otherwise, defaults to "other"
124 "kind": Optional(Any("build", "test", "other")),
125 # tier for this task
126 # Defaults to 1
127 "tier": Optional(int),
128 # task platform, in the form platform/collection, used to set
129 # treeherder.machine.platform and treeherder.collection or
130 # treeherder.labels
131 # Defaults to "default/opt"
132 "platform": Optional(str),
133 },
134 ),
135 # information for indexing this build so its artifacts can be discovered;
136 # if omitted, the build will not be indexed.
137 Optional("index"): {
138 # the name of the product this build produces
139 "product": str,
140 # the names to use for this task in the TaskCluster index
141 "job-name": str,
142 # Type of gecko v2 index to use
143 "type": str,
144 # The rank that the task will receive in the TaskCluster
145 # index. A newly completed task supersedes the currently
146 # indexed task iff it has a higher rank. If unspecified,
147 # 'by-tier' behavior will be used.
148 "rank": Any(
149 # Rank is equal the timestamp of the build_date for tier-1
150 # tasks, and zero for non-tier-1. This sorts tier-{2,3}
151 # builds below tier-1 in the index.
152 "by-tier",
153 # Rank is given as an integer constant (e.g. zero to make
154 # sure a task is last in the index).
155 int,
156 # Rank is equal to the timestamp of the build_date. This
157 # option can be used to override the 'by-tier' behavior
158 # for non-tier-1 tasks.
159 "build_date",
160 ),
161 },
162 # The `run_on_projects` attribute, defaulting to "all". This dictates the
163 # projects on which this task should be included in the target task set.
164 # See the attributes documentation for details.
165 Optional("run-on-projects"): optionally_keyed_by("build-platform", [str]),
166 Optional("run-on-tasks-for"): [str],
167 Optional("run-on-git-branches"): [str],
168 # The `shipping_phase` attribute, defaulting to None. This specifies the
169 # release promotion phase that this task belongs to.
170 Optional("shipping-phase"): Any(
171 None,
172 "build",
173 "promote",
174 "push",
175 "ship",
176 ),
177 # The `always-target` attribute will cause the task to be included in the
178 # target_task_graph regardless of filtering. Tasks included in this manner
179 # will be candidates for optimization even when `optimize_target_tasks` is
180 # False, unless the task was also explicitly chosen by the target_tasks
181 # method.
182 Required("always-target"): bool,
183 # Optimization to perform on this task during the optimization phase.
184 # Optimizations are defined in taskcluster/taskgraph/optimize.py.
185 Required("optimization"): OptimizationSchema,
186 # the provisioner-id/worker-type for the task. The following parameters will
187 # be substituted in this string:
188 # {level} -- the scm level of this push
189 "worker-type": str,
190 # Whether the task should use sccache compiler caching.
191 Required("needs-sccache"): bool,
192 # information specific to the worker implementation that will run this task
193 Optional("worker"): {
194 Required("implementation"): str,
195 Extra: object,
196 },
197 }
198 )
199
200 TC_TREEHERDER_SCHEMA_URL = (
201 "https://github.com/taskcluster/taskcluster-treeherder/"
202 "blob/master/schemas/task-treeherder-config.yml"
203 )
204
205
206 UNKNOWN_GROUP_NAME = (
207 "Treeherder group {} (from {}) has no name; add it to taskcluster/config.yml"
208 )
209
210 V2_ROUTE_TEMPLATES = [
211 "index.{trust-domain}.v2.{project}.latest.{product}.{job-name}",
212 "index.{trust-domain}.v2.{project}.pushdate.{build_date_long}.{product}.{job-name}",
213 "index.{trust-domain}.v2.{project}.pushlog-id.{pushlog_id}.{product}.{job-name}",
214 "index.{trust-domain}.v2.{project}.revision.{branch_rev}.{product}.{job-name}",
215 ]
216
217 # the roots of the treeherder routes
218 TREEHERDER_ROUTE_ROOT = "tc-treeherder"
219
220
221 def get_branch_rev(config):
222 return config.params["head_rev"]
223
224
225 @functools.lru_cache(maxsize=None)
226 def get_default_priority(graph_config, project):
227 return evaluate_keyed_by(
228 graph_config["task-priority"], "Graph Config", {"project": project}
229 )
230
231
232 @functools.lru_cache(maxsize=None)
233 def get_default_deadline(graph_config, project):
234 return evaluate_keyed_by(
235 graph_config["task-deadline-after"], "Graph Config", {"project": project}
236 )
237
238
239 # define a collection of payload builders, depending on the worker implementation
240 payload_builders = {}
241
242
243 @dataclass(frozen=True)
244 class PayloadBuilder:
245 schema: Schema
246 builder: Callable
247
248
249 def payload_builder(name, schema):
250 schema = Schema({Required("implementation"): name, Optional("os"): str}).extend(
251 schema
252 )
253
254 def wrap(func):
255 assert name not in payload_builders, f"duplicate payload builder name {name}"
256 payload_builders[name] = PayloadBuilder(schema, func) # type: ignore
257 return func
258
259 return wrap
260
261
262 # define a collection of index builders, depending on the type implementation
263 index_builders = {}
264
265
266 def index_builder(name):
267 def wrap(func):
268 assert name not in index_builders, f"duplicate index builder name {name}"
269 index_builders[name] = func
270 return func
271
272 return wrap
273
274
275 UNSUPPORTED_INDEX_PRODUCT_ERROR = """\
276 The index product {product} is not in the list of configured products in
277 `taskcluster/config.yml'.
278 """
279
280
281 def verify_index(config, index):
282 product = index["product"]
283 if product not in config.graph_config["index"]["products"]:
284 raise Exception(UNSUPPORTED_INDEX_PRODUCT_ERROR.format(product=product))
285
286
287 @payload_builder(
288 "docker-worker",
289 schema={
290 Required("os"): "linux",
291 # For tasks that will run in docker-worker, this is the name of the docker
292 # image or in-tree docker image to run the task in. If in-tree, then a
293 # dependency will be created automatically. This is generally
294 # `desktop-test`, or an image that acts an awful lot like it.
295 Required("docker-image"): Any(
296 # a raw Docker image path (repo/image:tag)
297 str,
298 # an in-tree generated docker image (from `taskcluster/docker/<name>`)
299 {"in-tree": str},
300 # an indexed docker image
301 {"indexed": str},
302 ),
303 # worker features that should be enabled
304 Required("relengapi-proxy"): bool,
305 Required("chain-of-trust"): bool,
306 Required("taskcluster-proxy"): bool,
307 Required("allow-ptrace"): bool,
308 Required("loopback-video"): bool,
309 Required("loopback-audio"): bool,
310 Required("docker-in-docker"): bool, # (aka 'dind')
311 Required("privileged"): bool,
312 # Paths to Docker volumes.
313 #
314 # For in-tree Docker images, volumes can be parsed from Dockerfile.
315 # This only works for the Dockerfile itself: if a volume is defined in
316 # a base image, it will need to be declared here. Out-of-tree Docker
317 # images will also require explicit volume annotation.
318 #
319 # Caches are often mounted to the same path as Docker volumes. In this
320 # case, they take precedence over a Docker volume. But a volume still
321 # needs to be declared for the path.
322 Optional("volumes"): [str],
323 # caches to set up for the task
324 Optional("caches"): [
325 {
326 # only one type is supported by any of the workers right now
327 "type": "persistent",
328 # name of the cache, allowing reuse by subsequent tasks naming the
329 # same cache
330 "name": str,
331 # location in the task image where the cache will be mounted
332 "mount-point": str,
333 # Whether the cache is not used in untrusted environments
334 # (like the Try repo).
335 Optional("skip-untrusted"): bool,
336 }
337 ],
338 # artifacts to extract from the task image after completion
339 Optional("artifacts"): [
340 {
341 # type of artifact -- simple file, or recursive directory,
342 # or a volume mounted directory.
343 "type": Any("file", "directory", "volume"),
344 # task image path from which to read artifact
345 "path": str,
346 # name of the produced artifact (root of the names for
347 # type=directory)
348 "name": str,
349 }
350 ],
351 # environment variables
352 Required("env"): {str: taskref_or_string},
353 # the command to run; if not given, docker-worker will default to the
354 # command in the docker image
355 Optional("command"): [taskref_or_string],
356 # the maximum time to run, in seconds
357 Required("max-run-time"): int,
358 # the exit status code(s) that indicates the task should be retried
359 Optional("retry-exit-status"): [int],
360 # the exit status code(s) that indicates the caches used by the task
361 # should be purged
362 Optional("purge-caches-exit-status"): [int],
363 # Whether any artifacts are assigned to this worker
364 Optional("skip-artifacts"): bool,
365 },
366 )
367 def build_docker_worker_payload(config, task, task_def):
368 worker = task["worker"]
369 level = int(config.params["level"])
370
371 image = worker["docker-image"]
372 if isinstance(image, dict):
373 if "in-tree" in image:
374 name = image["in-tree"]
375 docker_image_task = "docker-image-" + image["in-tree"]
376 assert "docker-image" not in task.get("dependencies", ()), (
377 "docker-image key in dependencies object is reserved"
378 )
379 task.setdefault("dependencies", {})["docker-image"] = docker_image_task
380
381 image = {
382 "path": "public/image.tar.zst",
383 "taskId": {"task-reference": "<docker-image>"},
384 "type": "task-image",
385 }
386
387 # Find VOLUME in Dockerfile.
388 volumes = dockerutil.parse_volumes(name)
389 for v in sorted(volumes):
390 if v in worker["volumes"]:
391 raise Exception(
392 f"volume {v} already defined; "
393 "if it is defined in a Dockerfile, "
394 "it does not need to be specified in the "
395 "worker definition"
396 )
397
398 worker["volumes"].append(v)
399
400 elif "indexed" in image:
401 image = {
402 "path": "public/image.tar.zst",
403 "namespace": image["indexed"],
404 "type": "indexed-image",
405 }
406 else:
407 raise Exception("unknown docker image type")
408
409 features = {}
410
411 if worker.get("relengapi-proxy"):
412 features["relengAPIProxy"] = True
413
414 if worker.get("taskcluster-proxy"):
415 features["taskclusterProxy"] = True
416
417 if worker.get("allow-ptrace"):
418 features["allowPtrace"] = True
419 task_def["scopes"].append("docker-worker:feature:allowPtrace")
420
421 if worker.get("chain-of-trust"):
422 features["chainOfTrust"] = True
423
424 if worker.get("docker-in-docker"):
425 features["dind"] = True
426
427 if task.get("needs-sccache"):
428 features["taskclusterProxy"] = True
429 task_def["scopes"].append(
430 "assume:project:taskcluster:{trust_domain}:level-{level}-sccache-buckets".format(
431 trust_domain=config.graph_config["trust-domain"],
432 level=config.params["level"],
433 )
434 )
435 worker["env"]["USE_SCCACHE"] = "1"
436 # Disable sccache idle shutdown.
437 worker["env"]["SCCACHE_IDLE_TIMEOUT"] = "0"
438 else:
439 worker["env"]["SCCACHE_DISABLE"] = "1"
440
441 capabilities = {}
442
443 for lo in "audio", "video":
444 if worker.get("loopback-" + lo):
445 capitalized = "loopback" + lo.capitalize()
446 devices = capabilities.setdefault("devices", {})
447 devices[capitalized] = True
448 task_def["scopes"].append("docker-worker:capability:device:" + capitalized)
449
450 if worker.get("privileged"):
451 capabilities["privileged"] = True
452 task_def["scopes"].append("docker-worker:capability:privileged")
453
454 task_def["payload"] = payload = {
455 "image": image,
456 "env": worker["env"],
457 }
458 if "command" in worker:
459 payload["command"] = worker["command"]
460
461 if "max-run-time" in worker:
462 payload["maxRunTime"] = worker["max-run-time"]
463
464 run_task = payload.get("command", [""])[0].endswith("run-task")
465
466 # run-task exits EXIT_PURGE_CACHES if there is a problem with caches.
467 # Automatically retry the tasks and purge caches if we see this exit
468 # code.
469 # TODO move this closer to code adding run-task once bug 1469697 is
470 # addressed.
471 if run_task:
472 worker.setdefault("retry-exit-status", []).append(72)
473 worker.setdefault("purge-caches-exit-status", []).append(72)
474
475 payload["onExitStatus"] = {}
476 if "retry-exit-status" in worker:
477 payload["onExitStatus"]["retry"] = worker["retry-exit-status"]
478 if "purge-caches-exit-status" in worker:
479 payload["onExitStatus"]["purgeCaches"] = worker["purge-caches-exit-status"]
480
481 if "artifacts" in worker:
482 artifacts = {}
483 for artifact in worker["artifacts"]:
484 artifacts[artifact["name"]] = {
485 "path": artifact["path"],
486 "type": artifact["type"],
487 "expires": task_def["expires"], # always expire with the task
488 }
489 payload["artifacts"] = artifacts
490
491 if isinstance(worker.get("docker-image"), str):
492 out_of_tree_image = worker["docker-image"]
493 else:
494 out_of_tree_image = None
495 image = worker.get("docker-image", {}).get("in-tree")
496
497 if "caches" in worker:
498 caches = {}
499
500 # run-task knows how to validate caches.
501 #
502 # To help ensure new run-task features and bug fixes, as well as the
503 # versions of tools such as mercurial or git, don't interfere with
504 # existing caches, we seed the underlying docker-image task id into
505 # cache names, for tasks using in-tree Docker images.
506 #
507 # But this mechanism only works for in-tree Docker images that are built
508 # with the current run-task! For out-of-tree Docker images, we have no
509 # way of knowing their content of run-task. So, in addition to varying
510 # cache names by the contents of run-task, we also take the Docker image
511 # name into consideration.
512 #
513 # This means that different Docker images will never share the same
514 # cache. This is a bit unfortunate, but is the safest thing to do.
515 #
516 # For out-of-tree Docker images, we don't strictly need to incorporate
517 # the run-task content into the cache name. However, doing so preserves
518 # the mechanism whereby changing run-task results in new caches
519 # everywhere.
520
521 # As an additional mechanism to force the use of different caches, the
522 # string literal in the variable below can be changed. This is
523 # preferred to changing run-task because it doesn't require images
524 # to be rebuilt.
525 cache_version = "v3"
526
527 if run_task:
528 suffix = f"{cache_version}-{_run_task_suffix()}"
529
530 if out_of_tree_image:
531 name_hash = hashlib.sha256(
532 out_of_tree_image.encode("utf-8")
533 ).hexdigest()
534 suffix += name_hash[0:12]
535 else:
536 suffix += "-<docker-image>"
537
538 else:
539 suffix = cache_version
540
541 skip_untrusted = config.params.is_try() or level == 1
542
543 for cache in worker["caches"]:
544 # Some caches aren't enabled in environments where we can't
545 # guarantee certain behavior. Filter those out.
546 if cache.get("skip-untrusted") and skip_untrusted:
547 continue
548
549 name = "{trust_domain}-level-{level}-{name}-{suffix}".format(
550 trust_domain=config.graph_config["trust-domain"],
551 level=config.params["level"],
552 name=cache["name"],
553 suffix=suffix,
554 )
555 caches[name] = cache["mount-point"]
556 task_def["scopes"].append({"task-reference": f"docker-worker:cache:{name}"})
557
558 # Assertion: only run-task is interested in this.
559 if run_task:
560 payload["env"]["TASKCLUSTER_CACHES"] = ";".join(sorted(caches.values()))
561
562 payload["cache"] = {"task-reference": caches}
563
564 # And send down volumes information to run-task as well.
565 if run_task and worker.get("volumes"):
566 payload["env"]["TASKCLUSTER_VOLUMES"] = ";".join(sorted(worker["volumes"]))
567
568 if payload.get("cache") and skip_untrusted: # type: ignore
569 payload["env"]["TASKCLUSTER_UNTRUSTED_CACHES"] = "1"
570
571 if features:
572 payload["features"] = features
573 if capabilities:
574 payload["capabilities"] = capabilities
575
576 check_caches_are_volumes(task)
577
578
579 @payload_builder(
580 "generic-worker",
581 schema={
582 Required("os"): Any("windows", "macosx", "linux", "linux-bitbar"),
583 # see http://schemas.taskcluster.net/generic-worker/v1/payload.json
584 # and https://docs.taskcluster.net/reference/workers/generic-worker/payload
585 # command is a list of commands to run, sequentially
586 # on Windows, each command is a string, on OS X and Linux, each command is
587 # a string array
588 Required("command"): Any(
589 [taskref_or_string],
590 [[taskref_or_string]], # Windows # Linux / OS X
591 ),
592 # artifacts to extract from the task image after completion; note that artifacts
593 # for the generic worker cannot have names
594 Optional("artifacts"): [
595 {
596 # type of artifact -- simple file, or recursive directory
597 "type": Any("file", "directory"),
598 # filesystem path from which to read artifact
599 "path": str,
600 # if not specified, path is used for artifact name
601 Optional("name"): str,
602 }
603 ],
604 # Directories and/or files to be mounted.
605 # The actual allowed combinations are stricter than the model below,
606 # but this provides a simple starting point.
607 # See https://docs.taskcluster.net/reference/workers/generic-worker/payload
608 Optional("mounts"): [
609 {
610 # A unique name for the cache volume, implies writable cache directory
611 # (otherwise mount is a read-only file or directory).
612 Optional("cache-name"): str,
613 # Optional content for pre-loading cache, or mandatory content for
614 # read-only file or directory. Pre-loaded content can come from either
615 # a task artifact or from a URL.
616 Optional("content"): {
617 # *** Either (artifact and task-id) or url must be specified. ***
618 # Artifact name that contains the content.
619 Optional("artifact"): str,
620 # Task ID that has the artifact that contains the content.
621 Optional("task-id"): taskref_or_string,
622 # URL that supplies the content in response to an unauthenticated
623 # GET request.
624 Optional("url"): str,
625 },
626 # *** Either file or directory must be specified. ***
627 # If mounting a cache or read-only directory, the filesystem location of
628 # the directory should be specified as a relative path to the task
629 # directory here.
630 Optional("directory"): str,
631 # If mounting a file, specify the relative path within the task
632 # directory to mount the file (the file will be read only).
633 Optional("file"): str,
634 # Required if and only if `content` is specified and mounting a
635 # directory (not a file). This should be the archive format of the
636 # content (either pre-loaded cache or read-only directory).
637 Optional("format"): Any("rar", "tar.bz2", "tar.gz", "zip"),
638 }
639 ],
640 # environment variables
641 Required("env"): {str: taskref_or_string},
642 # the maximum time to run, in seconds
643 Required("max-run-time"): int,
644 # the exit status code(s) that indicates the task should be retried
645 Optional("retry-exit-status"): [int],
646 # the exit status code(s) that indicates the caches used by the task
647 # should be purged
648 Optional("purge-caches-exit-status"): [int],
649 # os user groups for test task workers
650 Optional("os-groups"): [str],
651 # feature for test task to run as administarotr
652 Optional("run-as-administrator"): bool,
653 # feature for task to run as current OS user
654 Optional("run-task-as-current-user"): bool,
655 # optional features
656 Required("chain-of-trust"): bool,
657 Optional("taskcluster-proxy"): bool,
658 # Whether any artifacts are assigned to this worker
659 Optional("skip-artifacts"): bool,
660 },
661 )
662 def build_generic_worker_payload(config, task, task_def):
663 worker = task["worker"]
664
665 task_def["payload"] = {
666 "command": worker["command"],
667 "maxRunTime": worker["max-run-time"],
668 }
669
670 on_exit_status = {}
671 if "retry-exit-status" in worker:
672 on_exit_status["retry"] = worker["retry-exit-status"]
673 if "purge-caches-exit-status" in worker:
674 on_exit_status["purgeCaches"] = worker["purge-caches-exit-status"]
675 if worker["os"] == "windows":
676 on_exit_status.setdefault("retry", []).extend(
677 [
678 # These codes (on windows) indicate a process interruption,
679 # rather than a task run failure. See bug 1544403.
680 1073807364, # process force-killed due to system shutdown
681 3221225786, # sigint (any interrupt)
682 ]
683 )
684 if on_exit_status:
685 task_def["payload"]["onExitStatus"] = on_exit_status
686
687 env = worker.get("env", {})
688
689 if task.get("needs-sccache"):
690 env["USE_SCCACHE"] = "1"
691 # Disable sccache idle shutdown.
692 env["SCCACHE_IDLE_TIMEOUT"] = "0"
693 else:
694 env["SCCACHE_DISABLE"] = "1"
695
696 if env:
697 task_def["payload"]["env"] = env
698
699 artifacts = []
700
701 for artifact in worker.get("artifacts", []):
702 a = {
703 "path": artifact["path"],
704 "type": artifact["type"],
705 }
706 if "name" in artifact:
707 a["name"] = artifact["name"]
708 artifacts.append(a)
709
710 if artifacts:
711 task_def["payload"]["artifacts"] = artifacts
712
713 # Need to copy over mounts, but rename keys to respect naming convention
714 # * 'cache-name' -> 'cacheName'
715 # * 'task-id' -> 'taskId'
716 # All other key names are already suitable, and don't need renaming.
717 mounts = deepcopy(worker.get("mounts", []))
718 for mount in mounts:
719 if "cache-name" in mount:
720 mount["cacheName"] = "{trust_domain}-level-{level}-{name}".format(
721 trust_domain=config.graph_config["trust-domain"],
722 level=config.params["level"],
723 name=mount.pop("cache-name"),
724 )
725 task_def["scopes"].append(
726 "generic-worker:cache:{}".format(mount["cacheName"])
727 )
728 if "content" in mount:
729 if "task-id" in mount["content"]:
730 mount["content"]["taskId"] = mount["content"].pop("task-id")
731 if "artifact" in mount["content"]:
732 if not mount["content"]["artifact"].startswith("public/"):
733 task_def["scopes"].append(
734 "queue:get-artifact:{}".format(mount["content"]["artifact"])
735 )
736
737 if mounts:
738 task_def["payload"]["mounts"] = mounts
739
740 if worker.get("os-groups"):
741 task_def["payload"]["osGroups"] = worker["os-groups"]
742 task_def["scopes"].extend(
743 [
744 "generic-worker:os-group:{}/{}".format(task["worker-type"], group)
745 for group in worker["os-groups"]
746 ]
747 )
748
749 features = {}
750
751 if worker.get("chain-of-trust"):
752 features["chainOfTrust"] = True
753
754 if worker.get("taskcluster-proxy"):
755 features["taskclusterProxy"] = True
756
757 if worker.get("run-as-administrator", False):
758 features["runAsAdministrator"] = True
759 task_def["scopes"].append(
760 "generic-worker:run-as-administrator:{}".format(task["worker-type"]),
761 )
762
763 if worker.get("run-task-as-current-user", False):
764 features["runTaskAsCurrentUser"] = True
765 task_def["scopes"].append(
766 "generic-worker:run-task-as-current-user:{}".format(task["worker-type"]),
767 )
768
769 if features:
770 task_def["payload"]["features"] = features
771
772
773 @payload_builder(
774 "beetmover",
775 schema={
776 # the maximum time to run, in seconds
777 Required("max-run-time"): int,
778 # locale key, if this is a locale beetmover task
779 Optional("locale"): str,
780 Optional("partner-public"): bool,
781 Required("release-properties"): {
782 "app-name": str,
783 "app-version": str,
784 "branch": str,
785 "build-id": str,
786 "hash-type": str,
787 "platform": str,
788 },
789 # list of artifact URLs for the artifacts that should be beetmoved
790 Required("upstream-artifacts"): [
791 {
792 # taskId of the task with the artifact
793 Required("taskId"): taskref_or_string,
794 # type of signing task (for CoT)
795 Required("taskType"): str,
796 # Paths to the artifacts to sign
797 Required("paths"): [str],
798 # locale is used to map upload path and allow for duplicate simple names
799 Required("locale"): str,
800 }
801 ],
802 Optional("artifact-map"): object,
803 },
804 )
805 def build_beetmover_payload(config, task, task_def):
806 worker = task["worker"]
807 release_properties = worker["release-properties"]
808
809 task_def["payload"] = {
810 "maxRunTime": worker["max-run-time"],
811 "releaseProperties": {
812 "appName": release_properties["app-name"],
813 "appVersion": release_properties["app-version"],
814 "branch": release_properties["branch"],
815 "buildid": release_properties["build-id"],
816 "hashType": release_properties["hash-type"],
817 "platform": release_properties["platform"],
818 },
819 "upload_date": config.params["build_date"],
820 "upstreamArtifacts": worker["upstream-artifacts"],
821 }
822 if worker.get("locale"):
823 task_def["payload"]["locale"] = worker["locale"]
824 if worker.get("artifact-map"):
825 task_def["payload"]["artifactMap"] = worker["artifact-map"]
826 if worker.get("partner-public"):
827 task_def["payload"]["is_partner_repack_public"] = worker["partner-public"]
828
829
830 @payload_builder(
831 "invalid",
832 schema={
833 # an invalid task is one which should never actually be created; this is used in
834 # release automation on branches where the task just doesn't make sense
835 Extra: object,
836 },
837 )
838 def build_invalid_payload(config, task, task_def):
839 task_def["payload"] = "invalid task - should never be created"
840
841
842 @payload_builder(
843 "always-optimized",
844 schema={
845 Extra: object,
846 },
847 )
848 @payload_builder("succeed", schema={})
849 def build_dummy_payload(config, task, task_def):
850 task_def["payload"] = {}
851
852
853 transforms = TransformSequence()
854
855
856 @transforms.add
857 def set_implementation(config, tasks):
858 """
859 Set the worker implementation based on the worker-type alias.
860 """
861 for task in tasks:
862 worker = task.setdefault("worker", {})
863 if "implementation" in task["worker"]:
864 yield task
865 continue
866
867 impl, os = worker_type_implementation(config.graph_config, task["worker-type"])
868
869 tags = task.setdefault("tags", {})
870 tags["worker-implementation"] = impl
871 if os:
872 task["tags"]["os"] = os
873 worker["implementation"] = impl
874 if os:
875 worker["os"] = os
876
877 yield task
878
879
880 @transforms.add
881 def set_defaults(config, tasks):
882 for task in tasks:
883 task.setdefault("always-target", False)
884 task.setdefault("optimization", None)
885 task.setdefault("needs-sccache", False)
886
887 worker = task["worker"]
888 if worker["implementation"] in ("docker-worker",):
889 worker.setdefault("relengapi-proxy", False)
890 worker.setdefault("chain-of-trust", False)
891 worker.setdefault("taskcluster-proxy", False)
892 worker.setdefault("allow-ptrace", False)
893 worker.setdefault("loopback-video", False)
894 worker.setdefault("loopback-audio", False)
895 worker.setdefault("docker-in-docker", False)
896 worker.setdefault("privileged", False)
897 worker.setdefault("volumes", [])
898 worker.setdefault("env", {})
899 if "caches" in worker:
900 for c in worker["caches"]:
901 c.setdefault("skip-untrusted", False)
902 elif worker["implementation"] == "generic-worker":
903 worker.setdefault("env", {})
904 worker.setdefault("os-groups", [])
905 if worker["os-groups"] and worker["os"] != "windows":
906 raise Exception(
907 "os-groups feature of generic-worker is only supported on "
908 "Windows, not on {}".format(worker["os"])
909 )
910 worker.setdefault("chain-of-trust", False)
911 elif worker["implementation"] in (
912 "scriptworker-signing",
913 "beetmover",
914 "beetmover-push-to-release",
915 "beetmover-maven",
916 ):
917 worker.setdefault("max-run-time", 600)
918 elif worker["implementation"] == "push-apk":
919 worker.setdefault("commit", False)
920
921 yield task
922
923
924 @transforms.add
925 def task_name_from_label(config, tasks):
926 for task in tasks:
927 if "label" not in task:
928 if "name" not in task:
929 raise Exception("task has neither a name nor a label")
930 task["label"] = "{}-{}".format(config.kind, task["name"])
931 if task.get("name"):
932 del task["name"]
933 yield task
934
935
936 @transforms.add
937 def validate(config, tasks):
938 for task in tasks:
939 validate_schema(
940 task_description_schema,
941 task,
942 "In task {!r}:".format(task.get("label", "?no-label?")),
943 )
944 validate_schema(
945 payload_builders[task["worker"]["implementation"]].schema,
946 task["worker"],
947 "In task.run {!r}:".format(task.get("label", "?no-label?")),
948 )
949 yield task
950
951
952 @index_builder("generic")
953 def add_generic_index_routes(config, task):
954 index = task.get("index")
955 routes = task.setdefault("routes", [])
956
957 verify_index(config, index)
958
959 subs = config.params.copy()
960 subs["job-name"] = index["job-name"]
961 subs["build_date_long"] = time.strftime(
962 "%Y.%m.%d.%Y%m%d%H%M%S", time.gmtime(config.params["build_date"])
963 )
964 subs["product"] = index["product"]
965 subs["trust-domain"] = config.graph_config["trust-domain"]
966 subs["branch_rev"] = get_branch_rev(config)
967
968 for tpl in V2_ROUTE_TEMPLATES:
969 routes.append(tpl.format(**subs))
970
971 return task
972
973
974 @transforms.add
975 def process_treeherder_metadata(config, tasks):
976 for task in tasks:
977 routes = task.get("routes", [])
978 extra = task.get("extra", {})
979 task_th = task.get("treeherder")
980
981 if task_th:
982 # This `merged_th` object is just an intermediary that combines
983 # the defaults and whatever is in the task. Ultimately, the task
984 # transforms this data a bit in the `treeherder` object that is
985 # eventually set in the task.
986 merged_th = treeherder_defaults(config.kind, task["label"])
987 if isinstance(task_th, dict):
988 merged_th.update(task_th)
989
990 treeherder = extra.setdefault("treeherder", {})
991 extra.setdefault("treeherder-platform", merged_th["platform"])
992
993 machine_platform, collection = merged_th["platform"].split("/", 1)
994 treeherder["machine"] = {"platform": machine_platform}
995 treeherder["collection"] = {collection: True}
996
997 group_names = config.graph_config["treeherder"]["group-names"]
998 groupSymbol, symbol = split_symbol(merged_th["symbol"])
999 if groupSymbol != "?":
1000 treeherder["groupSymbol"] = groupSymbol
1001 if groupSymbol not in group_names:
1002 path = os.path.join(config.path, task.get("task-from", ""))
1003 raise Exception(UNKNOWN_GROUP_NAME.format(groupSymbol, path))
1004 treeherder["groupName"] = group_names[groupSymbol]
1005 treeherder["symbol"] = symbol
1006 if len(symbol) > 25 or len(groupSymbol) > 25:
1007 raise RuntimeError(
1008 "Treeherder group and symbol names must not be longer than "
1009 "25 characters: {} (see {})".format(
1010 treeherder["symbol"],
1011 TC_TREEHERDER_SCHEMA_URL,
1012 )
1013 )
1014 treeherder["jobKind"] = merged_th["kind"]
1015 treeherder["tier"] = merged_th["tier"]
1016
1017 branch_rev = get_branch_rev(config)
1018
1019 if config.params["tasks_for"].startswith("github-pull-request"):
1020 # In the past we used `project` for this, but that ends up being
1021 # set to the repository name of the _head_ repo, which is not correct
1022 # (and causes scope issues) if it doesn't match the name of the
1023 # base repo
1024 base_project = config.params["base_repository"].split("/")[-1]
1025 if base_project.endswith(".git"):
1026 base_project = base_project[:-4]
1027 th_project_suffix = "-pr"
1028 else:
1029 base_project = config.params["project"]
1030 th_project_suffix = ""
1031
1032 routes.append(
1033 "{}.v2.{}.{}.{}".format(
1034 TREEHERDER_ROUTE_ROOT,
1035 base_project + th_project_suffix,
1036 branch_rev,
1037 config.params["pushlog_id"],
1038 )
1039 )
1040
1041 task["routes"] = routes
1042 task["extra"] = extra
1043 yield task
1044
1045
1046 @transforms.add
1047 def add_index_routes(config, tasks):
1048 for task in tasks:
1049 index = task.get("index", {})
1050
1051 # The default behavior is to rank tasks according to their tier
1052 extra_index = task.setdefault("extra", {}).setdefault("index", {})
1053 rank = index.get("rank", "by-tier")
1054
1055 if rank == "by-tier":
1056 # rank is zero for non-tier-1 tasks and based on pushid for others;
1057 # this sorts tier-{2,3} builds below tier-1 in the index
1058 tier = task.get("extra", {}).get("treeherder", {}).get("tier", 3)
1059 extra_index["rank"] = 0 if tier > 1 else int(config.params["build_date"])
1060 elif rank == "build_date":
1061 extra_index["rank"] = int(config.params["build_date"])
1062 else:
1063 extra_index["rank"] = rank
1064
1065 if not index:
1066 yield task
1067 continue
1068
1069 index_type = index.get("type", "generic")
1070 if index_type not in index_builders:
1071 raise ValueError(f"Unknown index-type {index_type}")
1072 task = index_builders[index_type](config, task)
1073
1074 del task["index"]
1075 yield task
1076
1077
1078 @transforms.add
1079 def build_task(config, tasks):
1080 for task in tasks:
1081 level = str(config.params["level"])
1082
1083 provisioner_id, worker_type = get_worker_type(
1084 config.graph_config,
1085 task["worker-type"],
1086 level,
1087 )
1088 task["worker-type"] = "/".join([provisioner_id, worker_type])
1089 project = config.params["project"]
1090
1091 routes = task.get("routes", [])
1092 scopes = [
1093 s.format(level=level, project=project) for s in task.get("scopes", [])
1094 ]
1095
1096 # set up extra
1097 extra = task.get("extra", {})
1098 extra["parent"] = os.environ.get("TASK_ID", "")
1099
1100 if "expires-after" not in task:
1101 task["expires-after"] = (
1102 config.graph_config._config.get("task-expires-after", "28 days")
1103 if config.params.is_try()
1104 else "1 year"
1105 )
1106
1107 if "deadline-after" not in task:
1108 if "task-deadline-after" in config.graph_config:
1109 task["deadline-after"] = get_default_deadline(
1110 config.graph_config, config.params["project"]
1111 )
1112 else:
1113 task["deadline-after"] = "1 day"
1114
1115 if "priority" not in task:
1116 task["priority"] = get_default_priority(
1117 config.graph_config, config.params["project"]
1118 )
1119
1120 tags = task.get("tags", {})
1121 tags.update(
1122 {
1123 "createdForUser": config.params["owner"],
1124 "kind": config.kind,
1125 "label": task["label"],
1126 "project": config.params["project"],
1127 "trust-domain": config.graph_config["trust-domain"],
1128 }
1129 )
1130
1131 task_def = {
1132 "provisionerId": provisioner_id,
1133 "workerType": worker_type,
1134 "routes": routes,
1135 "created": {"relative-datestamp": "0 seconds"},
1136 "deadline": {"relative-datestamp": task["deadline-after"]},
1137 "expires": {"relative-datestamp": task["expires-after"]},
1138 "scopes": scopes,
1139 "metadata": {
1140 "description": task["description"],
1141 "name": task["label"],
1142 "owner": config.params["owner"],
1143 "source": config.params.file_url(config.path, pretty=True),
1144 },
1145 "extra": extra,
1146 "tags": tags,
1147 "priority": task["priority"],
1148 }
1149
1150 if task.get("requires", None):
1151 task_def["requires"] = task["requires"]
1152
1153 if task.get("extra", {}).get("treeherder"):
1154 branch_rev = get_branch_rev(config)
1155 if config.params["tasks_for"].startswith("github-pull-request"):
1156 # In the past we used `project` for this, but that ends up being
1157 # set to the repository name of the _head_ repo, which is not correct
1158 # (and causes scope issues) if it doesn't match the name of the
1159 # base repo
1160 base_project = config.params["base_repository"].split("/")[-1]
1161 if base_project.endswith(".git"):
1162 base_project = base_project[:-4]
1163 th_project_suffix = "-pr"
1164 else:
1165 base_project = config.params["project"]
1166 th_project_suffix = ""
1167
1168 # link back to treeherder in description
1169 th_push_link = (
1170 "https://treeherder.mozilla.org/#/jobs?repo={}&revision={}".format(
1171 config.params["project"] + th_project_suffix, branch_rev
1172 )
1173 )
1174 task_def["metadata"]["description"] += (
1175 f" ([Treeherder push]({th_push_link}))"
1176 )
1177
1178 # add the payload and adjust anything else as required (e.g., scopes)
1179 payload_builders[task["worker"]["implementation"]].builder(
1180 config, task, task_def
1181 )
1182
1183 attributes = task.get("attributes", {})
1184 # Resolve run-on-projects
1185 build_platform = attributes.get("build_platform")
1186 resolve_keyed_by(
1187 task,
1188 "run-on-projects",
1189 item_name=task["label"],
1190 **{"build-platform": build_platform},
1191 )
1192 attributes["run_on_projects"] = task.get("run-on-projects", ["all"])
1193 attributes["run_on_tasks_for"] = task.get("run-on-tasks-for", ["all"])
1194 # We don't want to pollute non git repos with this attribute. Moreover, target_tasks
1195 # already assumes the default value is ['all']
1196 if task.get("run-on-git-branches"):
1197 attributes["run_on_git_branches"] = task["run-on-git-branches"]
1198
1199 attributes["always_target"] = task["always-target"]
1200 # This logic is here since downstream tasks don't always match their
1201 # upstream dependency's shipping_phase.
1202 # A text_type task['shipping-phase'] takes precedence, then
1203 # an existing attributes['shipping_phase'], then fall back to None.
1204 if task.get("shipping-phase") is not None:
1205 attributes["shipping_phase"] = task["shipping-phase"]
1206 else:
1207 attributes.setdefault("shipping_phase", None)
1208
1209 # Set MOZ_AUTOMATION on all jobs.
1210 if task["worker"]["implementation"] in (
1211 "generic-worker",
1212 "docker-worker",
1213 ):
1214 payload = task_def.get("payload")
1215 if payload:
1216 env = payload.setdefault("env", {})
1217 env["MOZ_AUTOMATION"] = "1"
1218
1219 dependencies = task.get("dependencies", {})
1220 if_dependencies = task.get("if-dependencies", [])
1221 if if_dependencies:
1222 for i, dep in enumerate(if_dependencies):
1223 if dep in dependencies:
1224 if_dependencies[i] = dependencies[dep]
1225 continue
1226
1227 raise Exception(
1228 "{label} specifies '{dep}' in if-dependencies, "
1229 "but {dep} is not a dependency!".format(
1230 label=task["label"], dep=dep
1231 )
1232 )
1233
1234 yield {
1235 "label": task["label"],
1236 "description": task["description"],
1237 "task": task_def,
1238 "dependencies": dependencies,
1239 "if-dependencies": if_dependencies,
1240 "soft-dependencies": task.get("soft-dependencies", []),
1241 "attributes": attributes,
1242 "optimization": task.get("optimization", None),
1243 }
1244
1245
1246 @transforms.add
1247 def add_github_checks(config, tasks):
1248 """
1249 For git repositories, add checks route to all tasks.
1250
1251 This will be replaced by a configurable option in the future.
1252 """
1253 if config.params["repository_type"] != "git":
1254 for task in tasks:
1255 yield task
1256
1257 for task in tasks:
1258 task["task"]["routes"].append("checks")
1259 yield task
1260
1261
1262 @transforms.add
1263 def chain_of_trust(config, tasks):
1264 for task in tasks:
1265 if task["task"].get("payload", {}).get("features", {}).get("chainOfTrust"):
1266 image = task.get("dependencies", {}).get("docker-image")
1267 if image:
1268 cot = (
1269 task["task"].setdefault("extra", {}).setdefault("chainOfTrust", {})
1270 )
1271 cot.setdefault("inputs", {})["docker-image"] = {
1272 "task-reference": "<docker-image>"
1273 }
1274 yield task
1275
1276
1277 @transforms.add
1278 def check_task_identifiers(config, tasks):
1279 """Ensures that all tasks have well defined identifiers:
1280 ``^[a-zA-Z0-9_-]{1,38}$``
1281 """
1282 e = re.compile("^[a-zA-Z0-9_-]{1,38}$")
1283 for task in tasks:
1284 for attrib in ("workerType", "provisionerId"):
1285 if not e.match(task["task"][attrib]):
1286 raise Exception(
1287 "task {}.{} is not a valid identifier: {}".format(
1288 task["label"], attrib, task["task"][attrib]
1289 )
1290 )
1291 yield task
1292
1293
1294 @transforms.add
1295 def check_task_dependencies(config, tasks):
1296 """Ensures that tasks don't have more than 100 dependencies."""
1297 for task in tasks:
1298 number_of_dependencies = (
1299 len(task["dependencies"])
1300 + len(task["if-dependencies"])
1301 + len(task["soft-dependencies"])
1302 )
1303 if number_of_dependencies > MAX_DEPENDENCIES:
1304 raise Exception(
1305 "task {}/{} has too many dependencies ({} > {})".format(
1306 config.kind,
1307 task["label"],
1308 number_of_dependencies,
1309 MAX_DEPENDENCIES,
1310 )
1311 )
1312 yield task
1313
1314
1315 def check_caches_are_volumes(task):
1316 """Ensures that all cache paths are defined as volumes.
1317
1318 Caches and volumes are the only filesystem locations whose content
1319 isn't defined by the Docker image itself. Some caches are optional
1320 depending on the task environment. We want paths that are potentially
1321 caches to have as similar behavior regardless of whether a cache is
1322 used. To help enforce this, we require that all paths used as caches
1323 to be declared as Docker volumes. This check won't catch all offenders.
1324 But it is better than nothing.
1325 """
1326 volumes = set(task["worker"]["volumes"])
1327 paths = {c["mount-point"] for c in task["worker"].get("caches", [])}
1328 missing = paths - volumes
1329
1330 if not missing:
1331 return
1332
1333 raise Exception(
1334 "task {} (image {}) has caches that are not declared as "
1335 "Docker volumes: {} "
1336 "(have you added them as VOLUMEs in the Dockerfile?)".format(
1337 task["label"], task["worker"]["docker-image"], ", ".join(sorted(missing))
1338 )
1339 )
1340
1341
1342 @transforms.add
1343 def check_run_task_caches(config, tasks):
1344 """Audit for caches requiring run-task.
1345
1346 run-task manages caches in certain ways. If a cache managed by run-task
1347 is used by a non run-task task, it could cause problems. So we audit for
1348 that and make sure certain cache names are exclusive to run-task.
1349
1350 IF YOU ARE TEMPTED TO MAKE EXCLUSIONS TO THIS POLICY, YOU ARE LIKELY
1351 CONTRIBUTING TECHNICAL DEBT AND WILL HAVE TO SOLVE MANY OF THE PROBLEMS
1352 THAT RUN-TASK ALREADY SOLVES. THINK LONG AND HARD BEFORE DOING THAT.
1353 """
1354 re_reserved_caches = re.compile(
1355 """^
1356 (checkouts|tooltool-cache)
1357 """,
1358 re.VERBOSE,
1359 )
1360
1361 cache_prefix = "{trust_domain}-level-{level}-".format(
1362 trust_domain=config.graph_config["trust-domain"],
1363 level=config.params["level"],
1364 )
1365
1366 suffix = _run_task_suffix()
1367
1368 for task in tasks:
1369 payload = task["task"].get("payload", {})
1370 command = payload.get("command") or [""]
1371
1372 main_command = command[0] if isinstance(command[0], str) else ""
1373 run_task = main_command.endswith("run-task")
1374
1375 for cache in payload.get("cache", {}).get(
1376 "task-reference", payload.get("cache", {})
1377 ):
1378 if not cache.startswith(cache_prefix):
1379 raise Exception(
1380 "{} is using a cache ({}) which is not appropriate "
1381 "for its trust-domain and level. It should start with {}.".format(
1382 task["label"], cache, cache_prefix
1383 )
1384 )
1385
1386 cache = cache[len(cache_prefix) :]
1387
1388 if not re_reserved_caches.match(cache):
1389 continue
1390
1391 if not run_task:
1392 raise Exception(
1393 f"{task['label']} is using a cache ({cache}) reserved for run-task "
1394 "change the task to use run-task or use a different "
1395 "cache name"
1396 )
1397
1398 if suffix not in cache:
1399 raise Exception(
1400 f"{task['label']} is using a cache ({cache}) reserved for run-task "
1401 "but the cache name is not dependent on the contents "
1402 "of run-task; change the cache name to conform to the "
1403 "naming requirements"
1404 )
1405
1406 yield task