Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/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 functools
7 import hashlib
8 import io
9 import os
10 import re
11 from typing import Optional
12
13 from taskgraph.util.archive import create_tar_from_files, gzip_compressor
14
15 IMAGE_DIR = os.path.join(".", "taskcluster", "docker")
16
17 from .yaml import load_yaml
18
19
20 def docker_image(name: str, by_tag: bool = False) -> Optional[str]:
21 """
22 Resolve in-tree prebuilt docker image to ``<registry>/<repository>@sha256:<digest>``,
23 or ``<registry>/<repository>:<tag>`` if `by_tag` is `True`.
24
25 Args:
26 name (str): The image to build.
27 by_tag (bool): If True, will apply a tag based on VERSION file.
28 Otherwise will apply a hash based on HASH file.
29 Returns:
30 Optional[str]: Image if it can be resolved, otherwise None.
31 """
32 try:
33 with open(os.path.join(IMAGE_DIR, name, "REGISTRY")) as f:
34 registry = f.read().strip()
35 except OSError:
36 try:
37 with open(os.path.join(IMAGE_DIR, "REGISTRY")) as f:
38 registry = f.read().strip()
39 except OSError:
40 return None
41
42 if not by_tag:
43 hashfile = os.path.join(IMAGE_DIR, name, "HASH")
44 try:
45 with open(hashfile) as f:
46 return f"{registry}/{name}@{f.read().strip()}"
47 except OSError:
48 return None
49
50 try:
51 with open(os.path.join(IMAGE_DIR, name, "VERSION")) as f:
52 tag = f.read().strip()
53 except OSError:
54 tag = "latest"
55 return f"{registry}/{name}:{tag}"
56
57
58 class VoidWriter:
59 """A file object with write capabilities that does nothing with the written
60 data."""
61
62 def write(self, buf):
63 pass
64
65
66 def generate_context_hash(topsrcdir, image_path, args=None):
67 """Generates a sha256 hash for context directory used to build an image."""
68
69 return stream_context_tar(topsrcdir, image_path, VoidWriter(), args=args)
70
71
72 class HashingWriter:
73 """A file object with write capabilities that hashes the written data at
74 the same time it passes down to a real file object."""
75
76 def __init__(self, writer):
77 self._hash = hashlib.sha256()
78 self._writer = writer
79 self._written = 0
80
81 def write(self, buf):
82 self._hash.update(buf)
83 self._writer.write(buf)
84 self._written += len(buf)
85
86 def tell(self):
87 return self._written
88
89 def hexdigest(self):
90 return self._hash.hexdigest()
91
92
93 def create_context_tar(topsrcdir, context_dir, out_path, args=None):
94 """Create a context tarball.
95
96 A directory ``context_dir`` containing a Dockerfile will be assembled into
97 a gzipped tar file at ``out_path``.
98
99 We also scan the source Dockerfile for special syntax that influences
100 context generation.
101
102 If a line in the Dockerfile has the form ``# %include <path>``,
103 the relative path specified on that line will be matched against
104 files in the source repository and added to the context under the
105 path ``topsrcdir/``. If an entry is a directory, we add all files
106 under that directory.
107
108 If a line in the Dockerfile has the form ``# %ARG <name>``, occurrences of
109 the string ``$<name>`` in subsequent lines are replaced with the value
110 found in the ``args`` argument. Exception: this doesn't apply to VOLUME
111 definitions.
112
113 Returns the SHA-256 hex digest of the created archive.
114 """
115 with open(out_path, "wb") as fh:
116 with gzip_compressor(fh, filename=os.path.basename(out_path)) as gf:
117 return stream_context_tar(topsrcdir, context_dir, gf, args=args)
118
119
120 RUN_TASK_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), "run-task")
121 RUN_TASK_FILES = {
122 f"run-task/{path}": os.path.join(RUN_TASK_ROOT, path)
123 for path in [
124 "run-task",
125 "fetch-content",
126 "hgrc",
127 "robustcheckout.py",
128 ]
129 }
130 RUN_TASK_SNIPPET = [
131 "COPY run-task/run-task /usr/local/bin/run-task\n",
132 "COPY run-task/fetch-content /usr/local/bin/fetch-content\n",
133 "COPY run-task/robustcheckout.py /usr/local/mercurial/robustcheckout.py\n"
134 "COPY run-task/hgrc /etc/mercurial/hgrc.d/mozilla.rc\n",
135 ]
136
137
138 def stream_context_tar(topsrcdir, context_dir, out_file, args=None):
139 """Like create_context_tar, but streams the tar file to the `out_file` file
140 object."""
141 archive_files = {}
142 replace = []
143 content = []
144
145 topsrcdir = os.path.abspath(topsrcdir)
146 context_dir = os.path.join(topsrcdir, context_dir)
147
148 for root, dirs, files in os.walk(context_dir):
149 for f in files:
150 source_path = os.path.join(root, f)
151 archive_path = source_path[len(context_dir) + 1 :]
152 archive_files[archive_path] = source_path
153
154 # Parse Dockerfile for special syntax of extra files to include.
155 content = []
156 with open(os.path.join(context_dir, "Dockerfile")) as fh:
157 for line in fh:
158 if line.startswith("# %ARG"):
159 p = line[len("# %ARG ") :].strip()
160 if not args or p not in args:
161 raise Exception(f"missing argument: {p}")
162 replace.append((re.compile(rf"\${p}\b"), args[p]))
163 continue
164
165 for regexp, s in replace:
166 line = re.sub(regexp, s, line)
167
168 content.append(line)
169
170 if not line.startswith("# %include"):
171 continue
172
173 if line.strip() == "# %include-run-task":
174 content.extend(RUN_TASK_SNIPPET)
175 archive_files.update(RUN_TASK_FILES)
176 continue
177
178 p = line[len("# %include ") :].strip()
179 if os.path.isabs(p):
180 raise Exception(f"extra include path cannot be absolute: {p}")
181
182 fs_path = os.path.normpath(os.path.join(topsrcdir, p))
183 # Check for filesystem traversal exploits.
184 if not fs_path.startswith(topsrcdir):
185 raise Exception(f"extra include path outside topsrcdir: {p}")
186
187 if not os.path.exists(fs_path):
188 raise Exception(f"extra include path does not exist: {p}")
189
190 if os.path.isdir(fs_path):
191 for root, dirs, files in os.walk(fs_path):
192 for f in files:
193 source_path = os.path.join(root, f)
194 rel = source_path[len(fs_path) + 1 :]
195 archive_path = os.path.join("topsrcdir", p, rel)
196 archive_files[archive_path] = source_path
197 else:
198 archive_path = os.path.join("topsrcdir", p)
199 archive_files[archive_path] = fs_path
200
201 archive_files["Dockerfile"] = io.BytesIO("".join(content).encode("utf-8"))
202
203 writer = HashingWriter(out_file)
204 create_tar_from_files(writer, archive_files)
205 return writer.hexdigest()
206
207
208 @functools.lru_cache(maxsize=None)
209 def image_paths():
210 """Return a map of image name to paths containing their Dockerfile."""
211 config = load_yaml("taskcluster", "kinds", "docker-image", "kind.yml")
212 return {
213 k: os.path.join(IMAGE_DIR, v.get("definition", k))
214 for k, v in config["tasks"].items()
215 }
216
217
218 def image_path(name):
219 paths = image_paths()
220 if name in paths:
221 return paths[name]
222 return os.path.join(IMAGE_DIR, name)
223
224
225 @functools.lru_cache(maxsize=None)
226 def parse_volumes(image):
227 """Parse VOLUME entries from a Dockerfile for an image."""
228 volumes = set()
229
230 path = image_path(image)
231
232 with open(os.path.join(path, "Dockerfile"), "rb") as fh:
233 for line in fh:
234 line = line.strip()
235 # We assume VOLUME definitions don't use %ARGS.
236 if not line.startswith(b"VOLUME "):
237 continue
238
239 v = line.split(None, 1)[1]
240 if v.startswith(b"["):
241 raise ValueError(
242 "cannot parse array syntax for VOLUME; convert to multiple entries"
243 )
244
245 volumes |= {volume.decode("utf-8") for volume in v.split()}
246
247 return volumes