Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/transforms/run/run_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 Support for running tasks that are invoked via the `run-task` script.
6 """
7
8 import dataclasses
9 import os
10
11 from voluptuous import Any, Optional, Required
12
13 from taskgraph.transforms.run import run_task_using
14 from taskgraph.transforms.run.common import (
15 support_caches,
16 support_vcs_checkout,
17 )
18 from taskgraph.transforms.task import taskref_or_string
19 from taskgraph.util import path, taskcluster
20 from taskgraph.util.caches import CACHES
21 from taskgraph.util.schema import Schema
22
23 EXEC_COMMANDS = {
24 "bash": ["bash", "-cx"],
25 "powershell": ["powershell.exe", "-ExecutionPolicy", "Bypass"],
26 }
27
28 run_task_schema = Schema(
29 {
30 Required("using"): "run-task",
31 # Which caches to use. May take a boolean in which case either all
32 # (True) or no (False) caches will be used. Alternatively, it can
33 # accept a list of caches to enable. Defaults to only the checkout cache
34 # enabled.
35 Optional("use-caches", "caches"): Any(bool, list(CACHES.keys())),
36 # if true (the default), perform a checkout on the worker
37 Required("checkout"): Any(bool, {str: dict}),
38 Optional(
39 "cwd",
40 description="Path to run command in. If a checkout is present, the path "
41 "to the checkout will be interpolated with the key `checkout`",
42 ): str,
43 # The sparse checkout profile to use. Value is the filename relative to the
44 # directory where sparse profiles are defined (build/sparse-profiles/).
45 Required("sparse-profile"): Any(str, None),
46 # The command arguments to pass to the `run-task` script, after the
47 # checkout arguments. If a list, it will be passed directly; otherwise
48 # it will be included in a single argument to the command specified by
49 # `exec-with`.
50 Required("command"): Any([taskref_or_string], taskref_or_string),
51 # What to execute the command with in the event command is a string.
52 Optional("exec-with"): Any(*list(EXEC_COMMANDS)),
53 # Command used to invoke the `run-task` script. Can be used if the script
54 # or Python installation is in a non-standard location on the workers.
55 Optional("run-task-command"): list,
56 # Base work directory used to set up the task.
57 Required("workdir"): str,
58 # Whether to run as root. (defaults to False)
59 Optional("run-as-root"): bool,
60 }
61 )
62
63
64 def common_setup(config, task, taskdesc, command):
65 run = task["run"]
66 if run["checkout"]:
67 repo_configs = config.repo_configs
68 if len(repo_configs) > 1 and run["checkout"] is True:
69 raise Exception("Must explicitly specify checkouts with multiple repos.")
70 elif run["checkout"] is not True:
71 repo_configs = {
72 repo: dataclasses.replace(repo_configs[repo], **config)
73 for (repo, config) in run["checkout"].items()
74 }
75
76 vcs_path = support_vcs_checkout(
77 config,
78 task,
79 taskdesc,
80 repo_configs=repo_configs,
81 sparse=bool(run["sparse-profile"]),
82 )
83
84 for repo_config in repo_configs.values():
85 checkout_path = path.join(vcs_path, repo_config.path)
86 command.append(f"--{repo_config.prefix}-checkout={checkout_path}")
87
88 if run["sparse-profile"]:
89 command.append(
90 "--{}-sparse-profile=build/sparse-profiles/{}".format(
91 repo_config.prefix, # type: ignore
92 run["sparse-profile"],
93 )
94 )
95
96 if "cwd" in run:
97 run["cwd"] = path.normpath(run["cwd"].format(checkout=vcs_path))
98 elif "cwd" in run and "{checkout}" in run["cwd"]:
99 raise Exception(
100 "Found `{{checkout}}` interpolation in `cwd` for task {name} "
101 "but the task doesn't have a checkout: {cwd}".format(
102 cwd=run["cwd"], name=task.get("name", task.get("label"))
103 )
104 )
105
106 if "cwd" in run:
107 command.extend(("--task-cwd", run["cwd"]))
108
109 support_caches(config, task, taskdesc)
110 taskdesc["worker"].setdefault("env", {})["MOZ_SCM_LEVEL"] = config.params["level"]
111
112
113 worker_defaults = {
114 "checkout": True,
115 "sparse-profile": None,
116 "run-as-root": False,
117 }
118
119
120 def script_url(config, script):
121 if "MOZ_AUTOMATION" in os.environ and "TASK_ID" not in os.environ:
122 raise Exception("TASK_ID must be defined to use run-task on generic-worker")
123 task_id = os.environ.get("TASK_ID", "<TASK_ID>")
124 # use_proxy = False to avoid having all generic-workers turn on proxy
125 # Assumes the cluster allows anonymous downloads of public artifacts
126 tc_url = taskcluster.get_root_url(False)
127 # TODO: Use util/taskcluster.py:get_artifact_url once hack for Bug 1405889 is removed
128 return f"{tc_url}/api/queue/v1/task/{task_id}/artifacts/public/{script}"
129
130
131 @run_task_using(
132 "docker-worker", "run-task", schema=run_task_schema, defaults=worker_defaults
133 )
134 def docker_worker_run_task(config, task, taskdesc):
135 run = task["run"]
136 worker = taskdesc["worker"] = task["worker"]
137 command = run.pop("run-task-command", ["/usr/local/bin/run-task"])
138 common_setup(config, task, taskdesc, command)
139
140 run_command = run["command"]
141
142 # dict is for the case of `{'task-reference': str}`.
143 if isinstance(run_command, str) or isinstance(run_command, dict):
144 exec_cmd = EXEC_COMMANDS[run.pop("exec-with", "bash")]
145 run_command = exec_cmd + [run_command]
146 if run["run-as-root"]:
147 command.extend(("--user", "root", "--group", "root"))
148 command.append("--")
149 command.extend(run_command)
150 worker["command"] = command
151
152
153 @run_task_using(
154 "generic-worker", "run-task", schema=run_task_schema, defaults=worker_defaults
155 )
156 def generic_worker_run_task(config, task, taskdesc):
157 run = task["run"]
158 worker = taskdesc["worker"] = task["worker"]
159 is_win = worker["os"] == "windows"
160 is_bitbar = worker["os"] == "linux-bitbar"
161
162 command = run.pop("run-task-command", None)
163 if not command:
164 if is_win:
165 command = ["C:/mozilla-build/python3/python3.exe", "run-task"]
166 else:
167 command = ["./run-task"]
168
169 common_setup(config, task, taskdesc, command)
170
171 worker.setdefault("mounts", [])
172 worker["mounts"].append(
173 {
174 "content": {
175 "url": script_url(config, "run-task"),
176 },
177 "file": "./run-task",
178 }
179 )
180 if worker.get("env", {}).get("MOZ_FETCHES"):
181 worker["mounts"].append(
182 {
183 "content": {
184 "url": script_url(config, "fetch-content"),
185 },
186 "file": "./fetch-content",
187 }
188 )
189
190 run_command = run["command"]
191
192 if isinstance(run_command, str):
193 if is_win:
194 run_command = f'"{run_command}"'
195 exec_cmd = EXEC_COMMANDS[run.pop("exec-with", "bash")]
196 run_command = exec_cmd + [run_command]
197
198 if run["run-as-root"]:
199 command.extend(("--user", "root", "--group", "root"))
200 command.append("--")
201 if is_bitbar:
202 # Use the bitbar wrapper script which sets up the device and adb
203 # environment variables
204 command.append("/builds/taskcluster/script.py")
205 command.extend(run_command)
206
207 if is_win:
208 worker["command"] = [" ".join(command)]
209 else:
210 worker["command"] = [
211 ["chmod", "+x", "run-task"],
212 command,
213 ]