bicep/mysql: split backups into one file per db

This commit is contained in:
h7x4
2026-07-21 16:01:34 +09:00
parent 4525de1d10
commit d25d0f8b56
+25 -11
View File
@@ -41,24 +41,38 @@ in
path = with pkgs; [ path = with pkgs; [
cfg.package cfg.package
coreutils coreutils
diffutils
zstd zstd
]; ];
script = let script = ''
rotations = 2;
in ''
set -euo pipefail set -euo pipefail
OUT_FILE="$STATE_DIRECTORY/mysql-dump-$(date --iso-8601).sql.zst" dump() {
local name="$1" out tmp
out="$STATE_DIRECTORY/$name.sql.zst"
tmp="$out.tmp"
shift
"$@" | zstd -9 --rsyncable -f -o "$tmp"
if cmp -s "$tmp" "$out" 2>/dev/null; then
rm -f "$tmp"
else
mv -f "$tmp" "$out"
fi
}
mysqldump --all-databases | zstd --compress -9 --rsyncable -o "$OUT_FILE" declare -A keep
while IFS= read -r db; do
[ -n "$db" ] || continue
dump "$db" mysqldump --skip-dump-date --databases "$db"
keep["$db.sql.zst"]=1
done < <(mysql -N -e 'SHOW DATABASES' | grep -vE '^(information_schema|performance_schema)$')
# NOTE: this needs to be a hardlink for rrsync to allow sending it # drop dumps of databases that no longer exist
rm "$STATE_DIRECTORY/mysql-dump-latest.sql.zst" ||: for f in "$STATE_DIRECTORY"/*.sql.zst; do
ln -T "$OUT_FILE" "$STATE_DIRECTORY/mysql-dump-latest.sql.zst" [ -e "$f" ] || continue
base="$(basename "$f")"
while [ "$(find "$STATE_DIRECTORY" -type f -printf '.' | wc -c)" -gt '${toString (rotations + 1)}' ]; do [ -n "''${keep[$base]:-}" ] || rm -f "$f"
rm "$(find "$STATE_DIRECTORY" -type f -printf '%T+ %p\n' | sort | head -n 1 | cut -d' ' -f2)"
done done
''; '';