Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/verify.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 warnings
9 from abc import ABC, abstractmethod
10 from dataclasses import dataclass, field
11 from typing import Callable, Dict, List, Union
12
13 from taskgraph.config import GraphConfig
14 from taskgraph.parameters import Parameters
15 from taskgraph.taskgraph import TaskGraph
16 from taskgraph.util.attributes import match_run_on_projects
17 from taskgraph.util.treeherder import join_symbol
18
19 logger = logging.getLogger(__name__)
20
21
22 @dataclass(frozen=True)
23 class Verification(ABC):
24 func: Callable
25
26 @abstractmethod
27 def verify(self, **kwargs) -> None:
28 pass
29
30
31 @dataclass(frozen=True)
32 class InitialVerification(Verification):
33 """Verification that doesn't depend on any generation state."""
34
35 def verify(self):
36 self.func()
37
38
39 @dataclass(frozen=True)
40 class GraphVerification(Verification):
41 """Verification for a TaskGraph object."""
42
43 run_on_projects: Union[List, None] = field(default=None)
44
45 def verify(
46 self, graph: TaskGraph, graph_config: GraphConfig, parameters: Parameters
47 ):
48 if self.run_on_projects and not match_run_on_projects(
49 parameters["project"], self.run_on_projects
50 ):
51 return
52
53 scratch_pad = {}
54 graph.for_each_task(
55 self.func,
56 scratch_pad=scratch_pad,
57 graph_config=graph_config,
58 parameters=parameters,
59 )
60 self.func(
61 None,
62 graph,
63 scratch_pad=scratch_pad,
64 graph_config=graph_config,
65 parameters=parameters,
66 )
67
68
69 @dataclass(frozen=True)
70 class ParametersVerification(Verification):
71 """Verification for a set of parameters."""
72
73 def verify(self, parameters: Parameters):
74 self.func(parameters)
75
76
77 @dataclass(frozen=True)
78 class KindsVerification(Verification):
79 """Verification for kinds."""
80
81 def verify(self, kinds: dict):
82 self.func(kinds)
83
84
85 @dataclass(frozen=True)
86 class VerificationSequence:
87 """
88 Container for a sequence of verifications over a TaskGraph. Each
89 verification is represented as a callable taking (task, taskgraph,
90 scratch_pad), called for each task in the taskgraph, and one more
91 time with no task but with the taskgraph and the same scratch_pad
92 that was passed for each task.
93 """
94
95 _verifications: Dict = field(default_factory=dict)
96 _verification_types = {
97 "graph": GraphVerification,
98 "initial": InitialVerification,
99 "kinds": KindsVerification,
100 "parameters": ParametersVerification,
101 }
102
103 def __call__(self, name, *args, **kwargs):
104 for verification in self._verifications.get(name, []):
105 verification.verify(*args, **kwargs)
106
107 def add(self, name, **kwargs):
108 cls = self._verification_types.get(name, GraphVerification)
109
110 def wrap(func):
111 self._verifications.setdefault(name, []).append(cls(func, **kwargs))
112 return func
113
114 return wrap
115
116
117 verifications = VerificationSequence()
118
119
120 @verifications.add("full_task_graph")
121 def verify_task_graph_symbol(task, taskgraph, scratch_pad, graph_config, parameters):
122 """
123 This function verifies that tuple
124 (collection.keys(), machine.platform, groupSymbol, symbol) is unique
125 for a target task graph.
126 """
127 if task is None:
128 return
129 task_dict = task.task
130 if "extra" in task_dict:
131 extra = task_dict["extra"]
132 if "treeherder" in extra:
133 treeherder = extra["treeherder"]
134
135 collection_keys = tuple(sorted(treeherder.get("collection", {}).keys()))
136 if len(collection_keys) != 1:
137 raise Exception(
138 f"Task {task.label} can't be in multiple treeherder collections "
139 f"(the part of the platform after `/`): {collection_keys}"
140 )
141 platform = treeherder.get("machine", {}).get("platform")
142 group_symbol = treeherder.get("groupSymbol")
143 symbol = treeherder.get("symbol")
144
145 key = (platform, collection_keys[0], group_symbol, symbol)
146 if key in scratch_pad:
147 raise Exception(
148 "Duplicate treeherder platform and symbol in tasks "
149 "`{}` and `{}`: {} {}".format(
150 task.label,
151 scratch_pad[key],
152 f"{platform}/{collection_keys[0]}",
153 join_symbol(group_symbol, symbol),
154 )
155 )
156 else:
157 scratch_pad[key] = task.label
158
159
160 @verifications.add("full_task_graph")
161 def verify_trust_domain_v2_routes(
162 task, taskgraph, scratch_pad, graph_config, parameters
163 ):
164 """
165 This function ensures that any two tasks have distinct ``index.{trust-domain}.v2`` routes.
166 """
167 if task is None:
168 return
169 route_prefix = "index.{}.v2".format(graph_config["trust-domain"])
170 task_dict = task.task
171 routes = task_dict.get("routes", [])
172
173 for route in routes:
174 if route.startswith(route_prefix):
175 if route in scratch_pad:
176 raise Exception(
177 f"conflict between {task.label}:{scratch_pad[route]} for route: {route}"
178 )
179 else:
180 scratch_pad[route] = task.label
181
182
183 @verifications.add("full_task_graph")
184 def verify_routes_notification_filters(
185 task, taskgraph, scratch_pad, graph_config, parameters
186 ):
187 """
188 This function ensures that only understood filters for notifications are
189 specified.
190
191 See: https://docs.taskcluster.net/reference/core/taskcluster-notify/docs/usage
192 """
193 if task is None:
194 return
195 route_prefix = "notify."
196 valid_filters = (
197 "on-any",
198 "on-completed",
199 "on-defined",
200 "on-failed",
201 "on-exception",
202 "on-pending",
203 "on-resolved",
204 "on-running",
205 "on-transition",
206 )
207 task_dict = task.task
208 routes = task_dict.get("routes", [])
209
210 for route in routes:
211 if route.startswith(route_prefix):
212 # Get the filter of the route
213 route_filter = route.split(".")[-1]
214 if route_filter not in valid_filters:
215 raise Exception(
216 f"{task.label} has invalid notification filter ({route_filter})"
217 )
218 if route_filter == "on-any":
219 warnings.warn(
220 DeprecationWarning(
221 f"notification filter '{route_filter}' is deprecated. Use "
222 "'on-transition' or 'on-resolved'."
223 )
224 )
225
226
227 @verifications.add("full_task_graph")
228 def verify_dependency_tiers(task, taskgraph, scratch_pad, graph_config, parameters):
229 tiers = scratch_pad
230 if task is not None:
231 tiers[task.label] = (
232 task.task.get("extra", {}).get("treeherder", {}).get("tier", sys.maxsize)
233 )
234 else:
235
236 def printable_tier(tier):
237 if tier == sys.maxsize:
238 return "unknown"
239 return tier
240
241 for task in taskgraph.tasks.values():
242 tier = tiers[task.label]
243 for d in task.dependencies.values():
244 if taskgraph[d].task.get("workerType") == "always-optimized":
245 continue
246 if "dummy" in taskgraph[d].kind:
247 continue
248 if tier < tiers[d]:
249 raise Exception(
250 f"{task.label} (tier {printable_tier(tier)}) cannot depend on {d} (tier {printable_tier(tiers[d])})"
251 )
252
253
254 @verifications.add("full_task_graph")
255 def verify_toolchain_alias(task, taskgraph, scratch_pad, graph_config, parameters):
256 """
257 This function verifies that toolchain aliases are not reused.
258 """
259 if task is None:
260 return
261 attributes = task.attributes
262 if "toolchain-alias" in attributes:
263 keys = attributes["toolchain-alias"]
264 if not keys:
265 keys = []
266 elif isinstance(keys, str):
267 keys = [keys]
268 for key in keys:
269 if key in scratch_pad:
270 raise Exception(
271 "Duplicate toolchain-alias in tasks "
272 f"`{task.label}`and `{scratch_pad[key]}`: {key}"
273 )
274 else:
275 scratch_pad[key] = task.label
276
277
278 @verifications.add("optimized_task_graph")
279 def verify_always_optimized(task, taskgraph, scratch_pad, graph_config, parameters):
280 """
281 This function ensures that always-optimized tasks have been optimized.
282 """
283 if task is None:
284 return
285 if task.task.get("workerType") == "always-optimized":
286 raise Exception(f"Could not optimize the task {task.label!r}")