Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/actions/retrigger.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 logging
7 import sys
8 import textwrap
9
10 from slugid import nice as slugid
11
12 from taskgraph.util import taskcluster
13
14 from .registry import register_callback_action
15 from .util import (
16 combine_task_graph_files,
17 create_task_from_def,
18 create_tasks,
19 fetch_graph_and_labels,
20 relativize_datestamps,
21 )
22
23 logger = logging.getLogger(__name__)
24
25 RERUN_STATES = ("exception", "failed")
26
27
28 def _should_retrigger(task_graph, label):
29 """
30 Return whether a given task in the taskgraph should be retriggered.
31
32 This handles the case where the task isn't there by assuming it should not be.
33 """
34 if label not in task_graph:
35 logger.info(
36 f"Task {label} not in full taskgraph, assuming task should not be retriggered."
37 )
38 return False
39 return task_graph[label].attributes.get("retrigger", False)
40
41
42 @register_callback_action(
43 title="Retrigger",
44 name="retrigger",
45 symbol="rt",
46 cb_name="retrigger-decision",
47 permission="retrigger-decision",
48 description=textwrap.dedent(
49 """\
50 Create a clone of the task (retriggering decision, action, and cron tasks requires
51 special scopes)."""
52 ),
53 order=11,
54 context=[
55 {"kind": "decision-task"},
56 {"kind": "action-callback"},
57 {"kind": "cron-task"},
58 ],
59 )
60 def retrigger_decision_action(parameters, graph_config, input, task_group_id, task_id):
61 """For a single task, we try to just run exactly the same task once more.
62 It's quite possible that we don't have the scopes to do so (especially for
63 an action), but this is best-effort."""
64
65 # make all of the timestamps relative; they will then be turned back into
66 # absolute timestamps relative to the current time.
67 task = taskcluster.get_task_definition(task_id)
68 task = relativize_datestamps(task)
69 create_task_from_def(
70 slugid(), task, parameters["level"], graph_config["trust-domain"]
71 )
72
73
74 @register_callback_action(
75 title="Retrigger",
76 name="retrigger",
77 symbol="rt",
78 description=("Create a clone of the task."),
79 order=19, # must be greater than other orders in this file, as this is the fallback version
80 context=[{"retrigger": "true"}],
81 schema={
82 "type": "object",
83 "properties": {
84 "downstream": {
85 "type": "boolean",
86 "description": (
87 "If true, downstream tasks from this one will be cloned as well. "
88 "The dependencies will be updated to work with the new task at the root."
89 ),
90 "default": False,
91 },
92 "times": {
93 "type": "integer",
94 "default": 1,
95 "minimum": 1,
96 "maximum": 100,
97 "title": "Times",
98 "description": "How many times to run each task.",
99 },
100 },
101 },
102 )
103 @register_callback_action(
104 title="Retrigger (disabled)",
105 name="retrigger",
106 cb_name="retrigger-disabled",
107 symbol="rt",
108 description=(
109 "Create a clone of the task.\n\n"
110 "This type of task should typically be re-run instead of re-triggered."
111 ),
112 order=20, # must be greater than other orders in this file, as this is the fallback version
113 context=[{}],
114 schema={
115 "type": "object",
116 "properties": {
117 "downstream": {
118 "type": "boolean",
119 "description": (
120 "If true, downstream tasks from this one will be cloned as well. "
121 "The dependencies will be updated to work with the new task at the root."
122 ),
123 "default": False,
124 },
125 "times": {
126 "type": "integer",
127 "default": 1,
128 "minimum": 1,
129 "maximum": 100,
130 "title": "Times",
131 "description": "How many times to run each task.",
132 },
133 "force": {
134 "type": "boolean",
135 "default": False,
136 "description": (
137 "This task should not be re-triggered. "
138 "This can be overridden by passing `true` here."
139 ),
140 },
141 },
142 },
143 )
144 def retrigger_action(parameters, graph_config, input, task_group_id, task_id):
145 decision_task_id, full_task_graph, label_to_taskid = fetch_graph_and_labels(
146 parameters, graph_config, task_group_id=task_group_id
147 )
148
149 task = taskcluster.get_task_definition(task_id)
150 label = task["metadata"]["name"]
151
152 with_downstream = " "
153 to_run = [label]
154
155 if not input.get("force", None) and not _should_retrigger(full_task_graph, label):
156 logger.info(
157 f"Not retriggering task {label}, task should not be retrigged "
158 "and force not specified."
159 )
160 sys.exit(1)
161
162 if input.get("downstream"):
163 to_run = full_task_graph.graph.transitive_closure(
164 set(to_run), reverse=True
165 ).nodes
166 to_run = to_run & set(label_to_taskid.keys())
167 with_downstream = " (with downstream) "
168
169 times = input.get("times", 1)
170 for i in range(times):
171 create_tasks(
172 graph_config,
173 to_run,
174 full_task_graph,
175 label_to_taskid,
176 parameters,
177 decision_task_id,
178 f"{i}",
179 )
180
181 logger.info(f"Scheduled {label}{with_downstream}(time {i + 1}/{times})")
182 combine_task_graph_files(list(range(times)))
183
184
185 @register_callback_action(
186 title="Rerun",
187 name="rerun",
188 symbol="rr",
189 description=(
190 "Rerun a task.\n\n"
191 "This only works on failed or exception tasks in the original taskgraph,"
192 " and is CoT friendly."
193 ),
194 order=300,
195 context=[{}],
196 schema={"type": "object", "properties": {}},
197 )
198 def rerun_action(parameters, graph_config, input, task_group_id, task_id):
199 task = taskcluster.get_task_definition(task_id)
200 parameters = dict(parameters)
201 decision_task_id, full_task_graph, label_to_taskid = fetch_graph_and_labels(
202 parameters, graph_config, task_group_id=task_group_id
203 )
204 label = task["metadata"]["name"]
205 if task_id not in label_to_taskid.values():
206 logger.error(
207 f"Refusing to rerun {label}: taskId {task_id} not in decision task {decision_task_id} label_to_taskid!"
208 )
209
210 _rerun_task(task_id, label)
211
212
213 def _rerun_task(task_id, label):
214 state = taskcluster.state_task(task_id)
215 if state not in RERUN_STATES:
216 logger.warning(
217 f"No need to rerun {label}: state '{state}' not in {RERUN_STATES}!"
218 )
219 return
220 taskcluster.rerun_task(task_id)
221 logger.info(f"Reran {label}")
222
223
224 @register_callback_action(
225 title="Retrigger",
226 name="retrigger-multiple",
227 symbol="rt",
228 description=("Create a clone of the task."),
229 context=[],
230 schema={
231 "type": "object",
232 "properties": {
233 "requests": {
234 "type": "array",
235 "items": {
236 "tasks": {
237 "type": "array",
238 "description": "An array of task labels",
239 "items": {"type": "string"},
240 },
241 "times": {
242 "type": "integer",
243 "minimum": 1,
244 "maximum": 100,
245 "title": "Times",
246 "description": "How many times to run each task.",
247 },
248 "additionalProperties": False,
249 },
250 },
251 "additionalProperties": False,
252 },
253 },
254 )
255 def retrigger_multiple(parameters, graph_config, input, task_group_id, task_id):
256 decision_task_id, full_task_graph, label_to_taskid = fetch_graph_and_labels(
257 parameters, graph_config, task_group_id=task_group_id
258 )
259
260 suffixes = []
261 for i, request in enumerate(input.get("requests", [])):
262 times = request.get("times", 1)
263 rerun_tasks = [
264 label
265 for label in request.get("tasks")
266 if not _should_retrigger(full_task_graph, label)
267 ]
268 retrigger_tasks = [
269 label
270 for label in request.get("tasks")
271 if _should_retrigger(full_task_graph, label)
272 ]
273
274 for label in rerun_tasks:
275 # XXX we should not re-run tasks pulled in from other pushes
276 # In practice, this shouldn't matter, as only completed tasks
277 # are pulled in from other pushes and treeherder won't pass
278 # those labels.
279 _rerun_task(label_to_taskid[label], label)
280
281 for j in range(times):
282 suffix = f"{i}-{j}"
283 suffixes.append(suffix)
284 create_tasks(
285 graph_config,
286 retrigger_tasks,
287 full_task_graph,
288 label_to_taskid,
289 parameters,
290 decision_task_id,
291 suffix,
292 )
293
294 combine_task_graph_files(suffixes)