git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #47411 from graham-at-target/multi-layered-images-crafted

Multi-Layered Docker Images

commit56b4db9710ffddfe6efcf4c153123725e0f2aa2c authorlewo <lewo@abesis.fr> dateMon 1 Oct 2018, 09:48 (8 years ago) parentc417b26fb2d153
8 files changed+926−6
doc/functions.xml+171 nixos/tests/docker-tools.nix+4 pkgs/build-support/docker/default.nix+183−6 pkgs/build-support/docker/examples.nix+7 pkgs/build-support/docker/store-path-to-layer.sh+24 pkgs/build-support/references-by-popularity/closure-graph.py+520 pkgs/build-support/references-by-popularity/default.nix+15 pkgs/top-level/all-packages.nix+2
doc/functions.xml+171
@@ -682,6 +682,177 @@ 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 allows you to make very simple Docker images with very little code.
813+ This container will start up and run <command>hello</command>:
814+<programlisting><![CDATA[
815+pkgs.dockerTools.buildLayeredImage {
816+ name = "hello";
817+ config.Cmd = [ "${pkgs.hello}/bin/hello" ];
818+}
819+]]></programlisting>
820+ </para>
821+ </section>
822+
823+ <section xml:id="dockerTools-buildLayeredImage-arg-maxLayers">
824+ <title>Adjusting <varname>maxLayers</varname></title>
825+
826+ <para>
827+ Increasing the <varname>maxLayers</varname> increases the number of layers
828+ which have a chance to be shared between different images.
829+ </para>
830+
831+ <para>
832+ Modern Docker installations support up to 128 layers, however older
833+ versions support as few as 42.
834+ </para>
835+
836+ <para>
837+ If the produced image will not be extended by other Docker builds, it is
838+ safe to set <varname>maxLayers</varname> to <literal>128</literal>.
839+ However it will be impossible to extend the image further.
840+ </para>
841+
842+ <para>
843+ The first (<literal>maxLayers-2</literal>) most "popular" paths will have
844+ their own individual layers, then layer #<literal>maxLayers-1</literal>
845+ will contain all the remaining "unpopular" paths, and finally layer
846+ #<literal>maxLayers</literal> will contain the Image configuration.
847+ </para>
848+
849+ <para>
850+ Docker's Layers are not inherently ordered, they are content-addressable
851+ and are not explicitly layered until they are composed in to an Image.
852+ </para>
853+ </section>
854+ </section>
855+
685856 <section xml:id="ssec-pkgs-dockerTools-fetchFromRegistry">
686857 <title>pullImage</title>
687858
nixos/tests/docker-tools.nix+4
@@ -58,5 +58,9 @@ import ./make-test.nix ({ pkgs, ... }: {
5858 # Ensure Docker images can use an unstable date
5959 $docker->succeed("docker load --input='${pkgs.dockerTools.examples.bash}'");
6060 $docker->succeed("[ '1970-01-01T00:00:01Z' != \"\$(docker inspect ${pkgs.dockerTools.examples.unstableDate.imageName} | ${pkgs.jq}/bin/jq -r .[].Created)\" ]");
61+
62+ # Ensure Layered Docker images work
63+ $docker->succeed("docker load --input='${pkgs.dockerTools.examples.layered-image}'");
64+ $docker->succeed("docker run --rm ${pkgs.dockerTools.examples.layered-image.imageName}");
6165 '';
6266})
pkgs/build-support/docker/default.nix+183−6
@@ -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}:
@@ -77,7 +79,9 @@ rec {
7779 ln -sT ${docker.src}/components/engine/pkg/tarsum src/github.com/docker/docker/pkg/tarsum
7880 go build
7981
80− cp tarsum $out
82+ mkdir -p $out/bin
83+
84+ cp tarsum $out/bin/
8185 '';
8286
8387 # buildEnv creates symlinks to dirs, which is hard to edit inside the overlay VM
@@ -270,6 +274,81 @@ rec {
270274 perl ${pkgs.pathsFromGraph} closure-* > $out/storePaths
271275 '';
272276
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+
273352 # Create a "layer" (set of files).
274353 mkPureLayer = {
275354 # Name of the layer
@@ -287,7 +366,7 @@ rec {
287366 }:
288367 runCommand "docker-layer-${name}" {
289368 inherit baseJson contents extraCommands;
290− buildInputs = [ jshon rsync ];
369+ buildInputs = [ jshon rsync tarsum ];
291370 }
292371 ''
293372 mkdir layer
@@ -314,11 +393,11 @@ rec {
314393
315394 # Compute a checksum of the tarball.
316395 echo "Computing layer checksum..."
317− tarsum=$(${tarsum} < $out/layer.tar)
396+ tarhash=$(tarsum < $out/layer.tar)
318397
319398 # Add a 'checksum' field to the JSON, with the value set to the
320399 # checksum of the tarball.
321− cat ${baseJson} | jshon -s "$tarsum" -i checksum > $out/json
400+ cat ${baseJson} | jshon -s "$tarhash" -i checksum > $out/json
322401
323402 # Indicate to docker that we're using schema version 1.0.
324403 echo -n "1.0" > $out/VERSION
@@ -402,8 +481,8 @@ rec {
402481
403482 # Compute the tar checksum and add it to the output json.
404483 echo "Computing checksum..."
405− ts=$(${tarsum} < $out/layer.tar)
406− cat ${baseJson} | jshon -s "$ts" -i checksum > $out/json
484+ tarhash=$(${tarsum}/bin/tarsum < $out/layer.tar)
485+ cat ${baseJson} | jshon -s "$tarhash" -i checksum > $out/json
407486 # Indicate to docker that we're using schema version 1.0.
408487 echo -n "1.0" > $out/VERSION
409488
@@ -411,6 +490,104 @@ rec {
411490 '';
412491 };
413492
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+
414591 # 1. extract the base image
415592 # 2. create the layer
416593 # 3. add layer deps to the layer itself, diffing with the base image
pkgs/build-support/docker/examples.nix+7
@@ -150,4 +150,11 @@ rec {
150150 contents = [ pkgs.coreutils ];
151151 created = "now";
152152 };
153+
154+ # 10. Create a layered image
155+ layered-image = pkgs.dockerTools.buildLayeredImage {
156+ name = "layered-image";
157+ tag = "latest";
158+ config.Cmd = [ "${pkgs.hello}/bin/hello" ];
159+ };
153160}
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
pkgs/build-support/references-by-popularity/closure-graph.pynew file+520
@@ -0,0 +1,520 @@
1+# IMPORTANT: Making changes?
2+#
3+# Validate your changes with python3 ./closure-graph.py --test
4+
5+
6+# Using a simple algorithm, convert the references to a path in to a
7+# sorted list of dependent paths based on how often they're referenced
8+# and how deep in the tree they live. Equally-"popular" paths are then
9+# sorted by name.
10+#
11+# The existing writeReferencesToFile prints the paths in a simple
12+# ascii-based sorting of the paths.
13+#
14+# Sorting the paths by graph improves the chances that the difference
15+# between two builds appear near the end of the list, instead of near
16+# the beginning. This makes a difference for Nix builds which export a
17+# closure for another program to consume, if that program implements its
18+# own level of binary diffing.
19+#
20+# For an example, Docker Images. If each store path is a separate layer
21+# then Docker Images can be very efficiently transfered between systems,
22+# and we get very good cache reuse between images built with the same
23+# version of Nixpkgs. However, since Docker only reliably supports a
24+# small number of layers (42) it is important to pick the individual
25+# layers carefully. By storing very popular store paths in the first 40
26+# layers, we improve the chances that the next Docker image will share
27+# many of those layers.*
28+#
29+# Given the dependency tree:
30+#
31+# A - B - C - D -\
32+# \ \ \ \
33+# \ \ \ \
34+# \ \ - E ---- F
35+# \- G
36+#
37+# Nodes which have multiple references are duplicated:
38+#
39+# A - B - C - D - F
40+# \ \ \
41+# \ \ \- E - F
42+# \ \
43+# \ \- E - F
44+# \
45+# \- G
46+#
47+# Each leaf node is now replaced by a counter defaulted to 1:
48+#
49+# A - B - C - D - (F:1)
50+# \ \ \
51+# \ \ \- E - (F:1)
52+# \ \
53+# \ \- E - (F:1)
54+# \
55+# \- (G:1)
56+#
57+# Then each leaf counter is merged with its parent node, replacing the
58+# parent node with a counter of 1, and each existing counter being
59+# incremented by 1. That is to say `- D - (F:1)` becomes `- (D:1, F:2)`:
60+#
61+# A - B - C - (D:1, F:2)
62+# \ \ \
63+# \ \ \- (E:1, F:2)
64+# \ \
65+# \ \- (E:1, F:2)
66+# \
67+# \- (G:1)
68+#
69+# Then each leaf counter is merged with its parent node again, merging
70+# any counters, then incrementing each:
71+#
72+# A - B - (C:1, D:2, E:2, F:5)
73+# \ \
74+# \ \- (E:1, F:2)
75+# \
76+# \- (G:1)
77+#
78+# And again:
79+#
80+# A - (B:1, C:2, D:3, E:4, F:8)
81+# \
82+# \- (G:1)
83+#
84+# And again:
85+#
86+# (A:1, B:2, C:3, D:4, E:5, F:9, G:2)
87+#
88+# and then paths have the following "popularity":
89+#
90+# A 1
91+# B 2
92+# C 3
93+# D 4
94+# E 5
95+# F 9
96+# G 2
97+#
98+# and the popularity contest would result in the paths being printed as:
99+#
100+# F
101+# E
102+# D
103+# C
104+# B
105+# G
106+# A
107+#
108+# * Note: People who have used a Dockerfile before assume Docker's
109+# Layers are inherently ordered. However, this is not true -- Docker
110+# layers are content-addressable and are not explicitly layered until
111+# they are composed in to an Image.
112+
113+import sys
114+import json
115+import unittest
116+
117+from pprint import pprint
118+from collections import defaultdict
119+
120+# Find paths in the original dataset which are never referenced by
121+# any other paths
122+def find_roots(closures):
123+ roots = [];
124+
125+ for closure in closures:
126+ path = closure['path']
127+ if not any_refer_to(path, closures):
128+ roots.append(path)
129+
130+ return roots
131+
132+class TestFindRoots(unittest.TestCase):
133+ def test_find_roots(self):
134+ self.assertCountEqual(
135+ find_roots([
136+ {
137+ "path": "/nix/store/foo",
138+ "references": [
139+ "/nix/store/foo",
140+ "/nix/store/bar"
141+ ]
142+ },
143+ {
144+ "path": "/nix/store/bar",
145+ "references": [
146+ "/nix/store/bar",
147+ "/nix/store/tux"
148+ ]
149+ },
150+ {
151+ "path": "/nix/store/hello",
152+ "references": [
153+ ]
154+ }
155+ ]),
156+ ["/nix/store/foo", "/nix/store/hello"]
157+ )
158+
159+
160+def any_refer_to(path, closures):
161+ for closure in closures:
162+ if path != closure['path']:
163+ if path in closure['references']:
164+ return True
165+ return False
166+
167+class TestAnyReferTo(unittest.TestCase):
168+ def test_has_references(self):
169+ self.assertTrue(
170+ any_refer_to(
171+ "/nix/store/bar",
172+ [
173+ {
174+ "path": "/nix/store/foo",
175+ "references": [
176+ "/nix/store/bar"
177+ ]
178+ },
179+ ]
180+ ),
181+ )
182+ def test_no_references(self):
183+ self.assertFalse(
184+ any_refer_to(
185+ "/nix/store/foo",
186+ [
187+ {
188+ "path": "/nix/store/foo",
189+ "references": [
190+ "/nix/store/foo",
191+ "/nix/store/bar"
192+ ]
193+ },
194+ ]
195+ ),
196+ )
197+
198+def all_paths(closures):
199+ paths = []
200+ for closure in closures:
201+ paths.append(closure['path'])
202+ paths.extend(closure['references'])
203+ paths.sort()
204+ return list(set(paths))
205+
206+
207+class TestAllPaths(unittest.TestCase):
208+ def test_returns_all_paths(self):
209+ self.assertCountEqual(
210+ all_paths([
211+ {
212+ "path": "/nix/store/foo",
213+ "references": [
214+ "/nix/store/foo",
215+ "/nix/store/bar"
216+ ]
217+ },
218+ {
219+ "path": "/nix/store/bar",
220+ "references": [
221+ "/nix/store/bar",
222+ "/nix/store/tux"
223+ ]
224+ },
225+ {
226+ "path": "/nix/store/hello",
227+ "references": [
228+ ]
229+ }
230+ ]),
231+ ["/nix/store/foo", "/nix/store/bar", "/nix/store/hello", "/nix/store/tux",]
232+ )
233+ def test_no_references(self):
234+ self.assertFalse(
235+ any_refer_to(
236+ "/nix/store/foo",
237+ [
238+ {
239+ "path": "/nix/store/foo",
240+ "references": [
241+ "/nix/store/foo",
242+ "/nix/store/bar"
243+ ]
244+ },
245+ ]
246+ ),
247+ )
248+
249+# Convert:
250+#
251+# [
252+# { path: /nix/store/foo, references: [ /nix/store/foo, /nix/store/bar, /nix/store/baz ] },
253+# { path: /nix/store/bar, references: [ /nix/store/bar, /nix/store/baz ] },
254+# { path: /nix/store/baz, references: [ /nix/store/baz, /nix/store/tux ] },
255+# { path: /nix/store/tux, references: [ /nix/store/tux ] }
256+# ]
257+#
258+# To:
259+# {
260+# /nix/store/foo: [ /nix/store/bar, /nix/store/baz ],
261+# /nix/store/bar: [ /nix/store/baz ],
262+# /nix/store/baz: [ /nix/store/tux ] },
263+# /nix/store/tux: [ ]
264+# }
265+#
266+# Note that it drops self-references to avoid loops.
267+def make_lookup(closures):
268+ lookup = {}
269+
270+ for closure in closures:
271+ # paths often self-refer
272+ nonreferential_paths = [ref for ref in closure['references'] if ref != closure['path']]
273+ lookup[closure['path']] = nonreferential_paths
274+
275+ return lookup
276+
277+class TestMakeLookup(unittest.TestCase):
278+ def test_returns_lookp(self):
279+ self.assertDictEqual(
280+ make_lookup([
281+ {
282+ "path": "/nix/store/foo",
283+ "references": [
284+ "/nix/store/foo",
285+ "/nix/store/bar"
286+ ]
287+ },
288+ {
289+ "path": "/nix/store/bar",
290+ "references": [
291+ "/nix/store/bar",
292+ "/nix/store/tux"
293+ ]
294+ },
295+ {
296+ "path": "/nix/store/hello",
297+ "references": [
298+ ]
299+ }
300+ ]),
301+ {
302+ "/nix/store/foo": [ "/nix/store/bar" ],
303+ "/nix/store/bar": [ "/nix/store/tux" ],
304+ "/nix/store/hello": [ ],
305+ }
306+ )
307+
308+# Convert:
309+#
310+# /nix/store/foo with
311+# {
312+# /nix/store/foo: [ /nix/store/bar, /nix/store/baz ],
313+# /nix/store/bar: [ /nix/store/baz ],
314+# /nix/store/baz: [ /nix/store/tux ] },
315+# /nix/store/tux: [ ]
316+# }
317+#
318+# To:
319+#
320+# {
321+# /nix/store/bar: {
322+# /nix/store/baz: {
323+# /nix/store/tux: {}
324+# }
325+# },
326+# /nix/store/baz: {
327+# /nix/store/tux: {}
328+# }
329+# }
330+def make_graph_segment_from_root(root, lookup):
331+ children = {}
332+ for ref in lookup[root]:
333+ children[ref] = make_graph_segment_from_root(ref, lookup)
334+ return children
335+
336+class TestMakeGraphSegmentFromRoot(unittest.TestCase):
337+ def test_returns_graph(self):
338+ self.assertDictEqual(
339+ make_graph_segment_from_root("/nix/store/foo", {
340+ "/nix/store/foo": [ "/nix/store/bar" ],
341+ "/nix/store/bar": [ "/nix/store/tux" ],
342+ "/nix/store/tux": [ ],
343+ "/nix/store/hello": [ ],
344+ }),
345+ {
346+ "/nix/store/bar": {
347+ "/nix/store/tux": {}
348+ }
349+ }
350+ )
351+ def test_returns_graph_tiny(self):
352+ self.assertDictEqual(
353+ make_graph_segment_from_root("/nix/store/tux", {
354+ "/nix/store/foo": [ "/nix/store/bar" ],
355+ "/nix/store/bar": [ "/nix/store/tux" ],
356+ "/nix/store/tux": [ ],
357+ }),
358+ {}
359+ )
360+
361+# Convert a graph segment in to a popularity-counted dictionary:
362+#
363+# From:
364+# {
365+# /nix/store/foo: {
366+# /nix/store/bar: {
367+# /nix/store/baz: {
368+# /nix/store/tux: {}
369+# }
370+# }
371+# /nix/store/baz: {
372+# /nix/store/tux: {}
373+# }
374+# }
375+# }
376+#
377+# to:
378+# [
379+# /nix/store/foo: 1
380+# /nix/store/bar: 2
381+# /nix/store/baz: 4
382+# /nix/store/tux: 6
383+# ]
384+def graph_popularity_contest(full_graph):
385+ popularity = defaultdict(int)
386+ for path, subgraph in full_graph.items():
387+ popularity[path] += 1
388+ subcontest = graph_popularity_contest(subgraph)
389+ for subpath, subpopularity in subcontest.items():
390+ popularity[subpath] += subpopularity + 1
391+
392+ return popularity
393+
394+class TestGraphPopularityContest(unittest.TestCase):
395+ def test_counts_popularity(self):
396+ self.assertDictEqual(
397+ graph_popularity_contest({
398+ "/nix/store/foo": {
399+ "/nix/store/bar": {
400+ "/nix/store/baz": {
401+ "/nix/store/tux": {}
402+ }
403+ },
404+ "/nix/store/baz": {
405+ "/nix/store/tux": {}
406+ }
407+ }
408+ }),
409+ {
410+ "/nix/store/foo": 1,
411+ "/nix/store/bar": 2,
412+ "/nix/store/baz": 4,
413+ "/nix/store/tux": 6,
414+ }
415+ )
416+
417+# Emit a list of packages by popularity, most first:
418+#
419+# From:
420+# [
421+# /nix/store/foo: 1
422+# /nix/store/bar: 1
423+# /nix/store/baz: 2
424+# /nix/store/tux: 2
425+# ]
426+#
427+# To:
428+# [ /nix/store/baz /nix/store/tux /nix/store/bar /nix/store/foo ]
429+def order_by_popularity(paths):
430+ paths_by_popularity = defaultdict(list)
431+ popularities = []
432+ for path, popularity in paths.items():
433+ popularities.append(popularity)
434+ paths_by_popularity[popularity].append(path)
435+
436+ popularities = list(set(popularities))
437+ popularities.sort()
438+
439+ flat_ordered = []
440+ for popularity in popularities:
441+ paths = paths_by_popularity[popularity]
442+ paths.sort(key=package_name)
443+
444+ flat_ordered.extend(reversed(paths))
445+ return list(reversed(flat_ordered))
446+
447+
448+class TestOrderByPopularity(unittest.TestCase):
449+ def test_returns_in_order(self):
450+ self.assertEqual(
451+ order_by_popularity({
452+ "/nix/store/foo": 1,
453+ "/nix/store/bar": 1,
454+ "/nix/store/baz": 2,
455+ "/nix/store/tux": 2,
456+ }),
457+ [
458+ "/nix/store/baz",
459+ "/nix/store/tux",
460+ "/nix/store/bar",
461+ "/nix/store/foo"
462+ ]
463+ )
464+
465+def package_name(path):
466+ parts = path.split('-')
467+ start = parts.pop(0)
468+ # don't throw away any data, so the order is always the same.
469+ # even in cases where only the hash at the start has changed.
470+ parts.append(start)
471+ return '-'.join(parts)
472+
473+def main():
474+ filename = sys.argv[1]
475+ key = sys.argv[2]
476+
477+ with open(filename) as f:
478+ data = json.load(f)
479+
480+ # Data comes in as:
481+ # [
482+ # { path: /nix/store/foo, references: [ /nix/store/foo, /nix/store/bar, /nix/store/baz ] },
483+ # { path: /nix/store/bar, references: [ /nix/store/bar, /nix/store/baz ] },
484+ # { path: /nix/store/baz, references: [ /nix/store/baz, /nix/store/tux ] },
485+ # { path: /nix/store/tux, references: [ /nix/store/tux ] }
486+ # ]
487+ #
488+ # and we want to get out a list of paths ordered by how universally,
489+ # important they are, ie: tux is referenced by every path, transitively
490+ # so it should be #1
491+ #
492+ # [
493+ # /nix/store/tux,
494+ # /nix/store/baz,
495+ # /nix/store/bar,
496+ # /nix/store/foo,
497+ # ]
498+ graph = data[key]
499+
500+ roots = find_roots(graph);
501+ lookup = make_lookup(graph)
502+
503+ full_graph = {}
504+ for root in roots:
505+ full_graph[root] = make_graph_segment_from_root(root, lookup)
506+
507+ ordered = order_by_popularity(graph_popularity_contest(full_graph))
508+ missing = []
509+ for path in all_paths(graph):
510+ if path not in ordered:
511+ missing.append(path)
512+
513+ ordered.extend(missing)
514+ print("\n".join(ordered))
515+
516+if "--test" in sys.argv:
517+ # Don't pass --test otherwise unittest gets mad
518+ unittest.main(argv = [f for f in sys.argv if f != "--test" ])
519+else:
520+ main()
pkgs/build-support/references-by-popularity/default.nixnew file+15
@@ -0,0 +1,15 @@
1+{ runCommand, python3, coreutils }:
2+# Write the references of `path' to a file, in order of how "popular" each
3+# reference is. Nix 2 only.
4+path: runCommand "closure-paths"
5+{
6+ exportReferencesGraph.graph = path;
7+ __structuredAttrs = true;
8+ PATH = "${coreutils}/bin:${python3}/bin";
9+ builder = builtins.toFile "builder"
10+ ''
11+ . .attrs.sh
12+ python3 ${./closure-graph.py} .attrs.json graph > ''${outputs[out]}
13+ '';
14+ }
15+ ""
pkgs/top-level/all-packages.nix+2
@@ -365,6 +365,8 @@ with pkgs;
365365
366366 nukeReferences = callPackage ../build-support/nuke-references { };
367367
368+ referencesByPopularity = callPackage ../build-support/references-by-popularity { };
369+
368370 removeReferencesTo = callPackage ../build-support/remove-references-to { };
369371
370372 vmTools = callPackage ../build-support/vm { };