summaryrefslogtreecommitdiffstats
path: root/lass/3modules/mysql-backup.nix
blob: 516f96c345fc83eb6cafdf23883c548f3e74e602 (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
{ config, lib, pkgs, ... }:

with lib;

let

  cfg = config.lass.mysqlBackup;

  out = {
    options.lass.mysqlBackup = api;
    config = mkIf cfg.enable imp;
  };

  api = {
    enable = mkEnableOption "mysqlBackup";
    config = mkOption {
      type = with types; attrsOf (submodule ({ config, ... }: {
        options = {
          name = mkOption {
            type = types.str;
            default = config._module.args.name;
          };
          startAt = mkOption {
            type = with types; nullOr str; # TODO systemd.time(7)'s calendar event
            default = "*-*-* 01:15:00";
          };
          user = mkOption {
            type = str;
            default = "root";
          };
          password = mkOption {
            type = nullOr str;
            default = null;
            description = ''
              path to a file containing the mysqlPassword for the specified user.
            '';
          };
          databases = mkOption {
            type = listOf str;
            default = [];
          };
          location = mkOption {
            type = str;
            default = "/backups/sql_dumps";
          };
        };
      }));
      description = "configuration for mysqlBackup";
    };
  };

  imp = {

    services.mysql.ensureUsers = [
      { ensurePermissions = { "*.*" = "ALL"; }; name = "root"; }
    ];

    systemd.services =
      mapAttrs' (_: plan: nameValuePair "mysqlBackup-${plan.name}" {
        path = with pkgs; [
          mysql
          gzip
        ];
        serviceConfig = rec {
          ExecStart = start plan;
          SyslogIdentifier = ExecStart.name;
          Type = "oneshot";
          User = plan.user;
        };
        startAt = plan.startAt;
      }) cfg.config;
  };


  start = plan: let
    backupScript = plan: db: ''
      mkdir -p ${plan.location}
      mysqldump -u ${plan.user} ${optionalString (plan.password != null) "-p$(cat ${plan.password})"} ${db} | gzip -c > ${plan.location}/${db}.gz
    '';

  in pkgs.pkgs.writeDash "mysqlBackup.${plan.name}" ''
    ${concatMapStringsSep "\n" (backupScript plan) plan.databases}
  '';


in out