Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/taskcluster.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 datetime
8 import functools
9 import logging
10 import os
11 from typing import Dict, List, Union
12
13 import requests
14 import taskcluster_urls as liburls
15 from requests.packages.urllib3.util.retry import Retry # type: ignore
16
17 from taskgraph.task import Task
18 from taskgraph.util import yaml
19
20 logger = logging.getLogger(__name__)
21
22 # this is set to true for `mach taskgraph action-callback --test`
23 testing = False
24
25 # Default rootUrl to use if none is given in the environment; this should point
26 # to the production Taskcluster deployment used for CI.
27 PRODUCTION_TASKCLUSTER_ROOT_URL = None
28
29 # the maximum number of parallel Taskcluster API calls to make
30 CONCURRENCY = 50
31
32
33 @functools.lru_cache(maxsize=None)
34 def get_root_url(use_proxy):
35 """Get the current TASKCLUSTER_ROOT_URL.
36
37 When running in a task, this must come from $TASKCLUSTER_ROOT_URL; when run
38 on the command line, a default may be provided that points to the
39 production deployment of Taskcluster. If use_proxy is set, this attempts to
40 get TASKCLUSTER_PROXY_URL instead, failing if it is not set.
41 """
42 if use_proxy:
43 try:
44 return liburls.normalize_root_url(os.environ["TASKCLUSTER_PROXY_URL"])
45 except KeyError:
46 if "TASK_ID" not in os.environ:
47 raise RuntimeError(
48 "taskcluster-proxy is not available when not executing in a task"
49 )
50 else:
51 raise RuntimeError("taskcluster-proxy is not enabled for this task")
52
53 if "TASKCLUSTER_ROOT_URL" in os.environ:
54 logger.debug(
55 "Running in Taskcluster instance {}{}".format(
56 os.environ["TASKCLUSTER_ROOT_URL"],
57 (
58 " with taskcluster-proxy"
59 if "TASKCLUSTER_PROXY_URL" in os.environ
60 else ""
61 ),
62 )
63 )
64 return liburls.normalize_root_url(os.environ["TASKCLUSTER_ROOT_URL"])
65
66 if "TASK_ID" in os.environ:
67 raise RuntimeError("$TASKCLUSTER_ROOT_URL must be set when running in a task")
68
69 if PRODUCTION_TASKCLUSTER_ROOT_URL is None:
70 raise RuntimeError(
71 "Could not detect Taskcluster instance, set $TASKCLUSTER_ROOT_URL"
72 )
73
74 logger.debug("Using default TASKCLUSTER_ROOT_URL")
75 return liburls.normalize_root_url(PRODUCTION_TASKCLUSTER_ROOT_URL)
76
77
78 def requests_retry_session(
79 retries,
80 backoff_factor=0.1,
81 status_forcelist=(500, 502, 503, 504),
82 concurrency=CONCURRENCY,
83 session=None,
84 allowed_methods=None,
85 ):
86 session = session or requests.Session()
87 kwargs = {}
88 if allowed_methods is not None:
89 kwargs["allowed_methods"] = allowed_methods
90 retry = Retry(
91 total=retries,
92 read=retries,
93 connect=retries,
94 backoff_factor=backoff_factor,
95 status_forcelist=status_forcelist,
96 **kwargs,
97 )
98
99 # Default HTTPAdapter uses 10 connections. Mount custom adapter to increase
100 # that limit. Connections are established as needed, so using a large value
101 # should not negatively impact performance.
102 http_adapter = requests.adapters.HTTPAdapter( # type: ignore
103 pool_connections=concurrency,
104 pool_maxsize=concurrency,
105 max_retries=retry,
106 )
107 session.mount("http://", http_adapter)
108 session.mount("https://", http_adapter)
109
110 return session
111
112
113 @functools.lru_cache(maxsize=None)
114 def get_session():
115 return requests_retry_session(retries=5)
116
117
118 @functools.lru_cache(maxsize=None)
119 def get_retry_post_session():
120 allowed_methods = set(("POST",)) | Retry.DEFAULT_ALLOWED_METHODS
121 return requests_retry_session(retries=5, allowed_methods=allowed_methods)
122
123
124 def _do_request(url, method=None, session=None, **kwargs):
125 if method is None:
126 method = "post" if kwargs else "get"
127 if session is None:
128 session = get_session()
129 if method == "get":
130 kwargs["stream"] = True
131
132 response = getattr(session, method)(url, **kwargs)
133
134 if response.status_code >= 400:
135 # Consume content before raise_for_status, so that the connection can be
136 # reused.
137 response.content
138 response.raise_for_status()
139 return response
140
141
142 def _handle_artifact(path, response):
143 if path.endswith(".json"):
144 return response.json()
145 if path.endswith(".yml"):
146 return yaml.load_stream(response.content)
147 response.raw.read = functools.partial(response.raw.read, decode_content=True)
148 return response.raw
149
150
151 def get_artifact_url(task_id, path, use_proxy=False):
152 artifact_tmpl = liburls.api(
153 get_root_url(use_proxy), "queue", "v1", "task/{}/artifacts/{}"
154 )
155 return artifact_tmpl.format(task_id, path)
156
157
158 def get_artifact(task_id, path, use_proxy=False):
159 """
160 Returns the artifact with the given path for the given task id.
161
162 If the path ends with ".json" or ".yml", the content is deserialized as,
163 respectively, json or yaml, and the corresponding python data (usually
164 dict) is returned.
165 For other types of content, a file-like object is returned.
166 """
167 response = _do_request(get_artifact_url(task_id, path, use_proxy))
168 return _handle_artifact(path, response)
169
170
171 def list_artifacts(task_id, use_proxy=False):
172 response = _do_request(get_artifact_url(task_id, "", use_proxy).rstrip("/"))
173 return response.json()["artifacts"]
174
175
176 def get_artifact_prefix(task):
177 prefix = None
178 if isinstance(task, dict):
179 prefix = task.get("attributes", {}).get("artifact_prefix")
180 elif isinstance(task, Task):
181 prefix = task.attributes.get("artifact_prefix")
182 else:
183 raise Exception(f"Can't find artifact-prefix of non-task: {task}")
184 return prefix or "public/build"
185
186
187 def get_artifact_path(task, path):
188 return f"{get_artifact_prefix(task)}/{path}"
189
190
191 def get_index_url(index_path, use_proxy=False, multiple=False):
192 index_tmpl = liburls.api(get_root_url(use_proxy), "index", "v1", "task{}/{}")
193 return index_tmpl.format("s" if multiple else "", index_path)
194
195
196 def find_task_id(index_path, use_proxy=False):
197 try:
198 response = _do_request(get_index_url(index_path, use_proxy))
199 except requests.exceptions.HTTPError as e:
200 if e.response.status_code == 404: # type: ignore
201 raise KeyError(f"index path {index_path} not found")
202 raise
203 return response.json()["taskId"]
204
205
206 def find_task_id_batched(index_paths, use_proxy=False):
207 """Gets the task id of multiple tasks given their respective index.
208
209 Args:
210 index_paths (List[str]): A list of task indexes.
211 use_proxy (bool): Whether to use taskcluster-proxy (default: False)
212
213 Returns:
214 Dict[str, str]: A dictionary object mapping each valid index path
215 to its respective task id.
216
217 See the endpoint here:
218 https://docs.taskcluster.net/docs/reference/core/index/api#findTasksAtIndex
219 """
220 endpoint = liburls.api(get_root_url(use_proxy), "index", "v1", "tasks/indexes")
221 task_ids = {}
222 continuation_token = None
223
224 while True:
225 response = _do_request(
226 endpoint,
227 session=get_retry_post_session(),
228 json={
229 "indexes": index_paths,
230 },
231 params={"continuationToken": continuation_token},
232 )
233
234 response_data = response.json()
235 if not response_data["tasks"]:
236 break
237 response_tasks = response_data["tasks"]
238 if (len(task_ids) + len(response_tasks)) > len(index_paths):
239 # Sanity check
240 raise ValueError("more task ids were returned than were asked for")
241 task_ids.update((t["namespace"], t["taskId"]) for t in response_tasks)
242
243 continuationToken = response_data.get("continuationToken")
244 if continuationToken is None:
245 break
246 return task_ids
247
248
249 def get_artifact_from_index(index_path, artifact_path, use_proxy=False):
250 full_path = index_path + "/artifacts/" + artifact_path
251 response = _do_request(get_index_url(full_path, use_proxy))
252 return _handle_artifact(full_path, response)
253
254
255 def list_tasks(index_path, use_proxy=False):
256 """
257 Returns a list of task_ids where each task_id is indexed under a path
258 in the index. Results are sorted by expiration date from oldest to newest.
259 """
260 results = []
261 data = {}
262 while True:
263 response = _do_request(
264 get_index_url(index_path, use_proxy, multiple=True), json=data
265 )
266 response = response.json()
267 results += response["tasks"]
268 if response.get("continuationToken"):
269 data = {"continuationToken": response.get("continuationToken")}
270 else:
271 break
272
273 # We can sort on expires because in the general case
274 # all of these tasks should be created with the same expires time so they end up in
275 # order from earliest to latest action. If more correctness is needed, consider
276 # fetching each task and sorting on the created date.
277 results.sort(key=lambda t: parse_time(t["expires"]))
278 return [t["taskId"] for t in results]
279
280
281 def parse_time(timestamp):
282 """Turn a "JSON timestamp" as used in TC APIs into a datetime"""
283 return datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")
284
285
286 def get_task_url(task_id, use_proxy=False):
287 task_tmpl = liburls.api(get_root_url(use_proxy), "queue", "v1", "task/{}")
288 return task_tmpl.format(task_id)
289
290
291 @functools.lru_cache(maxsize=None)
292 def get_task_definition(task_id, use_proxy=False):
293 response = _do_request(get_task_url(task_id, use_proxy))
294 return response.json()
295
296
297 def cancel_task(task_id, use_proxy=False):
298 """Cancels a task given a task_id. In testing mode, just logs that it would
299 have cancelled."""
300 if testing:
301 logger.info(f"Would have cancelled {task_id}.")
302 else:
303 _do_request(get_task_url(task_id, use_proxy) + "/cancel", json={})
304
305
306 def status_task(task_id, use_proxy=False):
307 """Gets the status of a task given a task_id.
308
309 In testing mode, just logs that it would have retrieved status.
310
311 Args:
312 task_id (str): A task id.
313 use_proxy (bool): Whether to use taskcluster-proxy (default: False)
314
315 Returns:
316 dict: A dictionary object as defined here:
317 https://docs.taskcluster.net/docs/reference/platform/queue/api#status
318 """
319 if testing:
320 logger.info(f"Would have gotten status for {task_id}.")
321 else:
322 resp = _do_request(get_task_url(task_id, use_proxy) + "/status")
323 status = resp.json().get("status", {})
324 return status
325
326
327 def status_task_batched(task_ids, use_proxy=False):
328 """Gets the status of multiple tasks given task_ids.
329
330 In testing mode, just logs that it would have retrieved statuses.
331
332 Args:
333 task_id (List[str]): A list of task ids.
334 use_proxy (bool): Whether to use taskcluster-proxy (default: False)
335
336 Returns:
337 dict: A dictionary object as defined here:
338 https://docs.taskcluster.net/docs/reference/platform/queue/api#statuses
339 """
340 if testing:
341 logger.info(f"Would have gotten status for {len(task_ids)} tasks.")
342 return
343 endpoint = liburls.api(get_root_url(use_proxy), "queue", "v1", "tasks/status")
344 statuses = {}
345 continuation_token = None
346
347 while True:
348 response = _do_request(
349 endpoint,
350 session=get_retry_post_session(),
351 json={
352 "taskIds": task_ids,
353 },
354 params={
355 "continuationToken": continuation_token,
356 },
357 )
358 response_data = response.json()
359 if not response_data["statuses"]:
360 break
361 response_tasks = response_data["statuses"]
362 if (len(statuses) + len(response_tasks)) > len(task_ids):
363 raise ValueError("more task statuses were returned than were asked for")
364 statuses.update((t["taskId"], t["status"]) for t in response_tasks)
365 continuationToken = response_data.get("continuationToken")
366 if continuationToken is None:
367 break
368 return statuses
369
370
371 def state_task(task_id, use_proxy=False):
372 """Gets the state of a task given a task_id.
373
374 In testing mode, just logs that it would have retrieved state. This is a subset of the
375 data returned by :func:`status_task`.
376
377 Args:
378 task_id (str): A task id.
379 use_proxy (bool): Whether to use taskcluster-proxy (default: False)
380
381 Returns:
382 str: The state of the task, one of
383 ``pending, running, completed, failed, exception, unknown``.
384 """
385 if testing:
386 logger.info(f"Would have gotten state for {task_id}.")
387 else:
388 status = status_task(task_id, use_proxy=use_proxy).get("state") or "unknown" # type: ignore
389 return status
390
391
392 def rerun_task(task_id):
393 """Reruns a task given a task_id. In testing mode, just logs that it would
394 have reran."""
395 if testing:
396 logger.info(f"Would have rerun {task_id}.")
397 else:
398 _do_request(get_task_url(task_id, use_proxy=True) + "/rerun", json={})
399
400
401 def get_current_scopes():
402 """Get the current scopes. This only makes sense in a task with the Taskcluster
403 proxy enabled, where it returns the actual scopes accorded to the task."""
404 auth_url = liburls.api(get_root_url(True), "auth", "v1", "scopes/current")
405 resp = _do_request(auth_url)
406 return resp.json().get("scopes", [])
407
408
409 def get_purge_cache_url(provisioner_id, worker_type, use_proxy=False):
410 url_tmpl = liburls.api(
411 get_root_url(use_proxy), "purge-cache", "v1", "purge-cache/{}/{}"
412 )
413 return url_tmpl.format(provisioner_id, worker_type)
414
415
416 def purge_cache(provisioner_id, worker_type, cache_name, use_proxy=False):
417 """Requests a cache purge from the purge-caches service."""
418 if testing:
419 logger.info(f"Would have purged {provisioner_id}/{worker_type}/{cache_name}.")
420 else:
421 logger.info(f"Purging {provisioner_id}/{worker_type}/{cache_name}.")
422 purge_cache_url = get_purge_cache_url(provisioner_id, worker_type, use_proxy)
423 _do_request(purge_cache_url, json={"cacheName": cache_name})
424
425
426 def send_email(address, subject, content, link, use_proxy=False):
427 """Sends an email using the notify service"""
428 logger.info(f"Sending email to {address}.")
429 url = liburls.api(get_root_url(use_proxy), "notify", "v1", "email")
430 _do_request(
431 url,
432 json={
433 "address": address,
434 "subject": subject,
435 "content": content,
436 "link": link,
437 },
438 )
439
440
441 def list_task_group_incomplete_tasks(task_group_id):
442 """Generate the incomplete tasks in a task group"""
443 params = {}
444 while True:
445 url = liburls.api(
446 get_root_url(False),
447 "queue",
448 "v1",
449 f"task-group/{task_group_id}/list",
450 )
451 resp = _do_request(url, method="get", params=params).json()
452 for task in [t["status"] for t in resp["tasks"]]:
453 if task["state"] in ["running", "pending", "unscheduled"]:
454 yield task["taskId"]
455 if resp.get("continuationToken"):
456 params = {"continuationToken": resp.get("continuationToken")}
457 else:
458 break
459
460
461 @functools.lru_cache(maxsize=None)
462 def _get_deps(task_ids, use_proxy):
463 upstream_tasks = {}
464 for task_id in task_ids:
465 try:
466 task_def = get_task_definition(task_id, use_proxy)
467 except requests.HTTPError as e:
468 if e.response.status_code == 404:
469 continue
470 raise e
471
472 upstream_tasks[task_id] = task_def["metadata"]["name"]
473
474 upstream_tasks.update(_get_deps(tuple(task_def["dependencies"]), use_proxy))
475
476 return upstream_tasks
477
478
479 def get_ancestors(
480 task_ids: Union[List[str], str], use_proxy: bool = False
481 ) -> Dict[str, str]:
482 """Gets the ancestor tasks of the given task_ids as a dictionary of taskid -> label.
483
484 Args:
485 task_ids (str or [str]): A single task id or a list of task ids to find the ancestors of.
486 use_proxy (bool): See get_root_url.
487
488 Returns:
489 dict: A dict whose keys are task ids and values are task labels.
490 """
491 upstream_tasks: Dict[str, str] = {}
492
493 if isinstance(task_ids, str):
494 task_ids = [task_ids]
495
496 for task_id in task_ids:
497 try:
498 task_def = get_task_definition(task_id, use_proxy)
499 except requests.HTTPError as e:
500 # Task has most likely expired, which means it's no longer a
501 # dependency for the purposes of this function.
502 if e.response.status_code == 404:
503 continue
504
505 raise e
506
507 upstream_tasks.update(_get_deps(tuple(task_def["dependencies"]), use_proxy))
508
509 return copy.deepcopy(upstream_tasks)