]>
Commit | Line | Data |
---|---|---|
25a66962 MF |
1 | #!/usr/bin/env python3 |
2 | import os | |
3 | import sys | |
3fc75327 | 4 | from subprocess import check_call, CalledProcessError |
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): | |
3fc75327 MF |
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): | |
f0a474cc | 26 | print("New host",host,".") |
3fc75327 MF |
27 | os.makedir(host_dir) |
28 | if not os.path.exists(subvol_dir): | |
f0a474cc MF |
29 | try: |
30 | check_call(shlex.split("btrfs subvol create %s"% subvol_dir)) | |
3fc75327 | 31 | except CalledProcessError as ex: |
f0a474cc MF |
32 | print("Failed to create subvol! Aborting backup.") |
33 | return() | |
3fc75327 MF |
34 | |
35 | command = ("rsync -a --acls --xattrs --whole-file --numeric-ids --delete --delete-excluded --human-readable --inplace ") | |
f0a474cc MF |
36 | excludes = host_config.readline()[:-1] |
37 | try: | |
3fc75327 MF |
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) | |
f0a474cc MF |
42 | return() |
43 | todays_date = datetime.datetime.now().date().strftime("%F") | |
3fc75327 MF |
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 | |
f0a474cc | 50 | try: |
3fc75327 MF |
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: | |
f0a474cc | 53 | pass |
25a66962 MF |
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) | |
f0a474cc MF |
59 | br = BackupRunner("/etc/butterbackup", "/mnt/data2") |
60 | br.run() | |
25a66962 | 61 | sys.exit(0) |