Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/actions/registry.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 functools
7 from collections import namedtuple
8 from types import FunctionType
9
10 from mozilla_repo_urls import parse
11
12 from taskgraph import create
13 from taskgraph.config import load_graph_config
14 from taskgraph.parameters import Parameters
15 from taskgraph.util import hash, json, taskcluster, yaml
16 from taskgraph.util.python_path import import_sibling_modules
17
18 actions = []
19 callbacks = {}
20
21 Action = namedtuple("Action", ["order", "cb_name", "permission", "action_builder"])
22
23
24 def is_json(data):
25 """Return ``True``, if ``data`` is a JSON serializable data structure."""
26 try:
27 json.dumps(data)
28 except ValueError:
29 return False
30 return True
31
32
33 @functools.lru_cache(maxsize=None)
34 def read_taskcluster_yml(filename):
35 """Load and parse .taskcluster.yml, cached to save some time"""
36 return yaml.load_yaml(filename)
37
38
39 @functools.lru_cache(maxsize=None)
40 def hash_taskcluster_yml(filename):
41 """
42 Generate a hash of the given .taskcluster.yml. This is the first 10 digits
43 of the sha256 of the file's content, and is used by administrative scripts
44 to create a hook based on this content.
45 """
46 return hash.hash_path(filename)[:10]
47
48
49 def register_callback_action(
50 name,
51 title,
52 symbol,
53 description,
54 order=10000,
55 context=[],
56 available=lambda parameters: True,
57 schema=None,
58 permission="generic",
59 cb_name=None,
60 ):
61 """
62 Register an action callback that can be triggered from supporting
63 user interfaces, such as Treeherder.
64
65 This function is to be used as a decorator for a callback that takes
66 parameters as follows:
67
68 ``parameters``:
69 Decision task :class:`parameters <taskgraph.parameters.Parameters>`.
70 ``input``:
71 Input matching specified JSON schema, ``None`` if no ``schema``
72 parameter is given to ``register_callback_action``.
73 ``task_group_id``:
74 The id of the task-group this was triggered for.
75 ``task_id`` and `task``:
76 task identifier and task definition for task the action was triggered
77 for, ``None`` if no ``context`` parameters was given to
78 ``register_callback_action``.
79
80 Args:
81 name (str):
82 An identifier for this action, used by UIs to find the action.
83 title (str):
84 A human readable title for the action to be used as label on a button
85 or text on a link for triggering the action.
86 symbol (str):
87 Treeherder symbol for the action callback, this is the symbol that the
88 task calling your callback will be displayed as. This is usually 1-3
89 letters abbreviating the action title.
90 description (str):
91 A human readable description of the action in **markdown**.
92 This will be display as tooltip and in dialog window when the action
93 is triggered. This is a good place to describe how to use the action.
94 order (int):
95 Order of the action in menus, this is relative to the ``order`` of
96 other actions declared.
97 context (list of dict):
98 List of tag-sets specifying which tasks the action is can take as input.
99 If no tag-sets is specified as input the action is related to the
100 entire task-group, and won't be triggered with a given task.
101
102 Otherwise, if ``context = [{'k': 'b', 'p': 'l'}, {'k': 't'}]`` will only
103 be displayed in the context menu for tasks that has
104 ``task.tags.k == 'b' && task.tags.p = 'l'`` or ``task.tags.k = 't'``.
105 Essentially, this allows filtering on ``task.tags``.
106
107 If this is a function, it is given the decision parameters and must return
108 a value of the form described above.
109 available (function):
110 An optional function that given decision parameters decides if the
111 action is available. Defaults to a function that always returns ``True``.
112 schema (dict):
113 JSON schema specifying input accepted by the action.
114 This is optional and can be left ``null`` if no input is taken.
115 permission (str):
116 This defaults to ``generic`` and needs to be set for actions that
117 need additional permissions. It appears in fxci-config and various
118 role and hook names.
119 cb_name (str):
120 The name under which this function should be registered, defaulting to
121 `name`. This is used to generation actionPerm for non-generic hook
122 actions, and thus appears in ci-configuration and various role and hook
123 names. Unlike `name`, which can appear multiple times, cb_name must be
124 unique among all registered callbacks.
125
126 Returns:
127 function: Decorator to be used for the callback function.
128 """
129 mem = {"registered": False} # workaround nonlocal missing in 2.x
130
131 assert isinstance(title, str), "title must be a string"
132 assert isinstance(description, str), "description must be a string"
133 title = title.strip()
134 description = description.strip()
135
136 if not cb_name:
137 cb_name = name
138
139 # ensure that context is callable
140 if not callable(context):
141 context_value = context
142 context = lambda params: context_value # noqa
143
144 def register_callback(cb):
145 assert isinstance(name, str), "name must be a string"
146 assert isinstance(order, int), "order must be an integer"
147 assert callable(schema) or is_json(schema), (
148 "schema must be a JSON compatible object"
149 )
150 assert isinstance(cb, FunctionType), "callback must be a function"
151 # Allow for json-e > 25 chars in the symbol.
152 if "$" not in symbol:
153 assert 1 <= len(symbol) <= 25, "symbol must be between 1 and 25 characters"
154 assert isinstance(symbol, str), "symbol must be a string"
155
156 assert not mem["registered"], (
157 "register_callback_action must be used as decorator"
158 )
159 assert cb_name not in callbacks, f"callback name {cb_name} is not unique"
160
161 def action_builder(parameters, graph_config, decision_task_id):
162 if not available(parameters):
163 return None
164
165 # gather up the common decision-task-supplied data for this action
166 repository = {
167 "url": parameters["head_repository"],
168 "project": parameters["project"],
169 "level": parameters["level"],
170 "base_url": parameters["base_repository"],
171 }
172
173 push = {
174 "owner": "[email protected]",
175 "pushlog_id": parameters["pushlog_id"],
176 "revision": parameters["head_rev"],
177 "base_revision": parameters["base_rev"],
178 }
179 branch = parameters.get("head_ref")
180 if branch:
181 push["branch"] = branch
182 base_branch = parameters.get("base_ref")
183 if base_branch and branch != base_branch:
184 push["base_branch"] = base_branch
185
186 action = {
187 "name": name,
188 "title": title,
189 "description": description,
190 # target taskGroupId (the task group this decision task is creating)
191 "taskGroupId": decision_task_id,
192 "cb_name": cb_name,
193 "symbol": symbol,
194 }
195
196 rv = {
197 "name": name,
198 "title": title,
199 "description": description,
200 "context": context(parameters),
201 }
202 if schema:
203 rv["schema"] = (
204 schema(graph_config=graph_config) if callable(schema) else schema
205 )
206
207 trustDomain = graph_config["trust-domain"]
208 level = parameters["level"]
209 tcyml_hash = hash_taskcluster_yml(graph_config.taskcluster_yml)
210
211 # the tcyml_hash is prefixed with `/` in the hookId, so users will be granted
212 # hooks:trigger-hook:project-gecko/in-tree-action-3-myaction/*; if another
213 # action was named `myaction/release`, then the `*` in the scope would also
214 # match that action. To prevent such an accident, we prohibit `/` in hook
215 # names.
216 if "/" in permission:
217 raise Exception("`/` is not allowed in action names; use `-`")
218
219 if parameters["tasks_for"].startswith("github-pull-request"):
220 hookId = f"in-tree-pr-action-{level}-{permission}/{tcyml_hash}"
221 else:
222 hookId = f"in-tree-action-{level}-{permission}/{tcyml_hash}"
223
224 rv.update(
225 {
226 "kind": "hook",
227 "hookGroupId": f"project-{trustDomain}",
228 "hookId": hookId,
229 "hookPayload": {
230 # provide the decision-task parameters as context for triggerHook
231 "decision": {
232 "action": action,
233 "repository": repository,
234 "push": push,
235 },
236 # and pass everything else through from our own context
237 "user": {
238 "input": {"$eval": "input"},
239 "taskId": {"$eval": "taskId"}, # target taskId (or null)
240 "taskGroupId": {
241 "$eval": "taskGroupId"
242 }, # target task group
243 },
244 },
245 "extra": {
246 "actionPerm": permission,
247 },
248 }
249 )
250
251 return rv
252
253 actions.append(Action(order, cb_name, permission, action_builder))
254
255 mem["registered"] = True
256 callbacks[cb_name] = cb
257 return cb
258
259 return register_callback
260
261
262 def render_actions_json(parameters, graph_config, decision_task_id):
263 """
264 Render JSON object for the ``public/actions.json`` artifact.
265
266 Args:
267 parameters (:class:`~taskgraph.parameters.Parameters`):
268 Decision task parameters.
269
270 Returns:
271 dict:
272 JSON object representation of the ``public/actions.json``
273 artifact.
274 """
275 assert isinstance(parameters, Parameters), "requires instance of Parameters"
276 actions = []
277 for action in sorted(_get_actions(graph_config), key=lambda action: action.order):
278 action = action.action_builder(parameters, graph_config, decision_task_id)
279 if action:
280 assert is_json(action), "action must be a JSON compatible object"
281 actions.append(action)
282 return {
283 "version": 1,
284 "variables": {},
285 "actions": actions,
286 }
287
288
289 def sanity_check_task_scope(callback, parameters, graph_config):
290 """
291 If this action is not generic, then verify that this task has the necessary
292 scope to run the action. This serves as a backstop preventing abuse by
293 running non-generic actions using generic hooks. While scopes should
294 prevent serious damage from such abuse, it's never a valid thing to do.
295 """
296 for action in _get_actions(graph_config):
297 if action.cb_name == callback:
298 break
299 else:
300 raise ValueError(f"No action with cb_name {callback}")
301
302 parsed_base_url = parse(parameters["base_repository"])
303 parsed_head_url = parse(parameters["head_repository"])
304 action_scope = (
305 f"assume:{parsed_head_url.taskcluster_role_prefix}:action:{action.permission}"
306 )
307 pr_action_scope = f"assume:{parsed_base_url.taskcluster_role_prefix}:pr-action:{action.permission}"
308
309 # the scope should appear literally; no need for a satisfaction check. The use of
310 # get_current_scopes here calls the auth service through the Taskcluster Proxy, giving
311 # the precise scopes available to this task.
312 if not set((action_scope, pr_action_scope)) & set(taskcluster.get_current_scopes()):
313 raise ValueError(
314 f"Expected task scope {action_scope} or {pr_action_scope} for this action"
315 )
316
317
318 def trigger_action_callback(
319 task_group_id, task_id, input, callback, parameters, root, test=False
320 ):
321 """
322 Trigger action callback with the given inputs. If `test` is true, then run
323 the action callback in testing mode, without actually creating tasks.
324 """
325 graph_config = load_graph_config(root)
326 graph_config.register()
327 callbacks = _get_callbacks(graph_config)
328 cb = callbacks.get(callback, None)
329 if not cb:
330 raise Exception(
331 "Unknown callback: {}. Known callbacks: {}".format(
332 callback, ", ".join(callbacks)
333 )
334 )
335
336 if test:
337 create.testing = True
338 taskcluster.testing = True
339
340 if not test:
341 sanity_check_task_scope(callback, parameters, graph_config)
342
343 cb(Parameters(**parameters), graph_config, input, task_group_id, task_id)
344
345
346 def _load(graph_config):
347 # Load all modules from this folder, relying on the side-effects of register_
348 # functions to populate the action registry.
349 import_sibling_modules(exceptions=("util.py",))
350 return callbacks, actions
351
352
353 def _get_callbacks(graph_config):
354 return _load(graph_config)[0]
355
356
357 def _get_actions(graph_config):
358 return _load(graph_config)[1]