@@ -1,12 +1,30 @@
1−{ stdenv, lib, callPackage, runCommand, writeReferencesToFile, writeText, vmTools, writeScript
2−, docker, shadow, utillinux, coreutils, jshon, e2fsprogs, go, pigz, findutils }:
1+{
2+ callPackage,
3+ coreutils,
4+ docker,
5+ e2fsprogs,
6+ findutils,
7+ go,
8+ jshon,
9+ lib,
10+ pigz,
11+ runCommand,
12+ shadow,
13+ stdenv,
14+ storeDir ? builtins.storeDir,
15+ utillinux,
16+ vmTools,
17+ writeReferencesToFile,
18+ writeScript,
19+ writeText,
20+}:
321
422# WARNING: this API is unstable and may be subject to backwards-incompatible changes in the future.
5−
23+
624rec {
725
826 pullImage = callPackage ./pull.nix {};
9−
27+
1028 # We need to sum layer.tar, not a directory, hence tarsum instead of nix-hash.
1129 # And we cannot untar it, because then we cannot preserve permissions ecc.
1230 tarsum = runCommand "tarsum" {
@@ -23,110 +41,138 @@ rec {
2341
2442 cp tarsum $out
2543 '';
26−
44+
2745 # buildEnv creates symlinks to dirs, which is hard to edit inside the overlay VM
28− mergeDrvs = { drvs, onlyDeps ? false }:
46+ mergeDrvs = {
47+ derivations,
48+ onlyDeps ? false
49+ }:
2950 runCommand "merge-drvs" {
30− inherit drvs onlyDeps;
51+ inherit derivations onlyDeps;
3152 } ''
32− if [ -n "$onlyDeps" ]; then
33− echo $drvs > $out
53+ if [[ -n "$onlyDeps" ]]; then
54+ echo $derivations > $out
3455 exit 0
3556 fi
36−
57+
3758 mkdir $out
38− for drv in $drvs; do
39− echo Merging $drv
40− if [ -d "$drv" ]; then
41− cp -drf --preserve=mode -f $drv/* $out/
59+ for derivation in $derivations; do
60+ echo "Merging $derivation..."
61+ if [[ -d "$derivation" ]]; then
62+ # If it's a directory, copy all of its contents into $out.
63+ cp -drf --preserve=mode -f $derivation/* $out/
4264 else
65+ # Otherwise treat the derivation as a tarball and extract it
66+ # into $out.
4367 tar -C $out -xpf $drv || true
4468 fi
4569 done
4670 '';
47−
48− shellScript = text:
49− writeScript "script.sh" ''
50− #!${stdenv.shell}
51− set -e
52− export PATH=${coreutils}/bin:/bin
53−
54− ${text}
55− '';
5671
72+ # Helper for setting up the base files for managing users and
73+ # groups, only if such files don't exist already. It is suitable for
74+ # being used in a runAsRoot script.
5775 shadowSetup = ''
5876 export PATH=${shadow}/bin:$PATH
5977 mkdir -p /etc/pam.d
60− if [ ! -f /etc/passwd ]; then
78+ if [[ ! -f /etc/passwd ]]; then
6179 echo "root:x:0:0::/root:/bin/sh" > /etc/passwd
6280 echo "root:!x:::::::" > /etc/shadow
6381 fi
64− if [ ! -f /etc/group ]; then
82+ if [[ ! -f /etc/group ]]; then
6583 echo "root:x:0:" > /etc/group
6684 echo "root:x::" > /etc/gshadow
6785 fi
68− if [ ! -f /etc/pam.d/other ]; then
86+ if [[ ! -f /etc/pam.d/other ]]; then
6987 cat > /etc/pam.d/other <<EOF
70−account sufficient pam_unix.so
71−auth sufficient pam_rootok.so
72−password requisite pam_unix.so nullok sha512
73−session required pam_unix.so
74−EOF
88+ account sufficient pam_unix.so
89+ auth sufficient pam_rootok.so
90+ password requisite pam_unix.so nullok sha512
91+ session required pam_unix.so
92+ EOF
7593 fi
76− if [ ! -f /etc/login.defs ]; then
94+ if [[ ! -f /etc/login.defs ]]; then
7795 touch /etc/login.defs
7896 fi
7997 '';
8098
81− runWithOverlay = { name , fromImage ? null, fromImageName ? null, fromImageTag ? null
82− , diskSize ? 1024, preMount ? "", postMount ? "", postUmount ? "" }:
99+ # Run commands in a virtual machine.
100+ runWithOverlay = {
101+ name,
102+ fromImage ? null,
103+ fromImageName ? null,
104+ fromImageTag ? null,
105+ diskSize ? 1024,
106+ preMount ? "",
107+ postMount ? "",
108+ postUmount ? ""
109+ }:
83110 vmTools.runInLinuxVM (
84111 runCommand name {
85− preVM = vmTools.createEmptyImage { size = diskSize; fullName = "docker-run-disk"; };
86−
112+ preVM = vmTools.createEmptyImage {
113+ size = diskSize;
114+ fullName = "docker-run-disk";
115+ };
87116 inherit fromImage fromImageName fromImageTag;
88−
117+
89118 buildInputs = [ utillinux e2fsprogs jshon ];
90119 } ''
91120 rm -rf $out
92−
121+
93122 mkdir disk
94123 mkfs /dev/${vmTools.hd}
95124 mount /dev/${vmTools.hd} disk
96125 cd disk
97126
98− if [ -n "$fromImage" ]; then
99− echo Unpacking base image
127+ if [[ -n "$fromImage" ]]; then
128+ echo "Unpacking base image..."
100129 mkdir image
101130 tar -C image -xpf "$fromImage"
102131
103− if [ -z "$fromImageName" ]; then
104− fromImageName=$(jshon -k < image/repositories|head -n1)
132+ # If the image name isn't set, read it from the image repository json.
133+ if [[ -z "$fromImageName" ]]; then
134+ fromImageName=$(jshon -k < image/repositories | head -n 1)
135+ echo "From-image name wasn't set. Read $fromImageName."
105136 fi
106− if [ -z "$fromImageTag" ]; then
107− fromImageTag=$(jshon -e $fromImageName -k < image/repositories|head -n1)
137+
138+ # If the tag isn't set, use the name as an index into the json
139+ # and read the first key found.
140+ if [[ -z "$fromImageTag" ]]; then
141+ fromImageTag=$(jshon -e $fromImageName -k < image/repositories \
142+ | head -n1)
143+ echo "From-image tag wasn't set. Read $fromImageTag."
108144 fi
109− parentID=$(jshon -e $fromImageName -e $fromImageTag -u < image/repositories)
145+
146+ # Use the name and tag to get the parent ID field.
147+ parentID=$(jshon -e $fromImageName -e $fromImageTag -u \
148+ < image/repositories)
110149 fi
111150
151+ # Unpack all of the parent layers into the image.
112152 lowerdir=""
113− while [ -n "$parentID" ]; do
114− echo Unpacking layer $parentID
153+ while [[ -n "$parentID" ]]; do
154+ echo "Unpacking layer $parentID"
115155 mkdir -p image/$parentID/layer
116156 tar -C image/$parentID/layer -xpf image/$parentID/layer.tar
117157 rm image/$parentID/layer.tar
118158
119159 find image/$parentID/layer -name ".wh.*" -exec bash -c 'name="$(basename {}|sed "s/^.wh.//")"; mknod "$(dirname {})/$name" c 0 0; rm {}' \;
120160
161+ # Get the next lower directory and continue the loop.
121162 lowerdir=$lowerdir''${lowerdir:+:}image/$parentID/layer
122− parentID=$(cat image/$parentID/json|(jshon -e parent -u 2>/dev/null || true))
163+ parentID=$(cat image/$parentID/json \
164+ | (jshon -e parent -u 2>/dev/null || true))
123165 done
124166
125167 mkdir work
126168 mkdir layer
127169 mkdir mnt
128170
129− ${preMount}
171+ ${lib.optionalString (preMount != "") ''
172+ # Execute pre-mount steps
173+ echo "Executing pre-mount steps..."
174+ ${preMount}
175+ ''}
130176
131177 if [ -n "$lowerdir" ]; then
132178 mount -t overlay overlay -olowerdir=$lowerdir,workdir=work,upperdir=layer mnt
@@ -134,13 +180,19 @@ EOF
134180 mount --bind layer mnt
135181 fi
136182
137− ${postMount}
138−
183+ ${lib.optionalString (postMount != "") ''
184+ # Execute post-mount steps
185+ echo "Executing post-mount steps..."
186+ ${postMount}
187+ ''}
188+
139189 umount mnt
140190
141− pushd layer
142− find . -type c -exec bash -c 'name="$(basename {})"; touch "$(dirname {})/.wh.$name"; rm "{}"' \;
143− popd
191+ (
192+ cd layer
193+ cmd='name="$(basename {})"; touch "$(dirname {})/.wh.$name"; rm "{}"'
194+ find . -type c -exec bash -c "$cmd" \;
195+ )
144196
145197 ${postUmount}
146198 '');
@@ -150,76 +202,150 @@ EOF
150202 inherit name fromImage fromImageName fromImageTag diskSize;
151203
152204 postMount = ''
153− echo Packing raw image
205+ echo "Packing raw image..."
154206 tar -C mnt --mtime=0 -cf $out .
155207 '';
156208 };
157−
158− mkPureLayer = { baseJson, contents ? null, extraCommands ? "" }:
159− runCommand "docker-layer" {
209+
210+
211+ # Create an executable shell script which has the coreutils in its
212+ # PATH. Since root scripts are executed in a blank environment, even
213+ # things like `ls` or `echo` will be missing.
214+ shellScript = name: text:
215+ writeScript name ''
216+ #!${stdenv.shell}
217+ set -e
218+ export PATH=${coreutils}/bin:/bin
219+ ${text}
220+ '';
221+
222+ # Create a "layer" (set of files).
223+ mkPureLayer = {
224+ # Name of the layer
225+ name,
226+ # JSON containing configuration and metadata for this layer.
227+ baseJson,
228+ # Files to add to the layer.
229+ contents ? null,
230+ # Additional commands to run on the layer before it is tar'd up.
231+ extraCommands ? ""
232+ }:
233+ runCommand "docker-layer-${name}" {
160234 inherit baseJson contents extraCommands;
161235
162236 buildInputs = [ jshon ];
163− } ''
237+ }
238+ ''
164239 mkdir layer
165− if [ -n "$contents" ]; then
166− echo Adding contents
167− for c in $contents; do
168− cp -drf $c/* layer/
169− chmod -R ug+w layer/
240+ if [[ -n "$contents" ]]; then
241+ echo "Adding contents..."
242+ for item in $contents; do
243+ echo "Adding $item"
244+ cp -drf $item/* layer/
170245 done
246+ chmod -R ug+w layer/
247+ else
248+ echo "No contents to add to layer."
249+ fi
250+
251+ if [[ -n $extraCommands ]]; then
252+ (cd layer; eval "$extraCommands")
171253 fi
172254
173− pushd layer
174− ${extraCommands}
175− popd
176−
177− echo Packing layer
255+ # Tar up the layer and throw it into 'layer.tar'.
256+ echo "Packing layer..."
178257 mkdir $out
179258 tar -C layer --mtime=0 -cf $out/layer.tar .
180− ts=$(${tarsum} < $out/layer.tar)
181− cat ${baseJson} | jshon -s "$ts" -i checksum > $out/json
259+
260+ # Compute a checksum of the tarball.
261+ echo "Computing layer checksum..."
262+ tarsum=$(${tarsum} < $out/layer.tar)
263+
264+ # Add a 'checksum' field to the JSON, with the value set to the
265+ # checksum of the tarball.
266+ cat ${baseJson} | jshon -s "$tarsum" -i checksum > $out/json
267+
268+ # Indicate to docker that we're using schema version 1.0.
182269 echo -n "1.0" > $out/VERSION
270+
271+ echo "Finished building layer '${name}'"
183272 '';
184273
185− mkRootLayer = { runAsRoot, baseJson, fromImage ? null, fromImageName ? null, fromImageTag ? null
186− , diskSize ? 1024, contents ? null, extraCommands ? "" }:
187− let runAsRootScript = writeScript "run-as-root.sh" runAsRoot;
274+ # Make a "root" layer; required if we need to execute commands as a
275+ # privileged user on the image. The commands themselves will be
276+ # performed in a virtual machine sandbox.
277+ mkRootLayer = {
278+ # Name of the image.
279+ name,
280+ # Script to run as root. Bash.
281+ runAsRoot,
282+ # Files to add to the layer. If null, an empty layer will be created.
283+ contents ? null,
284+ # JSON containing configuration and metadata for this layer.
285+ baseJson,
286+ # Existing image onto which to append the new layer.
287+ fromImage ? null,
288+ # Name of the image we're appending onto.
289+ fromImageName ? null,
290+ # Tag of the image we're appending onto.
291+ fromImageTag ? null,
292+ # How much disk to allocate for the temporary virtual machine.
293+ diskSize ? 1024,
294+ # Commands (bash) to run on the layer; these do not require sudo.
295+ extraCommands ? ""
296+ }:
297+ # Generate an executable script from the `runAsRoot` text.
298+ let runAsRootScript = shellScript "run-as-root.sh" runAsRoot;
188299 in runWithOverlay {
189− name = "docker-layer";
190−
300+ name = "docker-layer-${name}";
301+
191302 inherit fromImage fromImageName fromImageTag diskSize;
192303
193− preMount = lib.optionalString (contents != null) ''
194− echo Adding contents
195− for c in ${builtins.toString contents}; do
196− cp -drf $c/* layer/
197− chmod -R ug+w layer/
304+ preMount = lib.optionalString (contents != null && contents != []) ''
305+ echo "Adding contents..."
306+ for item in ${toString contents}; do
307+ echo "Adding $item..."
308+ cp -drf $item/* layer/
198309 done
310+ chmod -R ug+w layer/
199311 '';
200312
201313 postMount = ''
202− mkdir -p mnt/{dev,proc,sys,nix/store}
314+ mkdir -p mnt/{dev,proc,sys} mnt${storeDir}
315+
316+ # Mount /dev, /sys and the nix store as shared folders.
203317 mount --rbind /dev mnt/dev
204318 mount --rbind /sys mnt/sys
205− mount --rbind /nix/store mnt/nix/store
319+ mount --rbind ${storeDir} mnt${storeDir}
206320
321+ # Execute the run as root script. See 'man unshare' for
322+ # details on what's going on here; basically this command
323+ # means that the runAsRootScript will be executed in a nearly
324+ # completely isolated environment.
207325 unshare -imnpuf --mount-proc chroot mnt ${runAsRootScript}
208− umount -R mnt/dev mnt/sys mnt/nix/store
209− rmdir --ignore-fail-on-non-empty mnt/dev mnt/proc mnt/sys mnt/nix/store mnt/nix
326+
327+ # Unmount directories and remove them.
328+ umount -R mnt/dev mnt/sys mnt${storeDir}
329+ rmdir --ignore-fail-on-non-empty \
330+ mnt/dev mnt/proc mnt/sys mnt${storeDir} \
331+ mnt$(dirname ${storeDir})
210332 '';
211−
333+
212334 postUmount = ''
213− pushd layer
214− ${extraCommands}
215− popd
335+ (cd layer; eval "${extraCommands}")
216336
217− echo Packing layer
337+ echo "Packing layer..."
218338 mkdir $out
219339 tar -C layer --mtime=0 -cf $out/layer.tar .
340+
341+ # Compute the tar checksum and add it to the output json.
342+ echo "Computing checksum..."
220343 ts=$(${tarsum} < $out/layer.tar)
221344 cat ${baseJson} | jshon -s "$ts" -i checksum > $out/json
345+ # Indicate to docker that we're using schema version 1.0.
222346 echo -n "1.0" > $out/VERSION
347+
348+ echo "Finished building layer '${name}'"
223349 '';
224350 };
225351
@@ -229,116 +355,144 @@ EOF
229355 # 4. compute the layer id
230356 # 5. put the layer in the image
231357 # 6. repack the image
232− buildImage = args@{ name, tag ? "latest"
233− , fromImage ? null, fromImageName ? null, fromImageTag ? null
234− , contents ? null, config ? null, runAsRoot ? null
235− , diskSize ? 1024, extraCommands ? "" }:
358+ buildImage = args@{
359+ # Image name.
360+ name,
361+ # Image tag.
362+ tag ? "latest",
363+ # Parent image, to append to.
364+ fromImage ? null,
365+ # Name of the parent image; will be read from the image otherwise.
366+ fromImageName ? null,
367+ # Tag of the parent image; will be read from the image otherwise.
368+ fromImageTag ? null,
369+ # Files to put on the image (a nix store path or list of paths).
370+ contents ? null,
371+ # Docker config; e.g. what command to run on the container.
372+ config ? null,
373+ # Optional bash script to run on the files prior to fixturizing the layer.
374+ extraCommands ? "",
375+ # Optional bash script to run as root on the image when provisioning.
376+ runAsRoot ? null,
377+ # Size of the virtual machine disk to provision when building the image.
378+ diskSize ? 1024,
379+ }:
236380
237381 let
238−
239382 baseName = baseNameOf name;
240383
384+ # Create a JSON blob of the configuration. Set the date to unix zero.
241385 baseJson = writeText "${baseName}-config.json" (builtins.toJSON {
242− created = "1970-01-01T00:00:01Z";
243− architecture = "amd64";
244− os = "linux";
245− config = config;
386+ created = "1970-01-01T00:00:01Z";
387+ architecture = "amd64";
388+ os = "linux";
389+ config = config;
246390 });
247391
248− layer = (if runAsRoot == null
249− then mkPureLayer { inherit baseJson contents extraCommands; }
250− else mkRootLayer { inherit baseJson fromImage fromImageName fromImageTag contents runAsRoot diskSize extraCommands; });
251− result = runCommand "${baseName}.tar.gz" {
392+ layer =
393+ if runAsRoot == null
394+ then mkPureLayer { inherit name baseJson contents extraCommands; }
395+ else mkRootLayer { inherit name baseJson fromImage fromImageName
396+ fromImageTag contents runAsRoot diskSize
397+ extraCommands; };
398+ result = runCommand "docker-image-${baseName}.tar.gz" {
252399 buildInputs = [ jshon pigz coreutils findutils ];
253−
254400 imageName = name;
255401 imageTag = tag;
256402 inherit fromImage baseJson;
257−
258403 layerClosure = writeReferencesToFile layer;
259−
260− passthru = {
261− buildArgs = args;
262− };
404+ passthru.buildArgs = args;
405+ passthru.layer = layer;
263406 } ''
264407 # Print tar contents:
265408 # 1: Interpreted as relative to the root directory
266409 # 2: With no trailing slashes on directories
267− # This is useful for ensuring that the output matches the values generated by the "find" command
410+ # This is useful for ensuring that the output matches the
411+ # values generated by the "find" command
268412 ls_tar() {
269− for f in $(tar -tf $1 | xargs realpath -ms --relative-to=.); do
270− if [ "$f" != "." ]; then
271− echo "/$f"
272− fi
273− done
413+ for f in $(tar -tf $1 | xargs realpath -ms --relative-to=.); do
414+ if [[ "$f" != "." ]]; then
415+ echo "/$f"
416+ fi
417+ done
274418 }
275−
419+
276420 mkdir image
277421 touch baseFiles
278− if [ -n "$fromImage" ]; then
279− echo Unpacking base image
422+ if [[ -n "$fromImage" ]]; then
423+ echo "Unpacking base image..."
280424 tar -C image -xpf "$fromImage"
281−
282− if [ -z "$fromImageName" ]; then
425+
426+ if [[ -z "$fromImageName" ]]; then
283427 fromImageName=$(jshon -k < image/repositories|head -n1)
284428 fi
285− if [ -z "$fromImageTag" ]; then
286− fromImageTag=$(jshon -e $fromImageName -k < image/repositories|head -n1)
429+ if [[ -z "$fromImageTag" ]]; then
430+ fromImageTag=$(jshon -e $fromImageName -k \
431+ < image/repositories|head -n1)
287432 fi
288− parentID=$(jshon -e $fromImageName -e $fromImageTag -u < image/repositories)
289−
433+ parentID=$(jshon -e $fromImageName -e $fromImageTag -u \
434+ < image/repositories)
435+
290436 for l in image/*/layer.tar; do
291− ls_tar $l >> baseFiles
437+ ls_tar image/*/layer.tar >> baseFiles
292438 done
293439 fi
294440
295441 chmod -R ug+rw image
296−
442+
297443 mkdir temp
298444 cp ${layer}/* temp/
299445 chmod ug+w temp/*
300446
447+ echo "$(dirname ${storeDir})" >> layerFiles
448+ echo '${storeDir}' >> layerFiles
301449 for dep in $(cat $layerClosure); do
302− find $dep -path "${layer}" -prune -o -print >> layerFiles
450+ find $dep >> layerFiles
303451 done
304452
305− if [ -s layerFiles ]; then
306− # FIXME: might not be /nix/store
307− echo '/nix' >> layerFiles
308− echo '/nix/store' >> layerFiles
309− fi
310−
311− echo Adding layer
453+ echo "Adding layer..."
454+ # Record the contents of the tarball with ls_tar.
312455 ls_tar temp/layer.tar >> baseFiles
313− comm <(sort -u baseFiles) <(sort -u layerFiles) -1 -3 > newFiles
314− tar -rpf temp/layer.tar --mtime=0 --no-recursion --files-from newFiles 2>/dev/null || true
315456
316− echo Adding meta
317−
318− if [ -n "$parentID" ]; then
457+ # Get the files in the new layer which were *not* present in
458+ # the old layer, and record them as newFiles.
459+ comm <(sort -n baseFiles|uniq) \
460+ <(sort -n layerFiles|uniq|grep -v ${layer}) -1 -3 > newFiles
461+ # Append the new files to the layer.
462+ tar -rpf temp/layer.tar --mtime=0 --no-recursion --files-from newFiles
463+
464+ echo "Adding meta..."
465+
466+ # If we have a parentID, add it to the json metadata.
467+ if [[ -n "$parentID" ]]; then
319468 cat temp/json | jshon -s "$parentID" -i parent > tmpjson
320469 mv tmpjson temp/json
321470 fi
322−
471+
472+ # Take the sha256 sum of the generated json and use it as the layer ID.
473+ # Compute the size and add it to the json under the 'Size' field.
323474 layerID=$(sha256sum temp/json|cut -d ' ' -f 1)
324475 size=$(stat --printf="%s" temp/layer.tar)
325476 cat temp/json | jshon -s "$layerID" -i id -n $size -i Size > tmpjson
326477 mv tmpjson temp/json
327478
479+ # Use the temp folder we've been working on to create a new image.
328480 mv temp image/$layerID
329−
481+
482+ # Store the json under the name image/repositories.
330483 jshon -n object \
331484 -n object -s "$layerID" -i "$imageTag" \
332485 -i "$imageName" > image/repositories
333486
487+ # Make the image read-only.
334488 chmod -R a-w image
335489
336− echo Cooking the image
490+ echo "Cooking the image..."
337491 tar -C image --mtime=0 -c . | pigz -nT > $out
492+
493+ echo "Finished."
338494 '';
339495
340496 in
341−
342− result;
343−
497+ result;
344498}