git.iko.soy/typeable/nixpkgs
on master help sign in
dockerTools.buildLayeredImage: init

Create a many-layered Docker Image. Implements much less than buildImage: - Doesn't support specific uids/gids - Doesn't support runninng commands after building - Doesn't require qemu - Doesn't create mutable copies of the files in the path - Doesn't support parent images If you want those feature, I recommend using buildLayeredImage as an input to buildImage. Notably, it does support: - Caching low level, common paths based on a graph traversial algorithm, see referencesByPopularity in 0a80233487993256e811f566b1c80a40394c03d6 - Configurable number of layers. If you're not using AUFS or not extending the image, you can specify a larger number of layers at build time: pkgs.dockerTools.buildLayeredImage { name = "hello"; maxLayers = 128; config.Cmd = [ "${pkgs.gitFull}/bin/git" ]; }; - Parallelized creation of the layers, improving build speed. - The contents of the image includes the closure of the configuration, so you don't have to specify paths in contents and config. With buildImage, paths referred to by the config were not included automatically in the image. Thus, if you wanted to call Git, you had to specify it twice: pkgs.dockerTools.buildImage { name = "hello"; contents = [ pkgs.gitFull ]; config.Cmd = [ "${pkgs.gitFull}/bin/git" ]; }; buildLayeredImage on the other hand includes the runtime closure of the config when calculating the contents of the image: pkgs.dockerTools.buildImage { name = "hello"; config.Cmd = [ "${pkgs.gitFull}/bin/git" ]; }; Minor Problems - If any of the store paths change, every layer will be rebuilt in the nix-build. However, beacuse the layers are bit-for-bit reproducable, when these images are loaded in to Docker they will match existing layers and not be imported or uploaded twice. Common Questions - Aren't Docker layers ordered? No. People who have used a Dockerfile before assume Docker's Layers are inherently ordered. However, this is not true -- Docker layers are content-addressable and are not explicitly layered until they are composed in to an Image. - What happens if I have more than maxLayers of store paths? The first (maxLayers-2) most "popular" paths will have their own individual layers, then layer #(maxLayers-1) will contain all the remaining "unpopular" paths, and finally layer #(maxLayers) will contain the Image configuration.

commit4fe900619080f0b1a804abbccaab500d819ead10 authorGraham Christensen <graham.christensen@target.com> dateTue 25 Sep 2018, 10:53 (8 years ago) parentfd04517
3 files changed+376
doc/functions.xml+177 pkgs/build-support/docker/default.nix+175 pkgs/build-support/docker/store-path-to-layer.sh+24
doc/functions.xml+177
@@ -682,6 +682,183 @@ hello latest de2bf4786de6 About a minute ago 25.2MB
682682 </example>
683683 </section>
684684
685+ <section xml:id="ssec-pkgs-dockerTools-buildLayeredImage">
686+ <title>buildLayeredImage</title>
687+
688+ <para>
689+ Create a Docker image with many of the store paths being on their own layer
690+ to improve sharing between images.
691+ </para>
692+
693+ <variablelist>
694+ <varlistentry>
695+ <term>
696+ <varname>name</varname>
697+ </term>
698+ <listitem>
699+ <para>
700+ The name of the resulting image.
701+ </para>
702+ </listitem>
703+ </varlistentry>
704+ <varlistentry>
705+ <term>
706+ <varname>tag</varname> <emphasis>optional</emphasis>
707+ </term>
708+ <listitem>
709+ <para>
710+ Tag of the generated image.
711+ </para>
712+ <para>
713+ <emphasis>Default:</emphasis> the output path's hash
714+ </para>
715+ </listitem>
716+ </varlistentry>
717+ <varlistentry>
718+ <term>
719+ <varname>contents</varname> <emphasis>optional</emphasis>
720+ </term>
721+ <listitem>
722+ <para>
723+ Top level paths in the container. Either a single derivation, or a list
724+ of derivations.
725+ </para>
726+ <para>
727+ <emphasis>Default:</emphasis> <literal>[]</literal>
728+ </para>
729+ </listitem>
730+ </varlistentry>
731+ <varlistentry>
732+ <term>
733+ <varname>config</varname> <emphasis>optional</emphasis>
734+ </term>
735+ <listitem>
736+ <para>
737+ Run-time configuration of the container. A full list of the options are
738+ available at in the
739+ <link xlink:href="https://github.com/moby/moby/blob/master/image/spec/v1.2.md#image-json-field-descriptions">
740+ Docker Image Specification v1.2.0 </link>.
741+ </para>
742+ <para>
743+ <emphasis>Default:</emphasis> <literal>{}</literal>
744+ </para>
745+ </listitem>
746+ </varlistentry>
747+ <varlistentry>
748+ <term>
749+ <varname>created</varname> <emphasis>optional</emphasis>
750+ </term>
751+ <listitem>
752+ <para>
753+ Date and time the layers were created. Follows the same
754+ <literal>now</literal> exception supported by
755+ <literal>buildImage</literal>.
756+ </para>
757+ <para>
758+ <emphasis>Default:</emphasis> <literal>1970-01-01T00:00:01Z</literal>
759+ </para>
760+ </listitem>
761+ </varlistentry>
762+ <varlistentry>
763+ <term>
764+ <varname>maxLayers</varname> <emphasis>optional</emphasis>
765+ </term>
766+ <listitem>
767+ <para>
768+ Maximum number of layers to create.
769+ </para>
770+ <para>
771+ <emphasis>Default:</emphasis> <literal>24</literal>
772+ </para>
773+ </listitem>
774+ </varlistentry>
775+ </variablelist>
776+
777+ <section xml:id="dockerTools-buildLayeredImage-arg-contents">
778+ <title>Behavior of <varname>contents</varname> in the final image</title>
779+
780+ <para>
781+ Each path directly listed in <varname>contents</varname> will have a
782+ symlink in the root of the image.
783+ </para>
784+
785+ <para>
786+ For example:
787+<programlisting><![CDATA[
788+pkgs.dockerTools.buildLayeredImage {
789+ name = "hello";
790+ contents = [ pkgs.hello ];
791+}
792+]]></programlisting>
793+ will create symlinks for all the paths in the <literal>hello</literal>
794+ package:
795+<screen><![CDATA[
796+/bin/hello -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/bin/hello
797+/share/info/hello.info -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/share/info/hello.info
798+/share/locale/bg/LC_MESSAGES/hello.mo -> /nix/store/h1zb1padqbbb7jicsvkmrym3r6snphxg-hello-2.10/share/locale/bg/LC_MESSAGES/hello.mo
799+]]></screen>
800+ </para>
801+ </section>
802+
803+ <section xml:id="dockerTools-buildLayeredImage-arg-config">
804+ <title>Automatic inclusion of <varname>config</varname> references</title>
805+
806+ <para>
807+ The closure of <varname>config</varname> is automatically included in the
808+ closure of the final image.
809+ </para>
810+
811+ <para>
812+ This is different from <function>pkgs.dockerTools.buildImage</function>
813+ which does <emphasis>not</emphasis> automatically include the
814+ configuration's closure.
815+ </para>
816+
817+ <para>
818+ This allows you to make very simple Docker images with very little code.
819+ This container will start up and run <command>hello</command>:
820+<programlisting><![CDATA[
821+pkgs.dockerTools.buildLayeredImage {
822+ name = "hello";
823+ config.Cmd = [ "${pkgs.hello}/bin/hello" ];
824+}
825+]]></programlisting>
826+ </para>
827+ </section>
828+
829+ <section xml:id="dockerTools-buildLayeredImage-arg-maxLayers">
830+ <title>Adjusting <varname>maxLayers</varname></title>
831+
832+ <para>
833+ Increasing the <varname>maxLayers</varname> increases the number of layers
834+ which have a chance to be shared between different images.
835+ </para>
836+
837+ <para>
838+ Modern Docker installations support up to 128 layers, however older
839+ versions support as few as 42.
840+ </para>
841+
842+ <para>
843+ If the produced image will not be extended by other Docker builds, it is
844+ safe to set <varname>maxLayers</varname> to <literal>128</literal>.
845+ However it will be impossible to extend the image further.
846+ </para>
847+
848+ <para>
849+ The first (<literal>maxLayers-2</literal>) most "popular" paths will have
850+ their own individual layers, then layer #<literal>maxLayers-1</literal>
851+ will contain all the remaining "unpopular" paths, and finally layer
852+ #<literal>maxLayers</literal> will contain the Image configuration.
853+ </para>
854+
855+ <para>
856+ Docker's Layers are not inherently ordered, they are content-addressable
857+ and are not explicitly layered until they are composed in to an Image.
858+ </para>
859+ </section>
860+ </section>
861+
685862 <section xml:id="ssec-pkgs-dockerTools-fetchFromRegistry">
686863 <title>pullImage</title>
687864
pkgs/build-support/docker/default.nix+175
@@ -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
pkgs/build-support/docker/store-path-to-layer.shnew file+24
@@ -0,0 +1,24 @@
1+#!/bin/sh
2+
3+set -eu
4+
5+layerNumber=$1
6+shift
7+
8+layerPath="./layers/$layerNumber"
9+echo "Creating layer #$layerNumber for $@"
10+
11+mkdir -p "$layerPath"
12+tar -rpf "$layerPath/layer.tar" --hard-dereference --sort=name \
13+ --mtime="@$SOURCE_DATE_EPOCH" \
14+ --owner=0 --group=0 "$@"
15+
16+# Compute a checksum of the tarball.
17+tarhash=$(tarsum < $layerPath/layer.tar)
18+
19+# Add a 'checksum' field to the JSON, with the value set to the
20+# checksum of the tarball.
21+cat ./generic.json | jshon -s "$tarhash" -i checksum > $layerPath/json
22+
23+# Indicate to docker that we're using schema version 1.0.
24+echo -n "1.0" > $layerPath/VERSION