4 , # The NixOS configuration to be installed onto the disk image.
7 , # The size of the disk, in megabytes.
8 # if "auto" size is calculated based on the contents copied to it and
9 # additionalSpace is taken into account.
12 , # additional disk space to be added to the image if diskSize "auto"
14 additionalSpace ? "512M"
16 , # size of the boot partition, is only used if partitionTableType is
17 # either "efi" or "hybrid"
18 # This will be undersized slightly, as this is actually the offset of
19 # the end of the partition. Generally it will be 1MiB smaller.
22 , # The files and directories to be placed in the target file system.
23 # This is a list of attribute sets {source, target, mode, user, group} where
24 # `source' is the file system object (regular file or directory) to be
25 # grafted in the file system at path `target', `mode' is a string containing
26 # the permissions that will be set (ex. "755"), `user' and `group' are the
27 # user and group name that will be set as owner of the files.
28 # `mode', `user', and `group' are optional.
29 # When setting one of `user' or `group', the other needs to be set too.
32 , # Type of partition table to use; either "legacy", "efi", or "none".
33 # For "efi" images, the GPT partition table is used and a mandatory ESP
34 # partition of reasonable size is created in addition to the root partition.
35 # For "legacy", the msdos partition table is used and a single large root
36 # partition is created.
37 # For "legacy+gpt", the GPT partition table is used, a 1MiB no-fs partition for
38 # use by the bootloader is created, and a single large root partition is
40 # For "hybrid", the GPT partition table is used and a mandatory ESP
41 # partition of reasonable size is created in addition to the root partition.
42 # Also a legacy MBR will be present.
43 # For "none", no partition table is created. Enabling `installBootLoader`
44 # most likely fails as GRUB will probably refuse to install.
45 partitionTableType ? "legacy"
47 , # Whether to invoke `switch-to-configuration boot` during image creation
48 installBootLoader ? true
50 , # The root file system type.
54 label ? if onlyNixStore then "nix-store" else "nixos"
56 , # The initial NixOS configuration file to be copied to
57 # /etc/nixos/configuration.nix.
60 , # Shell code executed after the VM has finished.
63 , # Copy the contents of the Nix store to the root of the image and
64 # skip further setup. Incompatible with `contents`,
65 # `installBootLoader` and `configFile`.
68 , name ? "nixos-disk-image"
70 , # Disk image format, one of qcow2, qcow2-compressed, vdi, vpc, raw.
73 , # Whether a nix channel based on the current source tree should be
74 # made available inside the image. Useful for interactive use of nix
75 # utils, but changes the hash of the image when the sources are
79 , # Additional store paths to copy to the image's store.
83 assert partitionTableType == "legacy" || partitionTableType == "legacy+gpt" || partitionTableType == "efi" || partitionTableType == "hybrid" || partitionTableType == "none";
84 # We use -E offset=X below, which is only supported by e2fsprogs
85 assert partitionTableType != "none" -> fsType == "ext4";
86 # Either both or none of {user,group} need to be set
88 (attrs: ((attrs.user or null) == null)
89 == ((attrs.group or null) == null))
91 assert onlyNixStore -> contents == [] && configFile == null && !installBootLoader;
95 let format' = format; in let
97 format = if format' == "qcow2-compressed" then "qcow2" else format';
99 compress = optionalString (format' == "qcow2-compressed") "-c";
101 filename = "nixos." + {
106 }.${format} or format;
108 rootPartition = { # switch-case
113 }.${partitionTableType};
115 partitionDiskScript = { # switch-case
117 parted --script $diskImage -- \
119 mkpart primary ext4 1MiB -1
122 parted --script $diskImage -- \
124 mkpart no-fs 1MB 2MB \
126 align-check optimal 1 \
127 mkpart primary ext4 2MB -1 \
128 align-check optimal 2 \
132 parted --script $diskImage -- \
134 mkpart ESP fat32 8MiB ${bootSize} \
136 mkpart primary ext4 ${bootSize} -1
139 parted --script $diskImage -- \
141 mkpart ESP fat32 8MiB ${bootSize} \
143 mkpart no-fs 0 1024KiB \
145 mkpart primary ext4 ${bootSize} -1
148 }.${partitionTableType};
150 nixpkgs = cleanSource pkgs.path;
152 # FIXME: merge with channel.nix / make-channel.nix.
153 channelSources = pkgs.runCommand "nixos-${config.system.nixos.version}" {} ''
155 cp -prd ${nixpkgs.outPath} $out/nixos
156 chmod -R u+w $out/nixos
157 if [ ! -e $out/nixos/nixpkgs ]; then
158 ln -s . $out/nixos/nixpkgs
160 rm -rf $out/nixos/.git
161 echo -n ${config.system.nixos.versionSuffix} > $out/nixos/.version-suffix
164 binPath = with pkgs; makeBinPath (
170 config.system.build.nixos-install
171 config.system.build.nixos-enter
174 ] ++ stdenv.initialPath);
176 # I'm preserving the line below because I'm going to search for it across nixpkgs to consolidate
177 # image building logic. The comment right below this now appears in 4 different places in nixpkgs :)
178 # !!! should use XML.
179 sources = map (x: x.source) contents;
180 targets = map (x: x.target) contents;
181 modes = map (x: x.mode or "''") contents;
182 users = map (x: x.user or "''") contents;
183 groups = map (x: x.group or "''") contents;
185 basePaths = [ config.system.build.toplevel ]
186 ++ lib.optional copyChannel channelSources;
188 additionalPaths' = subtractLists basePaths additionalPaths;
190 closureInfo = pkgs.closureInfo {
191 rootPaths = basePaths ++ additionalPaths';
194 blockSize = toString (4 * 1024); # ext4fs block size (not block device sector size)
197 export PATH=${binPath}
199 # Yes, mkfs.ext4 takes different units in different contexts. Fun.
200 sectorsToKilobytes() {
201 echo $(( ( "$1" * 512 ) / 1024 ))
205 echo $(( "$1" * 512 ))
208 # Given lines of numbers, adds them together
211 while read -r number; do
217 mebibyte=$(( 1024 * 1024 ))
219 # Approximative percentage of reserved space in an ext4 fs over 512MiB.
220 # 0.05208587646484375
221 # × 1000, integer part: 52
223 echo $(( $1 * 52 / 1000 ))
231 # Copy arbitrary other files into the image
232 # Semi-shamelessly copied from make-etc.sh. I (@copumpkin) shall factor this stuff out as part of
233 # https://github.com/NixOS/nixpkgs/issues/23052.
235 sources_=(${concatStringsSep " " sources})
236 targets_=(${concatStringsSep " " targets})
237 modes_=(${concatStringsSep " " modes})
240 for ((i = 0; i < ''${#targets_[@]}; i++)); do
241 source="''${sources_[$i]}"
242 target="''${targets_[$i]}"
243 mode="''${modes_[$i]}"
245 if [ -n "$mode" ]; then
246 rsync_chmod_flags="--chmod=$mode"
250 # Unfortunately cptofs only supports modes, not ownership, so we can't use
251 # rsync's --chown option. Instead, we change the ownerships in the
252 # VM script with chown.
253 rsync_flags="-a --no-o --no-g $rsync_chmod_flags"
254 if [[ "$source" =~ '*' ]]; then
255 # If the source name contains '*', perform globbing.
256 mkdir -p $root/$target
257 for fn in $source; do
258 rsync $rsync_flags "$fn" $root/$target/
261 mkdir -p $root/$(dirname $target)
262 if ! [ -e $root/$target ]; then
263 rsync $rsync_flags $source $root/$target
265 echo "duplicate entry $target -> $source"
273 # Provide a Nix database so that nixos-install can copy closures.
274 export NIX_STATE_DIR=$TMPDIR/state
275 nix-store --load-db < ${closureInfo}/registration
278 echo "running nixos-install..."
279 nixos-install --root $root --no-bootloader --no-root-passwd \
280 --system ${config.system.build.toplevel} \
281 ${if copyChannel then "--channel ${channelSources}" else "--no-channel-copy"} \
284 ${optionalString (additionalPaths' != []) ''
285 nix --extra-experimental-features nix-command copy --to $root --no-check-sigs ${concatStringsSep " " additionalPaths'}
290 ${if diskSize == "auto" then ''
291 ${if partitionTableType == "efi" || partitionTableType == "hybrid" then ''
292 # Add the GPT at the end
293 gptSpace=$(( 512 * 34 * 1 ))
294 # Normally we'd need to account for alignment and things, if bootSize
295 # represented the actual size of the boot partition. But it instead
296 # represents the offset at which it ends.
297 # So we know bootSize is the reserved space in front of the partition.
298 reservedSpace=$(( gptSpace + $(numfmt --from=iec '${bootSize}') ))
299 '' else if partitionTableType == "legacy+gpt" then ''
300 # Add the GPT at the end
301 gptSpace=$(( 512 * 34 * 1 ))
302 # And include the bios_grub partition; the ext4 partition starts at 2MB exactly.
303 reservedSpace=$(( gptSpace + 2 * mebibyte ))
304 '' else if partitionTableType == "legacy" then ''
305 # Add the 1MiB aligned reserved space (includes MBR)
306 reservedSpace=$(( mebibyte ))
310 additionalSpace=$(( $(numfmt --from=iec '${additionalSpace}') + reservedSpace ))
312 # Compute required space in filesystem blocks
313 diskUsage=$(find . ! -type d -print0 | du --files0-from=- --apparent-size --block-size "${blockSize}" | cut -f1 | sum_lines)
314 # Each inode takes space!
315 numInodes=$(find . | wc -l)
316 # Convert to bytes, inodes take two blocks each!
317 diskUsage=$(( (diskUsage + 2 * numInodes) * ${blockSize} ))
318 # Then increase the required space to account for the reserved blocks.
319 fudge=$(compute_fudge $diskUsage)
320 requiredFilesystemSpace=$(( diskUsage + fudge ))
322 diskSize=$(( requiredFilesystemSpace + additionalSpace ))
324 # Round up to the nearest mebibyte.
325 # This ensures whole 512 bytes sector sizes in the disk image
326 # and helps towards aligning partitions optimally.
327 if (( diskSize % mebibyte )); then
328 diskSize=$(( ( diskSize / mebibyte + 1) * mebibyte ))
331 truncate -s "$diskSize" $diskImage
333 printf "Automatic disk size...\n"
334 printf " Closure space use: %d bytes\n" $diskUsage
335 printf " fudge: %d bytes\n" $fudge
336 printf " Filesystem size needed: %d bytes\n" $requiredFilesystemSpace
337 printf " Additional space: %d bytes\n" $additionalSpace
338 printf " Disk image size: %d bytes\n" $diskSize
340 truncate -s ${toString diskSize}M $diskImage
343 ${partitionDiskScript}
345 ${if partitionTableType != "none" then ''
346 # Get start & length of the root partition in sectors to $START and $SECTORS.
347 eval $(partx $diskImage -o START,SECTORS --nr ${rootPartition} --pairs)
349 mkfs.${fsType} -b ${blockSize} -F -L ${label} $diskImage -E offset=$(sectorsToBytes $START) $(sectorsToKilobytes $SECTORS)K
351 mkfs.${fsType} -b ${blockSize} -F -L ${label} $diskImage
354 echo "copying staging root to image..."
355 cptofs -p ${optionalString (partitionTableType != "none") "-P ${rootPartition}"} \
358 $root${optionalString onlyNixStore builtins.storeDir}/* / ||
359 (echo >&2 "ERROR: cptofs failed. diskSize might be too small for closure."; exit 1)
362 moveOrConvertImage = ''
363 ${if format == "raw" then ''
364 mv $diskImage $out/${filename}
366 ${pkgs.qemu}/bin/qemu-img convert -f raw -O ${format} ${compress} $diskImage $out/${filename}
368 diskImage=$out/${filename}
371 buildImage = pkgs.vmTools.runInLinuxVM (
372 pkgs.runCommand name {
373 preVM = prepareImage;
374 buildInputs = with pkgs; [ util-linux e2fsprogs dosfstools ];
375 postVM = moveOrConvertImage + postVM;
378 export PATH=${binPath}:$PATH
380 rootDisk=${if partitionTableType != "none" then "/dev/vda${rootPartition}" else "/dev/vda"}
382 # Some tools assume these exist
385 # make systemd-boot find ESP without udev
387 ln -s /dev/vda1 /dev/block/254:1
391 mount $rootDisk $mountPoint
393 # Create the ESP and mount it. Unlike e2fsprogs, mkfs.vfat doesn't support an
394 # '-E offset=X' option, so we can't do this outside the VM.
395 ${optionalString (partitionTableType == "efi" || partitionTableType == "hybrid") ''
397 mkfs.vfat -n ESP /dev/vda1
398 mount /dev/vda1 /mnt/boot
401 # Install a configuration.nix
402 mkdir -p /mnt/etc/nixos
403 ${optionalString (configFile != null) ''
404 cp ${configFile} /mnt/etc/nixos/configuration.nix
407 ${lib.optionalString installBootLoader ''
408 # Set up core system link, GRUB, etc.
409 NIXOS_INSTALL_BOOTLOADER=1 nixos-enter --root $mountPoint -- /nix/var/nix/profiles/system/bin/switch-to-configuration boot
411 # The above scripts will generate a random machine-id and we don't want to bake a single ID into all our images
412 rm -f $mountPoint/etc/machine-id
415 # Set the ownerships of the contents. The modes are set in preVM.
416 # No globbing on targets, so no need to set -f
417 targets_=(${concatStringsSep " " targets})
418 users_=(${concatStringsSep " " users})
419 groups_=(${concatStringsSep " " groups})
420 for ((i = 0; i < ''${#targets_[@]}; i++)); do
421 target="''${targets_[$i]}"
422 user="''${users_[$i]}"
423 group="''${groups_[$i]}"
424 if [ -n "$user$group" ]; then
425 # We have to nixos-enter since we need to use the user and group of the VM
426 nixos-enter --root $mountPoint -- chown -R "$user:$group" "$target"
432 # Make sure resize2fs works. Note that resize2fs has stricter criteria for resizing than a normal
433 # mount, so the `-c 0` and `-i 0` don't affect it. Setting it to `now` doesn't produce deterministic
434 # output, of course, but we can fix that when/if we start making images deterministic.
435 ${optionalString (fsType == "ext4") ''
436 tune2fs -T now -c 0 -i 0 $rootDisk
442 pkgs.runCommand name {}
443 (prepareImage + moveOrConvertImage + postVM)