@@ -1,4 +1,5 @@
11{
2+ symlinkJoin,
23 coreutils,
34 docker,
45 e2fsprogs,
@@ -19,6 +20,7 @@
1920 utillinux,
2021 vmTools,
2122 writeReferencesToFile,
23+ referencesByPopularity,
2224 writeScript,
2325 writeText,
2426}:
@@ -272,6 +274,81 @@ rec {
272274 perl ${pkgs.pathsFromGraph} closure-* > $out/storePaths
273275 '';
274276
277+ # Create $maxLayers worth of Docker Layers, one layer per store path
278+ # unless there are more paths than $maxLayers. In that case, create
279+ # $maxLayers-1 for the most popular layers, and smush the remainaing
280+ # store paths in to one final layer.
281+ mkManyPureLayers = {
282+ name,
283+ # Files to add to the layer.
284+ closure,
285+ configJson,
286+ # Docker has a 42-layer maximum, we pick 24 to ensure there is plenty
287+ # of room for extension
288+ maxLayers ? 24
289+ }:
290+ runCommand "${name}-granular-docker-layers" {
291+ inherit maxLayers;
292+ paths = referencesByPopularity closure;
293+ buildInputs = [ jshon rsync tarsum ];
294+ enableParallelBuilding = true;
295+ }
296+ ''
297+ # Delete impurities for store path layers, so they don't get
298+ # shared and taint other projects.
299+ cat ${configJson} \
300+ | jshon -d config \
301+ | jshon -s "1970-01-01T00:00:01Z" -i created > generic.json
302+
303+ # WARNING!
304+ # The following code is fiddly w.r.t. ensuring every layer is
305+ # created, and that no paths are missed. If you change the
306+ # following head and tail call lines, double-check that your
307+ # code behaves properly when the number of layers equals:
308+ # maxLayers-1, maxLayers, and maxLayers+1
309+ head -n $((maxLayers - 1)) $paths | cat -n | xargs -P$NIX_BUILD_CORES -n2 ${./store-path-to-layer.sh}
310+ if [ $(cat $paths | wc -l) -ge $maxLayers ]; then
311+ tail -n+$maxLayers $paths | xargs ${./store-path-to-layer.sh} $maxLayers
312+ fi
313+
314+ echo "Finished building layer '$name'"
315+
316+ mv ./layers $out
317+ '';
318+
319+ # Create a "Customisation" layer which adds symlinks at the root of
320+ # the image to the root paths of the closure. Also add the config
321+ # data like what command to run and the environment to run it in.
322+ mkCustomisationLayer = {
323+ name,
324+ # Files to add to the layer.
325+ contents,
326+ baseJson,
327+ uid ? 0, gid ? 0,
328+ }:
329+ runCommand "${name}-customisation-layer" {
330+ buildInputs = [ jshon rsync tarsum ];
331+ }
332+ ''
333+ cp -r ${contents}/ ./layer
334+
335+ # Tar up the layer and throw it into 'layer.tar'.
336+ echo "Packing layer..."
337+ mkdir $out
338+ tar -C layer --sort=name --mtime="@$SOURCE_DATE_EPOCH" --owner=${toString uid} --group=${toString gid} -cf $out/layer.tar .
339+
340+ # Compute a checksum of the tarball.
341+ echo "Computing layer checksum..."
342+ tarhash=$(tarsum < $out/layer.tar)
343+
344+ # Add a 'checksum' field to the JSON, with the value set to the
345+ # checksum of the tarball.
346+ cat ${baseJson} | jshon -s "$tarhash" -i checksum > $out/json
347+
348+ # Indicate to docker that we're using schema version 1.0.
349+ echo -n "1.0" > $out/VERSION
350+ '';
351+
275352 # Create a "layer" (set of files).
276353 mkPureLayer = {
277354 # Name of the layer
@@ -413,6 +490,104 @@ rec {
413490 '';
414491 };
415492
493+ buildLayeredImage = {
494+ # Image Name
495+ name,
496+ # Image tag, the Nix's output hash will be used if null
497+ tag ? null,
498+ # Files to put on the image (a nix store path or list of paths).
499+ contents ? [],
500+ # Docker config; e.g. what command to run on the container.
501+ config ? {},
502+ # Time of creation of the image. Passing "now" will make the
503+ # created date be the time of building.
504+ created ? "1970-01-01T00:00:01Z",
505+ # Docker's lowest maximum layer limit is 42-layers for an old
506+ # version of the AUFS graph driver. We pick 24 to ensure there is
507+ # plenty of room for extension. I believe the actual maximum is
508+ # 128.
509+ maxLayers ? 24
510+ }:
511+ let
512+ uid = 0;
513+ gid = 0;
514+ baseName = baseNameOf name;
515+ contentsEnv = symlinkJoin { name = "bulk-layers"; paths = (if builtins.isList contents then contents else [ contents ]); };
516+
517+ configJson = let
518+ pure = writeText "${baseName}-config.json" (builtins.toJSON {
519+ inherit created config;
520+ architecture = "amd64";
521+ os = "linux";
522+ });
523+ impure = runCommand "${baseName}-standard-dynamic-date.json"
524+ { buildInputs = [ jq ]; }
525+ ''
526+ jq ".created = \"$(TZ=utc date --iso-8601="seconds")\"" ${pure} > $out
527+ '';
528+ in if created == "now" then impure else pure;
529+
530+ bulkLayers = mkManyPureLayers {
531+ name = baseName;
532+ closure = writeText "closure" "${contentsEnv} ${configJson}";
533+ # One layer will be taken up by the customisationLayer, so
534+ # take up one less.
535+ maxLayers = maxLayers - 1;
536+ inherit configJson;
537+ };
538+ customisationLayer = mkCustomisationLayer {
539+ name = baseName;
540+ contents = contentsEnv;
541+ baseJson = configJson;
542+ inherit uid gid;
543+ };
544+ result = runCommand "docker-image-${baseName}.tar.gz" {
545+ buildInputs = [ jshon pigz coreutils findutils jq ];
546+ # Image name and tag must be lowercase
547+ imageName = lib.toLower name;
548+ imageTag = if tag == null then "" else lib.toLower tag;
549+ baseJson = configJson;
550+ } ''
551+ ${lib.optionalString (tag == null) ''
552+ outName="$(basename "$out")"
553+ outHash=$(echo "$outName" | cut -d - -f 1)
554+
555+ imageTag=$outHash
556+ ''}
557+
558+ find ${bulkLayers} -mindepth 1 -maxdepth 1 | sort -t/ -k5 -n > layer-list
559+ echo ${customisationLayer} >> layer-list
560+
561+ mkdir image
562+ imageJson=$(cat ${configJson} | jq ". + {\"rootfs\": {\"diff_ids\": [], \"type\": \"layers\"}}")
563+ manifestJson=$(jq -n "[{\"RepoTags\":[\"$imageName:$imageTag\"]}]")
564+ for layer in $(cat layer-list); do
565+ layerChecksum=$(sha256sum $layer/layer.tar | cut -d ' ' -f1)
566+ layerID=$(sha256sum "$layer/json" | cut -d ' ' -f 1)
567+ ln -s "$layer" "./image/$layerID"
568+
569+ manifestJson=$(echo "$manifestJson" | jq ".[0].Layers |= [\"$layerID/layer.tar\"] + .")
570+ imageJson=$(echo "$imageJson" | jq ".history |= [{\"created\": \"$(jq -r .created ${configJson})\"}] + .")
571+ imageJson=$(echo "$imageJson" | jq ".rootfs.diff_ids |= [\"sha256:$layerChecksum\"] + .")
572+ done
573+ imageJsonChecksum=$(echo "$imageJson" | sha256sum | cut -d ' ' -f1)
574+ echo "$imageJson" > "image/$imageJsonChecksum.json"
575+ manifestJson=$(echo "$manifestJson" | jq ".[0].Config = \"$imageJsonChecksum.json\"")
576+ echo "$manifestJson" > image/manifest.json
577+
578+ jshon -n object \
579+ -n object -s "$layerID" -i "$imageTag" \
580+ -i "$imageName" > image/repositories
581+
582+ echo "Cooking the image..."
583+ tar -C image --dereference --hard-dereference --sort=name --mtime="@$SOURCE_DATE_EPOCH" --owner=0 --group=0 --mode=a-w --xform s:'^./':: -c . | pigz -nT > $out
584+
585+ echo "Finished."
586+ '';
587+
588+ in
589+ result;
590+
416591 # 1. extract the base image
417592 # 2. create the layer
418593 # 3. add layer deps to the layer itself, diffing with the base image