]>
Commit | Line | Data |
---|---|---|
1 | #!/usr/bin/env python3 | |
2 | import os | |
3 | import sys | |
4 | from subprocess import check_call, CalledProcessError | |
5 | import shlex | |
6 | import datetime | |
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) | |
14 | ||
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 | host_dir = os.path.join(self.dest_dir, host) | |
24 | subvol_dir = os.path.join(host_dir, "latest") | |
25 | if not os.path.exists(host_dir): | |
26 | print("New host",host,".") | |
27 | os.makedir(host_dir) | |
28 | if not os.path.exists(subvol_dir): | |
29 | try: | |
30 | check_call(shlex.split("btrfs subvol create %s"% subvol_dir)) | |
31 | except CalledProcessError as ex: | |
32 | print("Failed to create subvol! Aborting backup.") | |
33 | return() | |
34 | ||
35 | command = ("rsync -a --acls --xattrs --whole-file --numeric-ids --delete --delete-excluded --human-readable --inplace ") | |
36 | excludes = host_config.readline()[:-1] | |
37 | try: | |
38 | check_call(shlex.split(command + excludes + " root@%s:/ "%(host) + subvol_dir)) | |
39 | except CalledProcessError as ex: | |
40 | if ex.returncode not in (12, 30, 255): | |
41 | print("Rsync did not transfer anything from %s, skipping snapshot."%host) | |
42 | return() | |
43 | todays_date = datetime.datetime.now().date().strftime("%F") | |
44 | if os.path.exists(os.path.join(host_dir, todays_date)): | |
45 | #There is a snapshot for today, removing it and creating a new one | |
46 | try: | |
47 | check_call(shlex.split("btrfs subvol delete %s"%(os.path.join(host_dir, todays_date)))) | |
48 | except CalledProcessError as ex: | |
49 | pass | |
50 | try: | |
51 | check_call(shlex.split("btrfs subvol snapshot -r %s %s"%(subvol_dir,os.path.join(host_dir, todays_date)))) | |
52 | except CalledProcessError as ex: | |
53 | pass | |
54 | ||
55 | if __name__ == "__main__": | |
56 | if os.geteuid() != 0: | |
57 | print("You need to be root. Otherwise all permissions will be lost.") | |
58 | sys.exit(-1) | |
59 | br = BackupRunner("/etc/butterbackup", "/mnt/data2") | |
60 | br.run() | |
61 | sys.exit(0) |