-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup.py
More file actions
executable file
·80 lines (60 loc) · 1.87 KB
/
backup.py
File metadata and controls
executable file
·80 lines (60 loc) · 1.87 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
#! /usr/bin/env python3
import subprocess
import json
import logging
from datetime import datetime
from pathlib import Path
import sys
import tarfile
CONFIG_PATH = Path.home() / "backup/config.json"
def load_config():
with open(CONFIG_PATH) as f:
return json.load(f)
def setup_logging(log_file):
logging.basicConfig(
filename=log_file,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
def archive_builds(build_dir, output_dir):
timestamp = datetime.now().strftime("%Y-%m-%d")
archive_path = Path(output_dir) / f"builds_{timestamp}.tar.gz"
with tarfile.open(archive_path, "w:gz") as tar:
tar.add(build_dir, arcname=Path(build_dir).name)
def run_backup(sources, destination, exclude):
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
dest_path = Path(destination) / timestamp
dest_path.mkdir(parents=True, exisit_ok=True)
cmd = [
"rsync",
"-aAx",
"--delete",
"--numeric-ids",
"--link-dest", f"{Path(destination)}/latest"
]
for e in exclude:
cmd.extend(["--exclude", e])
cmd.extend(source)
cmd.append(str(dest_path))
logging.info("Running rsync command")
logging.info(" ".join(cmd))
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode != 0:
logging.error(result.stderr)
sys.exit(1)
# Update "latest" symlink
latest = Path(destination) / "latest"
if latest.exists() or latest.is_symlink():
latest.unlink()
latest.symlink_to(dest_path)
logging.info("Backup completed sucessfully")
def main():
config = load_config()
setup_logging(config["log_file"])
run_backup(
config["sources"],
config["destination"],
config["exclude"]
)
if __name__ == "__main__":
main()