summaryrefslogtreecommitdiff
path: root/custom/lvm-snapshots.nix
blob: ea69e1ff7eab62532ce36f6d7e1b85ac4fa7c2de (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.services.lvm-snapshots;

  snapshotMount = name: "${cfg.mountPoint}/${if isNull cfg.snapshots."${name}".mountName then name else cfg.snapshots."${name}".mountName}";
  snapshotName = name: "${name}-snapshot";

  snapshotConfig = {
    options = {
      LV = mkOption {
        type = types.str;
      };

      VG = mkOption {
        type = types.str;
      };

      mountName = mkOption {
        type = types.nullOr types.str;
        default = null;
      };
      
      cowSize = mkOption {
        type = types.str;
        default = "-l20%ORIGIN";
      };

      readOnly = mkOption {
        type = types.bool;
        default = true;
      };

      persist = mkOption {
        type = types.bool;
        default = false;
      };
    };
  };
in {
  options = {

    services.lvm-snapshots = {
      snapshots = mkOption {
        type = types.attrsOf (types.submodule snapshotConfig);
        default = {};
      };

      mountPoint = mkOption {
        type = types.path;
        readOnly = true;
        default = "/mnt";
      };
    };
  };

  
  config = mkIf (cfg != {}) {

    boot.kernelModules = [ "dm_snapshot" ];

    system.activationScripts = mapAttrs' (name: scfg: nameValuePair ("lvm-mountpoint" + name) ''
      mkdir -p ${snapshotMount name}
    '') cfg.snapshots;

    systemd.services = mapAttrs' (name: scfg: nameValuePair ("lvm-snapshot@" + snapshotName name) {
      enable = true;

      description = "LVM-snapshot of ${scfg.VG}/${scfg.LV}";

      unitConfig = {
        StopWhenUnneeded = true;
      };

      path = with pkgs; [ devicemapper ];
      
      script = ''
        lvcreate -s ${scfg.cowSize} --name ${snapshotName name} ${scfg.VG}/${scfg.LV}
      '';

      preStop = ''
        lvremove -f ${scfg.VG}/${snapshotName name}
      '';

      serviceConfig = with pkgs; {
        Type = "oneshot";
        RemainAfterExit = true;
      };
    }) cfg.snapshots;

    systemd.mounts = mapAttrsToList (name: scfg: {
      enable = true;

      unitConfig = {
        AssertPathIsDirectory = snapshotMount name;
        StopWhenUnneeded = !scfg.persist;
      };

      bindsTo = [ ("lvm-snapshot@" + snapshotName name + ".service") ];
      after = [ ("lvm-snapshot@" + snapshotName name + ".service") ];

      options = mkIf scfg.readOnly "ro";

      where = snapshotMount name;
      what = "/dev/" + scfg.VG + "/" + snapshotName name;
    }) cfg.snapshots;
  };
}