Compare commits

..
2 Commits
Author SHA1 Message Date
Jörg Thalheim d4c64aee75 better error if no disks are configured 2024-08-26 18:13:17 +02:00
Jörg Thalheim 54bf06ba8c debug memory usage 2024-08-15 15:07:22 +02:00
22 changed files with 166 additions and 670 deletions

No files matched your search

+3 -2
View File
@@ -41,8 +41,9 @@ recursive layouts.
Disko doesn't require installation: it can be run directly from nix-community Disko doesn't require installation: it can be run directly from nix-community
repository. The [Quickstart Guide](./docs/quickstart.md) documents how to run repository. The [Quickstart Guide](./docs/quickstart.md) documents how to run
Disko in its simplest form when installing NixOS. Alternatively, you can also Disko in its simplest form when installing NixOS. Alternatively, you can
use the new [disko-install](./docs/disko-install.md) tool, which combines `disko` and `nixos-install` into one step. also use the new [disko-install](./docs/disko-install.md) tool, which combines
the `disko` and `nixos-install` into one step.
For information on other use cases, including upgrading from an older version of For information on other use cases, including upgrading from an older version of
**disko**, using **disko** without NixOS and downloading the module, see the **disko**, using **disko** without NixOS and downloading the module, see the
+3 -3
View File
@@ -1,7 +1,7 @@
# since lsblk lacks zfs support, we have to do it this way # since lsblk lacks zfs support, we have to do it this way
def remove: def remove:
if .fstype == "zfs_member" then if .fstype == "zfs_member" then
"if type zpool >/dev/null; then zpool destroy -f \(.label); zpool labelclear -f \(.label); fi" "zpool destroy -f \(.label)"
elif .fstype == "LVM2_member" then elif .fstype == "LVM2_member" then
[ [
"vg=$(pvs \(.path) --noheadings --options vg_name | grep -o '[a-zA-Z0-9-]*')", "vg=$(pvs \(.path) --noheadings --options vg_name | grep -o '[a-zA-Z0-9-]*')",
@@ -14,8 +14,8 @@ def remove:
# maybe its zfs # maybe its zfs
[ [
# the next line has some horrible escaping # the next line has some horrible escaping
"zpool=$(if type zdb >/dev/null; then zdb -l \(.path) | sed -nr $'s/ +name: \\'(.*)\\'/\\\\1/p'; fi)", "zpool=$(zdb -l \(.path) | sed -nr $'s/ +name: \\'(.*)\\'/\\\\1/p')",
"if [[ -n \"${zpool}\" ]]; then zpool destroy -f \"$zpool\"; zpool labelclear -f \"$zpool\"; fi", "if [[ -n \"${zpool}\" ]]; then zpool destroy -f \"$zpool\"; fi",
"unset zpool" "unset zpool"
] ]
else else
-17
View File
@@ -1,17 +0,0 @@
# Running Interactive VMs with disko
disko now exports its own flavor of interactive VMs (similiar to config.system.build.vm).
Simply import the disko module and build the vm runner with:
```
nix build -L '.#nixosConfigurations.mymachine.config.system.build.vmWithDisko'
```
afterwards you can run the interactive VM with:
```
result/bin/disko-vm
```
extraConfig that is set in disko.tests.extraConfig is also applied to the interactive VMs.
imageSize of the VMs will be determined by the imageSize in the disk type in your disko config.
memorySize is set by disko.memSize
+1 -2
View File
@@ -15,8 +15,7 @@ existing partitions. Dual booting with other operating systems is not supported.
### Step 1: Choose a Disk Configuration ### Step 1: Choose a Disk Configuration
Real-world templates are provided in this Real-world templates are provided in this [repository](https://github.com/nix-community/disko-templates).
[repository](https://github.com/nix-community/disko-templates).
More disk layouts for all filesystems can be also found in the More disk layouts for all filesystems can be also found in the
[example](https://github.com/nix-community/disko/tree/master/example) directory [example](https://github.com/nix-community/disko/tree/master/example) directory
-34
View File
@@ -1,34 +0,0 @@
{
disko.devices = {
disk = {
main = {
device = "/dev/disk/by-path/pci-0000:02:00.0-nvme-1";
type = "disk";
content = {
type = "gpt";
partitions = {
ESP = {
end = "500M";
type = "EF00";
content = {
type = "filesystem";
format = "vfat";
mountpoint = "/boot";
};
};
root = {
name = "root";
end = "-0";
content = {
type = "filesystem";
format = "f2fs";
mountpoint = "/";
};
};
};
};
};
};
};
}
-113
View File
@@ -1,113 +0,0 @@
{
disko.devices = {
disk = {
x = {
type = "disk";
device = "/dev/sdx";
content = {
type = "gpt";
partitions = {
ESP = {
size = "64M";
type = "EF00";
content = {
type = "filesystem";
format = "vfat";
mountpoint = "/boot";
};
};
zfs = {
size = "100%";
content = {
type = "zfs";
pool = "zroot";
};
};
};
};
};
y = {
type = "disk";
device = "/dev/sdy";
content = {
type = "gpt";
partitions = {
zfs = {
size = "100%";
content = {
type = "zfs";
pool = "zroot";
};
};
};
};
};
z = {
type = "disk";
device = "/dev/sdz";
content = {
type = "gpt";
partitions = {
zfs = {
size = "100%";
content = {
type = "zfs";
pool = "zroot";
};
};
};
};
};
cache = {
type = "disk";
device = "/dev/vdc";
content = {
type = "gpt";
partitions = {
zfs = {
size = "100%";
content = {
type = "zfs";
pool = "zroot";
};
};
};
};
};
};
zpool = {
zroot = {
type = "zpool";
mode = {
topology = {
type = "topology";
vdev = [
{
mode = "mirror";
members = [ "x" "y" ];
}
];
special = {
members = [ "z" ];
};
cache = [ "cache" ];
};
};
rootFsOptions = {
compression = "zstd";
"com.sun:auto-snapshot" = "false";
};
mountpoint = "/";
datasets = {
# See examples/zfs.nix for more comprehensive usage.
zfs_fs = {
type = "zfs_fs";
mountpoint = "/zfs_fs";
options."com.sun:auto-snapshot" = "true";
};
};
};
};
};
}
Generated
+3 -3
View File
@@ -2,11 +2,11 @@
"nodes": { "nodes": {
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1725194671, "lastModified": 1721782431,
"narHash": "sha256-tLGCFEFTB5TaOKkpfw3iYT9dnk4awTP/q4w+ROpMfuw=", "narHash": "sha256-UNDpwjYxNXQet/g3mgRLsQ9zxrbm9j2JEvP4ijF3AWs=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "b833ff01a0d694b910daca6e2ff4a3f26dee478c", "rev": "4f02464258baaf54992debfd010a7a3662a25536",
"type": "github" "type": "github"
}, },
"original": { "original": {
-3
View File
@@ -16,8 +16,6 @@ let
# a version of makeDiskImage which runs outside of the store # a version of makeDiskImage which runs outside of the store
makeDiskImagesScript = args: (import ./make-disk-image.nix ({ inherit diskoLib; } // args)).impure; makeDiskImagesScript = args: (import ./make-disk-image.nix ({ inherit diskoLib; } // args)).impure;
makeVMRunner = args: (import ./interactive-vm.nix ({ inherit diskoLib; } // args)).pure;
testLib = import ./tests.nix { inherit lib makeTest eval-config; }; testLib = import ./tests.nix { inherit lib makeTest eval-config; };
# like lib.types.oneOf but instead of a list takes an attrset # like lib.types.oneOf but instead of a list takes an attrset
# uses the field "type" to find the correct type in the attrset # uses the field "type" to find the correct type in the attrset
@@ -197,7 +195,6 @@ let
|| isAttrsOfSubmodule o || isAttrsOfSubmodule o
# TODO don't hardcode diskoLib.subType options. # TODO don't hardcode diskoLib.subType options.
|| n == "content" || n == "partitions" || n == "datasets" || n == "swap" || n == "content" || n == "partitions" || n == "datasets" || n == "swap"
|| n == "mode"
); );
in in
lib.toShellVars lib.toShellVars
-89
View File
@@ -1,89 +0,0 @@
{ nixosConfig
, diskoLib
, pkgs ? nixosConfig.pkgs
, name ? "${nixosConfig.config.networking.hostName}-disko-images"
, extraConfig ? { }
}:
let
lib = pkgs.lib;
vm_disko = (diskoLib.testLib.prepareDiskoConfig nixosConfig.config diskoLib.testLib.devices).disko;
cfg_ = (lib.evalModules {
modules = lib.singleton {
# _file = toString input;
imports = lib.singleton { disko.devices = vm_disko.devices; };
options = {
disko.devices = lib.mkOption {
type = diskoLib.toplevel;
};
disko.testMode = lib.mkOption {
type = lib.types.bool;
default = true;
};
};
};
}).config;
disks = lib.attrValues cfg_.disko.devices.disk;
diskoImages = diskoLib.makeDiskImages {
nixosConfig = nixosConfig;
copyNixStore = false;
extraConfig = {
disko.devices = cfg_.disko.devices;
};
testMode = true;
imageFormat = "qcow2";
};
rootDisk = {
name = "root";
file = ''"$tmp"/${(builtins.head disks).name}.qcow2'';
driveExtraOpts.cache = "writeback";
driveExtraOpts.werror = "report";
deviceExtraOpts.bootindex = "1";
deviceExtraOpts.serial = "root";
};
otherDisks = map
(disk: {
name = disk.name;
file = ''"$tmp"/${disk.name}.qcow2'';
driveExtraOpts.werror = "report";
})
(builtins.tail disks);
vm = (nixosConfig.extendModules {
modules = [
({ modulesPath, ... }: {
imports = [
(modulesPath + "/virtualisation/qemu-vm.nix")
];
})
{
virtualisation.useEFIBoot = nixosConfig.config.disko.tests.efi;
virtualisation.memorySize = nixosConfig.config.disko.memSize;
virtualisation.useDefaultFilesystems = false;
virtualisation.diskImage = null;
virtualisation.qemu.drives = [ rootDisk ] ++ otherDisks;
boot.zfs.devNodes = "/dev/disk/by-uuid"; # needed because /dev/disk/by-id is empty in qemu-vms
boot.zfs.forceImportAll = true;
}
{
# generated from disko config
virtualisation.fileSystems = cfg_.disko.devices._config.fileSystems;
boot = cfg_.disko.devices._config.boot or { };
swapDevices = cfg_.disko.devices._config.swapDevices or [ ];
}
nixosConfig.config.disko.tests.extraConfig
];
}).config.system.build.vm;
in
{
pure = pkgs.writers.writeDashBin "disko-vm" ''
set -efux
export tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
${lib.concatMapStringsSep "\n" (disk: ''
${pkgs.qemu}/bin/qemu-img create -f qcow2 \
-b ${diskoImages}/${disk.name}.qcow2 \
-F qcow2 "$tmp"/${disk.name}.qcow2
'') disks}
set +f
${vm}/bin/run-*-vm
'';
}
+32 -26
View File
@@ -1,33 +1,24 @@
{ nixosConfig { nixosConfig
, diskoLib , diskoLib
, pkgs ? nixosConfig.config.disko.imageBuilderPkgs , pkgs ? nixosConfig.pkgs
, lib ? pkgs.lib , lib ? pkgs.lib
, name ? "${nixosConfig.config.networking.hostName}-disko-images" , name ? "${nixosConfig.config.networking.hostName}-disko-images"
, extraPostVM ? nixosConfig.config.disko.extraPostVM , extraPostVM ? nixosConfig.config.disko.extraPostVM
, checked ? false , checked ? false
, copyNixStore ? true
, testMode ? false
, extraConfig ? { }
, imageFormat ? "raw"
}: }:
let let
vmTools = pkgs.vmTools.override { vmTools = pkgs.vmTools.override {
rootModules = [ "9p" "9pnet_virtio" "virtio_pci" "virtio_blk" ] ++ nixosConfig.config.disko.extraRootModules; rootModules = [ "9p" "9pnet_virtio" "virtio_pci" "virtio_blk" ] ++ nixosConfig.config.disko.extraRootModules;
customQemu = nixosConfig.config.disko.imageBuilderQemu;
kernel = pkgs.aggregateModules kernel = pkgs.aggregateModules
(with nixosConfig.config.disko.imageBuilderKernelPackages; [ kernel ] (with nixosConfig.config.boot.kernelPackages; [ kernel ]
++ lib.optional (lib.elem "zfs" nixosConfig.config.disko.extraRootModules) zfs); ++ lib.optional (lib.elem "zfs" nixosConfig.config.disko.extraRootModules) zfs);
}; };
cleanedConfig = diskoLib.testLib.prepareDiskoConfig nixosConfig.config diskoLib.testLib.devices; cleanedConfig = diskoLib.testLib.prepareDiskoConfig nixosConfig.config diskoLib.testLib.devices;
systemToInstall = nixosConfig.extendModules { systemToInstall = nixosConfig.extendModules {
modules = [ modules = [{
extraConfig disko.devices = lib.mkForce cleanedConfig.disko.devices;
{ boot.loader.grub.devices = lib.mkForce cleanedConfig.boot.loader.grub.devices;
disko.testMode = true; }];
disko.devices = lib.mkForce cleanedConfig.disko.devices;
boot.loader.grub.devices = lib.mkForce cleanedConfig.boot.loader.grub.devices;
}
];
}; };
dependencies = with pkgs; [ dependencies = with pkgs; [
bash bash
@@ -40,7 +31,7 @@ let
findutils findutils
] ++ nixosConfig.config.disko.extraDependencies; ] ++ nixosConfig.config.disko.extraDependencies;
preVM = '' preVM = ''
${lib.concatMapStringsSep "\n" (disk: "${pkgs.qemu}/bin/qemu-img create -f ${imageFormat} ${disk.name}.${imageFormat} ${disk.imageSize}") (lib.attrValues nixosConfig.config.disko.devices.disk)} ${lib.concatMapStringsSep "\n" (disk: "truncate -s ${disk.imageSize} ${disk.name}.raw") (lib.attrValues nixosConfig.config.disko.devices.disk)}
# This makes disko work, when canTouchEfiVariables is set to true. # This makes disko work, when canTouchEfiVariables is set to true.
# Technically these boot entries will no be persisted this way, but # Technically these boot entries will no be persisted this way, but
# in most cases this is OK, because we can rely on the standard location for UEFI executables. # in most cases this is OK, because we can rely on the standard location for UEFI executables.
@@ -49,7 +40,7 @@ let
postVM = '' postVM = ''
# shellcheck disable=SC2154 # shellcheck disable=SC2154
mkdir -p "$out" mkdir -p "$out"
${lib.concatMapStringsSep "\n" (disk: "mv ${disk.name}.${imageFormat} \"$out\"/${disk.name}.${imageFormat}") (lib.attrValues nixosConfig.config.disko.devices.disk)} ${lib.concatMapStringsSep "\n" (disk: "mv ${disk.name}.raw \"$out\"/${disk.name}.raw") (lib.attrValues nixosConfig.config.disko.devices.disk)}
${extraPostVM} ${extraPostVM}
''; '';
@@ -57,7 +48,6 @@ let
rootPaths = [ systemToInstall.config.system.build.toplevel ]; rootPaths = [ systemToInstall.config.system.build.toplevel ];
}; };
partitioner = '' partitioner = ''
set -efux
# running udev, stolen from stage-1.sh # running udev, stolen from stage-1.sh
echo "running udev..." echo "running udev..."
ln -sfn /proc/self/fd /dev/fd ln -sfn /proc/self/fd /dev/fd
@@ -73,20 +63,36 @@ let
udevadm trigger --action=add udevadm trigger --action=add
udevadm settle udevadm settle
${lib.optionalString testMode ''
export IN_DISKO_TEST=1
''}
${systemToInstall.config.system.build.diskoScript} ${systemToInstall.config.system.build.diskoScript}
''; '';
installer = lib.optionalString copyNixStore '' installer = ''
if [[ -f /sys/module/zfs/parameters/zfs_arc_max ]]; then
# We have seen `cp` run out of memory when copying the store paths and using zfs.
# Default for ARC is 1/2 of RAM, we choose 1/4 of RAM.
# Since we mostly write to the store and don't read from it, we don't need a large ARC.
# This hopefully gives zfs enough time to free up memory.
QUARTER_RAM=$(($(grep MemTotal /proc/meminfo | awk '{print $2 * 1024}') / 4))
echo "$QUARTER_RAM" > /sys/module/zfs/parameters/zfs_arc_max
fi
# Useful for monitoring memory usage
#echo $(($(cat /sys/module/zfs/parameters/zfs_arc_max) / 1024 / 1024)) MB
#(while true; do
# ${pkgs.procps}/bin/free -h
# if [[ -f /sys/module/zfs/parameters/zfs_arc_max ]]; then ${pkgs.zfs}/bin/arcstat; fi
# ${pkgs.procps}/bin/ps -eo pid,ppid,comm,%mem,%cpu --sort=-%mem | head -n 4
# # this can be very verbose
# # ${pkgs.linuxPackages_latest.mm-tools}/bin/slabinfo
# sleep 1
#done) &
# populate nix db, so nixos-install doesn't complain # populate nix db, so nixos-install doesn't complain
export NIX_STATE_DIR=${systemToInstall.config.disko.rootMountPoint}/nix/var/nix export NIX_STATE_DIR=${systemToInstall.config.disko.rootMountPoint}/nix/var/nix
nix-store --load-db < "${closureInfo}/registration" nix-store --load-db < "${closureInfo}/registration"
# We copy files with cp because `nix copy` seems to have a large memory leak # We copy files with rsync because `nix copy` seems to have a large memory leak
mkdir -p ${systemToInstall.config.disko.rootMountPoint}/nix/store ${pkgs.rsync}/bin/rsync -rtpl --files-from=${closureInfo}/store-paths / ${systemToInstall.config.disko.rootMountPoint}
xargs cp --recursive --target ${systemToInstall.config.disko.rootMountPoint}/nix/store < ${closureInfo}/store-paths
${systemToInstall.config.system.build.nixos-install}/bin/nixos-install --root ${systemToInstall.config.disko.rootMountPoint} --system ${systemToInstall.config.system.build.toplevel} --keep-going --no-channel-copy -v --no-root-password --option binary-caches "" ${systemToInstall.config.system.build.nixos-install}/bin/nixos-install --root ${systemToInstall.config.disko.rootMountPoint} --system ${systemToInstall.config.system.build.toplevel} --keep-going --no-channel-copy -v --no-root-password --option binary-caches ""
umount -Rv ${systemToInstall.config.disko.rootMountPoint} umount -Rv ${systemToInstall.config.disko.rootMountPoint}
@@ -97,7 +103,7 @@ let
"-drive if=pflash,format=raw,unit=1,file=efivars.fd" "-drive if=pflash,format=raw,unit=1,file=efivars.fd"
] ++ builtins.map ] ++ builtins.map
(disk: (disk:
"-drive file=${disk.name}.${imageFormat},if=virtio,cache=unsafe,werror=report,format=${imageFormat}" "-drive file=${disk.name}.raw,if=virtio,cache=unsafe,werror=report,format=raw"
) )
(lib.attrValues nixosConfig.config.disko.devices.disk)); (lib.attrValues nixosConfig.config.disko.devices.disk));
in in
-18
View File
@@ -13,23 +13,6 @@ let
default = name; default = name;
description = "Path to the swap file (relative to the mountpoint)"; description = "Path to the swap file (relative to the mountpoint)";
}; };
priority = lib.mkOption {
type = lib.types.nullOr lib.types.int;
default = null;
description = lib.mdDoc ''
Specify the priority of the swap file. Priority is a value between 0 and 32767.
Higher numbers indicate higher priority.
null lets the kernel choose a priority, which will show up as a negative value.
'';
};
options = lib.mkOption {
type = lib.types.listOf lib.types.nonEmptyStr;
default = [ "defaults" ];
example = [ "nofail" ];
description = "Options used to mount the swap.";
};
}; };
})); }));
default = { }; default = { };
@@ -41,7 +24,6 @@ let
swapDevices = builtins.map swapDevices = builtins.map
(file: { (file: {
device = "${mountpoint}/${file.path}"; device = "${mountpoint}/${file.path}";
inherit (file) priority options;
}) })
(lib.attrValues swap); (lib.attrValues swap);
}; };
+1 -1
View File
@@ -20,7 +20,7 @@
type = lib.types.strMatching "[0-9]+[KMGTP]?"; type = lib.types.strMatching "[0-9]+[KMGTP]?";
description = '' description = ''
size of the image if the makeDiskImages function from diksoLib is used. size of the image if the makeDiskImages function from diksoLib is used.
is used as an argument to "qemu-img create ..." is used as an argument to truncate -s
''; '';
default = "2G"; default = "2G";
}; };
-1
View File
@@ -90,7 +90,6 @@
else if (config.format == "ext3") then [ pkgs.e2fsprogs ] else if (config.format == "ext3") then [ pkgs.e2fsprogs ]
else if (config.format == "ext4") then [ pkgs.e2fsprogs ] else if (config.format == "ext4") then [ pkgs.e2fsprogs ]
else if (config.format == "bcachefs") then [ pkgs.bcachefs-tools ] else if (config.format == "bcachefs") then [ pkgs.bcachefs-tools ]
else if (config.format == "f2fs") then [ pkgs.f2fs-tools ]
else [ ] else [ ]
); );
description = "Packages"; description = "Packages";
+6 -7
View File
@@ -45,15 +45,14 @@ in
}; };
priority = lib.mkOption { priority = lib.mkOption {
type = lib.types.int; type = lib.types.int;
default = default = if partition.config.size or "" == "100%" then
if partition.config.size or "" == "100%" then 9001
9001 else if partition.config.type == "EF02" then
else if partition.config.type == "EF02" then
# Boot partition should be created first, because some BIOS implementations require it. # Boot partition should be created first, because some BIOS implementations require it.
# Priority defaults to 100 here to support any potential use-case for placing partitions prior to EF02 # Priority defaults to 100 here to support any potential use-case for placing partitions prior to EF02
100 100
else else
1000; 1000;
defaultText = '' defaultText = ''
1000: normal partitions 1000: normal partitions
9001: partitions with 100% size 9001: partitions with 100% size
+13 -21
View File
@@ -114,23 +114,19 @@ in
default = '' default = ''
if ! blkid "${config.device}" >/dev/null || ! (blkid "${config.device}" -o export | grep -q '^TYPE='); then if ! blkid "${config.device}" >/dev/null || ! (blkid "${config.device}" -o export | grep -q '^TYPE='); then
${lib.optionalString config.askPassword '' ${lib.optionalString config.askPassword ''
set +x
askPassword() { askPassword() {
if [ -z ''${IN_DISKO_TEST+x} ]; then echo "Enter password for ${config.device}: "
set +x IFS= read -r -s password
echo "Enter password for ${config.device}: " echo "Enter password for ${config.device} again to be safe: "
IFS= read -r -s password IFS= read -r -s password_check
echo "Enter password for ${config.device} again to be safe: " export password
IFS= read -r -s password_check [ "$password" = "$password_check" ]
export password
[ "$password" = "$password_check" ]
set -x
else
export password=disko
fi
} }
until askPassword; do until askPassword; do
echo "Passwords did not match, please try again." echo "Passwords did not match, please try again."
done done
set -x
''} ''}
cryptsetup -q luksFormat ${config.device} ${toString config.extraFormatArgs} ${keyFileArgs} cryptsetup -q luksFormat ${config.device} ${toString config.extraFormatArgs} ${keyFileArgs}
${cryptsetupOpen} --persistent ${cryptsetupOpen} --persistent
@@ -151,15 +147,11 @@ in
dev = '' dev = ''
if ! cryptsetup status ${config.name} >/dev/null 2>/dev/null; then if ! cryptsetup status ${config.name} >/dev/null 2>/dev/null; then
${lib.optionalString config.askPassword '' ${lib.optionalString config.askPassword ''
if [ -z ''${IN_DISKO_TEST+x} ]; then set +x
set +x echo "Enter password for ${config.device}"
echo "Enter password for ${config.device}" IFS= read -r -s password
IFS= read -r -s password export password
export password set -x
set -x
else
export password=disko
fi
''} ''}
${cryptsetupOpen} ${cryptsetupOpen}
fi fi
+2 -2
View File
@@ -3,7 +3,7 @@ let
# Load kernel modules to ensure device mapper types are available # Load kernel modules to ensure device mapper types are available
kernelModules = lib.filter (x: x != "") (map kernelModules = lib.filter (x: x != "") (map
(lv: lib.optionalString (lv.lvm_type != null && lv.lvm_type != "thinlv") "dm-${lv.lvm_type}") (lv: lib.optionalString (lv.lvm_type != null && lv.lvm_type != "thinlv") "dm-${lv.lvm_type}")
(lib.attrValues config.lvs)); (lib.attrValues config.lvs));
in in
{ {
options = { options = {
@@ -125,7 +125,7 @@ in
_config = lib.mkOption { _config = lib.mkOption {
internal = true; internal = true;
readOnly = true; readOnly = true;
default = [{ boot.initrd.kernelModules = kernelModules; }] ++ default = [ { boot.initrd.kernelModules = kernelModules; } ] ++
map map
(lv: [ (lv: [
(lib.optional (lv.content != null) lv.content._config) (lib.optional (lv.content != null) lv.content._config)
+2 -12
View File
@@ -28,12 +28,6 @@
default = [ ]; default = [ ];
description = "Extra arguments"; description = "Extra arguments";
}; };
mountOptions = lib.mkOption {
type = lib.types.listOf lib.types.nonEmptyStr;
default = [ "defaults" ];
example = [ "nofail" ];
description = "Options used to mount the swap.";
};
priority = lib.mkOption { priority = lib.mkOption {
type = lib.types.nullOr lib.types.int; type = lib.types.nullOr lib.types.int;
default = null; default = null;
@@ -66,8 +60,7 @@
}; };
_create = diskoLib.mkCreateOption { _create = diskoLib.mkCreateOption {
inherit config options; inherit config options;
# TODO: we don't support encrypted swap yet default = ''
default = lib.optionalString (!config.randomEncryption) ''
if ! blkid "${config.device}" -o export | grep -q '^TYPE='; then if ! blkid "${config.device}" -o export | grep -q '^TYPE='; then
mkswap \ mkswap \
${toString config.extraArgs} \ ${toString config.extraArgs} \
@@ -88,9 +81,7 @@
}"} ${ }"} ${
lib.optionalString (config.priority != null) lib.optionalString (config.priority != null)
"--priority=${toString config.priority}" "--priority=${toString config.priority}"
} \ } ${config.device}
--options=${lib.concatStringsSep "," config.mountOptions} \
${config.device}
fi fi
''; '';
}; };
@@ -107,7 +98,6 @@
# forward discard/TRIM attempts through dm-crypt # forward discard/TRIM attempts through dm-crypt
allowDiscards = config.discardPolicy != null; allowDiscards = config.discardPolicy != null;
}; };
options = config.mountOptions;
}]; }];
boot.resumeDevice = lib.mkIf config.resumeDevice config.device; boot.resumeDevice = lib.mkIf config.resumeDevice config.device;
}]; }];
+33 -38
View File
@@ -59,45 +59,40 @@
# important to prevent accidental shadowing of mount points # important to prevent accidental shadowing of mount points
# since (create order != mount order) # since (create order != mount order)
# -p creates parents automatically # -p creates parents automatically
default = default = let
let createOptions = (lib.optionalAttrs (config.mountpoint != null) { mountpoint = config.mountpoint; }) // config.options;
createOptions = (lib.optionalAttrs (config.mountpoint != null) { mountpoint = config.mountpoint; }) // config.options; # All options defined as PROP_ONETIME or PROP_ONETIME_DEFAULT in https://github.com/openzfs/zfs/blob/master/module/zcommon/zfs_prop.c
# All options defined as PROP_ONETIME or PROP_ONETIME_DEFAULT in https://github.com/openzfs/zfs/blob/master/module/zcommon/zfs_prop.c onetimeProperties = [
onetimeProperties = [ "encryption"
"encryption" "casesensitivity"
"casesensitivity" "utf8only"
"utf8only" "normalization"
"normalization" "volblocksize"
"volblocksize" "pbkdf2iters"
"pbkdf2iters" "pbkdf2salt"
"pbkdf2salt" "keyformat"
"keyformat" ];
]; updateOptions = builtins.removeAttrs config.options onetimeProperties;
updateOptions = builtins.removeAttrs config.options (onetimeProperties ++ [ "mountpoint" ]); mountpoint = config.options.mountpoint or config.mountpoint;
mountpoint = config.options.mountpoint or config.mountpoint; in ''
in if ! zfs get type ${config._name} >/dev/null 2>&1; then
'' zfs create -up ${config._name} \
if ! zfs get type ${config._name} >/dev/null 2>&1; then ${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "-o ${n}=${v}") (createOptions))}
zfs create -up ${config._name} \ ${lib.optionalString (updateOptions != {}) ''
${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "-o ${n}=${v}") (createOptions))} else
${lib.optionalString (updateOptions != {}) '' zfs set ${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "${n}=${v}") updateOptions)} ${config._name}
else ${lib.optionalString (mountpoint != null) ''
zfs set ${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "${n}=${v}") updateOptions)} ${config._name} # zfs will try unmount the dataset to change the mountpoint
${lib.optionalString (mountpoint != null) '' # but this might fail if the dataset is in use
if [[ "$(zfs get -H -o value mountpoint ${config._name})" != "${mountpoint}" ]]; then if ! zfs set mountpoint=${mountpoint} ${config._name}; then
echo "Changing mountpoint to '${mountpoint}' for ${config._name}..." echo "Failed to set mountpoint to '${mountpoint}' for ${config._name}." >&2
# zfs will try unmount the dataset to change the mountpoint echo "You may need to run when the pool is not mounted i.e. in a recovery system:" >&2
# but this might fail if the dataset is in use echo " zfs set mountpoint=${mountpoint} ${config._name}" >&2
if ! zfs set mountpoint=${mountpoint} ${config._name}; then fi
echo "Failed to set mountpoint to '${mountpoint}' for ${config._name}." >&2
echo "You may need to run when the pool is not mounted i.e. in a recovery system:" >&2
echo " zfs set mountpoint=${mountpoint} ${config._name}" >&2
fi
fi
''}
''} ''}
fi ''}
''; fi
'';
} // { readOnly = false; }; } // { readOnly = false; };
_mount = diskoLib.mkMountOption { _mount = diskoLib.mkMountOption {
+40 -163
View File
@@ -1,15 +1,4 @@
{ config, options, lib, diskoLib, rootMountPoint, ... }: { config, options, lib, diskoLib, rootMountPoint, ... }:
let
# TODO: Consider expanding to handle `disk` `file` and `draid` mode options.
modeOptions = [
""
"mirror"
"raidz"
"raidz1"
"raidz2"
"raidz3"
];
in
{ {
options = { options = {
name = lib.mkOption { name = lib.mkOption {
@@ -24,76 +13,14 @@ in
description = "Type"; description = "Type";
}; };
mode = lib.mkOption { mode = lib.mkOption {
type = lib.types.enum [
""
"mirror"
"raidz"
"raidz2"
"raidz3"
];
default = ""; default = "";
type = (lib.types.oneOf [
(lib.types.enum modeOptions)
(lib.types.attrsOf (diskoLib.subType {
types = {
topology =
let
vdev = lib.types.submodule ({ name, ... }: {
options = {
mode = lib.mkOption {
type = lib.types.enum modeOptions;
default = "";
description = "Mode of the zfs vdev";
};
members = lib.mkOption {
type = lib.types.listOf lib.types.str;
description = "Members of the vdev";
};
};
});
parent = config;
in
lib.types.submodule
({ config, name, ... }: {
options = {
type = lib.mkOption {
type = lib.types.enum [ "topology" ];
default = "topology";
internal = true;
description = "Type";
};
# zfs device types
vdev = lib.mkOption {
type = lib.types.listOf vdev;
default = [ ];
description = ''
A list of storage vdevs. See
https://openzfs.github.io/openzfs-docs/man/master/7/zpoolconcepts.7.html#Virtual_Devices_(vdevs)
for details.
'';
example = [{
mode = "mirror";
members = [ "x" "y" "/dev/sda1" ];
}];
};
special = lib.mkOption {
type = lib.types.nullOr vdev;
default = null;
description = ''
A vdev definition for a special device. See
https://openzfs.github.io/openzfs-docs/man/master/7/zpoolconcepts.7.html#special
for details.
'';
};
cache = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = null;
description = ''
A dedicated zfs cache device (L2ARC). See
https://openzfs.github.io/openzfs-docs/man/master/7/zpoolconcepts.7.html#Cache_Devices
for details.
'';
};
# TODO: Consider supporting log, spare, and dedup options.
};
});
};
extraArgs.parent = config;
}))
]);
description = "Mode of the ZFS pool"; description = "Mode of the ZFS pool";
}; };
options = lib.mkOption { options = lib.mkOption {
@@ -133,92 +60,42 @@ in
}; };
_create = diskoLib.mkCreateOption { _create = diskoLib.mkCreateOption {
inherit config options; inherit config options;
default = default = ''
let readarray -t zfs_devices < <(cat "$disko_devices_dir"/zfs_${config.name})
formatOutput = mode: members: '' # Try importing the pool without mounting anything if it exists.
entries+=("${mode}=${ # This allows us to set mounpoints.
lib.concatMapStringsSep " " if zpool import -N -f '${config.name}' || zpool list '${config.name}'; then
(d: if lib.strings.hasPrefix "/" d then d else "/dev/disk/by-partlabel/disk-${d}-zfs") members echo "not creating zpool ${config.name} as a pool with that name already exists" >&2
}") else
''; continue=1
formatVdev = vdev: formatOutput vdev.mode vdev.members; for dev in "''${zfs_devices[@]}"; do
hasTopology = !(builtins.isString config.mode); if ! blkid "$dev" >/dev/null; then
mode = if hasTopology then "prescribed" else config.mode; # blkid fails, so device seems empty
topology = lib.optionalAttrs hasTopology config.mode.topology; :
in elif (blkid "$dev" -o export | grep '^PTUUID='); then
'' echo "device $dev already has a partuuid, skipping creating zpool ${config.name}" >&2
readarray -t zfs_devices < <(cat "$disko_devices_dir"/zfs_${config.name}) continue=0
if [ ''${#zfs_devices[@]} -eq 0 ]; then elif (blkid "$dev" -o export | grep '^TYPE=zfs_member'); then
echo "no devices found for zpool ${config.name}. Did you misspell the pool name?" >&2 # zfs_member is a zfs partition, so we try to add the device to the pool
exit 1 :
fi elif (blkid "$dev" -o export | grep '^TYPE='); then
# Try importing the pool without mounting anything if it exists. echo "device $dev already has a partition, skipping creating zpool ${config.name}" >&2
# This allows us to set mounpoints. continue=0
if zpool import -N -f '${config.name}' || zpool list '${config.name}'; then
echo "not creating zpool ${config.name} as a pool with that name already exists" >&2
else
continue=1
for dev in "''${zfs_devices[@]}"; do
if ! blkid "$dev" >/dev/null; then
# blkid fails, so device seems empty
:
elif (blkid "$dev" -o export | grep '^PTUUID='); then
echo "device $dev already has a partuuid, skipping creating zpool ${config.name}" >&2
continue=0
elif (blkid "$dev" -o export | grep '^TYPE=zfs_member'); then
# zfs_member is a zfs partition, so we try to add the device to the pool
:
elif (blkid "$dev" -o export | grep '^TYPE='); then
echo "device $dev already has a partition, skipping creating zpool ${config.name}" >&2
continue=0
fi
done
if [ $continue -eq 1 ]; then
topology=""
# For shell check
mode="${mode}"
if [ "$mode" != "prescribed" ]; then
topology="${mode} ''${zfs_devices[*]}"
else
entries=()
${lib.optionalString (hasTopology && topology.vdev != null)
(lib.concatMapStrings formatVdev topology.vdev)}
${lib.optionalString (hasTopology && topology.special != null)
(formatOutput "special ${topology.special.mode}" topology.special.members)}
${lib.optionalString (hasTopology && topology.cache != [])
(formatOutput "cache" topology.cache)}
all_devices=()
for line in "''${entries[@]}"; do
# lineformat is mode=device1 device2 device3
mode=''${line%%=*}
devs=''${line#*=}
IFS=' ' read -r -a devices <<< "$devs"
all_devices+=("''${devices[@]}")
topology+=" ''${mode} ''${devices[*]}"
done
# all_devices sorted should equal zfs_devices sorted
all_devices_list=$(echo "''${all_devices[*]}" | tr ' ' '\n' | sort)
zfs_devices_list=$(echo "''${zfs_devices[*]}" | tr ' ' '\n' | sort)
if [[ "$all_devices_list" != "$zfs_devices_list" ]]; then
echo "not all disks accounted for, skipping creating zpool ${config.name}" >&2
diff <(echo "$all_devices_list" ) <(echo "$zfs_devices_list") >&2
continue=0
fi
fi
fi fi
if [ $continue -eq 1 ]; then done
zpool create -f ${config.name} \ if [ $continue -eq 1 ]; then
-R ${rootMountPoint} \ zpool create -f ${config.name} \
${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "-o ${n}=${v}") config.options)} \ -R ${rootMountPoint} ${config.mode} \
${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "-O ${n}=${v}") config.rootFsOptions)} \ ${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "-o ${n}=${v}") config.options)} \
''${topology:+ $topology} ${lib.concatStringsSep " " (lib.mapAttrsToList (n: v: "-O ${n}=${v}") config.rootFsOptions)} \
if [[ $(zfs get -H mounted ${config.name} | cut -f3) == "yes" ]]; then "''${zfs_devices[@]}"
zfs unmount ${config.name} if [[ $(zfs get -H mounted ${config.name} | cut -f3) == "yes" ]]; then
fi zfs unmount ${config.name}
fi fi
fi fi
${lib.concatMapStrings (dataset: dataset._create) (lib.attrValues config.datasets)} fi
''; ${lib.concatMapStrings (dataset: dataset._create) (lib.attrValues config.datasets)}
'';
}; };
_mount = diskoLib.mkMountOption { _mount = diskoLib.mkMountOption {
inherit config options; inherit config options;
+27 -66
View File
@@ -10,36 +10,6 @@ let
in in
{ {
options.disko = { options.disko = {
imageBuilderQemu = lib.mkOption {
type = lib.types.nullOr lib.types.str;
description = ''
the qemu emulator string used when building disk images via make-disk-image.nix.
Useful when using binfmt on your build host, and wanting to build disk
images for a foreign architecture
'';
default = null;
example = lib.literalExpression "\${pkgs.qemu_kvm}/bin/qemu-system-aarch64";
};
imageBuilderPkgs = lib.mkOption {
type = lib.types.attrs;
description = ''
the pkgs instance used when building disk images via make-disk-image.nix.
Useful when the config's kernel won't boot in the image-builder.
'';
default = pkgs;
defaultText = lib.literalExpression "pkgs";
example = lib.literalExpression "pkgs";
};
imageBuilderKernelPackages = lib.mkOption {
type = lib.types.attrs;
description = ''
the kernel used when building disk images via make-disk-image.nix.
Useful when the config's kernel won't boot in the image-builder.
'';
default = config.boot.kernelPackages;
defaultText = lib.literalExpression "config.boot.kernelPackages";
example = lib.literalExpression "pkgs.linuxPackages_testing";
};
extraRootModules = lib.mkOption { extraRootModules = lib.mkOption {
type = lib.types.listOf lib.types.str; type = lib.types.listOf lib.types.str;
description = '' description = ''
@@ -99,15 +69,6 @@ in
type = lib.types.bool; type = lib.types.bool;
default = false; default = false;
}; };
testMode = lib.mkOption {
internal = true;
description = ''
this is true if the system is being run in test mode.
like a vm test or an interactive vm
'';
type = lib.types.bool;
default = false;
};
tests = { tests = {
efi = lib.mkOption { efi = lib.mkOption {
description = '' description = ''
@@ -137,35 +98,35 @@ in
}; };
}; };
}; };
config = lib.mkIf (cfg.devices.disk != { }) { config = {
system.build = (cfg.devices._scripts { inherit pkgs; checked = cfg.checkScripts; }) // { system.build = lib.mapAttrs (name: cfg:
if cfg.devices.disk == {} then
throw ''
Cannot provide ${name} without disks configured.
Current value of disko.devices.disk is empty.
Set up a disk configuration according to:
https://github.com/nix-community/disko/blob/master/docs/quickstart.md#step-1-choose-a-disk-configuration
''
else cfg)
(cfg.devices._scripts { inherit pkgs; checked = cfg.checkScripts; } // {
diskoImages = diskoLib.makeDiskImages {
nixosConfig = args;
};
# we keep these old outputs for compatibility diskoImagesScript = diskoLib.makeDiskImagesScript {
disko = builtins.trace "the .disko output is deprecated, please use .diskoScript instead" (cfg.devices._scripts { inherit pkgs; }).diskoScript; nixosConfig = args;
diskoNoDeps = builtins.trace "the .diskoNoDeps output is deprecated, please use .diskoScriptNoDeps instead" (cfg.devices._scripts { inherit pkgs; }).diskoScriptNoDeps; };
diskoImages = diskoLib.makeDiskImages { installTest = diskoLib.testLib.makeDiskoTest {
nixosConfig = args; inherit extendModules pkgs;
}; name = "${config.networking.hostName}-disko";
diskoImagesScript = diskoLib.makeDiskImagesScript { disko-config = builtins.removeAttrs config [ "_module" ];
nixosConfig = args; testMode = "direct";
}; efi = cfg.tests.efi;
extraSystemConfig = cfg.tests.extraConfig;
installTest = diskoLib.testLib.makeDiskoTest { extraTestScript = cfg.tests.extraChecks;
inherit extendModules pkgs; };
name = "${config.networking.hostName}-disko"; });
disko-config = builtins.removeAttrs config [ "_module" ];
testMode = "direct";
efi = cfg.tests.efi;
extraSystemConfig = cfg.tests.extraConfig;
extraTestScript = cfg.tests.extraChecks;
};
vmWithDisko = diskoLib.makeVMRunner {
inherit pkgs;
nixosConfig = args;
};
};
# we need to specify the keys here, so we don't get an infinite recursion error # we need to specify the keys here, so we don't get an infinite recursion error
-16
View File
@@ -1,16 +0,0 @@
{ pkgs ? import <nixpkgs> { }
, diskoLib ? pkgs.callPackage ../lib { }
}:
diskoLib.testLib.makeDiskoTest {
inherit pkgs;
name = "f2fs";
disko-config = ../example/f2fs.nix;
extraTestScript = ''
machine.succeed("mountpoint /");
machine.succeed("lsblk --fs >&2");
'';
# so that the installer boots with a f2fs enabled kernel
extraInstallerConfig = {
boot.supportedFilesystems = [ "f2fs" ];
};
}
-33
View File
@@ -1,33 +0,0 @@
{ pkgs ? import <nixpkgs> { }
, diskoLib ? pkgs.callPackage ../lib { }
}:
diskoLib.testLib.makeDiskoTest {
inherit pkgs;
name = "zfs-with-vdevs";
disko-config = ../example/zfs-with-vdevs.nix;
extraInstallerConfig.networking.hostId = "8425e349";
extraSystemConfig = {
networking.hostId = "8425e349";
};
extraTestScript = ''
def assert_property(ds, property, expected_value):
out = machine.succeed(f"zfs get -H {property} {ds} -o value").rstrip()
assert (
out == expected_value
), f"Expected {property}={expected_value} on {ds}, got: {out}"
# These fields are 0 if l2arc is disabled
assert (
machine.succeed(
"cat /proc/spl/kstat/zfs/arcstats"
" | grep '^l2_' | tr -s ' '"
" | cut -s -d ' ' -f3 | uniq"
).strip() != "0"
), "Excepted cache to be utilized."
assert_property("zroot", "compression", "zstd")
assert_property("zroot/zfs_fs", "com.sun:auto-snapshot", "true")
assert_property("zroot/zfs_fs", "compression", "zstd")
machine.succeed("mountpoint /zfs_fs");
'';
}