-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtask.py
More file actions
2689 lines (2333 loc) · 96.4 KB
/
task.py
File metadata and controls
2689 lines (2333 loc) · 96.4 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
These transformations take a task description and turn it into a TaskCluster
task definition (along with attributes, label, etc.). The input to these
transformations is generic to any kind of task, but abstracts away some of the
complexities of worker implementations, scopes, and treeherder annotations.
"""
import datetime
import hashlib
import os
import re
import time
from mozbuild.util import memoize
from mozilla_taskgraph.util.signed_artifacts import get_signed_artifacts
from taskcluster.utils import fromNow
from taskgraph import MAX_DEPENDENCIES
from taskgraph.transforms.base import TransformSequence
from taskgraph.transforms.task import payload_builder, payload_builders
from taskgraph.util.copy import deepcopy
from taskgraph.util.keyed_by import evaluate_keyed_by
from taskgraph.util.schema import (
Schema,
optionally_keyed_by,
resolve_keyed_by,
taskref_or_string,
validate_schema,
)
from taskgraph.util.treeherder import split_symbol
from voluptuous import All, Any, Extra, Match, NotIn, Optional, Required
from gecko_taskgraph import GECKO
from gecko_taskgraph.optimize.schema import OptimizationSchema
from gecko_taskgraph.transforms.job.common import get_expiration
from gecko_taskgraph.util import docker as dockerutil
from gecko_taskgraph.util.attributes import TRUNK_PROJECTS, is_try, release_level
from gecko_taskgraph.util.chunking import TEST_VARIANTS
from gecko_taskgraph.util.hash import hash_path
from gecko_taskgraph.util.partners import get_partners_to_be_published
from gecko_taskgraph.util.scriptworker import BALROG_ACTIONS, get_release_config
from gecko_taskgraph.util.workertypes import get_worker_type, worker_type_implementation
RUN_TASK_HG = os.path.join(GECKO, "taskcluster", "scripts", "run-task")
RUN_TASK_GIT = os.path.join(
GECKO,
"third_party",
"python",
"taskcluster_taskgraph",
"taskgraph",
"run-task",
"run-task",
)
SCCACHE_GCS_PROJECT = "sccache-3"
@memoize
def _run_task_suffix(repo_type):
"""String to append to cache names under control of run-task."""
if repo_type == "hg":
return hash_path(RUN_TASK_HG)[0:20]
return hash_path(RUN_TASK_GIT)[0:20]
def _compute_geckoview_version(app_version, moz_build_date):
"""Geckoview version string that matches geckoview gradle configuration"""
# Must be synchronized with /mobile/android/geckoview/build.gradle computeVersionCode(...)
version_without_milestone = re.sub(r"a[0-9]", "", app_version, 1)
parts = version_without_milestone.split(".")
return f"{parts[0]}.{parts[1]}.{moz_build_date}"
# A task description is a general description of a TaskCluster task
task_description_schema = Schema({
# the label for this task
Required("label"): str,
# description of the task (for metadata)
Required("description"): str,
# attributes for this task
Optional("attributes"): {str: object},
# relative path (from config.path) to the file task was defined in
Optional("task-from"): str,
# dependencies of this task, keyed by name; these are passed through
# verbatim and subject to the interpretation of the Task's get_dependencies
# method.
Optional("dependencies"): {
All(
str,
NotIn(
["self", "decision"],
"Can't use 'self` or 'decision' as depdency names.",
),
): object,
},
# Soft dependencies of this task, as a list of tasks labels
Optional("soft-dependencies"): [str],
# Dependencies that must be scheduled in order for this task to run.
Optional("if-dependencies"): [str],
Optional("requires"): Any("all-completed", "all-resolved"),
# expiration and deadline times, relative to task creation, with units
# (e.g., "14 days"). Defaults are set based on the project.
Optional("expires-after"): str,
Optional("deadline-after"): str,
Optional("expiration-policy"): str,
# custom routes for this task; the default treeherder routes will be added
# automatically
Optional("routes"): [str],
# custom scopes for this task; any scopes required for the worker will be
# added automatically. The following parameters will be substituted in each
# scope:
# {level} -- the scm level of this push
# {project} -- the project of this push
Optional("scopes"): [str],
# Tags
Optional("tags"): {str: str},
# custom "task.extra" content
Optional("extra"): {str: object},
# treeherder-related information; see
# https://firefox-ci-tc.services.mozilla.com/schemas/taskcluster-treeherder/v1/task-treeherder-config.json
# If not specified, no treeherder extra information or routes will be
# added to the task
Optional("treeherder"): {
# either a bare symbol, or "grp(sym)".
"symbol": str,
# the job kind
"kind": Any("build", "test", "other"),
# tier for this task
"tier": int,
# task platform, in the form platform/collection, used to set
# treeherder.machine.platform and treeherder.collection or
# treeherder.labels
"platform": Match("^[A-Za-z0-9_-]{1,50}/[A-Za-z0-9_-]{1,50}$"),
},
# information for indexing this build so its artifacts can be discovered;
# if omitted, the build will not be indexed.
Optional("index"): {
# the name of the product this build produces
"product": str,
# the names to use for this job in the TaskCluster index
"job-name": str,
# Type of gecko v2 index to use
"type": Any(
"generic",
"l10n",
"shippable",
"shippable-l10n",
"android-shippable",
"android-shippable-with-multi-l10n",
"shippable-with-multi-l10n",
),
# The rank that the task will receive in the TaskCluster
# index. A newly completed task supercedes the currently
# indexed task iff it has a higher rank. If unspecified,
# 'by-tier' behavior will be used.
"rank": Any(
# Rank is equal the timestamp of the build_date for tier-1
# tasks, and one for non-tier-1. This sorts tier-{2,3}
# builds below tier-1 in the index, but above eager-index.
"by-tier",
# Rank is given as an integer constant (e.g. zero to make
# sure a task is last in the index).
int,
# Rank is equal to the timestamp of the build_date. This
# option can be used to override the 'by-tier' behavior
# for non-tier-1 tasks.
"build_date",
),
},
# The `run_on_repo_type` attribute, defaulting to "hg". This dictates
# the types of repositories on which this task should be included in
# the target task set. See the attributes documentation for details.
Optional("run-on-repo-type"): [Any("git", "hg")],
# The `run_on_projects` attribute, defaulting to "all". This dictates the
# projects on which this task should be included in the target task set.
# See the attributes documentation for details.
Optional("run-on-projects"): optionally_keyed_by("build-platform", [str]),
# Like `run_on_projects`, `run-on-hg-branches` defaults to "all".
Optional("run-on-hg-branches"): optionally_keyed_by("project", [str]),
# Specifies git branches for which this task should run.
Optional("run-on-git-branches"): [str],
# The `shipping_phase` attribute, defaulting to None. This specifies the
# release promotion phase that this task belongs to.
Required("shipping-phase"): Any(
None,
"build",
"promote",
"push",
"ship",
),
# The `shipping_product` attribute, defaulting to None. This specifies the
# release promotion product that this task belongs to.
Required("shipping-product"): Any(None, str),
# The `always-target` attribute will cause the task to be included in the
# target_task_graph regardless of filtering. Tasks included in this manner
# will be candidates for optimization even when `optimize_target_tasks` is
# False, unless the task was also explicitly chosen by the target_tasks
# method.
Required("always-target"): bool,
# Optimization to perform on this task during the optimization phase.
# Optimizations are defined in taskcluster/gecko_taskgraph/optimize.py.
Required("optimization"): OptimizationSchema,
# the provisioner-id/worker-type for the task. The following parameters will
# be substituted in this string:
# {level} -- the scm level of this push
"worker-type": str,
# Whether the job should use sccache compiler caching.
Required("use-sccache"): bool,
# information specific to the worker implementation that will run this task
Optional("worker"): {
Required("implementation"): str,
Extra: object,
},
# Override the default priority for the project
Optional("priority"): str,
# Override the default 5 retries
Optional("retries"): int,
})
TC_TREEHERDER_SCHEMA_URL = (
"https://github.com/taskcluster/taskcluster-treeherder/"
"blob/master/schemas/task-treeherder-config.yml"
)
UNKNOWN_GROUP_NAME = (
"Treeherder group {} (from {}) has no name; add it to taskcluster/config.yml"
)
V2_ROUTE_TEMPLATES = [
"index.{trust-domain}.v2.{project}.latest.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.pushdate.{build_date_long}.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.pushdate.{build_date}.latest.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.pushlog-id.{pushlog_id}.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.revision.{branch_rev}.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.revision.{branch_git_rev}.{product}.{job-name}",
]
# {central, inbound, autoland} write to a "trunk" index prefix. This facilitates
# walking of tasks with similar configurations.
V2_TRUNK_ROUTE_TEMPLATES = [
"index.{trust-domain}.v2.trunk.revision.{branch_rev}.{product}.{job-name}",
]
V2_SHIPPABLE_TEMPLATES = [
"index.{trust-domain}.v2.{project}.shippable.latest.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.shippable.{build_date}.revision.{branch_rev}.{product}.{job-name}", # noqa - too long
"index.{trust-domain}.v2.{project}.shippable.{build_date}.latest.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.shippable.revision.{branch_rev}.{product}.{job-name}",
"index.{trust-domain}.v2.{project}.shippable.revision.{branch_git_rev}.{product}.{job-name}",
]
V2_SHIPPABLE_L10N_TEMPLATES = [
"index.{trust-domain}.v2.{project}.shippable.latest.{product}-l10n.{job-name}.{locale}",
"index.{trust-domain}.v2.{project}.shippable.{build_date}.revision.{branch_rev}.{product}-l10n.{job-name}.{locale}", # noqa - too long
"index.{trust-domain}.v2.{project}.shippable.{build_date}.latest.{product}-l10n.{job-name}.{locale}", # noqa - too long
"index.{trust-domain}.v2.{project}.shippable.revision.{branch_rev}.{product}-l10n.{job-name}.{locale}", # noqa - too long
]
V2_L10N_TEMPLATES = [
"index.{trust-domain}.v2.{project}.revision.{branch_rev}.{product}-l10n.{job-name}.{locale}",
"index.{trust-domain}.v2.{project}.pushdate.{build_date_long}.{product}-l10n.{job-name}.{locale}", # noqa - too long
"index.{trust-domain}.v2.{project}.pushlog-id.{pushlog_id}.{product}-l10n.{job-name}.{locale}",
"index.{trust-domain}.v2.{project}.latest.{product}-l10n.{job-name}.{locale}",
]
# This index is specifically for builds that include geckoview releases,
# so we can hard-code the project to "geckoview"
V2_GECKOVIEW_RELEASE = "index.{trust-domain}.v2.{project}.geckoview-version.{geckoview-version}.{product}.{job-name}" # noqa - too long
# the roots of the treeherder routes
TREEHERDER_ROUTE_ROOT = "tc-treeherder"
def get_branch_rev(config):
return config.params[
"{}head_rev".format(config.graph_config["project-repo-param-prefix"])
]
def get_branch_git_rev(config):
return config.params[
"{}head_git_rev".format(config.graph_config["project-repo-param-prefix"])
]
def get_branch_repo(config):
return config.params[
"{}head_repository".format(
config.graph_config["project-repo-param-prefix"],
)
]
def get_project_alias(config):
if config.params["tasks_for"].startswith("github-pull-request"):
return f"{config.params['project']}-pr"
return config.params["project"]
@memoize
def get_default_priority(graph_config, project):
return evaluate_keyed_by(
graph_config["task-priority"], "Graph Config", {"project": project}
)
# define a collection of index builders, depending on the type implementation
index_builders = {}
def index_builder(name):
def wrap(func):
assert name not in index_builders, f"duplicate index builder name {name}"
index_builders[name] = func
return func
return wrap
UNSUPPORTED_INDEX_PRODUCT_ERROR = """\
The gecko-v2 product {product} is not in the list of configured products in
`taskcluster/config.yml'.
"""
def verify_index(config, index):
product = index["product"]
if product not in config.graph_config["index"]["products"]:
raise Exception(UNSUPPORTED_INDEX_PRODUCT_ERROR.format(product=product))
RUN_TASK_RE = re.compile(r"run-task(-(git|hg))?$")
def is_run_task(cmd: str) -> bool:
return bool(re.search(RUN_TASK_RE, cmd))
@payload_builder(
"docker-worker",
schema={
Required("os"): "linux",
# For tasks that will run in docker-worker, this is the
# name of the docker image or in-tree docker image to run the task in. If
# in-tree, then a dependency will be created automatically. This is
# generally `desktop-test`, or an image that acts an awful lot like it.
Required("docker-image"): Any(
# a raw Docker image path (repo/image:tag)
str,
# an in-tree generated docker image (from `taskcluster/docker/<name>`)
{"in-tree": str},
# an indexed docker image
{"indexed": str},
),
# worker features that should be enabled
Required("chain-of-trust"): bool,
Required("taskcluster-proxy"): bool,
Required("allow-ptrace"): bool,
Required("loopback-video"): bool,
Required("loopback-audio"): bool,
Required("docker-in-docker"): bool, # (aka 'dind')
Required("privileged"): bool,
Optional("kvm"): bool,
# Paths to Docker volumes.
#
# For in-tree Docker images, volumes can be parsed from Dockerfile.
# This only works for the Dockerfile itself: if a volume is defined in
# a base image, it will need to be declared here. Out-of-tree Docker
# images will also require explicit volume annotation.
#
# Caches are often mounted to the same path as Docker volumes. In this
# case, they take precedence over a Docker volume. But a volume still
# needs to be declared for the path.
Optional("volumes"): [str],
Optional(
"required-volumes",
description=(
"Paths that are required to be volumes for performance reasons. "
"For in-tree images, these paths will be checked to verify that they "
"are defined as volumes."
),
): [str],
# caches to set up for the task
Optional("caches"): [
{
# only one type is supported by any of the workers right now
"type": "persistent",
# name of the cache, allowing re-use by subsequent tasks naming the
# same cache
"name": str,
# location in the task image where the cache will be mounted
"mount-point": str,
# Whether the cache is not used in untrusted environments
# (like the Try repo).
Optional("skip-untrusted"): bool,
}
],
# artifacts to extract from the task image after completion
Optional("artifacts"): [
{
# type of artifact -- simple file, or recursive directory
"type": Any("file", "directory"),
# task image path from which to read artifact
"path": str,
# name of the produced artifact (root of the names for
# type=directory)
"name": str,
"expires-after": str,
}
],
# environment variables
Required("env"): {str: taskref_or_string},
# the command to run; if not given, docker-worker will default to the
# command in the docker image
Optional("command"): [taskref_or_string],
# the maximum time to run, in seconds
Required("max-run-time"): int,
# the exit status code(s) that indicates the task should be retried
Optional("retry-exit-status"): [int],
# the exit status code(s) that indicates the caches used by the task
# should be purged
Optional("purge-caches-exit-status"): [int],
# Whether any artifacts are assigned to this worker
Optional("skip-artifacts"): bool,
},
)
def build_docker_worker_payload(config, task, task_def):
worker = task["worker"]
level = int(config.params["level"])
image = worker["docker-image"]
if isinstance(image, dict):
if "in-tree" in image:
name = image["in-tree"]
docker_image_task = "docker-image-" + image["in-tree"]
task.setdefault("dependencies", {})["docker-image"] = docker_image_task
image = {
"path": "public/image.tar.zst",
"taskId": {"task-reference": "<docker-image>"},
"type": "task-image",
}
# Find VOLUME in Dockerfile.
volumes = dockerutil.parse_volumes(name)
for v in sorted(volumes):
if v in worker["volumes"]:
raise Exception(
"volume %s already defined; "
"if it is defined in a Dockerfile, "
"it does not need to be specified in the "
"worker definition" % v
)
worker["volumes"].append(v)
elif "indexed" in image:
image = {
"path": "public/image.tar.zst",
"namespace": image["indexed"],
"type": "indexed-image",
}
else:
raise Exception("unknown docker image type")
features = {}
if worker.get("taskcluster-proxy"):
features["taskclusterProxy"] = True
if worker.get("allow-ptrace"):
features["allowPtrace"] = True
task_def["scopes"].append("docker-worker:feature:allowPtrace")
if worker.get("chain-of-trust"):
features["chainOfTrust"] = True
if worker.get("docker-in-docker"):
features["dind"] = True
# Never enable sccache on the toolchains repo, as there is no benefit from it
# because each push uses a different compiler.
if task.get("use-sccache") and config.params["project"] != "toolchains":
features["taskclusterProxy"] = True
task_def["scopes"].append(
"assume:project:taskcluster:{trust_domain}:level-{level}-sccache-buckets".format(
trust_domain=config.graph_config["trust-domain"],
level=config.params["level"],
)
)
worker["env"]["USE_SCCACHE"] = "1"
worker["env"]["SCCACHE_GCS_PROJECT"] = SCCACHE_GCS_PROJECT
# Disable sccache idle shutdown.
worker["env"]["SCCACHE_IDLE_TIMEOUT"] = "0"
else:
worker["env"]["SCCACHE_DISABLE"] = "1"
capabilities = {}
for lo in "audio", "video":
if worker.get("loopback-" + lo):
capitalized = "loopback" + lo.capitalize()
devices = capabilities.setdefault("devices", {})
devices[capitalized] = True
task_def["scopes"].append("docker-worker:capability:device:" + capitalized)
if worker.get("kvm"):
devices = capabilities.setdefault("devices", {})
devices["kvm"] = True
task_def["scopes"].append("docker-worker:capability:device:kvm")
if worker.get("privileged"):
capabilities["privileged"] = True
task_def["scopes"].append("docker-worker:capability:privileged")
task_def["payload"] = payload = {
"image": image,
"env": worker["env"],
}
if "command" in worker:
payload["command"] = worker["command"]
if "max-run-time" in worker:
payload["maxRunTime"] = worker["max-run-time"]
run_task = is_run_task(payload.get("command", [""])[0])
# run-task exits EXIT_PURGE_CACHES if there is a problem with caches.
# Automatically retry the tasks and purge caches if we see this exit
# code.
# TODO move this closer to code adding run-task once bug 1469697 is
# addressed.
if run_task:
worker.setdefault("retry-exit-status", []).append(72)
worker.setdefault("purge-caches-exit-status", []).append(72)
payload["onExitStatus"] = {}
if "retry-exit-status" in worker:
payload["onExitStatus"]["retry"] = worker["retry-exit-status"]
if "purge-caches-exit-status" in worker:
payload["onExitStatus"]["purgeCaches"] = worker["purge-caches-exit-status"]
if "artifacts" in worker:
artifacts = {}
for artifact in worker["artifacts"]:
artifacts[artifact["name"]] = {
"path": artifact["path"],
"type": artifact["type"],
"expires": {"relative-datestamp": artifact["expires-after"]},
}
payload["artifacts"] = artifacts
if isinstance(worker.get("docker-image"), str):
out_of_tree_image = worker["docker-image"]
else:
out_of_tree_image = None
image = worker.get("docker-image", {}).get("in-tree")
if "caches" in worker:
caches = {}
# run-task knows how to validate caches.
#
# To help ensure new run-task features and bug fixes don't interfere
# with existing caches, we seed the hash of run-task into cache names.
# So, any time run-task changes, we should get a fresh set of caches.
# This means run-task can make changes to cache interaction at any time
# without regards for backwards or future compatibility.
#
# But this mechanism only works for in-tree Docker images that are built
# with the current run-task! For out-of-tree Docker images, we have no
# way of knowing their content of run-task. So, in addition to varying
# cache names by the contents of run-task, we also take the Docker image
# name into consideration. This means that different Docker images will
# never share the same cache. This is a bit unfortunate. But it is the
# safest thing to do. Fortunately, most images are defined in-tree.
#
# For out-of-tree Docker images, we don't strictly need to incorporate
# the run-task content into the cache name. However, doing so preserves
# the mechanism whereby changing run-task results in new caches
# everywhere.
# As an additional mechanism to force the use of different caches, the
# string literal in the variable below can be changed. This is
# preferred to changing run-task because it doesn't require images
# to be rebuilt.
cache_version = "v3"
if run_task:
suffix = (
f"{cache_version}-{_run_task_suffix(config.params['repository_type'])}"
)
if out_of_tree_image:
name_hash = hashlib.sha256(
out_of_tree_image.encode("utf-8")
).hexdigest()
suffix += name_hash[0:12]
else:
suffix = cache_version
skip_untrusted = is_try(config.params) or level == 1
for cache in worker["caches"]:
# Some caches aren't enabled in environments where we can't
# guarantee certain behavior. Filter those out.
if cache.get("skip-untrusted") and skip_untrusted:
continue
name = "{trust_domain}-level-{level}-{name}-{suffix}".format(
trust_domain=config.graph_config["trust-domain"],
level=config.params["level"],
name=cache["name"],
suffix=suffix,
)
caches[name] = cache["mount-point"]
task_def["scopes"].append("docker-worker:cache:%s" % name)
# Assertion: only run-task is interested in this.
if run_task:
payload["env"]["TASKCLUSTER_CACHES"] = ";".join(sorted(caches.values()))
payload["cache"] = caches
# And send down volumes information to run-task as well.
if run_task and worker.get("volumes"):
payload["env"]["TASKCLUSTER_VOLUMES"] = ";".join(sorted(worker["volumes"]))
if payload.get("cache") and skip_untrusted:
payload["env"]["TASKCLUSTER_UNTRUSTED_CACHES"] = "1"
if features:
payload["features"] = features
if capabilities:
payload["capabilities"] = capabilities
check_caches_are_volumes(task)
check_required_volumes(task)
@payload_builder(
"generic-worker",
schema={
Required("os"): Any(
"windows", "macosx", "linux", "linux-bitbar", "linux-lambda"
),
# see http://schemas.taskcluster.net/generic-worker/v1/payload.json
# and https://docs.taskcluster.net/reference/workers/generic-worker/payload
# command is a list of commands to run, sequentially
# on Windows, each command is a string, on OS X and Linux, each command is
# a string array
Required("command"): Any(
[taskref_or_string],
[[taskref_or_string]], # Windows # Linux / OS X
),
# artifacts to extract from the task image after completion; note that artifacts
# for the generic worker cannot have names
Optional("artifacts"): [
{
# type of artifact -- simple file, or recursive directory
"type": Any("file", "directory"),
# filesystem path from which to read artifact
"path": str,
# if not specified, path is used for artifact name
Optional("name"): str,
"expires-after": str,
}
],
# Directories and/or files to be mounted.
# The actual allowed combinations are stricter than the model below,
# but this provides a simple starting point.
# See https://docs.taskcluster.net/reference/workers/generic-worker/payload
Optional("mounts"): [
{
# A unique name for the cache volume, implies writable cache directory
# (otherwise mount is a read-only file or directory).
Optional("cache-name"): str,
# Optional content for pre-loading cache, or mandatory content for
# read-only file or directory. Pre-loaded content can come from either
# a task artifact or from a URL.
Optional("content"): {
# *** Either (artifact and task-id) or url must be specified. ***
# Artifact name that contains the content.
Optional("artifact"): str,
# Task ID that has the artifact that contains the content.
Optional("task-id"): taskref_or_string,
# URL that supplies the content in response to an unauthenticated
# GET request.
Optional("url"): str,
},
# *** Either file or directory must be specified. ***
# If mounting a cache or read-only directory, the filesystem location of
# the directory should be specified as a relative path to the task
# directory here.
Optional("directory"): str,
# If mounting a file, specify the relative path within the task
# directory to mount the file (the file will be read only).
Optional("file"): str,
# Required if and only if `content` is specified and mounting a
# directory (not a file). This should be the archive format of the
# content (either pre-loaded cache or read-only directory).
Optional("format"): Any("rar", "tar.bz2", "tar.gz", "zip", "tar.xz"),
}
],
# environment variables
Required("env"): {str: taskref_or_string},
# the maximum time to run, in seconds
Required("max-run-time"): int,
# os user groups for test task workers
Optional("os-groups"): [str],
# feature for test task to run as administarotr
Optional("run-as-administrator"): bool,
# optional features
Required("chain-of-trust"): bool,
Optional("taskcluster-proxy"): bool,
# the exit status code(s) that indicates the task should be retried
Optional("retry-exit-status"): [int],
# Wether any artifacts are assigned to this worker
Optional("skip-artifacts"): bool,
},
)
def build_generic_worker_payload(config, task, task_def):
worker = task["worker"]
features = {}
task_def["payload"] = {
"command": worker["command"],
"maxRunTime": worker["max-run-time"],
}
if worker["os"] == "windows":
task_def["payload"]["onExitStatus"] = {
"retry": [
# These codes (on windows) indicate a process interruption,
# rather than a task run failure. See bug 1544403.
1073807364, # process force-killed due to system shutdown
3221225786, # sigint (any interrupt)
]
}
if "retry-exit-status" in worker:
task_def["payload"].setdefault("onExitStatus", {}).setdefault(
"retry", []
).extend(worker["retry-exit-status"])
if worker["os"] in ["linux-bitbar", "linux-lambda"]:
task_def["payload"].setdefault("onExitStatus", {}).setdefault("retry", [])
# exit code 4 is used to indicate an intermittent android device error
if 4 not in task_def["payload"]["onExitStatus"]["retry"]:
task_def["payload"]["onExitStatus"]["retry"].extend([4])
env = worker.get("env", {})
# Never enable sccache on the toolchains repo, as there is no benefit from it
# because each push uses a different compiler.
if task.get("use-sccache") and config.params["project"] != "toolchains":
features["taskclusterProxy"] = True
task_def["scopes"].append(
"assume:project:taskcluster:{trust_domain}:level-{level}-sccache-buckets".format(
trust_domain=config.graph_config["trust-domain"],
level=config.params["level"],
)
)
env["USE_SCCACHE"] = "1"
worker["env"]["SCCACHE_GCS_PROJECT"] = SCCACHE_GCS_PROJECT
# Disable sccache idle shutdown.
env["SCCACHE_IDLE_TIMEOUT"] = "0"
else:
env["SCCACHE_DISABLE"] = "1"
if env:
task_def["payload"]["env"] = env
artifacts = []
for artifact in worker.get("artifacts", []):
a = {
"path": artifact["path"],
"type": artifact["type"],
"expires": {"relative-datestamp": artifact["expires-after"]},
}
if "name" in artifact:
a["name"] = artifact["name"]
artifacts.append(a)
if artifacts:
task_def["payload"]["artifacts"] = artifacts
# Need to copy over mounts, but rename keys to respect naming convention
# * 'cache-name' -> 'cacheName'
# * 'task-id' -> 'taskId'
# All other key names are already suitable, and don't need renaming.
mounts = deepcopy(worker.get("mounts", []))
for mount in mounts:
if "cache-name" in mount:
mount["cacheName"] = "{trust_domain}-level-{level}-{name}".format(
trust_domain=config.graph_config["trust-domain"],
level=config.params["level"],
name=mount.pop("cache-name"),
)
task_def["scopes"].append(
"generic-worker:cache:{}".format(mount["cacheName"])
)
if "content" in mount:
if "task-id" in mount["content"]:
mount["content"]["taskId"] = mount["content"].pop("task-id")
if "artifact" in mount["content"]:
if not mount["content"]["artifact"].startswith("public/"):
task_def["scopes"].append(
"queue:get-artifact:{}".format(mount["content"]["artifact"])
)
if mounts:
task_def["payload"]["mounts"] = mounts
if worker.get("os-groups"):
task_def["payload"]["osGroups"] = worker["os-groups"]
task_def["scopes"].extend([
"generic-worker:os-group:{}/{}".format(task["worker-type"], group)
for group in worker["os-groups"]
])
if worker.get("chain-of-trust"):
features["chainOfTrust"] = True
if worker.get("taskcluster-proxy"):
features["taskclusterProxy"] = True
if worker.get("run-as-administrator", False):
features["runAsAdministrator"] = True
task_def["scopes"].append(
"generic-worker:run-as-administrator:{}".format(task["worker-type"]),
)
if features:
task_def["payload"]["features"] = features
@payload_builder(
"iscript",
schema={
Required("signing-type"): str,
# the maximum time to run, in seconds
Required("max-run-time"): int,
# list of artifact URLs for the artifacts that should be signed
Required("upstream-artifacts"): [
{
# taskId of the task with the artifact
Required("taskId"): taskref_or_string,
# type of signing task (for CoT)
Required("taskType"): str,
# Paths to the artifacts to sign
Required("paths"): [str],
# Signing formats to use on each of the paths
Required("formats"): [str],
Optional("singleFileGlobs"): [str],
}
],
# behavior for mac iscript
Optional("mac-behavior"): Any(
"apple_notarization",
"apple_notarization_stacked",
"mac_sign_and_pkg",
"mac_sign_and_pkg_hardened",
"mac_geckodriver",
"mac_notarize_geckodriver",
"mac_single_file",
"mac_notarize_single_file",
),
Optional("entitlements-url"): str,
Optional("requirements-plist-url"): str,
Optional("provisioning-profile-config"): [
{
Required("profile_name"): str,
Required("target_path"): str,
}
],
Optional("hardened-sign-config"): [
{
Optional("deep"): bool,
Optional("runtime"): bool,
Optional("force"): bool,
Optional("entitlements"): str,
Optional("requirements"): str,
Required("globs"): [str],
}
],
},
)
def build_iscript_payload(config, task, task_def):
worker = task["worker"]
task_def["payload"] = {
"maxRunTime": worker["max-run-time"],
"upstreamArtifacts": worker["upstream-artifacts"],
}
if worker.get("mac-behavior"):
task_def["payload"]["behavior"] = worker["mac-behavior"]
for attribute in (
"entitlements-url",
"requirements-plist-url",
"hardened-sign-config",
"provisioning-profile-config",
):
if worker.get(attribute):
task_def["payload"][attribute] = worker[attribute]
# Set scopes
scope_prefix = config.graph_config["scriptworker"]["scope-prefix"]
scopes = set(task_def.get("scopes", []))
scopes.add(f"{scope_prefix}:signing:cert:{worker['signing-type']}")
task_def["scopes"] = sorted(scopes)
artifacts = set(task.setdefault("attributes", {}).get("release_artifacts", []))
for upstream_artifact in worker["upstream-artifacts"]:
for path in upstream_artifact["paths"]:
artifacts.update(
get_signed_artifacts(
input=path,
formats=upstream_artifact["formats"],
behavior=worker.get("mac-behavior"),
)
)
task["attributes"]["release_artifacts"] = sorted(list(artifacts))
@payload_builder(
"beetmover",
schema={
# the maximum time to run, in seconds
Optional("max-run-time"): int,
# locale key, if this is a locale beetmover job
Optional("locale"): str,
Required("release-properties"): {
"app-name": str,
"app-version": str,
"branch": str,
"build-id": str,
"hash-type": str,
"platform": str,
},
# list of artifact URLs for the artifacts that should be beetmoved
Required("upstream-artifacts"): [
{
# taskId of the task with the artifact
Required("taskId"): taskref_or_string,
# type of signing task (for CoT)
Required("taskType"): str,
# Paths to the artifacts to sign
Required("paths"): [str],
# locale is used to map upload path and allow for duplicate simple names
Required("locale"): str,
}
],
Optional("artifact-map"): object,
},
)
def build_beetmover_payload(config, task, task_def):
worker = task["worker"]
release_config = get_release_config(config)
release_properties = worker["release-properties"]
task_def["payload"] = {
"releaseProperties": {
"appName": release_properties["app-name"],
"appVersion": release_properties["app-version"],
"branch": release_properties["branch"],
"buildid": release_properties["build-id"],
"hashType": release_properties["hash-type"],
"platform": release_properties["platform"],
},
"upload_date": config.params["build_date"],
"upstreamArtifacts": worker["upstream-artifacts"],
}
if worker.get("locale"):
task_def["payload"]["locale"] = worker["locale"]
if worker.get("artifact-map"):
task_def["payload"]["artifactMap"] = worker["artifact-map"]
if release_config:
task_def["payload"].update(release_config)
@payload_builder(
"beetmover-push-to-release",
schema={
# the maximum time to run, in seconds
Optional("max-run-time"): int,
Required("product"): str,
},
)
def build_beetmover_push_to_release_payload(config, task, task_def):
worker = task["worker"]
release_config = get_release_config(config)
partners = [f"{p}/{s}" for p, s, _ in get_partners_to_be_published(config)]
task_def["payload"] = {
"product": worker["product"],