Repository navigation
Expand file tree
/
Copy pathbackup.py
More file actions
189 lines (154 loc) · 7.34 KB
/
Copy pathbackup.py
File metadata and controls
189 lines (154 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
Backs up a game server's world/save directory.
Default: stop the docker container, tar the world, start it again — the
universal method, works for any container-based game server, no special
support needed from the game itself. This is real (but brief) downtime for
however long the tar+gzip takes.
--rcon opts into a no-downtime path instead, for servers that support it
(currently just Paper/vanilla Minecraft's RCON): pauses world saves
(`save-off`), flushes the current state to disk (`save-all flush`), tars,
then resumes saves (`save-on`) — the container is never stopped. rcon
host/port/password are always read from <server-dir>/server.properties
(enable-rcon must be true there), never passed on the command line, so
crontab -l never shows the password in plaintext.
Usage: backup.py <container> <server-dir> <world-path> <backup-path> [--rcon]
e.g.: backup.py paper /srv/paper world /mnt/paper-backup --rcon
backup.py some-other-game /srv/other-game save backups
<world-path>/<backup-path> may each be relative (resolved against
<server-dir>) or absolute (used as-is, <server-dir> ignored for that one).
Retention count is the KEEP_BACKUPS constant below, not a CLI arg.
"""
import argparse
import os
import socket
import struct
import subprocess
import sys
import tarfile
import time
SERVERDATA_AUTH = 3
SERVERDATA_AUTH_RESPONSE = 2
SERVERDATA_EXECCOMMAND = 2
RCON_TIMEOUT_S = 10
# save-all flush's console response usually only arrives once the write is
# done, but region-file writes can have their own async buffering — this is
# a cheap safety margin before we start reading files for the tar.
POST_FLUSH_SETTLE_S = 5
# How many backups to keep in <backup-path> — after a successful backup,
# the oldest ones beyond this count are deleted. <= 0 disables pruning
# entirely (keep everything forever). Edit this constant directly.
KEEP_BACKUPS = 5
def _recv_exact(sock, n):
data = b""
while len(data) < n:
chunk = sock.recv(n - len(data))
if not chunk:
raise ConnectionError("RCON connection closed unexpectedly")
data += chunk
return data
def _read_packet(sock):
(length,) = struct.unpack("<i", _recv_exact(sock, 4))
body = _recv_exact(sock, length)
request_id, packet_type = struct.unpack("<ii", body[:8])
payload = body[8:-2] # trailing two null bytes
return request_id, packet_type, payload
def _send_packet(sock, request_id, packet_type, payload: bytes):
body = struct.pack("<ii", request_id, packet_type) + payload + b"\x00\x00"
sock.sendall(struct.pack("<i", len(body)) + body)
class Rcon:
"""Minimal Source-RCON client — just enough to run a few admin commands
against Paper's built-in RCON server. No external dependency on purpose:
this only needs to run via cron on the host, nothing else touches it."""
def __init__(self, host, port, password, timeout=RCON_TIMEOUT_S):
self.sock = socket.create_connection((host, port), timeout=timeout)
self.sock.settimeout(timeout)
_send_packet(self.sock, 1, SERVERDATA_AUTH, password.encode("utf-8"))
# Minecraft's RCON sends an empty SERVERDATA_RESPONSE_VALUE ack
# packet before the real auth-response packet — skip anything that
# isn't the auth response itself.
while True:
request_id, packet_type, _ = _read_packet(self.sock)
if packet_type == SERVERDATA_AUTH_RESPONSE:
if request_id == -1:
raise RuntimeError("RCON authentication failed (check rcon.password)")
return
def command(self, cmd):
_send_packet(self.sock, 2, SERVERDATA_EXECCOMMAND, cmd.encode("utf-8"))
_, _, payload = _read_packet(self.sock)
return payload.decode("utf-8", errors="replace")
def close(self):
self.sock.close()
def resolve_path(base_dir, path):
"""path as-is if it's already absolute, else resolved relative to base_dir."""
return path if os.path.isabs(path) else os.path.join(base_dir, path)
def prune_old_backups(backup_dir, keep):
if keep <= 0:
return
names = sorted(f for f in os.listdir(backup_dir) if f.endswith(".tar.gz"))
for old in names[:-keep] if len(names) > keep else []:
path = os.path.join(backup_dir, old)
os.remove(path)
print(f"pruned old backup: {path}")
def read_server_properties(path):
props = {}
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
props[key.strip()] = value.strip()
return props
def make_backup(server_dir, world_path, backup_path):
"""Tars world_path into a fresh timestamped archive under backup_path,
then prunes old ones — the part shared by both backup modes, run while
whichever pause mechanism (RCON save-off or a stopped container) is
already in effect."""
backup_dir = resolve_path(server_dir, backup_path)
os.makedirs(backup_dir, exist_ok=True)
dest = os.path.join(backup_dir, time.strftime("%Y-%m-%d_%H-%M.tar.gz"))
with tarfile.open(dest, "w:gz") as tar:
tar.add(resolve_path(server_dir, world_path))
prune_old_backups(backup_dir, KEEP_BACKUPS)
def backup_via_rcon(server_dir, world_path, backup_path):
props_path = os.path.join(server_dir, "server.properties")
props = read_server_properties(props_path)
if props.get("enable-rcon", "false").lower() != "true":
print(f"--rcon given but enable-rcon isn't true in {props_path} — aborting.", file=sys.stderr)
sys.exit(1)
rcon_port = int(props.get("rcon.port", "25575"))
rcon_password = props.get("rcon.password", "")
rcon = Rcon("127.0.0.1", rcon_port, rcon_password)
try:
rcon.command("save-off")
rcon.command("save-all flush")
time.sleep(POST_FLUSH_SETTLE_S)
make_backup(server_dir, world_path, backup_path)
finally:
rcon.command("save-on")
rcon.close()
def backup_via_stop_start(container, server_dir, world_path, backup_path):
subprocess.run(["docker", "stop", container], check=True)
try:
make_backup(server_dir, world_path, backup_path)
finally:
subprocess.run(["docker", "start", container], check=True)
def parse_args():
p = argparse.ArgumentParser(description="Back up a game server's world/save directory.")
p.add_argument("container", help="Docker container name (stopped/started around the backup, unless --rcon)")
p.add_argument("server_dir", help="Server's root directory (also where server.properties lives, for --rcon)")
p.add_argument("world_path", help="World/save directory to back up — relative (resolved against server_dir) or absolute")
p.add_argument("backup_path", help="Where to write the backup — relative (resolved against server_dir) or absolute")
p.add_argument(
"--rcon", action="store_true",
help="Use RCON save-off/save-on instead of stopping the container — Minecraft/Paper only, needs enable-rcon=true in server.properties",
)
return p.parse_args()
def main():
args = parse_args()
if args.rcon:
backup_via_rcon(args.server_dir, args.world_path, args.backup_path)
else:
backup_via_stop_start(args.container, args.server_dir, args.world_path, args.backup_path)
if __name__ == "__main__":
main()