WIP: restic: add size-based snapshot retention #897
No files matched your search
Generated
+17
-14
@@ -91,7 +91,9 @@
|
|||||||
"nixpkgs": [
|
"nixpkgs": [
|
||||||
"nixpkgs"
|
"nixpkgs"
|
||||||
],
|
],
|
||||||
"systems": "systems"
|
"systems": [
|
||||||
|
"systems"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1770165109,
|
"lastModified": 1770165109,
|
||||||
@@ -360,7 +362,7 @@
|
|||||||
},
|
},
|
||||||
"flake-utils": {
|
"flake-utils": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"systems": "systems_2"
|
"systems": "systems"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1731533236,
|
"lastModified": 1731533236,
|
||||||
@@ -378,7 +380,7 @@
|
|||||||
},
|
},
|
||||||
"flake-utils_2": {
|
"flake-utils_2": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"systems": "systems_3"
|
"systems": "systems_2"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1731533236,
|
"lastModified": 1731533236,
|
||||||
@@ -396,7 +398,7 @@
|
|||||||
},
|
},
|
||||||
"flake-utils_3": {
|
"flake-utils_3": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"systems": "systems_4"
|
"systems": "systems_3"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1731533236,
|
"lastModified": 1731533236,
|
||||||
@@ -414,7 +416,7 @@
|
|||||||
},
|
},
|
||||||
"flake-utils_4": {
|
"flake-utils_4": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"systems": "systems_5"
|
"systems": "systems_4"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1731533236,
|
"lastModified": 1731533236,
|
||||||
@@ -432,7 +434,7 @@
|
|||||||
},
|
},
|
||||||
"flake-utils_5": {
|
"flake-utils_5": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"systems": "systems_6"
|
"systems": "systems_5"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1731533236,
|
"lastModified": 1731533236,
|
||||||
@@ -450,7 +452,7 @@
|
|||||||
},
|
},
|
||||||
"flake-utils_6": {
|
"flake-utils_6": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"systems": "systems_7"
|
"systems": "systems_6"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1731533236,
|
"lastModified": 1731533236,
|
||||||
@@ -716,6 +718,7 @@
|
|||||||
"personal-agent": "personal-agent",
|
"personal-agent": "personal-agent",
|
||||||
"qnaplcd-menu": "qnaplcd-menu",
|
"qnaplcd-menu": "qnaplcd-menu",
|
||||||
"status-jakehillion-me": "status-jakehillion-me",
|
"status-jakehillion-me": "status-jakehillion-me",
|
||||||
|
"systems": "systems_7",
|
||||||
"treefmt-nix": "treefmt-nix_5"
|
"treefmt-nix": "treefmt-nix_5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -918,16 +921,16 @@
|
|||||||
},
|
},
|
||||||
"systems_7": {
|
"systems_7": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1681028828,
|
"lastModified": 1742341894,
|
||||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
"narHash": "sha256-ZcOCmhgIqb5XGwTvjqhPHA8k71q1wLbKyK7/Pp4DawI=",
|
||||||
"owner": "nix-systems",
|
"owner": "JakeHillion",
|
||||||
"repo": "default",
|
"repo": "nix-systems",
|
||||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
"rev": "5d5894f8e9aa1a6f2963fb1b38ed8baea01d48c1",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
"owner": "nix-systems",
|
"owner": "JakeHillion",
|
||||||
"repo": "default",
|
"repo": "nix-systems",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -88,8 +88,9 @@
|
|||||||
"pbcli" = final.callPackage ./pkgs/pbcli.nix { };
|
"pbcli" = final.callPackage ./pkgs/pbcli.nix { };
|
||||||
"caddy-with-dns" = final.callPackage ./pkgs/caddy-with-dns.nix { };
|
"caddy-with-dns" = final.callPackage ./pkgs/caddy-with-dns.nix { };
|
||||||
"ogygia" = ogygia.packages.${final.system}.ogygia;
|
"ogygia" = ogygia.packages.${final.system}.ogygia;
|
||||||
"qnaplcd" = final.callPackage ./pkgs/qnaplcd.nix { inherit qnaplcd-menu; };
|
|
||||||
"opencode-plugin" = final.callPackage ./pkgs/opencode-plugin { };
|
"opencode-plugin" = final.callPackage ./pkgs/opencode-plugin { };
|
||||||
|
"qnaplcd" = final.callPackage ./pkgs/qnaplcd.nix { inherit qnaplcd-menu; };
|
||||||
|
"restic-forget" = final.callPackage ./pkgs/restic-forget.nix { };
|
||||||
})
|
})
|
||||||
];
|
];
|
||||||
mkSystem = import ./lib/mkSystem.nix { inherit inputs; };
|
mkSystem = import ./lib/mkSystem.nix { inherit inputs; };
|
||||||
|
|||||||
@@ -46,6 +46,21 @@ in
|
|||||||
opts = lib.mkOption {
|
opts = lib.mkOption {
|
||||||
type = listOf str;
|
type = listOf str;
|
||||||
};
|
};
|
||||||
|
maxSize = lib.mkOption {
|
||||||
|
default = null;
|
||||||
|
type = nullOr int;
|
||||||
|
description = "Max repo size in bytes. Oldest eligible snapshots forgotten when exceeded.";
|
||||||
|
};
|
||||||
|
minAgeDays = lib.mkOption {
|
||||||
|
default = 180;
|
||||||
|
type = int;
|
||||||
|
description = "Minimum snapshot age in days before eligible for size-based removal.";
|
||||||
|
};
|
||||||
|
repackSmall = lib.mkOption {
|
||||||
|
default = true;
|
||||||
|
type = bool;
|
||||||
|
description = "Repack small packs during prune. Disable for deep archive repos.";
|
||||||
|
};
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -133,8 +148,9 @@ in
|
|||||||
opts = [
|
opts = [
|
||||||
"--keep-within-daily 14d"
|
"--keep-within-daily 14d"
|
||||||
"--keep-within-weekly 2m"
|
"--keep-within-weekly 2m"
|
||||||
"--keep-within-monthly 18m"
|
"--keep-monthly unlimited"
|
||||||
];
|
];
|
||||||
|
maxSize = 2 * 1024 * 1024 * 1024 * 1024; # 2 TiB
|
||||||
};
|
};
|
||||||
|
|
||||||
clones = [
|
clones = [
|
||||||
@@ -164,6 +180,22 @@ in
|
|||||||
"aws-us-east-1" = {
|
"aws-us-east-1" = {
|
||||||
environmentFile = config.age.secrets."restic/aws-us-east-1.env".path;
|
environmentFile = config.age.secrets."restic/aws-us-east-1.env".path;
|
||||||
packSize = 128;
|
packSize = 128;
|
||||||
|
|
||||||
|
forgetConfig = {
|
||||||
|
timerConfig = {
|
||||||
|
OnCalendar = "Sun, 04:00 UTC";
|
||||||
|
RandomizedDelaySec = "2h";
|
||||||
|
Persistent = true;
|
||||||
|
};
|
||||||
|
opts = [
|
||||||
|
"--keep-within-daily 31d"
|
||||||
|
"--keep-within-weekly 16w"
|
||||||
|
"--keep-monthly unlimited"
|
||||||
|
];
|
||||||
|
maxSize = 5 * 1024 * 1024 * 1024 * 1024; # 5 TiB
|
||||||
|
minAgeDays = 180;
|
||||||
|
repackSmall = false; # deep archive: cannot repack
|
||||||
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -218,6 +250,9 @@ in
|
|||||||
|
|
||||||
mkForgetService = name: repo_cfg:
|
mkForgetService = name: repo_cfg:
|
||||||
if (repo_cfg.forgetConfig != null) then
|
if (repo_cfg.forgetConfig != null) then
|
||||||
|
let
|
||||||
|
fc = repo_cfg.forgetConfig;
|
||||||
|
in
|
||||||
lib.mkMerge [
|
lib.mkMerge [
|
||||||
{
|
{
|
||||||
description = "Restic forget service for ${name}";
|
description = "Restic forget service for ${name}";
|
||||||
@@ -227,14 +262,16 @@ in
|
|||||||
Group = "restic";
|
Group = "restic";
|
||||||
};
|
};
|
||||||
|
|
||||||
script = ''
|
path = [ pkgs.restic ];
|
||||||
set -xe
|
|
||||||
|
|
||||||
${pkgs.restic}/bin/restic forget ${lib.strings.concatStringsSep " " repo_cfg.forgetConfig.opts} \
|
script = ''
|
||||||
--prune \
|
${pkgs.restic-forget}/bin/restic-forget \
|
||||||
--repack-small \
|
--forget-args "${lib.strings.concatStringsSep " " fc.opts}" \
|
||||||
${lib.optionalString (repo_cfg.packSize != null) "--pack-size ${toString repo_cfg.packSize}"} \
|
${lib.optionalString (repo_cfg.packSize != null) "--pack-size ${toString repo_cfg.packSize}"} \
|
||||||
--retry-lock 30m
|
${lib.optionalString (fc.maxSize != null) "--max-size ${toString fc.maxSize}"} \
|
||||||
|
${lib.optionalString (fc.maxSize != null) "--min-age-days ${toString fc.minAgeDays}"} \
|
||||||
|
${lib.optionalString fc.repackSmall "--repack-small"} \
|
||||||
|
${lib.optionalString (!fc.repackSmall) "--max-repack-size 0"}
|
||||||
'';
|
'';
|
||||||
}
|
}
|
||||||
(mkRepoInfo repo_cfg)
|
(mkRepoInfo repo_cfg)
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{ lib, stdenv, python3, makeWrapper }:
|
||||||
|
|
||||||
|
let
|
||||||
|
python = python3.withPackages (ps: [ ps.pytest ]);
|
||||||
|
in
|
||||||
|
stdenv.mkDerivation {
|
||||||
|
pname = "restic-forget";
|
||||||
|
version = "0.1.0";
|
||||||
|
|
||||||
|
src = ./restic-forget;
|
||||||
|
|
||||||
|
nativeBuildInputs = [ makeWrapper ];
|
||||||
|
buildInputs = [ python ];
|
||||||
|
|
||||||
|
doCheck = true;
|
||||||
|
checkPhase = ''
|
||||||
|
${python}/bin/python -m pytest test_restic_forget.py -v
|
||||||
|
'';
|
||||||
|
|
||||||
|
installPhase = ''
|
||||||
|
mkdir -p $out/bin
|
||||||
|
cp restic_forget.py $out/bin/restic-forget
|
||||||
|
chmod +x $out/bin/restic-forget
|
||||||
|
wrapProgram $out/bin/restic-forget \
|
||||||
|
--prefix PATH : ${python}/bin
|
||||||
|
'';
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
description = "Restic forget with time-based and size-based retention";
|
||||||
|
license = lib.licenses.mit;
|
||||||
|
mainProgram = "restic-forget";
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Restic forget with time-based and optional size-based retention."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
|
||||||
|
def run_restic(*args):
|
||||||
|
"""Run a restic command and return stdout."""
|
||||||
|
cmd = ["restic", *args, "--retry-lock", "30m"]
|
||||||
|
print(f"+ {' '.join(cmd)}", flush=True)
|
||||||
|
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||||
|
return result.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def get_repo_size():
|
||||||
|
"""Get total repo size in bytes via restic stats --mode raw-data."""
|
||||||
|
output = run_restic("stats", "--mode", "raw-data", "--json")
|
||||||
|
return json.loads(output)["total_size"]
|
||||||
|
|
||||||
|
|
||||||
|
def get_snapshots():
|
||||||
|
"""Get all snapshots, sorted oldest first."""
|
||||||
|
output = run_restic("snapshots", "--json")
|
||||||
|
snapshots = json.loads(output)
|
||||||
|
return sorted(snapshots, key=lambda s: s["time"])
|
||||||
|
|
||||||
|
|
||||||
|
def parse_snapshot_time(time_str):
|
||||||
|
"""Parse a restic snapshot timestamp into a timezone-aware datetime.
|
||||||
|
|
||||||
|
Restic outputs timestamps like '2024-01-15T10:30:00.123456789+01:00'.
|
||||||
|
Python's fromisoformat can't handle nanosecond precision, so we truncate
|
||||||
|
fractional seconds to microseconds.
|
||||||
|
"""
|
||||||
|
# Truncate fractional seconds beyond 6 digits (microseconds)
|
||||||
|
time_str = re.sub(r"(\.\d{6})\d+", r"\1", time_str)
|
||||||
|
return datetime.fromisoformat(time_str)
|
||||||
|
|
||||||
|
|
||||||
|
def get_eligible_snapshots(snapshots, min_age_days):
|
||||||
|
"""Filter snapshots to those older than min_age_days, sorted oldest first."""
|
||||||
|
cutoff = datetime.now(timezone.utc) - timedelta(days=min_age_days)
|
||||||
|
eligible = []
|
||||||
|
for snap in snapshots:
|
||||||
|
snap_time = parse_snapshot_time(snap["time"])
|
||||||
|
if snap_time < cutoff:
|
||||||
|
eligible.append(snap)
|
||||||
|
return sorted(eligible, key=lambda s: s["time"])
|
||||||
|
|
||||||
|
|
||||||
|
def compute_num_to_forget(total_size, max_size, num_snapshots, eligible_count):
|
||||||
|
"""Estimate how many snapshots to forget to get under max_size.
|
||||||
|
|
||||||
|
Uses average size per snapshot as a heuristic. With deduplication, each
|
||||||
|
snapshot shares data with others, so the average overestimates the unique
|
||||||
|
contribution of each snapshot. This means we tend to under-delete, which
|
||||||
|
is the safe direction. The process converges over multiple runs.
|
||||||
|
|
||||||
|
Returns the number of snapshots to forget, capped at eligible_count.
|
||||||
|
"""
|
||||||
|
if num_snapshots == 0 or total_size <= max_size:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
excess = total_size - max_size
|
||||||
|
avg_per_snapshot = total_size / num_snapshots
|
||||||
|
|
||||||
|
if avg_per_snapshot <= 0:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# Ceiling division + 1 safety margin
|
||||||
|
num_to_forget = math.ceil(excess / avg_per_snapshot) + 1
|
||||||
|
return min(num_to_forget, eligible_count)
|
||||||
|
|
||||||
|
|
||||||
|
def time_based_forget(forget_args):
|
||||||
|
"""Run restic forget with time-based retention arguments."""
|
||||||
|
if not forget_args:
|
||||||
|
return
|
||||||
|
args = shlex.split(forget_args)
|
||||||
|
run_restic("forget", *args)
|
||||||
|
|
||||||
|
|
||||||
|
def size_based_forget(max_size, min_age_days):
|
||||||
|
"""Forget oldest eligible snapshots until estimated under max_size.
|
||||||
|
|
||||||
|
Returns the number of snapshots forgotten.
|
||||||
|
"""
|
||||||
|
total_size = get_repo_size()
|
||||||
|
print(f"Current repo size: {total_size} bytes", flush=True)
|
||||||
|
|
||||||
|
if total_size <= max_size:
|
||||||
|
print(
|
||||||
|
f"Repo size is within limit ({total_size} <= {max_size}). "
|
||||||
|
"No size-based cleanup needed.",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
excess = total_size - max_size
|
||||||
|
print(f"Excess: {excess} bytes over {max_size} limit", flush=True)
|
||||||
|
|
||||||
|
snapshots = get_snapshots()
|
||||||
|
if not snapshots:
|
||||||
|
print("No snapshots found.", flush=True)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
num_snapshots = len(snapshots)
|
||||||
|
print(f"Total snapshots: {num_snapshots}", flush=True)
|
||||||
|
|
||||||
|
eligible = get_eligible_snapshots(snapshots, min_age_days)
|
||||||
|
eligible_count = len(eligible)
|
||||||
|
print(
|
||||||
|
f"Eligible snapshots (older than {min_age_days} days): {eligible_count}",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if eligible_count == 0:
|
||||||
|
print(
|
||||||
|
f"No snapshots older than {min_age_days} days to forget. "
|
||||||
|
"Cannot reduce size further.",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
num_to_forget = compute_num_to_forget(
|
||||||
|
total_size, max_size, num_snapshots, eligible_count
|
||||||
|
)
|
||||||
|
print(f"Will forget {num_to_forget} snapshots", flush=True)
|
||||||
|
|
||||||
|
forgotten = 0
|
||||||
|
for snap in eligible[:num_to_forget]:
|
||||||
|
snap_id = snap["short_id"]
|
||||||
|
snap_time = snap["time"]
|
||||||
|
print(f"Forgetting snapshot {snap_id} from {snap_time}", flush=True)
|
||||||
|
run_restic("forget", snap_id)
|
||||||
|
forgotten += 1
|
||||||
|
|
||||||
|
print(f"Forgot {forgotten} snapshots.", flush=True)
|
||||||
|
return forgotten
|
||||||
|
|
||||||
|
|
||||||
|
def prune(pack_size=None, repack_small=False, max_repack_size=None):
|
||||||
|
"""Run restic prune with the given flags."""
|
||||||
|
args = ["prune"]
|
||||||
|
if repack_small:
|
||||||
|
args.append("--repack-small")
|
||||||
|
if max_repack_size is not None:
|
||||||
|
args.extend(["--max-repack-size", str(max_repack_size)])
|
||||||
|
if pack_size is not None:
|
||||||
|
args.extend(["--pack-size", str(pack_size)])
|
||||||
|
run_restic(*args)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Restic forget with time-based and size-based retention"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--forget-args",
|
||||||
|
type=str,
|
||||||
|
default="",
|
||||||
|
help="Arguments to pass to restic forget for time-based retention",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--max-size",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="Maximum repo size in bytes; oldest eligible snapshots forgotten when exceeded",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--min-age-days",
|
||||||
|
type=int,
|
||||||
|
default=180,
|
||||||
|
help="Minimum snapshot age in days before eligible for size-based removal",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--pack-size",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="Pack size in MiB for restic prune",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--repack-small",
|
||||||
|
action="store_true",
|
||||||
|
help="Repack small packs during prune",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--max-repack-size",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Maximum size to repack during prune (e.g., '0' for deep archive)",
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
print("=== Restic forget ===", flush=True)
|
||||||
|
|
||||||
|
# Step 1: Time-based forget
|
||||||
|
if args.forget_args:
|
||||||
|
print("--- Time-based forget ---", flush=True)
|
||||||
|
time_based_forget(args.forget_args)
|
||||||
|
|
||||||
|
# Step 2: Size-based forget
|
||||||
|
if args.max_size is not None:
|
||||||
|
print("--- Size-based forget ---", flush=True)
|
||||||
|
size_based_forget(args.max_size, args.min_age_days)
|
||||||
|
|
||||||
|
# Step 3: Prune
|
||||||
|
print("--- Prune ---", flush=True)
|
||||||
|
prune(
|
||||||
|
pack_size=args.pack_size,
|
||||||
|
repack_small=args.repack_small,
|
||||||
|
max_repack_size=args.max_repack_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 4: Report final size
|
||||||
|
if args.max_size is not None:
|
||||||
|
final_size = get_repo_size()
|
||||||
|
print(f"Final repo size: {final_size} bytes", flush=True)
|
||||||
|
|
||||||
|
print("=== Done ===", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
"""Tests for restic_forget.py."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from unittest.mock import MagicMock, call, patch
|
||||||
|
|
||||||
|
import restic_forget
|
||||||
|
|
||||||
|
|
||||||
|
def make_snapshot(short_id, days_ago, paths=None):
|
||||||
|
"""Create a snapshot dict as restic would return."""
|
||||||
|
t = datetime.now(timezone.utc) - timedelta(days=days_ago)
|
||||||
|
return {
|
||||||
|
"time": t.strftime("%Y-%m-%dT%H:%M:%S.%f+00:00"),
|
||||||
|
"short_id": short_id,
|
||||||
|
"id": short_id * 8,
|
||||||
|
"paths": paths or ["/data"],
|
||||||
|
"hostname": "test",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestParseSnapshotTime:
|
||||||
|
def test_basic_timestamp(self):
|
||||||
|
t = restic_forget.parse_snapshot_time(
|
||||||
|
"2024-01-15T10:30:00.123456+01:00"
|
||||||
|
)
|
||||||
|
assert t.year == 2024
|
||||||
|
assert t.month == 1
|
||||||
|
assert t.day == 15
|
||||||
|
|
||||||
|
def test_nanosecond_truncation(self):
|
||||||
|
# Restic outputs nanosecond precision; we truncate to microseconds
|
||||||
|
t = restic_forget.parse_snapshot_time(
|
||||||
|
"2024-01-15T10:30:00.123456789+01:00"
|
||||||
|
)
|
||||||
|
assert t.microsecond == 123456
|
||||||
|
|
||||||
|
def test_utc_timezone(self):
|
||||||
|
t = restic_forget.parse_snapshot_time("2024-06-01T00:00:00+00:00")
|
||||||
|
assert t.tzinfo is not None
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetEligibleSnapshots:
|
||||||
|
def test_filters_young_snapshots(self):
|
||||||
|
snapshots = [
|
||||||
|
make_snapshot("young1", days_ago=10),
|
||||||
|
make_snapshot("young2", days_ago=90),
|
||||||
|
]
|
||||||
|
eligible = restic_forget.get_eligible_snapshots(
|
||||||
|
snapshots, min_age_days=180
|
||||||
|
)
|
||||||
|
assert len(eligible) == 0
|
||||||
|
|
||||||
|
def test_includes_old_snapshots(self):
|
||||||
|
snapshots = [
|
||||||
|
make_snapshot("old1", days_ago=200),
|
||||||
|
make_snapshot("old2", days_ago=365),
|
||||||
|
]
|
||||||
|
eligible = restic_forget.get_eligible_snapshots(
|
||||||
|
snapshots, min_age_days=180
|
||||||
|
)
|
||||||
|
assert len(eligible) == 2
|
||||||
|
|
||||||
|
def test_mixed_ages(self):
|
||||||
|
snapshots = [
|
||||||
|
make_snapshot("young", days_ago=30),
|
||||||
|
make_snapshot("old", days_ago=200),
|
||||||
|
]
|
||||||
|
eligible = restic_forget.get_eligible_snapshots(
|
||||||
|
snapshots, min_age_days=180
|
||||||
|
)
|
||||||
|
assert len(eligible) == 1
|
||||||
|
assert eligible[0]["short_id"] == "old"
|
||||||
|
|
||||||
|
def test_sorted_oldest_first(self):
|
||||||
|
snapshots = [
|
||||||
|
make_snapshot("newer", days_ago=200),
|
||||||
|
make_snapshot("oldest", days_ago=400),
|
||||||
|
make_snapshot("middle", days_ago=300),
|
||||||
|
]
|
||||||
|
eligible = restic_forget.get_eligible_snapshots(
|
||||||
|
snapshots, min_age_days=180
|
||||||
|
)
|
||||||
|
assert [s["short_id"] for s in eligible] == [
|
||||||
|
"oldest",
|
||||||
|
"middle",
|
||||||
|
"newer",
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_boundary_just_under_cutoff(self):
|
||||||
|
# Snapshot younger than minAgeDays should not be eligible
|
||||||
|
snapshots = [make_snapshot("boundary", days_ago=179)]
|
||||||
|
eligible = restic_forget.get_eligible_snapshots(
|
||||||
|
snapshots, min_age_days=180
|
||||||
|
)
|
||||||
|
assert len(eligible) == 0
|
||||||
|
|
||||||
|
def test_boundary_just_over_cutoff(self):
|
||||||
|
# Snapshot older than minAgeDays should be eligible
|
||||||
|
snapshots = [make_snapshot("boundary", days_ago=181)]
|
||||||
|
eligible = restic_forget.get_eligible_snapshots(
|
||||||
|
snapshots, min_age_days=180
|
||||||
|
)
|
||||||
|
assert len(eligible) == 1
|
||||||
|
|
||||||
|
|
||||||
|
class TestComputeNumToForget:
|
||||||
|
def test_under_threshold_returns_zero(self):
|
||||||
|
result = restic_forget.compute_num_to_forget(
|
||||||
|
total_size=1000, max_size=2000, num_snapshots=10, eligible_count=5
|
||||||
|
)
|
||||||
|
assert result == 0
|
||||||
|
|
||||||
|
def test_no_snapshots_returns_zero(self):
|
||||||
|
result = restic_forget.compute_num_to_forget(
|
||||||
|
total_size=2000, max_size=1000, num_snapshots=0, eligible_count=0
|
||||||
|
)
|
||||||
|
assert result == 0
|
||||||
|
|
||||||
|
def test_basic_estimate(self):
|
||||||
|
# 6 TiB total, 5 TiB limit, 100 snapshots, 50 eligible
|
||||||
|
tib = 1024**4
|
||||||
|
result = restic_forget.compute_num_to_forget(
|
||||||
|
total_size=6 * tib,
|
||||||
|
max_size=5 * tib,
|
||||||
|
num_snapshots=100,
|
||||||
|
eligible_count=50,
|
||||||
|
)
|
||||||
|
# excess = 1 TiB, avg = 6 TiB / 100 = 61.4 GiB
|
||||||
|
# ceil(1 TiB / 61.4 GiB) + 1 = ceil(16.67) + 1 = 18
|
||||||
|
assert result == 18
|
||||||
|
|
||||||
|
def test_caps_at_eligible_count(self):
|
||||||
|
tib = 1024**4
|
||||||
|
result = restic_forget.compute_num_to_forget(
|
||||||
|
total_size=10 * tib,
|
||||||
|
max_size=5 * tib,
|
||||||
|
num_snapshots=10,
|
||||||
|
eligible_count=3,
|
||||||
|
)
|
||||||
|
assert result == 3
|
||||||
|
|
||||||
|
def test_small_excess(self):
|
||||||
|
# Just barely over: should forget at least 2 (ceil(small/avg) + 1)
|
||||||
|
result = restic_forget.compute_num_to_forget(
|
||||||
|
total_size=1001,
|
||||||
|
max_size=1000,
|
||||||
|
num_snapshots=100,
|
||||||
|
eligible_count=50,
|
||||||
|
)
|
||||||
|
assert result == 2 # ceil(1/10.01) + 1 = 1 + 1 = 2
|
||||||
|
|
||||||
|
def test_single_snapshot(self):
|
||||||
|
result = restic_forget.compute_num_to_forget(
|
||||||
|
total_size=2000, max_size=1000, num_snapshots=1, eligible_count=1
|
||||||
|
)
|
||||||
|
assert result == 1
|
||||||
|
|
||||||
|
|
||||||
|
class TestTimeBased:
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_forget_called_with_args(self, mock_run):
|
||||||
|
restic_forget.time_based_forget(
|
||||||
|
"--keep-within-daily 14d --keep-within-weekly 2m"
|
||||||
|
)
|
||||||
|
mock_run.assert_called_once_with(
|
||||||
|
"forget",
|
||||||
|
"--keep-within-daily",
|
||||||
|
"14d",
|
||||||
|
"--keep-within-weekly",
|
||||||
|
"2m",
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_empty_args_skips(self, mock_run):
|
||||||
|
restic_forget.time_based_forget("")
|
||||||
|
mock_run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestSizeBasedForget:
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_under_threshold_skips(self, mock_run):
|
||||||
|
mock_run.return_value = json.dumps({"total_size": 1000})
|
||||||
|
forgotten = restic_forget.size_based_forget(
|
||||||
|
max_size=2000, min_age_days=180
|
||||||
|
)
|
||||||
|
assert forgotten == 0
|
||||||
|
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_no_eligible_snapshots(self, mock_run):
|
||||||
|
stats_json = json.dumps({"total_size": 3000})
|
||||||
|
snapshots_json = json.dumps([make_snapshot("young", days_ago=10)])
|
||||||
|
|
||||||
|
mock_run.side_effect = [stats_json, snapshots_json]
|
||||||
|
forgotten = restic_forget.size_based_forget(
|
||||||
|
max_size=2000, min_age_days=180
|
||||||
|
)
|
||||||
|
assert forgotten == 0
|
||||||
|
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_forgets_oldest_first(self, mock_run):
|
||||||
|
stats_json = json.dumps({"total_size": 3000})
|
||||||
|
snapshots = [
|
||||||
|
make_snapshot("old1", days_ago=400),
|
||||||
|
make_snapshot("old2", days_ago=300),
|
||||||
|
make_snapshot("old3", days_ago=200),
|
||||||
|
make_snapshot("young", days_ago=10),
|
||||||
|
]
|
||||||
|
snapshots_json = json.dumps(snapshots)
|
||||||
|
|
||||||
|
# run_restic calls: stats, snapshots, then forget for each
|
||||||
|
mock_run.side_effect = [stats_json, snapshots_json, "", "", ""]
|
||||||
|
|
||||||
|
forgotten = restic_forget.size_based_forget(
|
||||||
|
max_size=2000, min_age_days=180
|
||||||
|
)
|
||||||
|
assert forgotten > 0
|
||||||
|
|
||||||
|
# Verify forget calls were for the oldest snapshots
|
||||||
|
forget_calls = [
|
||||||
|
c for c in mock_run.call_args_list if c[0][0] == "forget"
|
||||||
|
]
|
||||||
|
# First forget should be the oldest snapshot
|
||||||
|
assert forget_calls[0][0][1] == "old1"
|
||||||
|
|
||||||
|
|
||||||
|
class TestPrune:
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_repack_small(self, mock_run):
|
||||||
|
restic_forget.prune(pack_size=64, repack_small=True)
|
||||||
|
mock_run.assert_called_once_with(
|
||||||
|
"prune", "--repack-small", "--pack-size", "64"
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_max_repack_size_zero(self, mock_run):
|
||||||
|
restic_forget.prune(pack_size=128, max_repack_size="0")
|
||||||
|
mock_run.assert_called_once_with(
|
||||||
|
"prune", "--max-repack-size", "0", "--pack-size", "128"
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_no_flags(self, mock_run):
|
||||||
|
restic_forget.prune()
|
||||||
|
mock_run.assert_called_once_with("prune")
|
||||||
|
|
||||||
|
|
||||||
|
class TestMain:
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_time_only(self, mock_run):
|
||||||
|
"""When no --max-size, only time-based forget + prune runs."""
|
||||||
|
mock_run.return_value = ""
|
||||||
|
restic_forget.main(
|
||||||
|
["--forget-args", "--keep-within-daily 14d", "--repack-small"]
|
||||||
|
)
|
||||||
|
|
||||||
|
calls = mock_run.call_args_list
|
||||||
|
# Should have: forget, prune
|
||||||
|
assert calls[0][0][0] == "forget"
|
||||||
|
assert calls[1][0][0] == "prune"
|
||||||
|
assert "--repack-small" in calls[1][0]
|
||||||
|
|
||||||
|
@patch("restic_forget.run_restic")
|
||||||
|
def test_size_based_with_max_repack_size(self, mock_run):
|
||||||
|
"""Deep archive config: --max-repack-size 0 instead of --repack-small."""
|
||||||
|
stats_json = json.dumps({"total_size": 1000})
|
||||||
|
|
||||||
|
# forget args call, then stats (size check), then prune, then final stats
|
||||||
|
mock_run.side_effect = ["", stats_json, "", stats_json]
|
||||||
|
|
||||||
|
restic_forget.main(
|
||||||
|
[
|
||||||
|
"--forget-args",
|
||||||
|
"--keep-within-daily 31d",
|
||||||
|
"--max-size",
|
||||||
|
"2000",
|
||||||
|
"--max-repack-size",
|
||||||
|
"0",
|
||||||
|
"--pack-size",
|
||||||
|
"128",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
prune_calls = [
|
||||||
|
c for c in mock_run.call_args_list if c[0][0] == "prune"
|
||||||
|
]
|
||||||
|
assert len(prune_calls) == 1
|
||||||
|
assert "--max-repack-size" in prune_calls[0][0]
|
||||||
|
assert "--repack-small" not in prune_calls[0][0]
|
||||||
Reference in new issue
Block a user