Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/transforms/run/common.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 Common support for various task types. These functions are all named after the
6 worker implementation they operate on, and take the same three parameters, for
7 consistency.
8 """
9
10 from typing import Any, Dict, List, Union
11
12 from taskgraph.transforms.base import TransformConfig
13 from taskgraph.util import json, path
14 from taskgraph.util.caches import CACHES, get_checkout_dir
15 from taskgraph.util.taskcluster import get_artifact_prefix
16
17
18 def get_vcsdir_name(os):
19 if os == "windows":
20 return "src"
21 else:
22 return "vcs"
23
24
25 def add_cache(task, taskdesc, name, mount_point, skip_untrusted=False):
26 """Adds a cache based on the worker's implementation.
27
28 Args:
29 task (dict): Tasks object.
30 taskdesc (dict): Target task description to modify.
31 name (str): Name of the cache.
32 mount_point (path): Path on the host to mount the cache.
33 skip_untrusted (bool): Whether cache is used in untrusted environments
34 (default: False). Only applies to docker-worker.
35 """
36 worker = task["worker"]
37 if worker["implementation"] not in ("docker-worker", "generic-worker"):
38 # caches support not implemented
39 return
40
41 if worker["implementation"] == "docker-worker":
42 taskdesc["worker"].setdefault("caches", []).append(
43 {
44 "type": "persistent",
45 "name": name,
46 "mount-point": mount_point,
47 "skip-untrusted": skip_untrusted,
48 }
49 )
50
51 elif worker["implementation"] == "generic-worker":
52 taskdesc["worker"].setdefault("mounts", []).append(
53 {
54 "cache-name": name,
55 "directory": mount_point,
56 }
57 )
58
59
60 def add_artifacts(config, task, taskdesc, path):
61 taskdesc["worker"].setdefault("artifacts", []).append(
62 {
63 "name": get_artifact_prefix(taskdesc),
64 "path": path,
65 "type": "directory",
66 }
67 )
68
69
70 def docker_worker_add_artifacts(config, task, taskdesc):
71 """Adds an artifact directory to the task"""
72 path = "{workdir}/artifacts/".format(**task["run"])
73 taskdesc["worker"]["env"]["UPLOAD_DIR"] = path
74 add_artifacts(config, task, taskdesc, path)
75
76
77 def generic_worker_add_artifacts(config, task, taskdesc):
78 """Adds an artifact directory to the task"""
79 # The path is the location on disk; it doesn't necessarily
80 # mean the artifacts will be public or private; that is set via the name
81 # attribute in add_artifacts.
82 add_artifacts(config, task, taskdesc, path=get_artifact_prefix(taskdesc))
83
84
85 def support_vcs_checkout(config, task, taskdesc, repo_configs, sparse=False):
86 """Update a task with parameters to enable a VCS checkout.
87
88 This can only be used with ``run-task`` tasks, as the cache name is
89 reserved for ``run-task`` tasks.
90 """
91 worker = task["worker"]
92 assert worker["os"] in ("linux", "macosx", "windows")
93 is_win = worker["os"] == "windows"
94 is_docker = worker["implementation"] == "docker-worker"
95
96 checkoutdir = get_checkout_dir(task)
97 if is_win:
98 hgstore = "y:/hg-shared"
99 elif is_docker:
100 hgstore = f"{checkoutdir}/hg-store"
101 else:
102 hgstore = f"{checkoutdir}/hg-shared"
103
104 vcsdir = f"{checkoutdir}/{get_vcsdir_name(worker['os'])}"
105 env = taskdesc["worker"].setdefault("env", {})
106 env.update(
107 {
108 "HG_STORE_PATH": hgstore,
109 "REPOSITORIES": json.dumps(
110 {repo.prefix: repo.name for repo in repo_configs.values()}
111 ),
112 "VCS_PATH": vcsdir,
113 }
114 )
115 for repo_config in repo_configs.values():
116 env.update(
117 {
118 f"{repo_config.prefix.upper()}_{key}": value
119 for key, value in {
120 "BASE_REPOSITORY": repo_config.base_repository,
121 "HEAD_REPOSITORY": repo_config.head_repository,
122 "HEAD_REV": repo_config.head_rev,
123 "HEAD_REF": repo_config.head_ref,
124 "REPOSITORY_TYPE": repo_config.type,
125 "SSH_SECRET_NAME": repo_config.ssh_secret_name,
126 }.items()
127 if value is not None
128 }
129 )
130 if repo_config.ssh_secret_name:
131 taskdesc["scopes"].append(f"secrets:get:{repo_config.ssh_secret_name}")
132
133 # only some worker platforms have taskcluster-proxy enabled
134 if task["worker"]["implementation"] in ("docker-worker",):
135 taskdesc["worker"]["taskcluster-proxy"] = True
136
137 return vcsdir
138
139
140 def should_use_cache(
141 name: str,
142 use_caches: Union[bool, List[str]],
143 has_checkout: bool,
144 ) -> bool:
145 # Never enable the checkout cache if there's no clone. This allows
146 # 'checkout' to be specified as a default cache without impacting
147 # irrelevant tasks.
148 if name == "checkout" and not has_checkout:
149 return False
150
151 if isinstance(use_caches, bool):
152 return use_caches
153
154 return name in use_caches
155
156
157 def support_caches(
158 config: TransformConfig, task: Dict[str, Any], taskdesc: Dict[str, Any]
159 ):
160 """Add caches for common tools."""
161 run = task["run"]
162 worker = task["worker"]
163 workdir = run.get("workdir")
164 base_cache_dir = ".task-cache"
165 if worker["implementation"] == "docker-worker":
166 workdir = workdir or "/builds/worker"
167 base_cache_dir = path.join(workdir, base_cache_dir)
168
169 use_caches = run.get("use-caches")
170 if use_caches is None:
171 # Use project default values for filtering caches, default to
172 # checkout cache if no selection is specified.
173 taskgraph_config = config.graph_config.get("taskgraph") or {}
174 use_caches = taskgraph_config.get("run", {}).get("use-caches", ["checkout"])
175
176 for name, cache_cfg in CACHES.items():
177 if not should_use_cache(name, use_caches, run["checkout"]):
178 continue
179
180 if "cache_dir" in cache_cfg:
181 assert callable(cache_cfg["cache_dir"])
182 cache_dir = cache_cfg["cache_dir"](task)
183 else:
184 cache_dir = f"{base_cache_dir}/{name}"
185
186 if "cache_name" in cache_cfg:
187 assert callable(cache_cfg["cache_name"])
188 cache_name = cache_cfg["cache_name"](config, task)
189 else:
190 cache_name = name
191
192 if cache_cfg.get("env"):
193 env = taskdesc["worker"].setdefault("env", {})
194 # If cache_dir is already absolute, the `.join` call returns it as
195 # is. In that case, {task_workdir} will get interpolated by
196 # run-task.
197 env[cache_cfg["env"]] = cache_dir
198 add_cache(task, taskdesc, cache_name, cache_dir)