Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/docker.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 os
7 import shlex
8 import subprocess
9 import tarfile
10 import tempfile
11 from io import BytesIO
12 from textwrap import dedent
13 from typing import List, Optional
14
15 try:
16 import zstandard as zstd
17 except ImportError as e:
18 zstd = e
19
20 from taskgraph.util import docker, json
21 from taskgraph.util.taskcluster import (
22 get_artifact_url,
23 get_root_url,
24 get_session,
25 get_task_definition,
26 )
27
28 DEPLOY_WARNING = """
29 *****************************************************************
30 WARNING: Image is not suitable for deploying/pushing.
31
32 To automatically tag the image the following files are required:
33 - {image_dir}/REGISTRY
34 - {image_dir}/VERSION
35
36 The REGISTRY file contains the Docker registry hosting the image.
37 A default REGISTRY file may also be defined in the parent docker
38 directory.
39
40 The VERSION file contains the version of the image.
41 *****************************************************************
42 """
43
44
45 def get_image_digest(image_name):
46 from taskgraph.generator import load_tasks_for_kind
47 from taskgraph.parameters import Parameters
48
49 params = Parameters(
50 level=os.environ.get("MOZ_SCM_LEVEL", "3"),
51 strict=False,
52 )
53 tasks = load_tasks_for_kind(params, "docker-image")
54 task = tasks[f"docker-image-{image_name}"]
55 return task.attributes["cached_task"]["digest"]
56
57
58 def load_image_by_name(image_name, tag=None):
59 from taskgraph.generator import load_tasks_for_kind
60 from taskgraph.optimize.strategies import IndexSearch
61 from taskgraph.parameters import Parameters
62
63 params = Parameters(
64 level=os.environ.get("MOZ_SCM_LEVEL", "3"),
65 strict=False,
66 )
67 tasks = load_tasks_for_kind(params, "docker-image")
68 task = tasks[f"docker-image-{image_name}"]
69
70 indexes = task.optimization.get("index-search", [])
71 task_id = IndexSearch().should_replace_task(task, {}, None, indexes)
72
73 if task_id in (True, False):
74 print(
75 "Could not find artifacts for a docker image "
76 "named `{image_name}`. Local commits and other changes "
77 "in your checkout may cause this error. Try "
78 "updating to a fresh checkout of {project} "
79 "to download image.".format(
80 image_name=image_name, project=params["project"]
81 )
82 )
83 return False
84
85 return load_image_by_task_id(task_id, tag)
86
87
88 def load_image_by_task_id(task_id, tag=None):
89 artifact_url = get_artifact_url(task_id, "public/image.tar.zst")
90 result = load_image(artifact_url, tag)
91 print("Found docker image: {}:{}".format(result["image"], result["tag"]))
92 if tag:
93 print(f"Re-tagged as: {tag}")
94 else:
95 tag = "{}:{}".format(result["image"], result["tag"])
96 print(f"Try: docker run -ti --rm {tag} bash")
97 return tag
98
99
100 def build_context(name, outputFile, args=None):
101 """Build a context.tar for image with specified name."""
102 if not name:
103 raise ValueError("must provide a Docker image name")
104 if not outputFile:
105 raise ValueError("must provide a outputFile")
106
107 image_dir = docker.image_path(name)
108 if not os.path.isdir(image_dir):
109 raise Exception(f"image directory does not exist: {image_dir}")
110
111 docker.create_context_tar(".", image_dir, outputFile, args)
112
113
114 def build_image(name, tag, args=None):
115 """Build a Docker image of specified name.
116
117 Output from image building process will be printed to stdout.
118 """
119 if not name:
120 raise ValueError("must provide a Docker image name")
121
122 image_dir = docker.image_path(name)
123 if not os.path.isdir(image_dir):
124 raise Exception(f"image directory does not exist: {image_dir}")
125
126 tag = tag or docker.docker_image(name, by_tag=True)
127
128 buf = BytesIO()
129 docker.stream_context_tar(".", image_dir, buf, args)
130 cmdargs = ["docker", "image", "build", "--no-cache", "-"]
131 if tag:
132 cmdargs.insert(-1, f"-t={tag}")
133 subprocess.run(cmdargs, input=buf.getvalue(), check=True)
134
135 msg = f"Successfully built {name}"
136 if tag:
137 msg += f" and tagged with {tag}"
138 print(msg)
139
140 if not tag or tag.endswith(":latest"):
141 print(DEPLOY_WARNING.format(image_dir=os.path.relpath(image_dir), image=name))
142
143
144 def load_image(url, imageName=None, imageTag=None):
145 """
146 Load docker image from URL as imageName:tag, if no imageName or tag is given
147 it will use whatever is inside the zstd compressed tarball.
148
149 Returns an object with properties 'image', 'tag' and 'layer'.
150 """
151 if isinstance(zstd, ImportError):
152 raise ImportError(
153 dedent(
154 """
155 zstandard is not installed! Use `pip install taskcluster-taskgraph[load-image]`
156 to use this feature.
157 """
158 )
159 ) from zstd
160
161 # If imageName is given and we don't have an imageTag
162 # we parse out the imageTag from imageName, or default it to 'latest'
163 # if no imageName and no imageTag is given, 'repositories' won't be rewritten
164 if imageName and not imageTag:
165 if ":" in imageName:
166 imageName, imageTag = imageName.split(":", 1)
167 else:
168 imageTag = "latest"
169
170 info = {}
171
172 def download_and_modify_image():
173 # This function downloads and edits the downloaded tar file on the fly.
174 # It emits chunked buffers of the edited tar file, as a generator.
175 print(f"Downloading from {url}")
176 # get_session() gets us a requests.Session set to retry several times.
177 req = get_session().get(url, stream=True)
178 req.raise_for_status()
179
180 with zstd.ZstdDecompressor().stream_reader(req.raw) as ifh: # type: ignore
181 tarin = tarfile.open(
182 mode="r|",
183 fileobj=ifh,
184 bufsize=zstd.DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE, # type: ignore
185 )
186
187 # Stream through each member of the downloaded tar file individually.
188 for member in tarin:
189 # Non-file members only need a tar header. Emit one.
190 if not member.isfile():
191 yield member.tobuf(tarfile.GNU_FORMAT)
192 continue
193
194 # Open stream reader for the member
195 reader = tarin.extractfile(member)
196
197 # If member is `repositories`, we parse and possibly rewrite the
198 # image tags.
199 if member.name == "repositories":
200 # Read and parse repositories
201 repos = json.loads(reader.read()) # type: ignore
202 reader.close() # type: ignore
203
204 # If there is more than one image or tag, we can't handle it
205 # here.
206 if len(repos.keys()) > 1:
207 raise Exception("file contains more than one image")
208 info["image"] = image = list(repos.keys())[0]
209 if len(repos[image].keys()) > 1:
210 raise Exception("file contains more than one tag")
211 info["tag"] = tag = list(repos[image].keys())[0]
212 info["layer"] = layer = repos[image][tag]
213
214 # Rewrite the repositories file
215 data = json.dumps({imageName or image: {imageTag or tag: layer}})
216 reader = BytesIO(data.encode("utf-8"))
217 member.size = len(data)
218
219 # Emit the tar header for this member.
220 yield member.tobuf(tarfile.GNU_FORMAT)
221 # Then emit its content.
222 remaining = member.size
223 while remaining:
224 length = min(remaining, zstd.DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE) # type: ignore
225 buf = reader.read(length) # type: ignore
226 remaining -= len(buf)
227 yield buf
228 # Pad to fill a 512 bytes block, per tar format.
229 remainder = member.size % 512
230 if remainder:
231 yield ("\0" * (512 - remainder)).encode("utf-8")
232
233 reader.close() # type: ignore
234
235 subprocess.run(
236 ["docker", "image", "load"], input=b"".join(download_and_modify_image())
237 )
238
239 # Check that we found a repositories file
240 if not info.get("image") or not info.get("tag") or not info.get("layer"):
241 raise Exception("No repositories file found!")
242
243 return info
244
245
246 def _index(l: List, s: str) -> Optional[int]:
247 try:
248 return l.index(s)
249 except ValueError:
250 pass
251
252
253 def load_task(task_id, remove=True, user=None):
254 user = user or "worker"
255 task_def = get_task_definition(task_id)
256
257 if (
258 impl := task_def.get("tags", {}).get("worker-implementation")
259 ) != "docker-worker":
260 print(f"Tasks with worker-implementation '{impl}' are not supported!")
261 return 1
262
263 command = task_def["payload"].get("command")
264 if not command or not command[0].endswith("run-task"):
265 print("Only tasks using `run-task` are supported!")
266 return 1
267
268 # Remove the payload section of the task's command. This way run-task will
269 # set up the task (clone repos, download fetches, etc) but won't actually
270 # start the core of the task. Instead we'll drop the user into an interactive
271 # shell and provide the ability to resume the task command.
272 task_command = None
273 if index := _index(command, "--"):
274 task_command = shlex.join(command[index + 1 :])
275 # I attempted to run the interactive bash shell here, but for some
276 # reason when executed through `run-task`, the interactive shell
277 # doesn't work well. There's no shell prompt on newlines and tab
278 # completion doesn't work. That's why it is executed outside of
279 # `run-task` below, and why we need to parse `--task-cwd`.
280 command[index + 1 :] = [
281 "echo",
282 "Task setup complete!\nRun `exec-task` to execute the task's command.",
283 ]
284
285 # Parse `--task-cwd` so we know where to execute the task's command later.
286 if index := _index(command, "--task-cwd"):
287 task_cwd = command[index + 1]
288 else:
289 for arg in command:
290 if arg.startswith("--task-cwd="):
291 task_cwd = arg.split("=", 1)[1]
292 break
293 else:
294 task_cwd = "$TASK_WORKDIR"
295
296 image_task_id = task_def["payload"]["image"]["taskId"]
297 image_tag = load_image_by_task_id(image_task_id)
298
299 # Set some env vars the worker would normally set.
300 env = {
301 "RUN_ID": "0",
302 "TASK_GROUP_ID": task_def.get("taskGroupId", ""),
303 "TASK_ID": task_id,
304 "TASKCLUSTER_ROOT_URL": get_root_url(False),
305 }
306 # Add the task's environment variables.
307 env.update(task_def["payload"].get("env", {}))
308
309 envfile = None
310 initfile = None
311 try:
312 command = [
313 "docker",
314 "run",
315 "-it",
316 image_tag,
317 "bash",
318 "-c",
319 f"{shlex.join(command)} && cd $TASK_WORKDIR && su -p {user}",
320 ]
321
322 if remove:
323 command.insert(2, "--rm")
324
325 if env:
326 envfile = tempfile.NamedTemporaryFile("w+", delete=False)
327 envfile.write("\n".join([f"{k}={v}" for k, v in env.items()]))
328 envfile.close()
329
330 command.insert(2, f"--env-file={envfile.name}")
331
332 if task_command:
333 initfile = tempfile.NamedTemporaryFile("w+", delete=False)
334 initfile.write(
335 dedent(
336 f"""
337 function exec-task() {{
338 echo "Starting task: {task_command}";
339 pushd {task_cwd};
340 {task_command};
341 popd
342 }}
343 """
344 ).lstrip()
345 )
346 initfile.close()
347
348 command[2:2] = ["-v", f"{initfile.name}:/builds/worker/.bashrc"]
349
350 proc = subprocess.run(command)
351 finally:
352 if envfile:
353 os.remove(envfile.name)
354
355 if initfile:
356 os.remove(initfile.name)
357
358 return proc.returncode