-
-
Save vinanrra/2571ff5e9a1b64df7e55758bf30cd578 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
import os, sys, datetime, lzma, tarfile | |
MAX_BACKUPS = 10 | |
BACKUP_DIR = "backups" | |
SERVER_DIR = "" # set your server installation directory here, eg. /home/vhserver | |
DIRS_TO_BACKUP = [ | |
"lgsm/config-lgsm", | |
"savedir", | |
] | |
if not SERVER_DIR: | |
print("Set your server directory!!") | |
exit(1) | |
os.chdir(SERVER_DIR) | |
log_file = open("backup-log.txt", "a+") | |
archive_name = "valheim-backup-" + datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%M%S") + ".tar.xz" | |
def log(s): | |
log_file.write(f"{datetime.datetime.now()} {str(s)}\n") | |
def get_size(start_path): | |
total_size = 0 | |
for dirpath, dirnames, filenames in os.walk(start_path): | |
for f in filenames: | |
fp = os.path.join(dirpath, f) | |
if not os.path.islink(fp): | |
total_size += os.path.getsize(fp) | |
if total_size < 1024: | |
return "{:.2f}".format(total_size)+"B" | |
total_size /= 1024 | |
if total_size < 1024: | |
return "{:.2f}".format(total_size)+"KB" | |
total_size /= 1024 | |
if total_size < 1024: | |
return "{:.2f}".format(total_size)+"MB" | |
total_size /= 1024 | |
return "{:.2f}".format(total_size)+"GB" | |
log("Beginning backup") | |
try: | |
backups = os.listdir(BACKUP_DIR) | |
if len(backups) >= MAX_BACKUPS: | |
log(f"Backup limit reached (>={MAX_BACKUPS})") | |
oldest_file = "" | |
oldest_time = 0 | |
for fp in backups: | |
fp = os.path.join(BACKUP_DIR, fp) | |
mtime = os.path.getmtime(fp) | |
if not oldest_file or mtime < oldest_time: | |
oldest_file = fp | |
oldest_time = mtime | |
log("Removing oldest backup "+oldest_file) | |
os.remove(oldest_file) | |
with tarfile.open(os.path.join(BACKUP_DIR, archive_name), "w:xz") as archive: | |
for d in DIRS_TO_BACKUP: | |
if not os.path.exists(d) or not os.path.isdir(d): | |
log(d+" is not a directory") | |
continue | |
log(f"Adding {d} to archive ({get_size(d)})") | |
archive.add(d) | |
log("Complete") | |
except Exception as e: | |
log(f"Error completing backup: {str(e)}") | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment