backups for mine
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
{pkgs}:
|
||||
pkgs.writeShellScript "s3-retention" ''
|
||||
set -eu
|
||||
|
||||
if [ "$#" -ne 7 ]; then
|
||||
echo "Usage: $0 bucket endpoint region prefix archivePrefix retentionDays workDir" >&2
|
||||
exit 1
|
||||
fi
|
||||
bucket=$1
|
||||
endpoint=$2
|
||||
region=$3
|
||||
prefix=$4
|
||||
archive_prefix=$5
|
||||
retention_days=$6
|
||||
work_dir=$7
|
||||
remote_prefix="''${prefix:+$prefix/}"
|
||||
|
||||
temp_dir="$(${pkgs.coreutils}/bin/mktemp -d "$work_dir/.s3-retention.XXXXXXXXXX")"
|
||||
trap '${pkgs.coreutils}/bin/rm -rf "$temp_dir"' EXIT
|
||||
remote_list="$temp_dir/objects.json"
|
||||
remote_delete_dir="$temp_dir/delete"
|
||||
${pkgs.awscli2}/bin/aws s3api list-objects-v2 \
|
||||
--bucket "$bucket" \
|
||||
--prefix "$remote_prefix" \
|
||||
--endpoint-url "$endpoint" \
|
||||
--region "$region" \
|
||||
--output json > "$remote_list"
|
||||
${pkgs.python3}/bin/python3 - "$remote_list" "$remote_delete_dir" \
|
||||
"$(( $(${pkgs.coreutils}/bin/date +%s) - retention_days * 86400 ))" \
|
||||
"$remote_prefix$archive_prefix" <<'PY'
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
objects_path, delete_dir, cutoff, key_prefix = sys.argv[1:]
|
||||
cutoff = int(cutoff)
|
||||
archive_pattern = re.compile(
|
||||
re.escape(key_prefix) + r"\d{8}T\d{6}Z\.tar\.zst\Z"
|
||||
)
|
||||
with open(objects_path, encoding="utf-8") as stream:
|
||||
objects = json.load(stream).get("Contents", [])
|
||||
|
||||
old_keys = []
|
||||
for item in objects:
|
||||
key = item.get("Key", "")
|
||||
if not archive_pattern.fullmatch(key):
|
||||
continue
|
||||
modified = datetime.datetime.fromisoformat(
|
||||
item["LastModified"].replace("Z", "+00:00")
|
||||
)
|
||||
if int(modified.timestamp()) < cutoff:
|
||||
old_keys.append(key)
|
||||
|
||||
os.makedirs(delete_dir, exist_ok=True)
|
||||
# The S3 endpoint disconnects when deleting multiple existing archives at once.
|
||||
for number, key in enumerate(old_keys):
|
||||
manifest_path = os.path.join(delete_dir, f"batch-{number:04d}.json")
|
||||
with open(manifest_path, "w", encoding="utf-8") as stream:
|
||||
json.dump({"Objects": [{"Key": key}], "Quiet": True}, stream)
|
||||
PY
|
||||
for remote_manifest in "$remote_delete_dir"/*.json; do
|
||||
[ -f "$remote_manifest" ] || continue
|
||||
${pkgs.awscli2}/bin/aws s3api delete-objects \
|
||||
--bucket "$bucket" \
|
||||
--delete "file://$remote_manifest" \
|
||||
--endpoint-url "$endpoint" \
|
||||
--region "$region" \
|
||||
--query '{Errors: Errors}' \
|
||||
--output json > "$temp_dir/result.json"
|
||||
if ! ${pkgs.jq}/bin/jq -e '(.Errors // []) | length == 0' "$temp_dir/result.json" > /dev/null; then
|
||||
${pkgs.coreutils}/bin/cat "$temp_dir/result.json" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
''
|
||||
Reference in New Issue
Block a user