backups for mine
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
- [Minecraft incident log](./minecraft-incidents.md)
|
||||
- [WorldOfSosal source versions and reset](./world-of-sosal-reset.md)
|
||||
- [Project Zomboid backups](./project-zomboid-backups.md)
|
||||
- [Minecraft backups](./minecraft-backups.md)
|
||||
- [Gitea Kanban CLI](./gitea-kanban-cli.md)
|
||||
- [AFFiNE document typography](./affine-typography.md)
|
||||
- [Native AFFiNE deployment and migration](./affine-native.md)
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
# Minecraft backups
|
||||
|
||||
`services.minecraft-backups` adds scheduled S3 archives to the Minecraft module.
|
||||
Neuro enables it for `vanilla`, `createAeronautics`, `wowMineMap`, and Horizon.
|
||||
Enabled nix-minecraft servers are discovered automatically. Horizon is registered
|
||||
explicitly because it runs a separate native engine.
|
||||
|
||||
Each server has a `minecraft-backup-<name>.timer`, scheduled every six hours
|
||||
with up to ten minutes of jitter. S3 retains regular timestamped archives for
|
||||
14 days under `minecraft/neuro/<name>/` in `backup-hectic-lab`.
|
||||
Horizon also keeps its existing native backups.
|
||||
|
||||
Set `services.minecraft-backups.onCalendar` to change the schedule. Its default
|
||||
is `"*-*-* 00/6:00:00"` (00:00, 06:00, 12:00, and 18:00 in the host timezone).
|
||||
S3 retention is configured separately with `services.minecraft-backups.s3.retentionDays`.
|
||||
|
||||
## Snapshot and local storage
|
||||
|
||||
A running server is shut down through its normal systemd stop command while
|
||||
rsync copies its data to a private staging directory. A failed or forced
|
||||
shutdown prevents the snapshot. The server starts again before compression
|
||||
or upload. An already inactive server stays inactive.
|
||||
|
||||
An exit trap and the backup unit's `ExecStopPost` restore a server that the backup
|
||||
stopped if copying fails or the backup is terminated. A `restart-needed` marker
|
||||
persists until starting the server succeeds.
|
||||
|
||||
Staging and pending archives live in `/var/lib/minecraft-backups/<name>/`.
|
||||
Staging remains for the next incremental copy. A completed archive is removed
|
||||
locally only after a successful upload. Failed uploads leave it for the next
|
||||
run, which retries pending archives before taking another snapshot.
|
||||
|
||||
Archives contain server data, including worlds and runtime lists such as
|
||||
whitelists and operators. Regenerated mods, libraries, resources, caches,
|
||||
logs, existing backups, and secret-bearing `server.properties` are excluded.
|
||||
Reapply the matching Nix configuration when restoring.
|
||||
|
||||
S3 cleanup only deletes names matching that server's timestamped archive format.
|
||||
Manual archives and other prefixes are preserved. Cleanup uses the same helper
|
||||
as PZ: individual object deletions and explicit validation of S3 deletion errors.
|
||||
|
||||
## wowMineMap live-backup investigation, 2026-11-16
|
||||
|
||||
Read-only inspection through `ssh neuro` confirmed that wowMineMap is running
|
||||
Minecraft 1.21.1 / NeoForge 21.1.250 with Sable 2.0.5 and Distant Horizons 3.3.3.
|
||||
Its data resides on ext4 at `/dev/nvme0n1p2`; there is no configured snapshot
|
||||
backend for this mount.
|
||||
|
||||
The Java process has seven Distant Horizons SQLite databases open across the
|
||||
dimensions, including their WAL and shared-memory files. The Azeroth main
|
||||
database was about 2.2 GB with a separate nonempty WAL. Copying these files
|
||||
independently is not a database snapshot.
|
||||
|
||||
One component was verified without stopping the game: Python's SQLite Backup
|
||||
API copied `world/data/DistantHorizons.sqlite`, opened with `mode=ro`, into an
|
||||
in-memory database. The copy reported journal mode `wal`, 1286 pages, six tables,
|
||||
and `PRAGMA quick_check` returned `ok`. No backup file was written on neuro.
|
||||
This verifies that database-copy mechanism, not a full-world restore.
|
||||
|
||||
Inspection with `javap` of the deployed Minecraft server and Sable jars found:
|
||||
|
||||
- `MinecraftServer.saveEverything` calls `PlayerList.saveAll` before applying
|
||||
the chunk-saving flags.
|
||||
- `PlayerList.remove(ServerPlayer)` calls `save(player)` during logout without
|
||||
consulting the world's `noSave` flag.
|
||||
- `MinecraftServer.saveAllChunks` also writes the main world metadata using
|
||||
`LevelStorageAccess.saveDataTag` outside the per-level skip-save logic.
|
||||
- Sable's `sable$saveSubLevels` injection runs before `ServerLevel.saveLevelData`,
|
||||
inside the level's skip-save guard. That particular hook is not evidence that
|
||||
Sable ignores `save-off`.
|
||||
|
||||
Consequently, `save-off` plus `save-all flush` does not make the entire server
|
||||
directory immutable while players keep playing. A file copy can combine frozen
|
||||
chunks with later player inventories or world metadata. SQLite snapshots alone
|
||||
do not provide a common checkpoint for those different data stores.
|
||||
|
||||
No live mode with guarantees equivalent to an orderly stopped-server copy has
|
||||
been established for this pack. The stop-based implementation has therefore
|
||||
not been replaced or deployed. A full-world live restore test was not run,
|
||||
because there is not yet a coordinated snapshot mechanism to test.
|
||||
|
||||
The next implementation step would be an in-process NeoForge checkpoint that
|
||||
coordinates world, player, Sable, and SQLite persistence, followed by a restore
|
||||
test on a disposable WorldOfSosal instance. Production was not stopped,
|
||||
restarted, sent save commands, or deployed during this investigation; the
|
||||
six-hour schedule and fourteen-day retention remain unchanged.
|
||||
|
||||
## Credentials and deployment
|
||||
|
||||
Before enabling the timers on neuro, provision a root-owned file with mode 0600:
|
||||
|
||||
```text
|
||||
/var/lib/minecraft-backups/s3-credentials
|
||||
```
|
||||
|
||||
Its contents use the systemd environment-file format:
|
||||
|
||||
```sh
|
||||
AWS_ACCESS_KEY_ID=...
|
||||
AWS_SECRET_ACCESS_KEY=...
|
||||
```
|
||||
|
||||
The key must allow listing the bucket and uploading/deleting objects under
|
||||
`minecraft/neuro/`. Keep the file outside the repository and `/nix/store`.
|
||||
A missing file prevents the backup from starting, before it stops any server.
|
||||
|
||||
The committed configuration does not provision this secret. Apply the neuro
|
||||
configuration after the file exists, then check:
|
||||
|
||||
```sh
|
||||
systemctl list-timers 'minecraft-backup-*'
|
||||
systemctl start minecraft-backup-vanilla.service
|
||||
journalctl -u minecraft-backup-vanilla.service
|
||||
```
|
||||
|
||||
## Restore
|
||||
|
||||
Stop that server's backup timer and game service. Download the chosen
|
||||
`minecraft-<name>-<timestamp>.tar.zst` from its S3 prefix. Preserve the current
|
||||
data directory separately before replacing anything.
|
||||
|
||||
Extract the archive into the server's data directory while the game is stopped.
|
||||
Archives contain paths relative to that directory. Restore file ownership to the
|
||||
game service's user (`minecraft` for Java servers, `horizon` for Horizon),
|
||||
reapply the matching Nix configuration and runtime secrets, then start the game
|
||||
and its backup timer.
|
||||
@@ -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
|
||||
''
|
||||
@@ -0,0 +1,180 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
let
|
||||
cfg = config.services.minecraft-backups;
|
||||
minecraft = config.services.minecraft-servers;
|
||||
servers = lib.filterAttrs (_: server: server.enable) cfg.servers;
|
||||
prune = import ../../../lib/s3-retention.nix { inherit pkgs; };
|
||||
stateDir = name: "${cfg.stateDir}/${name}";
|
||||
restore = name: server: pkgs.writeShellScript "minecraft-backup-resume-${name}" ''
|
||||
set -eu
|
||||
marker=${lib.escapeShellArg "${stateDir name}/restart-needed"}
|
||||
if [ -e "$marker" ]; then
|
||||
${pkgs.systemd}/bin/systemctl start ${lib.escapeShellArg server.service}
|
||||
${pkgs.coreutils}/bin/rm -f "$marker"
|
||||
fi
|
||||
'';
|
||||
backup = name: server: pkgs.writeShellScript "minecraft-backup-${name}" ''
|
||||
set -eu
|
||||
umask 077
|
||||
state_dir=${lib.escapeShellArg (stateDir name)}
|
||||
archive_dir="$state_dir/archive"
|
||||
staging_dir="$state_dir/staging"
|
||||
${pkgs.coreutils}/bin/install -d -m 0700 "$archive_dir" "$staging_dir"
|
||||
exec 9>"$state_dir/lock"
|
||||
${pkgs.util-linux}/bin/flock 9
|
||||
: "''${AWS_ACCESS_KEY_ID:?AWS_ACCESS_KEY_ID is required}"
|
||||
: "''${AWS_SECRET_ACCESS_KEY:?AWS_SECRET_ACCESS_KEY is required}"
|
||||
upload() {
|
||||
${pkgs.awscli2}/bin/aws s3 cp "$1" \
|
||||
${lib.escapeShellArg "s3://${cfg.s3.bucket}/${cfg.s3.prefix}/${name}/"}"''${1##*/}" \
|
||||
--endpoint-url ${lib.escapeShellArg cfg.s3.endpoint} \
|
||||
--region ${lib.escapeShellArg cfg.s3.region} \
|
||||
--cli-connect-timeout 30 --cli-read-timeout 300 --only-show-errors
|
||||
${pkgs.coreutils}/bin/rm -f "$1"
|
||||
}
|
||||
# Retry a failed upload before creating another local archive.
|
||||
for pending in "$archive_dir"/minecraft-${name}-????????T??????Z.tar.zst; do
|
||||
[ -f "$pending" ] || continue
|
||||
upload "$pending"
|
||||
done
|
||||
${restore name server}
|
||||
trap '${restore name server}' EXIT
|
||||
unit=${lib.escapeShellArg server.service}
|
||||
if ${pkgs.systemd}/bin/systemctl is-active --quiet "$unit"; then
|
||||
${pkgs.coreutils}/bin/touch "$state_dir/restart-needed"
|
||||
${pkgs.systemd}/bin/systemctl stop "$unit"
|
||||
if [ "$(${pkgs.systemd}/bin/systemctl show "$unit" -p Result --value)" != success ]; then
|
||||
echo "Minecraft did not stop cleanly; refusing to copy $unit" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
${pkgs.rsync}/bin/rsync -a --delete --delete-excluded \
|
||||
${lib.concatMapStringsSep " \\\n " (path: "--exclude=${lib.escapeShellArg "/${path}"}") server.exclude} \
|
||||
${lib.escapeShellArg "${server.directory}/"} "$staging_dir/"
|
||||
${restore name server}
|
||||
trap - EXIT
|
||||
timestamp="$(${pkgs.coreutils}/bin/date -u +%Y%m%dT%H%M%SZ)"
|
||||
archive="$archive_dir/minecraft-${name}-$timestamp.tar.zst"
|
||||
trap '${pkgs.coreutils}/bin/rm -f "$archive.tmp"' EXIT
|
||||
${pkgs.gnutar}/bin/tar \
|
||||
--use-compress-program=${lib.escapeShellArg "${pkgs.zstd}/bin/zstd -T2"} \
|
||||
-C "$staging_dir" -cf "$archive.tmp" .
|
||||
${pkgs.coreutils}/bin/mv "$archive.tmp" "$archive"
|
||||
trap - EXIT
|
||||
upload "$archive"
|
||||
${prune} \
|
||||
${lib.escapeShellArg cfg.s3.bucket} \
|
||||
${lib.escapeShellArg cfg.s3.endpoint} \
|
||||
${lib.escapeShellArg cfg.s3.region} \
|
||||
${lib.escapeShellArg "${cfg.s3.prefix}/${name}"} \
|
||||
${lib.escapeShellArg "minecraft-${name}-"} \
|
||||
${toString cfg.s3.retentionDays} "$state_dir"
|
||||
'';
|
||||
in {
|
||||
options.services.minecraft-backups = {
|
||||
enable = lib.mkEnableOption "scheduled Minecraft archives in S3";
|
||||
onCalendar = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "*-*-* 00/6:00:00";
|
||||
description = "Backup schedule for each server.";
|
||||
};
|
||||
stateDir = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "/var/lib/minecraft-backups";
|
||||
description = "Private staging trees and archives awaiting upload.";
|
||||
};
|
||||
s3 = {
|
||||
bucket = lib.mkOption { type = lib.types.str; };
|
||||
endpoint = lib.mkOption { type = lib.types.str; };
|
||||
region = lib.mkOption { type = lib.types.str; };
|
||||
prefix = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "minecraft/${config.networking.hostName}";
|
||||
};
|
||||
credentialsFile = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "Runtime environment file containing AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.";
|
||||
};
|
||||
retentionDays = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 14;
|
||||
};
|
||||
};
|
||||
servers = lib.mkOption {
|
||||
default = {};
|
||||
description = "Enabled nix-minecraft servers are included automatically; additional engines can be declared here.";
|
||||
type = lib.types.attrsOf (lib.types.submodule {
|
||||
options = {
|
||||
enable = lib.mkOption { type = lib.types.bool; default = true; };
|
||||
service = lib.mkOption { type = lib.types.str; };
|
||||
directory = lib.mkOption { type = lib.types.str; };
|
||||
exclude = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [
|
||||
"logs" "crash-reports" "backups" "cache" "libraries" "versions"
|
||||
"mods" "resources" "*.jar" "server.properties"
|
||||
];
|
||||
description = "Root entries regenerated by deployment, logs, and secret-bearing server properties.";
|
||||
};
|
||||
};
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
assertions = [
|
||||
{
|
||||
assertion = lib.hasPrefix "/" cfg.stateDir
|
||||
&& !lib.hasPrefix "/nix/store/" cfg.stateDir;
|
||||
message = "Minecraft backup stateDir must be an absolute runtime path.";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasPrefix "/" cfg.s3.credentialsFile
|
||||
&& !lib.hasPrefix "/nix/store/" cfg.s3.credentialsFile;
|
||||
message = "Minecraft S3 credentials must be a runtime file outside /nix/store.";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasPrefix "https://" cfg.s3.endpoint;
|
||||
message = "Minecraft S3 endpoint must use HTTPS.";
|
||||
}
|
||||
] ++ lib.mapAttrsToList (name: server: {
|
||||
assertion = builtins.match "[a-zA-Z0-9_-]+" name != null
|
||||
&& lib.hasPrefix "/" server.directory
|
||||
&& !(server.directory == cfg.stateDir || lib.hasPrefix "${server.directory}/" cfg.stateDir)
|
||||
&& !(server.directory == cfg.stateDir || lib.hasPrefix "${cfg.stateDir}/" server.directory);
|
||||
message = "Minecraft backup ${name} needs a safe name and a source directory separate from backup state.";
|
||||
}) servers;
|
||||
|
||||
services.minecraft-backups.servers = lib.mapAttrs (name: _: {
|
||||
service = lib.mkDefault "minecraft-server-${name}.service";
|
||||
directory = lib.mkDefault "${minecraft.dataDir}/${name}";
|
||||
}) (lib.filterAttrs (_: server: minecraft.enable && server.enable) minecraft.servers);
|
||||
|
||||
systemd.tmpfiles.rules = [ "d ${cfg.stateDir} 0700 root root - -" ]
|
||||
++ lib.mapAttrsToList (name: _: "d ${stateDir name} 0700 root root - -") servers;
|
||||
systemd.services = lib.mapAttrs' (name: server: lib.nameValuePair "minecraft-backup-${name}" {
|
||||
description = "S3 backup of Minecraft ${name}";
|
||||
wants = [ "network-online.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
unitConfig.ConditionPathIsDirectory = server.directory;
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
User = "root";
|
||||
UMask = "0077";
|
||||
EnvironmentFile = cfg.s3.credentialsFile;
|
||||
ExecStart = backup name server;
|
||||
# Also restore a stopped server when timeout/SIGKILL bypasses shell traps.
|
||||
ExecStopPost = restore name server;
|
||||
TimeoutStartSec = "2h";
|
||||
};
|
||||
}) servers;
|
||||
systemd.timers = lib.mapAttrs' (name: _: lib.nameValuePair "minecraft-backup-${name}" {
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnCalendar = cfg.onCalendar;
|
||||
Persistent = true;
|
||||
RandomizedDelaySec = "10min";
|
||||
};
|
||||
}) servers;
|
||||
};
|
||||
}
|
||||
@@ -46,6 +46,7 @@
|
||||
timestampArchivePattern = "project-zomboid-${cfg.serverName}-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]Z.tar.zst";
|
||||
saveDir = "${zomboidDir}/Saves/Multiplayer/${cfg.serverName}";
|
||||
serverConfigDir = "${zomboidDir}/Server";
|
||||
s3RetentionScript = import ../../../../lib/s3-retention.nix {inherit pkgs;};
|
||||
backupScript = pkgs.writeShellScript "project-zomboid-backup" ''
|
||||
set -eu
|
||||
|
||||
@@ -163,69 +164,14 @@
|
||||
-mmin +${toString (backupCfg.retentionDays * 1440)} -delete
|
||||
''}
|
||||
|
||||
remote_prefix="$s3_prefix"
|
||||
if [ -n "$remote_prefix" ]; then
|
||||
remote_prefix="$remote_prefix/"
|
||||
fi
|
||||
archive_prefix=${lib.escapeShellArg "project-zomboid-${cfg.serverName}-"}
|
||||
remote_list="$staging_dir/.remote-objects.json"
|
||||
remote_delete_dir="$staging_dir/.remote-delete"
|
||||
${pkgs.awscli2}/bin/aws s3api list-objects-v2 \
|
||||
--bucket "$s3_bucket" \
|
||||
--prefix "$remote_prefix" \
|
||||
--endpoint-url ${lib.escapeShellArg s3Endpoint} \
|
||||
--region ${lib.escapeShellArg s3Region} \
|
||||
--output json > "$remote_list"
|
||||
${pkgs.python3}/bin/python3 - "$remote_list" "$remote_delete_dir" \
|
||||
"$(( $(${pkgs.coreutils}/bin/date +%s) - ${toString (backupCfg.s3.remoteRetentionDays * 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)
|
||||
for batch_number in range(0, len(old_keys), 1000):
|
||||
batch = old_keys[batch_number:batch_number + 1000]
|
||||
manifest_path = os.path.join(
|
||||
delete_dir, f"batch-{batch_number // 1000:04d}.json"
|
||||
)
|
||||
with open(manifest_path, "w", encoding="utf-8") as stream:
|
||||
json.dump(
|
||||
{"Objects": [{"Key": key} for key in batch], "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 "$s3_bucket" \
|
||||
--delete "file://$remote_manifest" \
|
||||
--endpoint-url ${lib.escapeShellArg s3Endpoint} \
|
||||
--region ${lib.escapeShellArg s3Region} \
|
||||
--only-show-errors
|
||||
done
|
||||
${pkgs.coreutils}/bin/rm -rf "$remote_list" "$remote_delete_dir"
|
||||
${s3RetentionScript} \
|
||||
"$s3_bucket" \
|
||||
${lib.escapeShellArg s3Endpoint} \
|
||||
${lib.escapeShellArg s3Region} \
|
||||
"$s3_prefix" \
|
||||
${lib.escapeShellArg "project-zomboid-${cfg.serverName}-"} \
|
||||
${toString backupCfg.s3.remoteRetentionDays} \
|
||||
"$staging_dir"
|
||||
''}
|
||||
|
||||
${lib.optionalString (!backupCfg.s3.enable) ''
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
./public-tunnel.nix
|
||||
./world-import.nix
|
||||
./modpack-import.nix
|
||||
../../../module/generic/minecraft-backups.nix
|
||||
];
|
||||
|
||||
services.minecraft-servers = {
|
||||
@@ -15,4 +16,18 @@
|
||||
eula = true;
|
||||
openFirewall = true;
|
||||
};
|
||||
|
||||
services.minecraft-backups = {
|
||||
enable = true;
|
||||
s3 = {
|
||||
bucket = "backup-hectic-lab";
|
||||
endpoint = "https://hel1.your-objectstorage.com";
|
||||
region = "hel1";
|
||||
credentialsFile = "/var/lib/minecraft-backups/s3-credentials";
|
||||
};
|
||||
servers.horizon = {
|
||||
service = "horizon.service";
|
||||
directory = "/var/lib/horizon";
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@ in (import ./affine.nix { inherit system inputs self pkgs; }) //
|
||||
(import ./affine-chatgpt.nix { inherit system inputs pkgs; }) //
|
||||
(import ./affine-frontend.nix { inherit system inputs pkgs; }) //
|
||||
(import ./element.nix { inherit system inputs pkgs; }) //
|
||||
(import ./horizon.nix { inherit system inputs pkgs; }) // {
|
||||
(import ./horizon.nix { inherit system inputs pkgs; }) //
|
||||
(import ./minecraft-backups.nix { inherit system inputs pkgs; }) // {
|
||||
p4d-module-basic =
|
||||
assert enabledCfg.users.users.p4d.isSystemUser;
|
||||
assert enabledCfg.users.users.p4d.group == "p4d";
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
{ system, inputs, pkgs, ... }:
|
||||
let
|
||||
lib = inputs.nixpkgs.lib;
|
||||
clock = pkgs.writeShellScriptBin "date" ''
|
||||
case "$*" in
|
||||
+%s) echo 1700000000 ;;
|
||||
"-u +%Y%m%dT%H%M%SZ") echo 20231114T221320Z ;;
|
||||
*) exit 97 ;;
|
||||
esac
|
||||
'';
|
||||
coreutils = pkgs.symlinkJoin {
|
||||
name = "minecraft-backup-test-coreutils";
|
||||
paths = [ pkgs.coreutils ];
|
||||
postBuild = ''
|
||||
rm "$out/bin/date"
|
||||
ln -s ${clock}/bin/date "$out/bin/date"
|
||||
'';
|
||||
};
|
||||
systemctl = pkgs.writeShellScriptBin "systemctl" ''
|
||||
set -eu
|
||||
case "$1" in
|
||||
is-active) test "$(cat /build/control/state)" = active ;;
|
||||
stop)
|
||||
echo inactive > /build/control/state
|
||||
echo "''${STOP_RESULT:-success}" > /build/control/result
|
||||
;;
|
||||
start) echo active > /build/control/state ;;
|
||||
show) cat /build/control/result ;;
|
||||
*) exit 99 ;;
|
||||
esac
|
||||
'';
|
||||
rsync = pkgs.writeShellScriptBin "rsync" ''
|
||||
set -eu
|
||||
test "$(cat /build/control/state)" = inactive
|
||||
test "''${FAIL_COPY:-0}" = 0 || exit 31
|
||||
exec ${pkgs.rsync}/bin/rsync "$@"
|
||||
'';
|
||||
aws = pkgs.writeShellScriptBin "aws" ''
|
||||
set -eu
|
||||
case "$1 $2" in
|
||||
"s3 cp")
|
||||
test "''${FAIL_UPLOAD:-0}" = 0 || exit 32
|
||||
cp "$3" "/build/bucket/''${3##*/}"
|
||||
;;
|
||||
"s3api list-objects-v2")
|
||||
cat /build/objects.json
|
||||
;;
|
||||
"s3api delete-objects")
|
||||
shift 2
|
||||
while [ "$1" != --delete ]; do shift; done
|
||||
manifest="''${2#file://}"
|
||||
if [ "''${FAIL_DELETE:-0}" = 1 ]; then
|
||||
echo '{"Errors":[{"Code":"AccessDenied"}]}'
|
||||
else
|
||||
${pkgs.jq}/bin/jq -r '.Objects[].Key' "$manifest" |
|
||||
while IFS= read -r key; do rm -f "/build/bucket/''${key##*/}"; done
|
||||
echo '{"Errors":null}'
|
||||
fi
|
||||
;;
|
||||
*) exit 98 ;;
|
||||
esac
|
||||
'';
|
||||
cfg = (lib.nixosSystem {
|
||||
inherit system;
|
||||
inherit pkgs;
|
||||
modules = [
|
||||
inputs.nix-minecraft.nixosModules.minecraft-servers
|
||||
({ config, lib, ... }: import ../../nixos/module/generic/minecraft-backups.nix {
|
||||
inherit config lib;
|
||||
pkgs = pkgs // { systemd = systemctl; inherit rsync coreutils; awscli2 = aws; };
|
||||
})
|
||||
{
|
||||
system.stateVersion = "25.05";
|
||||
services.minecraft-servers = {
|
||||
enable = true;
|
||||
eula = true;
|
||||
servers.auto = { enable = true; package = pkgs.hello; };
|
||||
servers.disabled = { enable = false; package = pkgs.hello; };
|
||||
};
|
||||
services.minecraft-backups = {
|
||||
enable = true;
|
||||
stateDir = "/build/backups";
|
||||
s3 = {
|
||||
bucket = "test";
|
||||
endpoint = "https://s3.invalid";
|
||||
region = "test";
|
||||
prefix = "minecraft";
|
||||
credentialsFile = "/run/test-credentials";
|
||||
};
|
||||
servers.test = {
|
||||
directory = "/build/source";
|
||||
service = "minecraft-test.service";
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
}).config;
|
||||
service = cfg.systemd.services.minecraft-backup-test;
|
||||
runCase = name: test: pkgs.runCommand "minecraft-backup-${name}" {
|
||||
nativeBuildInputs = [ pkgs.jq pkgs.gnutar pkgs.zstd ];
|
||||
} ''
|
||||
set -eu
|
||||
mkdir -p /build/source/world /build/control /build/bucket /build/backups/test
|
||||
echo active > /build/control/state
|
||||
echo success > /build/control/result
|
||||
echo world-data > /build/source/world/level.dat
|
||||
echo secret > /build/source/server.properties
|
||||
touch /build/bucket/minecraft-test-20200101T000000Z.tar.zst /build/bucket/manual.tar.zst
|
||||
touch /build/bucket/minecraft-test-20990101T000000Z.tar.zst /build/bucket/minecraft-other-20200101T000000Z.tar.zst
|
||||
echo '{"Contents":[
|
||||
{"Key":"minecraft/test/minecraft-test-20200101T000000Z.tar.zst","LastModified":"2020-01-01T00:00:00Z"},
|
||||
{"Key":"minecraft/test/manual.tar.zst","LastModified":"2020-01-01T00:00:00Z"},
|
||||
{"Key":"minecraft/test/minecraft-test-20990101T000000Z.tar.zst","LastModified":"2099-01-01T00:00:00Z"},
|
||||
{"Key":"minecraft/other/minecraft-other-20200101T000000Z.tar.zst","LastModified":"2020-01-01T00:00:00Z"}
|
||||
]}' > /build/objects.json
|
||||
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test
|
||||
${test}
|
||||
touch "$out"
|
||||
'';
|
||||
in {
|
||||
minecraft-backup-enabled-server-timers =
|
||||
assert cfg.services.minecraft-backups.servers.auto.directory == "/srv/minecraft/auto";
|
||||
assert cfg.services.minecraft-backups.servers.auto.service == "minecraft-server-auto.service";
|
||||
assert builtins.filter (name: lib.hasPrefix "minecraft-backup-" name)
|
||||
(builtins.attrNames cfg.systemd.timers) == [ "minecraft-backup-auto" "minecraft-backup-test" ];
|
||||
assert cfg.systemd.timers.minecraft-backup-auto.timerConfig.OnCalendar == "*-*-* 00/6:00:00";
|
||||
pkgs.runCommand "minecraft-backup-enabled-server-timers" {} ''touch "$out"'';
|
||||
minecraft-backup-upload-and-retention = runCase "upload-and-retention" ''
|
||||
${service.serviceConfig.ExecStart}
|
||||
test "$(cat /build/control/state)" = active
|
||||
test ! -e /build/backups/test/restart-needed
|
||||
test ! -e /build/bucket/minecraft-test-20200101T000000Z.tar.zst
|
||||
test -e /build/bucket/manual.tar.zst
|
||||
test -e /build/bucket/minecraft-test-20990101T000000Z.tar.zst
|
||||
test -e /build/bucket/minecraft-other-20200101T000000Z.tar.zst
|
||||
test -z "$(find /build/backups/test/archive -name '*.tar.zst' -print)"
|
||||
mkdir /build/restored
|
||||
tar --zstd -xf /build/bucket/minecraft-test-20231114T221320Z.tar.zst -C /build/restored
|
||||
test "$(cat /build/restored/world/level.dat)" = world-data
|
||||
test ! -e /build/restored/server.properties
|
||||
'';
|
||||
minecraft-backup-copy-failure-resumes-server = runCase "copy-failure-resumes-server" ''
|
||||
if FAIL_COPY=1 ${service.serviceConfig.ExecStart}; then exit 1; fi
|
||||
test "$(cat /build/control/state)" = active
|
||||
test ! -e /build/backups/test/restart-needed
|
||||
'';
|
||||
minecraft-backup-upload-failure-keeps-archive = runCase "upload-failure-keeps-archive" ''
|
||||
if FAIL_UPLOAD=1 ${service.serviceConfig.ExecStart}; then exit 1; fi
|
||||
test "$(cat /build/control/state)" = active
|
||||
test "$(find /build/backups/test/archive -name '*.tar.zst' | wc -l)" -eq 1
|
||||
test "$(stat -c %a /build/backups/test/archive/*.tar.zst)" = 600
|
||||
# A subsequent copy failure still allows the pending archive to be uploaded first.
|
||||
if FAIL_COPY=1 ${service.serviceConfig.ExecStart}; then exit 1; fi
|
||||
test -z "$(find /build/backups/test/archive -name '*.tar.zst' -print)"
|
||||
test -e /build/bucket/minecraft-test-20231114T221320Z.tar.zst
|
||||
'';
|
||||
minecraft-backup-inactive-server-stays-inactive = runCase "inactive-server-stays-inactive" ''
|
||||
echo inactive > /build/control/state
|
||||
${service.serviceConfig.ExecStart}
|
||||
test "$(cat /build/control/state)" = inactive
|
||||
'';
|
||||
minecraft-backup-unclean-stop-refuses-snapshot = runCase "unclean-stop-refuses-snapshot" ''
|
||||
if STOP_RESULT=timeout ${service.serviceConfig.ExecStart}; then exit 1; fi
|
||||
test "$(cat /build/control/state)" = active
|
||||
test ! -e /build/backups/test/staging/world/level.dat
|
||||
'';
|
||||
minecraft-backup-timeout-resumes-server = runCase "timeout-resumes-server" ''
|
||||
echo inactive > /build/control/state
|
||||
touch /build/backups/test/restart-needed
|
||||
${service.serviceConfig.ExecStopPost}
|
||||
test "$(cat /build/control/state)" = active
|
||||
test ! -e /build/backups/test/restart-needed
|
||||
'';
|
||||
minecraft-backup-delete-errors-fail-service = runCase "delete-errors-fail-service" ''
|
||||
if FAIL_DELETE=1 ${service.serviceConfig.ExecStart}; then exit 1; fi
|
||||
test "$(cat /build/control/state)" = active
|
||||
test -e /build/bucket/minecraft-test-20200101T000000Z.tar.zst
|
||||
'';
|
||||
}
|
||||
Reference in New Issue
Block a user