204 lines
9.8 KiB
Nix
204 lines
9.8 KiB
Nix
{ config, lib, pkgs, ... }:
|
|
let
|
|
minecraft = config.services.minecraft-servers;
|
|
restores = lib.filterAttrs (_: restore: restore.enable) config.services.minecraft-backup-restores;
|
|
marker = ".minecraft-backup-restore-complete";
|
|
# Python's data filter resolves symlink chains against the extraction tree and
|
|
# rejects escaping links and special files. Also reject absolute/traversal
|
|
# names outright (data_filter alone strips leading slashes).
|
|
extract = pkgs.writeText "minecraft-restore-extract.py" ''
|
|
import pathlib
|
|
import sys
|
|
import tarfile
|
|
|
|
def safe_member(member: tarfile.TarInfo, destination: str) -> tarfile.TarInfo | None:
|
|
path = pathlib.PurePosixPath(member.name)
|
|
if path.is_absolute() or ".." in path.parts or path.parts == ("${marker}",):
|
|
raise tarfile.FilterError(f"Unsafe archive entry: {member.name}")
|
|
# nix-minecraft regenerates this as an absolute store symlink. Keep
|
|
# bootstrap's EULA rather than restoring a possibly obsolete store path.
|
|
if path.parts == ("eula.txt",):
|
|
return None
|
|
return tarfile.data_filter(member, destination)
|
|
|
|
with tarfile.open(sys.argv[1], mode="r:") as archive:
|
|
archive.extractall(sys.argv[2], filter=safe_member)
|
|
'';
|
|
fresh = pkgs.writeText "minecraft-restore-fresh.py" ''
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
|
|
target = pathlib.Path(sys.argv[1])
|
|
level_name = sys.argv[2]
|
|
if os.path.lexists(target / level_name):
|
|
sys.exit(f"Refusing existing Minecraft level directory: {target / level_name}")
|
|
# Refuse even incomplete saves, including custom level-name directories
|
|
# and save signatures nested beneath mod-specific dimension paths.
|
|
for directory, directories, files in os.walk(target, followlinks=False):
|
|
for name in directories + files:
|
|
path = pathlib.Path(directory) / name
|
|
if (
|
|
name in {"level.dat", "level.dat_old", "session.lock", "region",
|
|
"entities", "poi", "playerdata", "advancements", "stats",
|
|
"dimensions", "DIM-1", "DIM1"}
|
|
or name.endswith((".mca", ".mcr"))
|
|
or (path.parent == target and (
|
|
name.startswith("world") or name == level_name
|
|
))
|
|
):
|
|
sys.exit(f"Refusing existing Minecraft world state: {path}")
|
|
'';
|
|
script = name: restore:
|
|
let
|
|
target = "${minecraft.dataDir}/${restore.serverName}";
|
|
levelName = toString (minecraft.servers.${restore.serverName}.serverProperties.level-name or "world");
|
|
identity = builtins.toJSON { inherit name; inherit (restore) bucket key endpoint; };
|
|
in pkgs.writeShellScript "minecraft-backup-restore-${name}" ''
|
|
set -euo pipefail
|
|
umask 077
|
|
target=${lib.escapeShellArg target}
|
|
${pkgs.coreutils}/bin/mkdir -p ${lib.escapeShellArg minecraft.dataDir}
|
|
exec 9>${lib.escapeShellArg "${minecraft.dataDir}/.minecraft-restore-${restore.serverName}.lock"}
|
|
${pkgs.util-linux}/bin/flock 9
|
|
if [ -L "$target" ]; then
|
|
echo "Refusing symlink restore target: $target" >&2
|
|
exit 1
|
|
fi
|
|
if [ -e "$target/${marker}" ] || [ -L "$target/${marker}" ]; then
|
|
if [ -f "$target/${marker}" ] && [ ! -L "$target/${marker}" ] &&
|
|
[ "$(${pkgs.coreutils}/bin/cat "$target/${marker}")" = ${lib.escapeShellArg identity} ]; then
|
|
exit 0
|
|
fi
|
|
echo "Restore marker does not match the configured S3 backup: $target/${marker}" >&2
|
|
exit 1
|
|
fi
|
|
${pkgs.python3}/bin/python ${fresh} "$target" ${lib.escapeShellArg levelName}
|
|
work="$(${pkgs.coreutils}/bin/mktemp -d ${lib.escapeShellArg "${minecraft.dataDir}/.minecraft-restore-${restore.serverName}.XXXXXX"})"
|
|
trap '${pkgs.coreutils}/bin/rm -rf -- "$work"' EXIT
|
|
trap 'exit 1' HUP INT TERM
|
|
${pkgs.coreutils}/bin/mkdir "$work/server"
|
|
if [ -e "$target" ]; then
|
|
test -d "$target"
|
|
${pkgs.coreutils}/bin/cp -a -- "$target/." "$work/server/"
|
|
fi
|
|
: "''${AWS_ACCESS_KEY_ID:?AWS_ACCESS_KEY_ID is required}"
|
|
: "''${AWS_SECRET_ACCESS_KEY:?AWS_SECRET_ACCESS_KEY is required}"
|
|
${pkgs.awscli2}/bin/aws s3 cp \
|
|
${lib.escapeShellArg "s3://${restore.bucket}/${restore.key}"} "$work/backup.tar.zst" \
|
|
--endpoint-url ${lib.escapeShellArg restore.endpoint} \
|
|
--region ${lib.escapeShellArg restore.region} \
|
|
--cli-connect-timeout 30 --cli-read-timeout 300 --only-show-errors
|
|
${lib.optionalString (restore.expectedSize != null) ''
|
|
test "$(${pkgs.coreutils}/bin/stat -c %s "$work/backup.tar.zst")" = ${toString restore.expectedSize}
|
|
''}
|
|
${pkgs.zstd}/bin/zstd --test --quiet "$work/backup.tar.zst"
|
|
${pkgs.zstd}/bin/zstd --decompress --stdout "$work/backup.tar.zst" > "$work/backup.tar"
|
|
${pkgs.python3}/bin/python ${extract} "$work/backup.tar" "$work/server"
|
|
# Require the configured save, not an unrelated nested level.dat that
|
|
# would let Minecraft silently generate a fresh world after this restore.
|
|
test -f "$work/server"/${lib.escapeShellArg "${levelName}/level.dat"}
|
|
printf '%s\n' ${lib.escapeShellArg identity} > "$work/server/${marker}"
|
|
${pkgs.coreutils}/bin/chown -hR minecraft:minecraft "$work/server"
|
|
# The marker moves with the tree in the same atomic operation. When a
|
|
# bootstrap exists, exchange leaves it in work/server for trap cleanup;
|
|
# an exchange failure leaves the original directory untouched.
|
|
if [ -e "$target" ]; then
|
|
${pkgs.coreutils}/bin/mv --exchange --no-copy -T "$work/server" "$target"
|
|
else
|
|
${pkgs.coreutils}/bin/mv --no-copy -T "$work/server" "$target"
|
|
fi
|
|
'';
|
|
in {
|
|
options.services.minecraft-backup-restores = lib.mkOption {
|
|
default = {};
|
|
description = "One-time full S3 backup restores, optionally after modpack bootstrap. The regenerated root eula.txt is retained from bootstrap.";
|
|
type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: {
|
|
options = {
|
|
enable = lib.mkEnableOption "one-time Minecraft backup restore";
|
|
serverName = lib.mkOption { type = lib.types.str; default = name; };
|
|
completionMarker = lib.mkOption {
|
|
type = lib.types.str;
|
|
readOnly = true;
|
|
default = "${minecraft.dataDir}/${config.services.minecraft-backup-restores.${name}.serverName}/${marker}";
|
|
description = "Persistent marker path; bootstrap units should use ConditionPathExists=!<this path> to preserve restored configuration on subsequent boots.";
|
|
};
|
|
bucket = lib.mkOption { type = lib.types.str; };
|
|
key = lib.mkOption {
|
|
type = lib.types.str;
|
|
description = "Exact S3 object key ending in .tar.zst.";
|
|
};
|
|
endpoint = lib.mkOption { type = lib.types.str; };
|
|
region = lib.mkOption { type = lib.types.str; };
|
|
credentialsFile = lib.mkOption {
|
|
type = lib.types.str;
|
|
description = "Runtime EnvironmentFile outside /nix/store containing AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.";
|
|
};
|
|
expectedSize = lib.mkOption {
|
|
type = lib.types.nullOr lib.types.ints.positive;
|
|
default = null;
|
|
description = "Expected compressed object size in bytes.";
|
|
};
|
|
timeout = lib.mkOption { type = lib.types.str; default = "2h"; };
|
|
afterUnits = lib.mkOption {
|
|
type = lib.types.listOf lib.types.str;
|
|
default = [];
|
|
description = "Required units that finish before restore, e.g. modpack bootstrap. Backup files override bootstrap files; bootstrap-only mods remain.";
|
|
};
|
|
};
|
|
}));
|
|
};
|
|
|
|
config = lib.mkIf (restores != {}) {
|
|
assertions = [
|
|
{
|
|
assertion = lib.hasPrefix "/" minecraft.dataDir && !lib.hasPrefix "/nix/store/" minecraft.dataDir;
|
|
message = "Minecraft restores require an absolute runtime dataDir.";
|
|
}
|
|
{
|
|
assertion = lib.length (lib.unique (map (restore: restore.serverName) (lib.attrValues restores))) == lib.length (lib.attrNames restores);
|
|
message = "Minecraft restores must have unique server targets.";
|
|
}
|
|
] ++ lib.concatLists (lib.mapAttrsToList (name: restore: [
|
|
{
|
|
assertion = builtins.match "[a-zA-Z0-9_-]+" name != null
|
|
&& builtins.match "[a-zA-Z0-9_-]+" restore.serverName != null
|
|
&& minecraft.enable
|
|
&& (minecraft.servers.${restore.serverName}.enable or false);
|
|
message = "Minecraft restore ${name} must target an enabled Minecraft server and use safe names.";
|
|
}
|
|
{
|
|
assertion = lib.hasPrefix "/" restore.credentialsFile
|
|
&& !lib.hasPrefix "/nix/store/" restore.credentialsFile;
|
|
message = "Minecraft restore ${name} credentials must be a runtime file outside /nix/store.";
|
|
}
|
|
{
|
|
assertion = lib.hasPrefix "https://" restore.endpoint && lib.hasSuffix ".tar.zst" restore.key;
|
|
message = "Minecraft restore ${name} requires HTTPS and an exact .tar.zst object key.";
|
|
}
|
|
]) restores);
|
|
|
|
systemd.services = lib.mkMerge (lib.mapAttrsToList (name: restore: {
|
|
"minecraft-backup-restore-${name}" = {
|
|
description = "One-time full backup restore of Minecraft ${restore.serverName}";
|
|
wants = [ "network-online.target" ];
|
|
after = [ "network-online.target" ] ++ restore.afterUnits;
|
|
requires = restore.afterUnits;
|
|
before = [ "minecraft-server-${restore.serverName}.service" ];
|
|
serviceConfig = {
|
|
Type = "oneshot";
|
|
User = "root";
|
|
UMask = "0077";
|
|
EnvironmentFile = restore.credentialsFile;
|
|
ExecStart = script name restore;
|
|
TimeoutStartSec = restore.timeout;
|
|
};
|
|
};
|
|
"minecraft-server-${restore.serverName}" = {
|
|
requires = [ "minecraft-backup-restore-${name}.service" ];
|
|
after = [ "minecraft-backup-restore-${name}.service" ];
|
|
};
|
|
}) restores);
|
|
};
|
|
}
|