Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/actions/util.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 import copy
7 import logging
8 import os
9 import re
10 from concurrent import futures
11 from functools import reduce
12
13 from requests.exceptions import HTTPError
14
15 from taskgraph import create
16 from taskgraph.decision import read_artifact, rename_artifact, write_artifact
17 from taskgraph.optimize.base import optimize_task_graph
18 from taskgraph.taskgraph import TaskGraph
19 from taskgraph.util.taskcluster import (
20 CONCURRENCY,
21 get_artifact,
22 get_session,
23 list_tasks,
24 parse_time,
25 )
26 from taskgraph.util.taskgraph import find_decision_task
27
28 logger = logging.getLogger(__name__)
29
30
31 def get_parameters(decision_task_id):
32 return get_artifact(decision_task_id, "public/parameters.yml")
33
34
35 def fetch_graph_and_labels(parameters, graph_config, task_group_id=None):
36 try:
37 # Look up the decision_task id in the index
38 decision_task_id = find_decision_task(parameters, graph_config)
39 except KeyError:
40 if not task_group_id:
41 raise
42 # Not found (e.g. from github-pull-request), fall back to the task group id.
43 decision_task_id = task_group_id
44
45 # First grab the graph and labels generated during the initial decision task
46 full_task_graph = get_artifact(decision_task_id, "public/full-task-graph.json")
47 _, full_task_graph = TaskGraph.from_json(full_task_graph)
48 label_to_taskid = get_artifact(decision_task_id, "public/label-to-taskid.json")
49
50 # fetch everything in parallel; this avoids serializing any delay in downloading
51 # each artifact (such as waiting for the artifact to be mirrored locally)
52 with futures.ThreadPoolExecutor(CONCURRENCY) as e:
53 fetches = []
54
55 # fetch any modifications made by action tasks and swap out new tasks
56 # for old ones
57 def fetch_action(task_id):
58 logger.info(f"fetching label-to-taskid.json for action task {task_id}")
59 try:
60 run_label_to_id = get_artifact(task_id, "public/label-to-taskid.json")
61 label_to_taskid.update(run_label_to_id)
62 except HTTPError as e:
63 if e.response.status_code != 404:
64 raise
65 logger.debug(f"No label-to-taskid.json found for {task_id}: {e}")
66
67 # for backwards compatibility, look up actions via pushlog-id
68 pushlog_namespace = "{}.v2.{}.pushlog-id.{}.actions".format(
69 graph_config["trust-domain"],
70 parameters["project"],
71 parameters["pushlog_id"],
72 )
73 # ... but also look by revision, since github doesn't have pushlog-id
74 rev_namespace = "{}.v2.{}.revision.{}.actions".format(
75 graph_config["trust-domain"],
76 parameters["project"],
77 parameters["head_rev"],
78 )
79 for task_id in set(list_tasks(pushlog_namespace) + list_tasks(rev_namespace)):
80 fetches.append(e.submit(fetch_action, task_id))
81
82 # Similarly for cron tasks..
83 def fetch_cron(task_id):
84 logger.info(f"fetching label-to-taskid.json for cron task {task_id}")
85 try:
86 run_label_to_id = get_artifact(task_id, "public/label-to-taskid.json")
87 label_to_taskid.update(run_label_to_id)
88 except HTTPError as e:
89 if e.response.status_code != 404:
90 raise
91 logger.debug(f"No label-to-taskid.json found for {task_id}: {e}")
92
93 namespace = "{}.v2.{}.revision.{}.cron".format(
94 graph_config["trust-domain"], parameters["project"], parameters["head_rev"]
95 )
96 for task_id in list_tasks(namespace):
97 fetches.append(e.submit(fetch_cron, task_id))
98
99 # now wait for each fetch to complete, raising an exception if there
100 # were any issues
101 for f in futures.as_completed(fetches):
102 f.result()
103
104 return (decision_task_id, full_task_graph, label_to_taskid)
105
106
107 def create_task_from_def(task_id, task_def, level, trust_domain):
108 """Create a new task from a definition rather than from a label
109 that is already in the full-task-graph. The task definition will
110 have {relative-datestamp': '..'} rendered just like in a decision task.
111 Use this for entirely new tasks or ones that change internals of the task.
112 It is useful if you want to "edit" the full_task_graph and then hand
113 it to this function. No dependencies will be scheduled. You must handle
114 this yourself. Seeing how create_tasks handles it might prove helpful."""
115 task_def["schedulerId"] = f"{trust_domain}-level-{level}"
116 label = task_def["metadata"]["name"]
117 session = get_session()
118 create.create_task(session, task_id, label, task_def)
119
120
121 def update_parent(task, graph):
122 task.task.setdefault("extra", {})["parent"] = os.environ.get("TASK_ID", "")
123 return task
124
125
126 def update_dependencies(task, graph):
127 if os.environ.get("TASK_ID"):
128 task.task.setdefault("dependencies", []).append(os.environ["TASK_ID"])
129 return task
130
131
132 def create_tasks(
133 graph_config,
134 to_run,
135 full_task_graph,
136 label_to_taskid,
137 params,
138 decision_task_id=None,
139 suffix="",
140 modifier=lambda t: t,
141 ):
142 """Create new tasks. The task definition will have {relative-datestamp':
143 '..'} rendered just like in a decision task. Action callbacks should use
144 this function to create new tasks,
145 allowing easy debugging with `mach taskgraph action-callback --test`.
146 This builds up all required tasks to run in order to run the tasks requested.
147
148 Optionally this function takes a `modifier` function that is passed in each
149 task before it is put into a new graph. It should return a valid task. Note
150 that this is passed _all_ tasks in the graph, not just the set in to_run. You
151 may want to skip modifying tasks not in your to_run list.
152
153 If `suffix` is given, then it is used to give unique names to the resulting
154 artifacts. If you call this function multiple times in the same action,
155 pass a different suffix each time to avoid overwriting artifacts.
156
157 If you wish to create the tasks in a new group, leave out decision_task_id.
158
159 Returns an updated label_to_taskid containing the new tasks"""
160 if suffix:
161 suffix = f"-{suffix}"
162 to_run = set(to_run)
163
164 # Copy to avoid side-effects later
165 full_task_graph = copy.deepcopy(full_task_graph)
166 label_to_taskid = label_to_taskid.copy()
167
168 target_graph = full_task_graph.graph.transitive_closure(to_run)
169 target_task_graph = TaskGraph(
170 {l: modifier(full_task_graph[l]) for l in target_graph.nodes},
171 target_graph,
172 )
173 target_task_graph.for_each_task(update_parent)
174 if decision_task_id and decision_task_id != os.environ.get("TASK_ID"):
175 target_task_graph.for_each_task(update_dependencies)
176 optimized_task_graph, label_to_taskid = optimize_task_graph(
177 target_task_graph,
178 to_run,
179 params,
180 to_run,
181 decision_task_id,
182 existing_tasks=label_to_taskid,
183 )
184 write_artifact(f"task-graph{suffix}.json", optimized_task_graph.to_json())
185 write_artifact(f"label-to-taskid{suffix}.json", label_to_taskid)
186 write_artifact(f"to-run{suffix}.json", list(to_run))
187 create.create_tasks(
188 graph_config,
189 optimized_task_graph,
190 label_to_taskid,
191 params,
192 decision_task_id,
193 )
194 return label_to_taskid
195
196
197 def _update_reducer(accumulator, new_value):
198 "similar to set or dict `update` method, but returning the modified object"
199 accumulator.update(new_value)
200 return accumulator
201
202
203 def combine_task_graph_files(suffixes):
204 """Combine task-graph-{suffix}.json files into a single task-graph.json file.
205
206 Since Chain of Trust verification requires a task-graph.json file that
207 contains all children tasks, we can combine the various task-graph-0.json
208 type files into a master task-graph.json file at the end.
209
210 Actions also look for various artifacts, so we combine those in a similar
211 fashion.
212
213 In the case where there is only one suffix, we simply rename it to avoid the
214 additional cost of uploading two copies of the same data.
215 """
216
217 if len(suffixes) == 1:
218 for filename in ["task-graph", "label-to-taskid", "to-run"]:
219 rename_artifact(f"{filename}-{suffixes[0]}.json", f"{filename}.json")
220 return
221
222 def combine(file_contents, base):
223 return reduce(_update_reducer, file_contents, base)
224
225 files = [read_artifact(f"task-graph-{suffix}.json") for suffix in suffixes]
226 write_artifact("task-graph.json", combine(files, dict()))
227
228 files = [read_artifact(f"label-to-taskid-{suffix}.json") for suffix in suffixes]
229 write_artifact("label-to-taskid.json", combine(files, dict()))
230
231 files = [read_artifact(f"to-run-{suffix}.json") for suffix in suffixes]
232 write_artifact("to-run.json", list(combine(files, set())))
233
234
235 def relativize_datestamps(task_def):
236 """
237 Given a task definition as received from the queue, convert all datestamps
238 to {relative_datestamp: ..} format, with the task creation time as "now".
239 The result is useful for handing to ``create_task``.
240 """
241 base = parse_time(task_def["created"])
242 # borrowed from https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js
243 ts_pattern = re.compile(
244 r"^\d\d\d\d-[0-1]\d-[0-3]\d[t\s]"
245 r"(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?"
246 r"(?:z|[+-]\d\d:\d\d)$",
247 re.I,
248 )
249
250 def recurse(value):
251 if isinstance(value, str):
252 if ts_pattern.match(value):
253 value = parse_time(value)
254 diff = value - base
255 return {"relative-datestamp": f"{int(diff.total_seconds())} seconds"}
256 if isinstance(value, list):
257 return [recurse(e) for e in value]
258 if isinstance(value, dict):
259 return {k: recurse(v) for k, v in value.items()}
260 return value
261
262 return recurse(task_def)
263
264
265 def add_args_to_command(cmd_parts, extra_args=[]):
266 """
267 Add custom command line args to a given command.
268
269 Args:
270 cmd_parts: the raw command as seen by taskcluster
271 extra_args: array of args we want to add
272 """
273 cmd_type = "default"
274 if len(cmd_parts) == 1 and isinstance(cmd_parts[0], dict):
275 # windows has single cmd part as dict: 'task-reference', with long string
276 cmd_parts = cmd_parts[0]["task-reference"].split(" ")
277 cmd_type = "dict"
278 elif len(cmd_parts) == 1 and (
279 isinstance(cmd_parts[0], str) or isinstance(cmd_parts[0], str)
280 ):
281 # windows has single cmd part as a long string
282 cmd_parts = cmd_parts[0].split(" ")
283 cmd_type = "unicode"
284 elif len(cmd_parts) == 1 and isinstance(cmd_parts[0], list):
285 # osx has an single value array with an array inside
286 cmd_parts = cmd_parts[0]
287 cmd_type = "subarray"
288
289 cmd_parts.extend(extra_args)
290
291 if cmd_type == "dict":
292 cmd_parts = [{"task-reference": " ".join(cmd_parts)}]
293 elif cmd_type == "unicode":
294 cmd_parts = [" ".join(cmd_parts)]
295 elif cmd_type == "subarray":
296 cmd_parts = [cmd_parts]
297 return cmd_parts