Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/morph.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 """
6 Graph morphs are modifications to task-graphs that take place *after* the
7 optimization phase.
8
9 These graph morphs are largely invisible to developers running `./mach`
10 locally, so they should be limited to changes that do not modify the meaning of
11 the graph.
12 """
13
14 # Note that the translation of `{'task-reference': '..'}` and
15 # `artifact-reference` are handled in the optimization phase (since
16 # optimization involves dealing with taskIds directly). Similarly,
17 # `{'relative-datestamp': '..'}` is handled at the last possible moment during
18 # task creation.
19
20 import logging
21 import os
22 import re
23
24 from slugid import nice as slugid
25
26 from .graph import Graph
27 from .task import Task
28 from .taskgraph import TaskGraph
29 from .util.workertypes import get_worker_type
30
31 here = os.path.abspath(os.path.dirname(__file__))
32 logger = logging.getLogger(__name__)
33 MAX_ROUTES = 64
34
35 registered_morphs = []
36
37
38 def register_morph(func):
39 registered_morphs.append(func)
40 return func
41
42
43 def amend_taskgraph(taskgraph, label_to_taskid, to_add):
44 """Add the given tasks to the taskgraph, returning a new taskgraph"""
45 new_tasks = taskgraph.tasks.copy()
46 new_edges = set(taskgraph.graph.edges)
47 for task in to_add:
48 new_tasks[task.task_id] = task
49 assert task.label not in label_to_taskid
50 label_to_taskid[task.label] = task.task_id
51 for depname, dep in task.dependencies.items():
52 new_edges.add((task.task_id, dep, depname))
53
54 taskgraph = TaskGraph(new_tasks, Graph(set(new_tasks), new_edges)) # type: ignore
55 return taskgraph, label_to_taskid
56
57
58 def derive_index_task(task, taskgraph, label_to_taskid, parameters, graph_config):
59 """Create the shell of a task that depends on `task` and on the given docker
60 image."""
61 purpose = "index-task"
62 label = f"{purpose}-{task.label}"
63 provisioner_id, worker_type = get_worker_type(
64 graph_config, "misc", parameters["level"]
65 )
66
67 task_def = {
68 "provisionerId": provisioner_id,
69 "workerType": worker_type,
70 "dependencies": [task.task_id],
71 "created": {"relative-datestamp": "0 seconds"},
72 "deadline": task.task["deadline"],
73 # no point existing past the parent task's deadline
74 "expires": task.task["deadline"],
75 "metadata": {
76 "name": label,
77 "description": "{} for {}".format(
78 purpose, task.task["metadata"]["description"]
79 ),
80 "owner": task.task["metadata"]["owner"],
81 "source": task.task["metadata"]["source"],
82 },
83 "scopes": [],
84 "payload": {
85 "image": {
86 "path": "public/image.tar.zst",
87 "namespace": "taskgraph.cache.level-3.docker-images.v2.index-task.latest",
88 "type": "indexed-image",
89 },
90 "features": {
91 "taskclusterProxy": True,
92 },
93 "maxRunTime": 600,
94 },
95 }
96
97 # only include the docker-image dependency here if it is actually in the
98 # taskgraph (has not been optimized). It is included in
99 # task_def['dependencies'] unconditionally.
100 dependencies = {"parent": task.task_id}
101
102 task = Task(
103 kind="misc",
104 label=label,
105 attributes={},
106 task=task_def,
107 dependencies=dependencies,
108 )
109 task.task_id = slugid() # type: ignore
110 return task, taskgraph, label_to_taskid
111
112
113 def make_index_task(parent_task, taskgraph, label_to_taskid, parameters, graph_config):
114 index_paths = [
115 r.split(".", 1)[1] for r in parent_task.task["routes"] if r.startswith("index.")
116 ]
117 parent_task.task["routes"] = [
118 r for r in parent_task.task["routes"] if not r.startswith("index.")
119 ]
120
121 task, taskgraph, label_to_taskid = derive_index_task(
122 parent_task, taskgraph, label_to_taskid, parameters, graph_config
123 )
124
125 # we need to "summarize" the scopes, otherwise a particularly
126 # namespace-heavy index task might have more scopes than can fit in a
127 # temporary credential.
128 scopes = set()
129 domain_index_regex = re.compile(
130 r"({trust_domain}\.v2\.[^.]*\.).*".format(
131 trust_domain=re.escape(graph_config["trust-domain"])
132 )
133 )
134 index_path_res = [domain_index_regex]
135 for path in graph_config["taskgraph"].get("index-path-regexes", ()):
136 index_path_res.append(re.compile(path))
137 for path in index_paths:
138 for index_path_re in index_path_res:
139 match = index_path_re.match(path)
140 if match:
141 path = match.group(1) + "*"
142 break
143 scope = f"index:insert-task:{path}"
144 scopes.add(scope)
145 task.task["scopes"] = sorted(scopes)
146
147 task.task["payload"]["command"] = ["insert-indexes.js"] + index_paths
148 task.task["payload"]["env"] = {
149 "TARGET_TASKID": parent_task.task_id,
150 "INDEX_RANK": parent_task.task.get("extra", {}).get("index", {}).get("rank", 0),
151 }
152 return task, taskgraph, label_to_taskid
153
154
155 @register_morph
156 def add_index_tasks(taskgraph, label_to_taskid, parameters, graph_config):
157 """
158 The TaskCluster queue only allows 64 routes on a task. In the event a task
159 exceeds this limit, this graph morph adds "index tasks" that depend on it
160 and do the index insertions directly, avoiding the limit on task.routes.
161 """
162 logger.debug("Morphing: adding index tasks")
163
164 added = []
165 for label, task in taskgraph.tasks.items():
166 if len(task.task.get("routes", [])) <= MAX_ROUTES:
167 continue
168 task, taskgraph, label_to_taskid = make_index_task(
169 task, taskgraph, label_to_taskid, parameters, graph_config
170 )
171 added.append(task)
172
173 if added:
174 taskgraph, label_to_taskid = amend_taskgraph(taskgraph, label_to_taskid, added)
175 logger.info(f"Added {len(added)} index tasks")
176
177 return taskgraph, label_to_taskid
178
179
180 def _get_morph_url():
181 """
182 Guess a URL for the current file, for source metadata for created tasks.
183
184 If we checked out the taskgraph code with run-task in the decision task,
185 we can use TASKGRAPH_* to find the right version, which covers the
186 existing use case.
187 """
188 taskgraph_repo = os.environ.get(
189 "TASKGRAPH_HEAD_REPOSITORY", "https://github.com/taskcluster/taskgraph"
190 )
191 taskgraph_rev = os.environ.get("TASKGRAPH_HEAD_REV", "default")
192 return f"{taskgraph_repo}/raw-file/{taskgraph_rev}/src/taskgraph/morph.py"
193
194
195 @register_morph
196 def add_code_review_task(taskgraph, label_to_taskid, parameters, graph_config):
197 logger.debug("Morphing: adding code review task")
198
199 review_config = parameters.get("code-review")
200 if not review_config:
201 return taskgraph, label_to_taskid
202
203 code_review_tasks = {}
204 for label, task in taskgraph.tasks.items():
205 if task.attributes.get("code-review"):
206 code_review_tasks[task.label] = task.task_id
207
208 if code_review_tasks:
209 code_review_task_def = {
210 "provisionerId": "built-in",
211 "workerType": "succeed",
212 "dependencies": sorted(code_review_tasks.values()),
213 # This option permits to run the task
214 # regardless of the dependencies tasks exit status
215 # as we are interested in the task failures
216 "requires": "all-resolved",
217 "created": {"relative-datestamp": "0 seconds"},
218 "deadline": {"relative-datestamp": "1 day"},
219 # no point existing past the parent task's deadline
220 "expires": {"relative-datestamp": "1 day"},
221 "metadata": {
222 "name": "code-review",
223 "description": "List all issues found in static analysis and linting tasks",
224 "owner": parameters["owner"],
225 "source": _get_morph_url(),
226 },
227 "scopes": [],
228 "payload": {},
229 "routes": ["project.relman.codereview.v1.try_ending"],
230 "extra": {
231 "code-review": {
232 "phabricator-build-target": review_config[
233 "phabricator-build-target"
234 ],
235 "repository": parameters["head_repository"],
236 "revision": parameters["head_rev"],
237 }
238 },
239 }
240 task = Task(
241 kind="misc",
242 label="code-review",
243 attributes={},
244 task=code_review_task_def,
245 dependencies=code_review_tasks,
246 )
247 task.task_id = slugid() # type: ignore
248 taskgraph, label_to_taskid = amend_taskgraph(taskgraph, label_to_taskid, [task])
249 logger.info("Added code review task.")
250
251 return taskgraph, label_to_taskid
252
253
254 def morph(taskgraph, label_to_taskid, parameters, graph_config):
255 """Apply all morphs"""
256 for m in registered_morphs:
257 taskgraph, label_to_taskid = m(
258 taskgraph, label_to_taskid, parameters, graph_config
259 )
260 return taskgraph, label_to_taskid