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 diskSize
9
10 # The files and directories to be placed in the target file system.
11 # This is a list of attribute sets {source, target} where `source'
12 # is the file system object (regular file or directory) to be
13 # grafted in the file system at path `target'.
14, contents ? []
15
16, # Type of partition table to use; either "legacy", "efi", or "none".
17 # For "efi" images, the GPT partition table is used and a mandatory ESP
18 # partition of reasonable size is created in addition to the root partition.
19 # If `installBootLoader` is true, GRUB will be installed in EFI mode.
20 # For "legacy", the msdos partition table is used and a single large root
21 # partition is created. If `installBootLoader` is true, GRUB will be
22 # installed in legacy mode.
23 # For "none", no partition table is created. Enabling `installBootLoader`
24 # most likely fails as GRUB will probably refuse to install.
25 partitionTableType ? "legacy"
26
27, # The root file system type.
28 fsType ? "ext4"
29
30, # The initial NixOS configuration file to be copied to
31 # /etc/nixos/configuration.nix.
32 configFile ? null
33
34, # Shell code executed after the VM has finished.
35 postVM ? ""
36
37, name ? "nixos-disk-image"
38
39, # Disk image format, one of qcow2, qcow2-compressed, vpc, raw.
40 format ? "raw"
41}:
42
43assert partitionTableType == "legacy" || partitionTableType == "efi" || partitionTableType == "none";
44# We use -E offset=X below, which is only supported by e2fsprogs
45assert partitionTableType != "none" -> fsType == "ext4";
46
47with lib;
48
49let format' = format; in let
50
51 format = if format' == "qcow2-compressed" then "qcow2" else format';
52
53 compress = optionalString (format' == "qcow2-compressed") "-c";
54
55 filename = "nixos." + {
56 qcow2 = "qcow2";
57 vpc = "vhd";
58 raw = "img";
59 }.${format};
60
61 rootPartition = { # switch-case
62 legacy = "1";
63 efi = "2";
64 }.${partitionTableType};
65
66 partitionDiskScript = { # switch-case
67 legacy = ''
68 parted --script $diskImage -- \
69 mklabel msdos \
70 mkpart primary ext4 1MiB -1
71 '';
72 efi = ''
73 parted --script $diskImage -- \
74 mklabel gpt \
75 mkpart ESP fat32 8MiB 256MiB \
76 set 1 boot on \
77 mkpart primary ext4 256MiB -1
78 '';
79 none = "";
80 }.${partitionTableType};
81
82 nixpkgs = cleanSource pkgs.path;
83
84 # FIXME: merge with channel.nix / make-channel.nix.
85 channelSources = pkgs.runCommand "nixos-${config.system.nixos.version}" {} ''
86 mkdir -p $out
87 cp -prd ${nixpkgs} $out/nixos
88 chmod -R u+w $out/nixos
89 if [ ! -e $out/nixos/nixpkgs ]; then
90 ln -s . $out/nixos/nixpkgs
91 fi
92 rm -rf $out/nixos/.git
93 echo -n ${config.system.nixos.versionSuffix} > $out/nixos/.version-suffix
94 '';
95
96 binPath = with pkgs; makeBinPath (
97 [ rsync
98 utillinux
99 parted
100 e2fsprogs
101 lkl
102 config.system.build.nixos-install
103 config.system.build.nixos-enter
104 nix
105 ] ++ stdenv.initialPath);
106
107 # I'm preserving the line below because I'm going to search for it across nixpkgs to consolidate
108 # image building logic. The comment right below this now appears in 4 different places in nixpkgs :)
109 # !!! should use XML.
110 sources = map (x: x.source) contents;
111 targets = map (x: x.target) contents;
112
113 closureInfo = pkgs.closureInfo { rootPaths = [ config.system.build.toplevel channelSources ]; };
114
115 prepareImage = ''
116 export PATH=${binPath}
117
118 # Yes, mkfs.ext4 takes different units in different contexts. Fun.
119 sectorsToKilobytes() {
120 echo $(( ( "$1" * 512 ) / 1024 ))
121 }
122
123 sectorsToBytes() {
124 echo $(( "$1" * 512 ))
125 }
126
127 mkdir $out
128 diskImage=nixos.raw
129 truncate -s ${toString diskSize}M $diskImage
130
131 ${partitionDiskScript}
132
133 ${if partitionTableType != "none" then ''
134 # Get start & length of the root partition in sectors to $START and $SECTORS.
135 eval $(partx $diskImage -o START,SECTORS --nr ${rootPartition} --pairs)
136
137 mkfs.${fsType} -F -L nixos $diskImage -E offset=$(sectorsToBytes $START) $(sectorsToKilobytes $SECTORS)K
138 '' else ''
139 mkfs.${fsType} -F -L nixos $diskImage
140 ''}
141
142 root="$PWD/root"
143 mkdir -p $root
144
145 # Copy arbitrary other files into the image
146 # Semi-shamelessly copied from make-etc.sh. I (@copumpkin) shall factor this stuff out as part of
147 # https://github.com/NixOS/nixpkgs/issues/23052.
148 set -f
149 sources_=(${concatStringsSep " " sources})
150 targets_=(${concatStringsSep " " targets})
151 set +f
152
153 for ((i = 0; i < ''${#targets_[@]}; i++)); do
154 source="''${sources_[$i]}"
155 target="''${targets_[$i]}"
156
157 if [[ "$source" =~ '*' ]]; then
158 # If the source name contains '*', perform globbing.
159 mkdir -p $root/$target
160 for fn in $source; do
161 rsync -a --no-o --no-g "$fn" $root/$target/
162 done
163 else
164 mkdir -p $root/$(dirname $target)
165 if ! [ -e $root/$target ]; then
166 rsync -a --no-o --no-g $source $root/$target
167 else
168 echo "duplicate entry $target -> $source"
169 exit 1
170 fi
171 fi
172 done
173
174 export HOME=$TMPDIR
175
176 # Provide a Nix database so that nixos-install can copy closures.
177 export NIX_STATE_DIR=$TMPDIR/state
178 nix-store --load-db < ${closureInfo}/registration
179
180 echo "running nixos-install..."
181 nixos-install --root $root --no-bootloader --no-root-passwd \
182 --system ${config.system.build.toplevel} --channel ${channelSources} --substituters ""
183
184 echo "copying staging root to image..."
185 cptofs -p ${optionalString (partitionTableType != "none") "-P ${rootPartition}"} -t ${fsType} -i $diskImage $root/* /
186 '';
187in pkgs.vmTools.runInLinuxVM (
188 pkgs.runCommand name
189 { preVM = prepareImage;
190 buildInputs = with pkgs; [ utillinux e2fsprogs dosfstools ];
191 postVM = ''
192 ${if format == "raw" then ''
193 mv $diskImage $out/${filename}
194 '' else ''
195 ${pkgs.qemu}/bin/qemu-img convert -f raw -O ${format} ${compress} $diskImage $out/${filename}
196 ''}
197 diskImage=$out/${filename}
198 ${postVM}
199 '';
200 memSize = 1024;
201 }
202 ''
203 export PATH=${binPath}:$PATH
204
205 rootDisk=${if partitionTableType != "none" then "/dev/vda${rootPartition}" else "/dev/vda"}
206
207 # Some tools assume these exist
208 ln -s vda /dev/xvda
209 ln -s vda /dev/sda
210
211 mountPoint=/mnt
212 mkdir $mountPoint
213 mount $rootDisk $mountPoint
214
215 # Create the ESP and mount it. Unlike e2fsprogs, mkfs.vfat doesn't support an
216 # '-E offset=X' option, so we can't do this outside the VM.
217 ${optionalString (partitionTableType == "efi") ''
218 mkdir -p /mnt/boot
219 mkfs.vfat -n ESP /dev/vda1
220 mount /dev/vda1 /mnt/boot
221 ''}
222
223 # Install a configuration.nix
224 mkdir -p /mnt/etc/nixos
225 ${optionalString (configFile != null) ''
226 cp ${configFile} /mnt/etc/nixos/configuration.nix
227 ''}
228
229 # Set up core system link, GRUB, etc.
230 NIXOS_INSTALL_BOOTLOADER=1 nixos-enter --root $mountPoint -- /nix/var/nix/profiles/system/bin/switch-to-configuration boot
231
232 # The above scripts will generate a random machine-id and we don't want to bake a single ID into all our images
233 rm -f $mountPoint/etc/machine-id
234
235 umount -R /mnt
236
237 # Make sure resize2fs works. Note that resize2fs has stricter criteria for resizing than a normal
238 # mount, so the `-c 0` and `-i 0` don't affect it. Setting it to `now` doesn't produce deterministic
239 # output, of course, but we can fix that when/if we start making images deterministic.
240 ${optionalString (fsType == "ext4") ''
241 tune2fs -T now -c 0 -i 0 $rootDisk
242 ''}
243 ''
244)