stream_layered_image.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. #! /nix/store/nki9ywqzbvz68vr75kn2r7g1q84f5agy-python3-3.9.6/bin/python
  2. """
  3. This script generates a Docker image from a set of store paths. Uses
  4. Docker Image Specification v1.2 as reference [1].
  5. It expects a JSON file with the following properties and writes the
  6. image as an uncompressed tarball to stdout:
  7. * "architecture", "config", "os", "created", "repo_tag" correspond to
  8. the fields with the same name on the image spec [2].
  9. * "created" can be "now".
  10. * "created" is also used as mtime for files added to the image.
  11. * "store_layers" is a list of layers in ascending order, where each
  12. layer is the list of store paths to include in that layer.
  13. The main challenge for this script to create the final image in a
  14. streaming fashion, without dumping any intermediate data to disk
  15. for performance.
  16. A docker image has each layer contents archived as separate tarballs,
  17. and they later all get enveloped into a single big tarball in a
  18. content addressed fashion. However, because how "tar" format works,
  19. we have to know about the name (which includes the checksum in our
  20. case) and the size of the tarball before we can start adding it to the
  21. outer tarball. We achieve that by creating the layer tarballs twice;
  22. on the first iteration we calculate the file size and the checksum,
  23. and on the second one we actually stream the contents. 'add_layer_dir'
  24. function does all this.
  25. [1]: https://github.com/moby/moby/blob/master/image/spec/v1.2.md
  26. [2]: https://github.com/moby/moby/blob/4fb59c20a4fb54f944fe170d0ff1d00eb4a24d6f/image/spec/v1.2.md#image-json-field-descriptions
  27. """ # noqa: E501
  28. import io
  29. import os
  30. import re
  31. import sys
  32. import json
  33. import hashlib
  34. import pathlib
  35. import tarfile
  36. import itertools
  37. import threading
  38. from datetime import datetime, timezone
  39. from collections import namedtuple
  40. def archive_paths_to(obj, paths, mtime):
  41. """
  42. Writes the given store paths as a tar file to the given stream.
  43. obj: Stream to write to. Should have a 'write' method.
  44. paths: List of store paths.
  45. """
  46. # gettarinfo makes the paths relative, this makes them
  47. # absolute again
  48. def append_root(ti):
  49. ti.name = "/" + ti.name
  50. return ti
  51. def apply_filters(ti):
  52. ti.mtime = mtime
  53. ti.uid = 0
  54. ti.gid = 0
  55. ti.uname = "root"
  56. ti.gname = "root"
  57. return ti
  58. def nix_root(ti):
  59. ti.mode = 0o0555 # r-xr-xr-x
  60. return ti
  61. def dir(path):
  62. ti = tarfile.TarInfo(path)
  63. ti.type = tarfile.DIRTYPE
  64. return ti
  65. with tarfile.open(fileobj=obj, mode="w|") as tar:
  66. # To be consistent with the docker utilities, we need to have
  67. # these directories first when building layer tarballs.
  68. tar.addfile(apply_filters(nix_root(dir("/gnu"))))
  69. tar.addfile(apply_filters(nix_root(dir("/gnu/store"))))
  70. for path in paths:
  71. path = pathlib.Path(path)
  72. if path.is_symlink():
  73. files = [path]
  74. else:
  75. files = itertools.chain([path], path.rglob("*"))
  76. for filename in sorted(files):
  77. ti = append_root(tar.gettarinfo(filename))
  78. # copy hardlinks as regular files
  79. if ti.islnk():
  80. ti.type = tarfile.REGTYPE
  81. ti.linkname = ""
  82. ti.size = filename.stat().st_size
  83. ti = apply_filters(ti)
  84. if ti.isfile():
  85. with open(filename, "rb") as f:
  86. tar.addfile(ti, f)
  87. else:
  88. tar.addfile(ti)
  89. class ExtractChecksum:
  90. """
  91. A writable stream which only calculates the final file size and
  92. sha256sum, while discarding the actual contents.
  93. """
  94. def __init__(self):
  95. self._digest = hashlib.sha256()
  96. self._size = 0
  97. def write(self, data):
  98. self._digest.update(data)
  99. self._size += len(data)
  100. def extract(self):
  101. """
  102. Returns: Hex-encoded sha256sum and size as a tuple.
  103. """
  104. return (self._digest.hexdigest(), self._size)
  105. FromImage = namedtuple("FromImage", ["tar", "manifest_json", "image_json"])
  106. # Some metadata for a layer
  107. LayerInfo = namedtuple("LayerInfo", ["size", "checksum", "path", "paths"])
  108. def load_from_image(from_image_str):
  109. """
  110. Loads the given base image, if any.
  111. from_image_str: Path to the base image archive.
  112. Returns: A 'FromImage' object with references to the loaded base image,
  113. or 'None' if no base image was provided.
  114. """
  115. if from_image_str is None:
  116. return None
  117. base_tar = tarfile.open(from_image_str)
  118. manifest_json_tarinfo = base_tar.getmember("manifest.json")
  119. with base_tar.extractfile(manifest_json_tarinfo) as f:
  120. manifest_json = json.load(f)
  121. image_json_tarinfo = base_tar.getmember(manifest_json[0]["Config"])
  122. with base_tar.extractfile(image_json_tarinfo) as f:
  123. image_json = json.load(f)
  124. return FromImage(base_tar, manifest_json, image_json)
  125. def add_base_layers(tar, from_image):
  126. """
  127. Adds the layers from the given base image to the final image.
  128. tar: 'tarfile.TarFile' object for new layers to be added to.
  129. from_image: 'FromImage' object with references to the loaded base image.
  130. """
  131. if from_image is None:
  132. print("No 'fromImage' provided", file=sys.stderr)
  133. return []
  134. layers = from_image.manifest_json[0]["Layers"]
  135. checksums = from_image.image_json["rootfs"]["diff_ids"]
  136. layers_checksums = zip(layers, checksums)
  137. for num, (layer, checksum) in enumerate(layers_checksums, start=1):
  138. layer_tarinfo = from_image.tar.getmember(layer)
  139. checksum = re.sub(r"^sha256:", "", checksum)
  140. tar.addfile(layer_tarinfo, from_image.tar.extractfile(layer_tarinfo))
  141. path = layer_tarinfo.path
  142. size = layer_tarinfo.size
  143. print("Adding base layer", num, "from", path, file=sys.stderr)
  144. yield LayerInfo(size=size, checksum=checksum, path=path, paths=[path])
  145. from_image.tar.close()
  146. def overlay_base_config(from_image, final_config):
  147. """
  148. Overlays the final image 'config' JSON on top of selected defaults from the
  149. base image 'config' JSON.
  150. from_image: 'FromImage' object with references to the loaded base image.
  151. final_config: 'dict' object of the final image 'config' JSON.
  152. """
  153. if from_image is None:
  154. return final_config
  155. base_config = from_image.image_json["config"]
  156. # Preserve environment from base image
  157. final_env = base_config.get("Env", []) + final_config.get("Env", [])
  158. if final_env:
  159. # Resolve duplicates (last one wins) and format back as list
  160. resolved_env = {entry.split("=", 1)[0]: entry for entry in final_env}
  161. final_config["Env"] = list(resolved_env.values())
  162. return final_config
  163. def add_layer_dir(tar, paths, store_dir, mtime):
  164. """
  165. Appends given store paths to a TarFile object as a new layer.
  166. tar: 'tarfile.TarFile' object for the new layer to be added to.
  167. paths: List of store paths.
  168. store_dir: the root directory of the nix store
  169. mtime: 'mtime' of the added files and the layer tarball.
  170. Should be an integer representing a POSIX time.
  171. Returns: A 'LayerInfo' object containing some metadata of
  172. the layer added.
  173. """
  174. invalid_paths = [i for i in paths if not i.startswith(store_dir)]
  175. assert len(invalid_paths) == 0, \
  176. f"Expecting absolute paths from {store_dir}, but got: {invalid_paths}"
  177. # First, calculate the tarball checksum and the size.
  178. extract_checksum = ExtractChecksum()
  179. archive_paths_to(
  180. extract_checksum,
  181. paths,
  182. mtime=mtime,
  183. )
  184. (checksum, size) = extract_checksum.extract()
  185. path = f"{checksum}/layer.tar"
  186. layer_tarinfo = tarfile.TarInfo(path)
  187. layer_tarinfo.size = size
  188. layer_tarinfo.mtime = mtime
  189. # Then actually stream the contents to the outer tarball.
  190. read_fd, write_fd = os.pipe()
  191. with open(read_fd, "rb") as read, open(write_fd, "wb") as write:
  192. def producer():
  193. archive_paths_to(
  194. write,
  195. paths,
  196. mtime=mtime,
  197. )
  198. write.close()
  199. # Closing the write end of the fifo also closes the read end,
  200. # so we don't need to wait until this thread is finished.
  201. #
  202. # Any exception from the thread will get printed by the default
  203. # exception handler, and the 'addfile' call will fail since it
  204. # won't be able to read required amount of bytes.
  205. threading.Thread(target=producer).start()
  206. tar.addfile(layer_tarinfo, read)
  207. return LayerInfo(size=size, checksum=checksum, path=path, paths=paths)
  208. def add_customisation_layer(target_tar, customisation_layer, mtime):
  209. """
  210. Adds the customisation layer as a new layer. This is layer is structured
  211. differently; given store path has the 'layer.tar' and corresponding
  212. sha256sum ready.
  213. tar: 'tarfile.TarFile' object for the new layer to be added to.
  214. customisation_layer: Path containing the layer archive.
  215. mtime: 'mtime' of the added layer tarball.
  216. """
  217. checksum_path = os.path.join(customisation_layer, "checksum")
  218. with open(checksum_path) as f:
  219. checksum = f.read().strip()
  220. assert len(checksum) == 64, f"Invalid sha256 at ${checksum_path}."
  221. layer_path = os.path.join(customisation_layer, "layer.tar")
  222. path = f"{checksum}/layer.tar"
  223. tarinfo = target_tar.gettarinfo(layer_path)
  224. tarinfo.name = path
  225. tarinfo.mtime = mtime
  226. with open(layer_path, "rb") as f:
  227. target_tar.addfile(tarinfo, f)
  228. return LayerInfo(
  229. size=None,
  230. checksum=checksum,
  231. path=path,
  232. paths=[customisation_layer]
  233. )
  234. def add_bytes(tar, path, content, mtime):
  235. """
  236. Adds a file to the tarball with given path and contents.
  237. tar: 'tarfile.TarFile' object.
  238. path: Path of the file as a string.
  239. content: Contents of the file.
  240. mtime: 'mtime' of the file. Should be an integer representing a POSIX time.
  241. """
  242. assert type(content) is bytes
  243. ti = tarfile.TarInfo(path)
  244. ti.size = len(content)
  245. ti.mtime = mtime
  246. tar.addfile(ti, io.BytesIO(content))
  247. def main():
  248. with open(sys.argv[1], "r") as f:
  249. conf = json.load(f)
  250. created = (
  251. datetime.now(tz=timezone.utc)
  252. if conf["created"] == "now"
  253. else datetime.fromisoformat(conf["created"])
  254. )
  255. mtime = int(created.timestamp())
  256. store_dir = conf["store_dir"]
  257. from_image = load_from_image(conf["from_image"])
  258. with tarfile.open(mode="w|", fileobj=sys.stdout.buffer) as tar:
  259. layers = []
  260. layers.extend(add_base_layers(tar, from_image))
  261. start = len(layers) + 1
  262. for num, store_layer in enumerate(conf["store_layers"], start=start):
  263. print("Creating layer", num, "from paths:", store_layer,
  264. file=sys.stderr)
  265. info = add_layer_dir(tar, store_layer, store_dir, mtime=mtime)
  266. layers.append(info)
  267. print("Adding manifests...", file=sys.stderr)
  268. image_json = {
  269. "created": datetime.isoformat(created),
  270. "architecture": conf["architecture"],
  271. "os": "linux",
  272. "config": overlay_base_config(from_image, conf["config"]),
  273. "rootfs": {
  274. "diff_ids": [f"sha256:{layer.checksum}" for layer in layers],
  275. "type": "layers",
  276. },
  277. "history": [
  278. {
  279. "created": datetime.isoformat(created),
  280. "comment": f"store paths: {layer.paths}"
  281. }
  282. for layer in layers
  283. ],
  284. }
  285. image_json = json.dumps(image_json, indent=4).encode("utf-8")
  286. image_json_checksum = hashlib.sha256(image_json).hexdigest()
  287. image_json_path = f"{image_json_checksum}.json"
  288. add_bytes(tar, image_json_path, image_json, mtime=mtime)
  289. manifest_json = [
  290. {
  291. "Config": image_json_path,
  292. "RepoTags": [conf["repo_tag"]],
  293. "Layers": [layer.path for layer in layers],
  294. }
  295. ]
  296. manifest_json = json.dumps(manifest_json, indent=4).encode("utf-8")
  297. add_bytes(tar, "manifest.json", manifest_json, mtime=mtime)
  298. print("Done.", file=sys.stderr)
  299. if __name__ == "__main__":
  300. main()