aboutsummaryrefslogtreecommitdiff
path: root/modules/apps/filebackup.nix
blob: 55412a171d337ad06c02af8c12c4bf79a9ef32a0 (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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
{ config, pkgs, lib, ... }:
let

  inherit (builtins)
    isBool isList isString ;
  inherit (lib)
    concatMapStringsSep concatStringsSep filterAttrs
    hasPrefix mapAttrsToList mkIf
    mkOption optionalString removeSuffix ;
  inherit (lib.types)
    attrsOf bool enum int listOf nullOr path str submodule ;

  cfg = config.nixsap.apps.filebackup;
  privateDir = "/run/filebackup";

  s3cmd = "${pkgs.s3cmd}/bin/s3cmd ${optionalString (cfg.s3cfg != null) "-c '${cfg.s3cfg}'"}";

  gpgPubKeys = cfg.encrypt;
  gpg = "${pkgs.gpg}/bin/gpg2";
  pubring = pkgs.runCommand "pubring.kbx" {} ''
    ${gpg} --homedir . --import ${toString gpgPubKeys}
    cp pubring.kbx $out
  '';

  default = d: t: mkOption { type = t; default = d; };
  optional = type: mkOption { type = nullOr type; default = null; };
  sub = options: submodule { inherit options; } ;
  mandatory = type: mkOption { inherit type; };
  concatMapAttrsSep = s: f: attrs: concatStringsSep s (mapAttrsToList f attrs);

  command = sub
    {
      absolute-names      = optional bool;
      exclude             = optional (listOf str);
      exclude-from        = optional path;
      exclude-vcs         = optional bool;
      exclude-vcs-ignores = optional bool;
      group               = optional str;
      ignore-case         = optional bool;
      mode                = optional str;
      owner               = optional str;
      path                = mandatory (listOf path);
    };

  job = name: o:
    let
      args = filterAttrs (k: v:
          v != null && k != "_module"
          && ( k != "path" )
        ) o;

      mkArg = k: v:
       if isBool v then (optionalString v "--${k}")
       else if isList v then concatMapStringsSep " " (i: "--${k}='${i}'") v
       else if isString v then "--${k}='${v}'"
       else "--${k}=${toString v}" ;

      tar = pkgs.writeBashScript "tar-${name}" ''
        exec ${pkgs.gnutar}/bin/tar -c -f- \
          ${concatMapAttrsSep " " mkArg args} \
          "$@"
      '';

    in pkgs.writeBashScript "tar-${name}-job" ''
      set -euo pipefail
      cd "${cfg.tarballDir}/$DATE"
      host=$(${pkgs.nettools}/bin/hostname -f)

      tarball="${name}@$host,$DATE.tar.xz"
      ${
        if (gpgPubKeys != []) then
          ''aim="$tarball.gpg"''
        else
          ''aim="$tarball"''
      }

      if ! [ -r "$aim" ]; then
        ${tar} ${concatMapStringsSep " " (p: "'${p}'") o.path} \
          | ${pkgs.pxz}/bin/pxz -2 -T2 > "$tarball.tmp"
        mv "$tarball".tmp "$tarball"

        ${optionalString (gpgPubKeys != []) ''
          recipient=( $(${gpg} --homedir '${privateDir}/gnupg' -k --with-colons --fast-list-mode | \
            ${pkgs.gawk}/bin/awk -F: '/^pub/{print $5}') )
          r=( "''${recipient[@]/#/-r}" )
          ${gpg} --homedir '${privateDir}/gnupg' --batch --no-tty --yes \
            "''${r[@]}" --trust-model always \
            --compress-algo none \
            -v -e "$tarball"
          rm -f "$tarball"
        ''}
      else
        echo "$aim exists. Not creating." >&2
      fi
      ${optionalString (cfg.s3uri != null) ''
        remote="${removeSuffix "/" cfg.s3uri}/$DATE/$aim"
        if ! ${s3cmd} ls "$remote" | ${pkgs.gnugrep}/bin/grep -qF "/$aim"; then
          ${s3cmd} put "$aim" "$remote"
        else
          echo "$remote exists. Not uploading." >&2
        fi
      ''}
    '';

  preStart = ''
    mkdir --mode=0750 -p '${cfg.tarballDir}'
    chown -R ${cfg.user}:${cfg.user} '${cfg.tarballDir}'
    chmod -R u=rwX,g=rX,o= ${cfg.tarballDir}

    rm -rf '${privateDir}'
    mkdir --mode=0700 -p '${privateDir}'
    chown ${cfg.user}:${cfg.user} '${privateDir}'
  '';

  main = pkgs.writeBashScriptBin "filebackup" ''
    set -euo pipefail
    umask 0027
    DATE=$(date --iso-8601)
    HOME='${privateDir}'
    PARALLEL_SHELL=${pkgs.bash}/bin/bash
    export DATE
    export HOME
    export PARALLEL_SHELL

    clean() {
      ${pkgs.findutils}/bin/find '${cfg.tarballDir}' \
        -name '*.tmp' -exec rm -rf {} + || true
    }

    listSets() {
      ${pkgs.findutils}/bin/find '${cfg.tarballDir}' \
        -maxdepth 1 -mindepth 1 -type d -name '????-??-??' \
        | sort -V
    }

    enoughStorage() {
      local n
      local used
      local total
      local avg
      local p
      n=$(listSets | wc -l)
      used=$(du -x -s --block-size=1M '${cfg.tarballDir}' | cut -f1)
      total=$(df --output=size --block-size=1M '${cfg.tarballDir}' | tail -n 1)
      if [ "$n" -eq 0 ]; then
        echo "no sets" >&2
        return 0
      fi

      avg=$(( used / n ))
      p=$(( 100 * avg * (n + 1) / total ))
      printf "estimated storage: %d of %d MiB (%d%%, max ${toString cfg.storage}%%)\n" \
             "$((used + avg))" "$total" "$p" >&2
      if [ "$p" -le ${toString cfg.storage} ]; then
        return 0
      else
        return 1
      fi
    }

    clean

    listSets | head -n -${toString (cfg.slots - 1)} \
      | ${pkgs.findutils}/bin/xargs --no-run-if-empty rm -rfv \
      || true

    while ! enoughStorage; do
      listSets | head -n 1 \
      | ${pkgs.findutils}/bin/xargs --no-run-if-empty rm -rfv \
      || true
    done

    mkdir -p "${cfg.tarballDir}/$DATE"

    ${optionalString (gpgPubKeys != []) ''
      # shellcheck disable=SC2174
      mkdir --mode=0700 -p '${privateDir}/gnupg'
      ln -sf ${pubring} '${privateDir}/gnupg/pubring.kbx'
    ''}

    failed=0
    log="${cfg.tarballDir}/$DATE/joblog.txt"

    # shellcheck disable=SC2016
    ${pkgs.parallel}/bin/parallel \
      --halt-on-error 0 \
      --joblog "$log" \
      --jobs 50% \
      --line-buffer \
      --no-notice \
      --no-run-if-empty \
      --retries 2 \
      --rpl '{nixbase} s:^/nix/store/[^-]+-tar-(.+)-job$:$1:' \
      --tagstr '* {nixbase}:' \
      --timeout ${toString (6 * 60 * 60)} ::: \
      ${concatMapAttrsSep " " job cfg.files} \
      || failed=$?

    cat "$log"
    clean

    du -sh "${cfg.tarballDir}/$DATE" || true
    exit "$failed"
  '';

in {
  options.nixsap.apps.filebackup = {
    user = mkOption {
      description = "User to run as";
      default = "filebackup";
      type = str;
    };

    tarballDir = mkOption {
      description = "Directory to save tarballs in";
      default = "/filebackup";
      type = path;
    };

    slots = mkOption {
      description = ''
        How many backup sets should be kept locally.
        However, old sets will be removed anyway if storage
        constraints apply.
        '';
      default = 60;
      type = int;
    };

    storage = mkOption {
      description = ''
        Percent of storage backups can occupy.
      '';
      default = 75;
      type = int;
    };

    encrypt = mkOption {
      description = "Public GPG key(s) for encrypting the dumps";
      default = [ ];
      type = listOf path;
    };

    s3cfg = mkOption {
      description = "s3cmd config file (secret)";
      type = nullOr path;
      default = null;
    };

    s3uri = mkOption {
      description = "S3 bucket URI with prefix in s3cmd format";
      type = nullOr str;
      default = null;
      example = "s3://backups/nightly";
    };

    files = mkOption {
      description = "tar commands";
      default = {};
      type = attrsOf command;
    };
  };

  config = mkIf (cfg.files != {}) {
    nixsap.system.users.daemons = [ cfg.user ];
    nixsap.deployment.keyrings.${cfg.user} = [ cfg.s3cfg ];
    systemd.services.filebackup = {
      description = "Directory backup with tar";
      after = [ "local-fs.target" "keys.target" ];
      wants = [ "keys.target" ];
      startAt = "02:00";
      inherit preStart;
      serviceConfig = {
        ExecStart = "${main}/bin/filebackup";
        User = cfg.user;
        PermissionsStartOnly = true;
      };
    };
  };
}