summary refs log tree commit diff
path: root/nixos/modules/system/boot/grow-partition.nix
blob: 897602f9826ab32bb14dfc8c05af50b7b3d44f68 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# This module automatically grows the root partition.
# This allows an instance to be created with a bigger root filesystem
# than provided by the machine image.

{ config, lib, pkgs, ... }:

with lib;

{
  imports = [
    (mkRenamedOptionModule [ "virtualisation" "growPartition" ] [ "boot" "growPartition" ])
  ];

  options = {
    boot.growPartition = mkEnableOption (lib.mdDoc "growing the root partition on boot");
  };

  config = mkIf config.boot.growPartition {
    assertions = [
      {
        assertion = !config.boot.initrd.systemd.repart.enable && !config.systemd.repart.enable;
        message = "systemd-repart already grows the root partition and thus you should not use boot.growPartition";
      }
    ];
    systemd.services.growpart = {
      wantedBy = [ "-.mount" ];
      after = [ "-.mount" ];
      before = [ "systemd-growfs-root.service" ];
      conflicts = [ "shutdown.target" ];
      unitConfig.DefaultDependencies = false;
      serviceConfig = {
        Type = "oneshot";
        RemainAfterExit = true;
        TimeoutSec = "infinity";
        # growpart returns 1 if the partition is already grown
        SuccessExitStatus = "0 1";
      };

      script = ''
        rootDevice="${config.fileSystems."/".device}"
        rootDevice="$(readlink -f "$rootDevice")"
        parentDevice="$rootDevice"
        while [ "''${parentDevice%[0-9]}" != "''${parentDevice}" ]; do
          parentDevice="''${parentDevice%[0-9]}";
        done
        partNum="''${rootDevice#''${parentDevice}}"
        if [ "''${parentDevice%[0-9]p}" != "''${parentDevice}" ] && [ -b "''${parentDevice%p}" ]; then
          parentDevice="''${parentDevice%p}"
        fi
        "${pkgs.cloud-utils.guest}/bin/growpart" "$parentDevice" "$partNum"
      '';
    };
  };
}