]>
Commit | Line | Data |
---|---|---|
25a66962 MF |
1 | #!/usr/bin/env python3 |
2 | import os | |
3 | import sys | |
f0a474cc | 4 | from subprocess import check_call |
25a66962 MF |
5 | import shlex |
6 | import datetime | |
f0a474cc MF |
7 | class BackupRunner(): |
8 | def __init__(self, config_dir, dest_dir): | |
9 | self.config_dir = config_dir | |
10 | self.dest_dir = dest_dir | |
11 | if not os.path.exists(self.config_dir): | |
12 | print("No config found", self.config_dir) | |
13 | sys-exit(-1) | |
25a66962 | 14 | |
f0a474cc MF |
15 | def run(self): |
16 | self.hosts = os.listdir(self.config_dir) | |
17 | for host in self.hosts: | |
18 | fp = open(os.path.join(self.config_dir, host),"r") | |
19 | self.backup_host(host, fp) | |
20 | fp.close() | |
21 | ||
22 | def backup_host(self, host, host_config): | |
23 | subvol_dir = os.path.join(self.dest_dir, host) | |
24 | dest_dir = os.path.join(subvol_dir, "latest") | |
25 | if not os.path.exists(subvol_dir): | |
26 | print("New host",host,".") | |
27 | try: | |
28 | check_call(shlex.split("btrfs subvol create %s"% subvol_dir)) | |
29 | except subprocess.CalledProcessError as ex: | |
30 | print("Failed to create subvol! Aborting backup.") | |
31 | return() | |
32 | os.makedirs(dest_dir) | |
33 | command = ("rsync --timeout=10 -a --numeric-ids --delete --delete-excluded --human-readable --inplace ") | |
34 | excludes = host_config.readline()[:-1] | |
35 | try: | |
36 | check_call(shlex.split(command + excludes + " root@%s:/ "%(host) + dest_dir)) | |
37 | except subprocess.CalledProcessError as ex: | |
38 | if ex.returncode not in (30, 255): | |
39 | print("Rsync did not transfer anything, skipping snapshot.") | |
40 | return() | |
41 | todays_date = datetime.datetime.now().date().strftime("%F") | |
42 | try: | |
43 | check_call(shlex.split("btrfs subvol snapshot %s %s"%(subvol_dir,os.path.join(subvol_dir, todays_date)))) | |
44 | except subprocess.CalledProcessError as ex: | |
45 | pass | |
25a66962 MF |
46 | |
47 | if __name__ == "__main__": | |
48 | if os.geteuid() != 0: | |
49 | print("You need to be root. Otherwise all permissions will be lost.") | |
50 | sys.exit(-1) | |
f0a474cc MF |
51 | br = BackupRunner("/etc/butterbackup", "/mnt/data2") |
52 | br.run() | |
25a66962 | 53 | sys.exit(0) |