1{ pkgs
2, lib
3
4, # The NixOS configuration to be installed onto the disk image.
5 config
6
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.
10 diskSize ? "auto"
11
12, # additional disk space to be added to the image if diskSize "auto"
13 # is used
14 additionalSpace ? "512M"
15
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.
20 bootSize ? "256M"
21
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.
30 contents ? []
31
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
39 # created.
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"
46
47, # Whether to invoke `switch-to-configuration boot` during image creation
48 installBootLoader ? true
49
50, # The root file system type.
51 fsType ? "ext4"
52
53, # Filesystem label
54 label ? if onlyNixStore then "nix-store" else "nixos"
55
56, # The initial NixOS configuration file to be copied to
57 # /etc/nixos/configuration.nix.
58 configFile ? null
59
60, # Shell code executed after the VM has finished.
61 postVM ? ""
62
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`.
66 onlyNixStore ? false
67
68, name ? "nixos-disk-image"
69
70, # Disk image format, one of qcow2, qcow2-compressed, vdi, vpc, raw.
71 format ? "raw"
72
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
76 # updated.
77 copyChannel ? true
78
79, # Additional store paths to copy to the image's store.
80 additionalPaths ? []
81}:
82
83assert partitionTableType == "legacy" || partitionTableType == "legacy+gpt" || partitionTableType == "efi" || partitionTableType == "hybrid" || partitionTableType == "none";
84# We use -E offset=X below, which is only supported by e2fsprogs
85assert partitionTableType != "none" -> fsType == "ext4";
86# Either both or none of {user,group} need to be set
87assert lib.all
88 (attrs: ((attrs.user or null) == null)
89 == ((attrs.group or null) == null))
90 contents;
91assert onlyNixStore -> contents == [] && configFile == null && !installBootLoader;
92
93with lib;
94
95let format' = format; in let
96
97 format = if format' == "qcow2-compressed" then "qcow2" else format';
98
99 compress = optionalString (format' == "qcow2-compressed") "-c";
100
101 filename = "nixos." + {
102 qcow2 = "qcow2";
103 vdi = "vdi";
104 vpc = "vhd";
105 raw = "img";
106 }.${format} or format;
107
108 rootPartition = { # switch-case
109 legacy = "1";
110 "legacy+gpt" = "2";
111 efi = "2";
112 hybrid = "3";
113 }.${partitionTableType};
114
115 partitionDiskScript = { # switch-case
116 legacy = ''
117 parted --script $diskImage -- \
118 mklabel msdos \
119 mkpart primary ext4 1MiB -1
120 '';
121 "legacy+gpt" = ''
122 parted --script $diskImage -- \
123 mklabel gpt \
124 mkpart no-fs 1MB 2MB \
125 set 1 bios_grub on \
126 align-check optimal 1 \
127 mkpart primary ext4 2MB -1 \
128 align-check optimal 2 \
129 print
130 '';
131 efi = ''
132 parted --script $diskImage -- \
133 mklabel gpt \
134 mkpart ESP fat32 8MiB ${bootSize} \
135 set 1 boot on \
136 mkpart primary ext4 ${bootSize} -1
137 '';
138 hybrid = ''
139 parted --script $diskImage -- \
140 mklabel gpt \
141 mkpart ESP fat32 8MiB ${bootSize} \
142 set 1 boot on \
143 mkpart no-fs 0 1024KiB \
144 set 2 bios_grub on \
145 mkpart primary ext4 ${bootSize} -1
146 '';
147 none = "";
148 }.${partitionTableType};
149
150 nixpkgs = cleanSource pkgs.path;
151
152 # FIXME: merge with channel.nix / make-channel.nix.
153 channelSources = pkgs.runCommand "nixos-${config.system.nixos.version}" {} ''
154 mkdir -p $out
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
159 fi
160 rm -rf $out/nixos/.git
161 echo -n ${config.system.nixos.versionSuffix} > $out/nixos/.version-suffix
162 '';
163
164 binPath = with pkgs; makeBinPath (
165 [ rsync
166 util-linux
167 parted
168 e2fsprogs
169 lkl
170 config.system.build.nixos-install
171 config.system.build.nixos-enter
172 nix
173 ] ++ stdenv.initialPath);
174
175 # I'm preserving the line below because I'm going to search for it across nixpkgs to consolidate
176 # image building logic. The comment right below this now appears in 4 different places in nixpkgs :)
177 # !!! should use XML.
178 sources = map (x: x.source) contents;
179 targets = map (x: x.target) contents;
180 modes = map (x: x.mode or "''") contents;
181 users = map (x: x.user or "''") contents;
182 groups = map (x: x.group or "''") contents;
183
184 basePaths = [ config.system.build.toplevel ]
185 ++ lib.optional copyChannel channelSources;
186
187 additionalPaths' = subtractLists basePaths additionalPaths;
188
189 closureInfo = pkgs.closureInfo {
190 rootPaths = basePaths ++ additionalPaths';
191 };
192
193 blockSize = toString (4 * 1024); # ext4fs block size (not block device sector size)
194
195 prepareImage = ''
196 export PATH=${binPath}
197
198 # Yes, mkfs.ext4 takes different units in different contexts. Fun.
199 sectorsToKilobytes() {
200 echo $(( ( "$1" * 512 ) / 1024 ))
201 }
202
203 sectorsToBytes() {
204 echo $(( "$1" * 512 ))
205 }
206
207 # Given lines of numbers, adds them together
208 sum_lines() {
209 local acc=0
210 while read -r number; do
211 acc=$((acc+number))
212 done
213 echo "$acc"
214 }
215
216 mebibyte=$(( 1024 * 1024 ))
217
218 # Approximative percentage of reserved space in an ext4 fs over 512MiB.
219 # 0.05208587646484375
220 # × 1000, integer part: 52
221 compute_fudge() {
222 echo $(( $1 * 52 / 1000 ))
223 }
224
225 mkdir $out
226
227 root="$PWD/root"
228 mkdir -p $root
229
230 # Copy arbitrary other files into the image
231 # Semi-shamelessly copied from make-etc.sh. I (@copumpkin) shall factor this stuff out as part of
232 # https://github.com/NixOS/nixpkgs/issues/23052.
233 set -f
234 sources_=(${concatStringsSep " " sources})
235 targets_=(${concatStringsSep " " targets})
236 modes_=(${concatStringsSep " " modes})
237 set +f
238
239 for ((i = 0; i < ''${#targets_[@]}; i++)); do
240 source="''${sources_[$i]}"
241 target="''${targets_[$i]}"
242 mode="''${modes_[$i]}"
243
244 if [ -n "$mode" ]; then
245 rsync_chmod_flags="--chmod=$mode"
246 else
247 rsync_chmod_flags=""
248 fi
249 # Unfortunately cptofs only supports modes, not ownership, so we can't use
250 # rsync's --chown option. Instead, we change the ownerships in the
251 # VM script with chown.
252 rsync_flags="-a --no-o --no-g $rsync_chmod_flags"
253 if [[ "$source" =~ '*' ]]; then
254 # If the source name contains '*', perform globbing.
255 mkdir -p $root/$target
256 for fn in $source; do
257 rsync $rsync_flags "$fn" $root/$target/
258 done
259 else
260 mkdir -p $root/$(dirname $target)
261 if ! [ -e $root/$target ]; then
262 rsync $rsync_flags $source $root/$target
263 else
264 echo "duplicate entry $target -> $source"
265 exit 1
266 fi
267 fi
268 done
269
270 export HOME=$TMPDIR
271
272 # Provide a Nix database so that nixos-install can copy closures.
273 export NIX_STATE_DIR=$TMPDIR/state
274 nix-store --load-db < ${closureInfo}/registration
275
276 chmod 755 "$TMPDIR"
277 echo "running nixos-install..."
278 nixos-install --root $root --no-bootloader --no-root-passwd \
279 --system ${config.system.build.toplevel} \
280 ${if copyChannel then "--channel ${channelSources}" else "--no-channel-copy"} \
281 --substituters ""
282
283 ${optionalString (additionalPaths' != []) ''
284 nix copy --to $root --no-check-sigs ${concatStringsSep " " additionalPaths'}
285 ''}
286
287 diskImage=nixos.raw
288
289 ${if diskSize == "auto" then ''
290 ${if partitionTableType == "efi" || partitionTableType == "hybrid" then ''
291 # Add the GPT at the end
292 gptSpace=$(( 512 * 34 * 1 ))
293 # Normally we'd need to account for alignment and things, if bootSize
294 # represented the actual size of the boot partition. But it instead
295 # represents the offset at which it ends.
296 # So we know bootSize is the reserved space in front of the partition.
297 reservedSpace=$(( gptSpace + $(numfmt --from=iec '${bootSize}') ))
298 '' else if partitionTableType == "legacy+gpt" then ''
299 # Add the GPT at the end
300 gptSpace=$(( 512 * 34 * 1 ))
301 # And include the bios_grub partition; the ext4 partition starts at 2MB exactly.
302 reservedSpace=$(( gptSpace + 2 * mebibyte ))
303 '' else if partitionTableType == "legacy" then ''
304 # Add the 1MiB aligned reserved space (includes MBR)
305 reservedSpace=$(( mebibyte ))
306 '' else ''
307 reservedSpace=0
308 ''}
309 additionalSpace=$(( $(numfmt --from=iec '${additionalSpace}') + reservedSpace ))
310
311 # Compute required space in filesystem blocks
312 diskUsage=$(find . ! -type d -print0 | du --files0-from=- --apparent-size --block-size "${blockSize}" | cut -f1 | sum_lines)
313 # Each inode takes space!
314 numInodes=$(find . | wc -l)
315 # Convert to bytes, inodes take two blocks each!
316 diskUsage=$(( (diskUsage + 2 * numInodes) * ${blockSize} ))
317 # Then increase the required space to account for the reserved blocks.
318 fudge=$(compute_fudge $diskUsage)
319 requiredFilesystemSpace=$(( diskUsage + fudge ))
320
321 diskSize=$(( requiredFilesystemSpace + additionalSpace ))
322
323 # Round up to the nearest mebibyte.
324 # This ensures whole 512 bytes sector sizes in the disk image
325 # and helps towards aligning partitions optimally.
326 if (( diskSize % mebibyte )); then
327 diskSize=$(( ( diskSize / mebibyte + 1) * mebibyte ))
328 fi
329
330 truncate -s "$diskSize" $diskImage
331
332 printf "Automatic disk size...\n"
333 printf " Closure space use: %d bytes\n" $diskUsage
334 printf " fudge: %d bytes\n" $fudge
335 printf " Filesystem size needed: %d bytes\n" $requiredFilesystemSpace
336 printf " Additional space: %d bytes\n" $additionalSpace
337 printf " Disk image size: %d bytes\n" $diskSize
338 '' else ''
339 truncate -s ${toString diskSize}M $diskImage
340 ''}
341
342 ${partitionDiskScript}
343
344 ${if partitionTableType != "none" then ''
345 # Get start & length of the root partition in sectors to $START and $SECTORS.
346 eval $(partx $diskImage -o START,SECTORS --nr ${rootPartition} --pairs)
347
348 mkfs.${fsType} -b ${blockSize} -F -L ${label} $diskImage -E offset=$(sectorsToBytes $START) $(sectorsToKilobytes $SECTORS)K
349 '' else ''
350 mkfs.${fsType} -b ${blockSize} -F -L ${label} $diskImage
351 ''}
352
353 echo "copying staging root to image..."
354 cptofs -p ${optionalString (partitionTableType != "none") "-P ${rootPartition}"} \
355 -t ${fsType} \
356 -i $diskImage \
357 $root${optionalString onlyNixStore builtins.storeDir}/* / ||
358 (echo >&2 "ERROR: cptofs failed. diskSize might be too small for closure."; exit 1)
359 '';
360
361 moveOrConvertImage = ''
362 ${if format == "raw" then ''
363 mv $diskImage $out/${filename}
364 '' else ''
365 ${pkgs.qemu}/bin/qemu-img convert -f raw -O ${format} ${compress} $diskImage $out/${filename}
366 ''}
367 diskImage=$out/${filename}
368 '';
369
370 buildImage = pkgs.vmTools.runInLinuxVM (
371 pkgs.runCommand name {
372 preVM = prepareImage;
373 buildInputs = with pkgs; [ util-linux e2fsprogs dosfstools ];
374 postVM = moveOrConvertImage + postVM;
375 memSize = 1024;
376 } ''
377 export PATH=${binPath}:$PATH
378
379 rootDisk=${if partitionTableType != "none" then "/dev/vda${rootPartition}" else "/dev/vda"}
380
381 # Some tools assume these exist
382 ln -s vda /dev/xvda
383 ln -s vda /dev/sda
384 # make systemd-boot find ESP without udev
385 mkdir /dev/block
386 ln -s /dev/vda1 /dev/block/254:1
387
388 mountPoint=/mnt
389 mkdir $mountPoint
390 mount $rootDisk $mountPoint
391
392 # Create the ESP and mount it. Unlike e2fsprogs, mkfs.vfat doesn't support an
393 # '-E offset=X' option, so we can't do this outside the VM.
394 ${optionalString (partitionTableType == "efi" || partitionTableType == "hybrid") ''
395 mkdir -p /mnt/boot
396 mkfs.vfat -n ESP /dev/vda1
397 mount /dev/vda1 /mnt/boot
398 ''}
399
400 # Install a configuration.nix
401 mkdir -p /mnt/etc/nixos
402 ${optionalString (configFile != null) ''
403 cp ${configFile} /mnt/etc/nixos/configuration.nix
404 ''}
405
406 ${lib.optionalString installBootLoader ''
407 # Set up core system link, GRUB, etc.
408 NIXOS_INSTALL_BOOTLOADER=1 nixos-enter --root $mountPoint -- /nix/var/nix/profiles/system/bin/switch-to-configuration boot
409
410 # The above scripts will generate a random machine-id and we don't want to bake a single ID into all our images
411 rm -f $mountPoint/etc/machine-id
412 ''}
413
414 # Set the ownerships of the contents. The modes are set in preVM.
415 # No globbing on targets, so no need to set -f
416 targets_=(${concatStringsSep " " targets})
417 users_=(${concatStringsSep " " users})
418 groups_=(${concatStringsSep " " groups})
419 for ((i = 0; i < ''${#targets_[@]}; i++)); do
420 target="''${targets_[$i]}"
421 user="''${users_[$i]}"
422 group="''${groups_[$i]}"
423 if [ -n "$user$group" ]; then
424 # We have to nixos-enter since we need to use the user and group of the VM
425 nixos-enter --root $mountPoint -- chown -R "$user:$group" "$target"
426 fi
427 done
428
429 umount -R /mnt
430
431 # Make sure resize2fs works. Note that resize2fs has stricter criteria for resizing than a normal
432 # mount, so the `-c 0` and `-i 0` don't affect it. Setting it to `now` doesn't produce deterministic
433 # output, of course, but we can fix that when/if we start making images deterministic.
434 ${optionalString (fsType == "ext4") ''
435 tune2fs -T now -c 0 -i 0 $rootDisk
436 ''}
437 ''
438 );
439in
440 if onlyNixStore then
441 pkgs.runCommand name {}
442 (prepareImage + moveOrConvertImage + postVM)
443 else buildImage