@@ -10,6 +10,8 @@
1010 lib,
1111 pkgs,
1212 pigz,
13+ nixUnstable,
14+ perl,
1315 runCommand,
1416 rsync,
1517 shadow,
@@ -27,7 +29,7 @@
2729rec {
2830
2931 examples = import ./examples.nix {
30− inherit pkgs buildImage pullImage shadowSetup;
32+ inherit pkgs buildImage pullImage shadowSetup buildImageWithNixDb;
3133 };
3234
3335 pullImage =
@@ -239,6 +241,19 @@ rec {
239241 ${text}
240242 '';
241243
244+ nixRegistration = contents: runCommand "nix-registration" {
245+ buildInputs = [ nixUnstable perl ];
246+ # For obtaining the closure of `contents'.
247+ exportReferencesGraph =
248+ let contentsList = if builtins.isList contents then contents else [ contents ];
249+ in map (x: [("closure-" + baseNameOf x) x]) contentsList;
250+ }
251+ ''
252+ mkdir $out
253+ printRegistration=1 perl ${pkgs.pathsFromGraph} closure-* > $out/db.dump
254+ perl ${pkgs.pathsFromGraph} closure-* > $out/storePaths
255+ '';
256+
242257 # Create a "layer" (set of files).
243258 mkPureLayer = {
244259 # Name of the layer
@@ -544,4 +559,37 @@ rec {
544559
545560 in
546561 result;
562+
563+ # Build an image and populate its nix database with the provided
564+ # contents. The main purpose is to be able to use nix commands in
565+ # the container.
566+ # Be careful since this doesn't work well with multilayer.
567+ buildImageWithNixDb = args@{ contents ? null, extraCommands ? "", ... }:
568+ buildImage (args // {
569+ extraCommands = ''
570+ echo "Generating the nix database..."
571+ echo "Warning: only the database of the deepest Nix layer is loaded."
572+ echo " If you want to use nix commands in the container, it would"
573+ echo " be better to only have one layer that contains a nix store."
574+ # This requires Nix 1.12 or higher
575+ export NIX_REMOTE=local?root=$PWD
576+ ${nixUnstable}/bin/nix-store --load-db < ${nixRegistration contents}/db.dump
577+
578+ # We fill the store in order to run the 'verify' command that
579+ # generates hash and size of output paths.
580+ # Note when Nix 1.12 is be the stable one, the database dump
581+ # generated by the exportReferencesGraph function will
582+ # contains sha and size. See
583+ # https://github.com/NixOS/nix/commit/c2b0d8749f7e77afc1c4b3e8dd36b7ee9720af4a
584+ storePaths=$(cat ${nixRegistration contents}/storePaths)
585+ echo "Copying everything to /nix/store (will take a while)..."
586+ cp -prd $storePaths nix/store/
587+ ${nixUnstable}/bin/nix-store --verify --check-contents
588+
589+ mkdir -p nix/var/nix/gcroots/docker/
590+ for i in ${lib.concatStringsSep " " contents}; do
591+ ln -s $i nix/var/nix/gcroots/docker/$(basename $i)
592+ done;
593+ '' + extraCommands;
594+ });
547595}