]> git.frykholm.com Git - butterbackup.git/blob - butterbackup.py
Refactor and add some error handling.
[butterbackup.git] / butterbackup.py
1 #!/usr/bin/env python3
2 import os
3 import sys
4 from subprocess import check_call
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 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
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)
51 br = BackupRunner("/etc/butterbackup", "/mnt/data2")
52 br.run()
53 sys.exit(0)