Daily backup jobs with Restic

#| file: modules/nixos/backups.nix
{
  pkgs,
  lib,
  config,
  ...
}:
let
  resticCmd = lib.getExe pkgs.restic;
  <<withRepo>>
in
{
  options.mjm.backups = lib.mkOption {
    default = { };
    type =
      lib.types.attrsOf
      <| lib.types.submodule (
        { name, ... }:
        {
          options = {
            <<options>>
          };
        }
      );
  };

  config = lib.mkIf (config.mjm.backups != { }) {
    <<config>>
  };

  _class = "nixos";
}

This module allows services to configure automatic daily backup jobs using Restic. It largely exists because of a limitation in the NixOS Restic module: there was no way to prepare files for a backup once and then back them up to two different Restic repositories. This is important to me because I want my backups to be stored both in my lab's local Garage cluster and in an offsite location that will be safe if my house burns down. I could have done this with multiple backup jobs, but then the preparation work would be duplicated, and in some cases, it's non-trivial work.

Because of this, I adapted that NixOS module into my own that serves my needs. It's been changed a lot since then, so while there may be some similarities between it and the official NixOS module, it's not a goal of mine to follow that module now that they've diverged.

Options

These options are available within the scope of a particular entry of mjm.backups.

repositoryName = lib.mkOption {
  type = lib.types.str;
  default = name;
};

A name for the Restic repository used to store the backups. Usually doesn't need to be set manually, as it defaults to the name of the job (the key of the job in mjm.backups).

paths = lib.mkOption {
  type = with lib.types; listOf str;
  default = [ ];
};

List of paths on disk that will be backed up.

exclude = lib.mkOption {
  type = with lib.types; listOf str;
  default = [ ];
};

List of paths that will be excluded from backups, even if they would otherwise be included by being part of the paths option. This can be used to exclude ephemeral files like logs or caches while otherwise backing up all of the data for a service.

user = lib.mkOption {
  type = lib.types.str;
  default = "root";
};

The user the backup job will run as. This should be a user that has permissions to read the files listed in paths as well as perform any preparation or cleanup actions for the job.

backupPrepareCommand = lib.mkOption {
  type = with lib.types; nullOr lines;
  default = null;
};

Optional execline script that will be run before performing the backup which can be used to prepare the contents of the backup. If the content that needs to be backed up doesn't normally exist on disk in the right form, this script can be used to create it as needed.

backupCleanupCommand = lib.mkOption {
  type = with lib.types; nullOr lines;
  default = null;
};

Optional execline script that will run after performing the backup. This is usually used to clean up any artifacts produced by the prepare command that are not needed anymore after the backup job has completed.

Config

mjm.spire.entries = {
  "backups-${config.networking.hostName}" = {
    spiffe_id = "svc/backups";
    parent_id = config.networking.hostName;
  };
  spiffe-creds-backups = {
    spiffe_id = "svc/backups";
    selectors = [
      {
        type = "systemd";
        value = "id:spiffe-creds@backups.service";
      }
    ];
  };
};
mjm.vault.services = [ "backups" ];
systemd.sockets."spiffe-creds@backups" = {
  overrideStrategy = "asDropin";
  wantedBy = [ "sockets.target" ];
};

This configuration does the same thing as:

mjm.services.backups = {
  secrets.enable = true;
};

But the above would cause infinite recursion, because entries in mjm.services can enable PostgreSQL, which has a backup job, which would then add a new service. So instead, the same work is done by hand.

systemd.timers = lib.mapAttrs' (
  name: cfg:
  lib.nameValuePair "restic-backups-${name}" {
    description = "Daily Restic Backup '${name}'";
    wantedBy = [ "timers.target" ];
    timerConfig = {
      OnCalendar = "daily";
      RandomizedDelaySec = "2h";
    };
  }
) config.mjm.backups;

Each backup job gets a systemd timer to run it daily. The start time is randomized a bit, so not every backup job is running at the same time. This especially matters if the same job is running on multiple hosts, as only one can lock the repository at a time, so it's important for them to be staggered.

systemd.services = lib.mapAttrs' (
  name: cfg:
  let
    <<prepareScript>>
    <<startScript>>
  in
  lib.nameValuePair "restic-backups-${name}" {
    description = "Daily Restic Backup '${name}'";
    environment = {
      RESTIC_CACHE_DIR = "/var/cache/restic-backups-${name}";
      RESTIC_PASSWORD_FILE = "%d/${name}.backup_password";
    };
    restartIfChanged = false;
    wants = [ "network-online.target" ];
    after = [ "network-online.target" ];
    startLimitBurst = 4;
    startLimitIntervalSec = 600;
    credentials = {
      backups = [
        "b2_key_id"
        "b2_application_key"
      ];
      ${name} = [ "backup_password" ];
    };
    serviceConfig = {
      Type = "oneshot";
      ExecStart = [
        "${startScript} onsite"
        "${startScript} offsite"
      ];
      ExecStartPre =
        lib.optional (cfg.backupPrepareCommand != null)
          "${pkgs.execline.writeScript "backup-prepare-command" "-P" cfg.backupPrepareCommand}"
        ++ [
          "${prepareScript} onsite"
          "${prepareScript} offsite"
        ];
      ExecStopPost =
        lib.optional (cfg.backupCleanupCommand != null)
          "${pkgs.execline.writeScript "backup-cleanup-command" "-P" cfg.backupCleanupCommand}";
      User = cfg.user;
      RuntimeDirectory = "restic-backups-${name}";
      CacheDirectory = "restic-backups-${name}";
      CacheDirectoryMode = "0700";
      PrivateTmp = true;
      Restart = "on-failure";
      RestartSec = "2m";
    };
  }
) config.mjm.backups;

Each backup job also produces a systemd service called "restic-backups-${name}" that performs the backup. This is the service that the daily timer will start. There's not as much going on here as it looks from the number of lines. I'll focus on just the important things.

Each job needs three credentials loaded from Vault. The "backups" service has credentials for accessing the Backblaze B2 bucket that stores off-site backups. The name of the job itself is expected to match a service that is already running on the host and has a secret called "backup_password" with a password to use for the repositories.

If the job defined a backupPrepareCommand, that is run first before anything else. Then both the on-site and off-site Restic repositories for the job are prepared if needed. Then the backup is performed for each location. The scripts to do this work are covered next.

prepareScript = pkgs.execline.writeScript "backup-prepare-${name}" "-S1" ''
  ${withRepo.${name}} $1

  if -nt { ${resticCmd} snapshots } ${resticCmd} init
'';

Both the prepare and start scripts for the job take a single argument, which is expected to be either "onsite" or "offsite" indicating one of two locations for the Restic repository. Each script is run once for each of the two locations. The location is passed to a "withRepo" script created for the job that sets up the environment for accessing the repository at that location. That script will be covered in more detail shortly.

After this bit of setup, preparing is simple: it creates the repository if it doesn't already exist.

TODO: "restic cat config --no-lock >/dev/null" is a better way to check if the repo exists.

startScript = pkgs.execline.writeScript "backup-start-${name}" "-S1" ''
  ${withRepo.${name}} $1

  if { ${resticCmd} backup ${excludeFlags} --files-from=${includePaths} }
  if { ${resticCmd} forget --prune --keep-weekly 4 --keep-daily 7 }
  ${resticCmd} check
'';

includePaths = cfg.paths |> lib.concatStringsSep "\n" |> pkgs.writeText "include-patterns";
excludeFlags =
  lib.optionalString (cfg.exclude != [ ])
    "--exclude-file=${cfg.exclude |> lib.concatStringsSep "\n" |> pkgs.writeText "exclude-patterns"}";

The start script actually performs the backup. Just like prepare, it uses the "withRepo" script to set up the environment for the given location. Then it performs a sequence of restic commands. It performs the backup, including and excluding files as configured for the job. Then it prunes the existing backups so that it keeps every day for the last week, then 4 weekly backups after that. Finally, it does a check to make sure the repository is consistent.

withRepo =
  config.mjm.backups
  |> lib.mapAttrs (
    name: cfg:
    let
      <<onsiteRepository>>
      <<offsiteRepository>>
    in
    pkgs.execline.writeScript "restic-with-repo-${name}" "-s1" ''
      define kind $1
      case $kind {
        "onsite" {
          <<with-repo-onsite>>
        }
        "offsite" {
          <<with-repo-offsite>>
        }
      }

      foreground { fdmove -c 1 2 echo "first argument must be onsite or offsite, got ''${kind}" }
      exit 1
    ''
  );

withRepo is an attribute set that holds an execline script for each backup job that will set up the environment correctly for targeting that job at either its on-site or off-site repository. This logic is used in a few different places so it makes sense to be able to reuse it.

The script checks its first argument and uses it to determine which path to follow. "onsite" and "offsite" are valid options; anything else produces an error.

onsiteRepository = "s3:http://localhost:3902/restic-backups/${cfg.repositoryName}";

On-site backups are stored in S3-compatible storage using Garage. They are all stored in a "restic-backups" bucket, under a key named for the job's repository.

#| id: with-repo-onsite
export RESTIC_REPOSITORY ${onsiteRepository}
export AWS_DEFAULT_REGION home
export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI /creds
exec $@

For on-site backups, AWS credentials can be fetched on-demand using SPIFFE credentials, similar to services that set s3.enable. The withRepo script just sets the necessary variables for that before executing the remaining arguments that were passed in.

offsiteRepository = "s3:s3.us-west-001.backblazeb2.com/mjm-restic-backups/${cfg.repositoryName}";

Off-site backups are also stored in S3-compatible storage, but in Backblaze B2 in this case. The bucket names are global, so it is prefixed with "mjm-", but otherwise this is very similar to the on-site storage.

#| id: with-repo-offsite
export RESTIC_REPOSITORY ${offsiteRepository}
importas -S CREDENTIALS_DIRECTORY
backtick AWS_ACCESS_KEY_ID { cat ''${CREDENTIALS_DIRECTORY}/backups.b2_key_id }
backtick AWS_SECRET_ACCESS_KEY { cat ''${CREDENTIALS_DIRECTORY}/backups.b2_application_key }
exec $@

The credentials for B2 cannot be fetched automatically. A static key ID and application key are stored in Vault, and the backup job is already set up to have that credential. withRepo just needs to read the files into the appropriate environment variables before executing the remaining arguments that were passed in.

environment.systemPackages = lib.mapAttrsToList (
  name: cfg:
  let
    <<innerScript>>
  in
  pkgs.execline.writeScriptBin "restic-${name}" "-s1" ''
    <<wrapper-env-setup>>
    <<wrapper-systemd-run>>
  ''
) config.mjm.backups;

Each backup job also gets a command added to the PATH on the host. This command wraps restic so that arbitrary restic commands can be run against the repositories for the job. This can be used to check on the snapshots or to restore files. It works to emulate the environment used in the systemd service for the job.

#| id: wrapper-env-setup
export BACKUP_KIND $1
export RESTIC_CACHE_DIR ${
  config.systemd.services."restic-backups-${name}".environment.RESTIC_CACHE_DIR
}

importas -S PATH
export PATH ${config.systemd.services."restic-backups-${name}".environment.PATH}:$PATH

First, the wrapper script sets up some environment variables that will be used later. BACKUP_KIND is one of the two valid locations mentioned earlier, and is taken from the first argument to the script. The rest will be passed along to restic. RESTIC_CACHE_DIR and PATH are taken from the systemd service for the job, with PATH being prepended to the existing PATH rather than overwriting it completely.

#| id: wrapper-systemd-run
${pkgs.systemd}/bin/systemd-run
  --service-type=oneshot
  --wait -qt --collect
  -p User=${cfg.user}
  -p LoadCredential=backups.b2_key_id:/run/backups-creds.sock
  -p LoadCredential=backups.b2_application_key:/run/backups-creds.sock
  -p LoadCredential=${name}.backup_password:/run/${name}-creds.sock
  -E BACKUP_KIND
  -E RESTIC_CACHE_DIR
  -E PATH
  ${innerScript}
  $@

Once the environment is setup, the wrapper uses systemd-run to fire off a one-off systemd service to run the command. The main benefit of this is the ability to use LoadCredential to load the necessary secrets, just like the actual job does. The service runs an inner script that does a little bit of extra work before calling restic.

innerScript = pkgs.execline.writeScript "restic-${name}-inner" "-S0" ''
  multisubstitute {
    importas -S BACKUP_KIND
    importas -S CREDENTIALS_DIRECTORY
  }

  ${withRepo.${name}} $BACKUP_KIND
  export RESTIC_PASSWORD_FILE ''${CREDENTIALS_DIRECTORY}/${name}.backup_password
  ${resticCmd} $@
'';

The inner script is needed for two reasons. It lets us use the withRepo script again to set up the environment for accessing the repository. It also works around a limitation of systemd-run when it comes to credentials. There's not a way to use specifiers like %d with -E or even -p Environment, and since the service name is random, there isn't really a way to get the credentials directory in the invocation of systemd-run. Instead, the script that the service runs can look at the $CREDENTIALS_DIRECTORY environment variable, so we do that in order to set the RESTIC_PASSWORD_FILE variable.

With all of the preparation done, the inner script execs into restic, passing it the additional arguments that were passed to the wrapper.

Proxy Information
Original URL
gemini://midna.dev/homelab/modules/nixos/backups/
Status Code
Success (20)
Meta
text/gemini;lang=en-US
Capsule Response Time
21.130312 milliseconds
Gemini-to-HTML Time
0.711334 milliseconds

This content has been proxied by September (UNKNO).