borg-backup.sh.j2 2.6 KB
Newer Older
1
2
#!/usr/bin/env bash

3
4
set -e

5
src="/"
6
7
snapshotdir="backup-snapshot"
backup_mountdir="/backup"
8

9
10
declare -a list_of_btrfs_submounts

11
12
13
14
15
16
##
#  usage : is_btrfs( $path )
# return : whether $path is on a btrfs
# source: makechrootpkg from devtools
##
is_btrfs() {
17
    [[ -e "$1" && "$(stat -f -c %T "$1")" == btrfs ]]
18
19
}

20
21
22
##
#  usage : delete_snapshot( $path )
##
23
delete_snapshot() {
24
    btrfs subvolume delete --commit-after "$1"
25
26
}

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
##
# exit cleanup handler
##
cleanup() {
  if is_btrfs "$src"; then
      umount -R "$backup_mountdir"
      for vol in $list_of_btrfs_submounts; do
          delete_snapshot "$vol/$snapshotdir"
      done
      rmdir "$backup_mountdir"
  fi
}

trap cleanup EXIT

42
43
44
45
46
47
# Dump databases to /root/backup-{postgres,mysql} before taking a btrfs snapshot
systemctl is-active postgresql && /usr/local/bin/backup-postgres.sh || true
if systemctl is-active mysqld || systemctl is-active mariadb; then
    /usr/local/bin/backup-mysql.sh || true
fi

48
if is_btrfs "$src"; then
49
50
    # List all btrfs submounts we want to backup, e.g. homedir.archlinux.org with "/ /home"
    list_of_btrfs_submounts=$(findmnt -Rl -o target,fstype,options / | grep btrfs | grep -v docker | grep -v "subvol=\/[[:alnum:]]" | cut -d ' ' -f1)
51
52

    if [[ -d "$backup_mountdir" ]]; then
53
54
55
        if [[ $(findmnt -M "$backup_mountdir") ]]; then
            umount -R "$backup_mountdir"
        fi
56
57
58
59
60
61
62
63
64
65
66
        rmdir "$backup_mountdir"
    fi
    mkdir "$backup_mountdir"
    for vol in $list_of_btrfs_submounts; do
        if [[ -d "$vol/$snapshotdir" ]]; then
            delete_snapshot "$vol/$snapshotdir"
        fi

        btrfs subvolume snapshot -r "$vol" "$vol/$snapshotdir"
        mount -o bind "$vol/$snapshotdir" "$backup_mountdir/$vol"
    done
67
68
else
    backup_mountdir="$src"
69
70
fi

71
{{ item['borg_cmd'] }} create -v --stats -C zstd \
72
73
74
75
76
77
78
79
    -e /proc \
    -e /sys \
    -e /dev \
    -e /run \
    -e /tmp \
    -e /var/cache \
    -e /var/lib/archbuild \
    -e /var/lib/archbuilddest \
80
81
82
83
84
85
    -e /var/lib/docker \
    -e "$backup_mountdir/proc" \
    -e "$backup_mountdir/sys" \
    -e "$backup_mountdir/dev" \
    -e "$backup_mountdir/run" \
    -e "$backup_mountdir/tmp" \
86
87
88
    -e "$backup_mountdir/var/cache" \
    -e "$backup_mountdir/var/lib/archbuild" \
    -e "$backup_mountdir/var/lib/archbuilddest" \
89
    -e "$backup_mountdir/var/lib/docker" \
90
    {{ item['host'] }}/{{ item['dir'] }}::$(date "+%Y%m%d-%H%M%S") "$backup_mountdir"
91

92
{{ item['borg_cmd'] }} prune -v {{ item['host'] }}/{{ item['dir'] }} --keep-daily=7 --keep-weekly=4 --keep-monthly=6
93
94
95
96

{% if item['compact_after_prune'] %}
{{ item['borg_cmd'] }} compact -v {{ item['host'] }}/{{ item['dir'] }}
{% endif %}