borgbackup.sh 2.05 KB
Newer Older
Fjen Undso's avatar
Fjen Undso committed
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
set -euo pipefail

# some helpers and error handling:
info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM

# load config
source ./borgbackup.config.sh

# borg backup
info "Starting backup"
Fjen Undso's avatar
Fjen Undso committed
13
TMPFILE1="$(mktemp)"
Fjen Undso's avatar
Fjen Undso committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
borg create \
     --verbose \
     --stats \
     --compression "$COMPRESS" \
     $BORG_PARAMS \
     '::{hostname}-{now}' \
     $BORG_PATHS \
     2>&1 | tee "$TMPFILE1"
backup_exit=$?


# Use the `prune` subcommand to maintain 7 daily, 4 weekly and 12 monthly
# archives of THIS machine. --prefix `hostname`- is very important to
# limit prune's operation to this machine's archives and not apply to
# other machine's archives also.
info "Pruning repository"
Fjen Undso's avatar
Fjen Undso committed
30
TMPFILE2="$(mktemp)"
Fjen Undso's avatar
Fjen Undso committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
borg prune \
     --prefix '{hostname}-' \
     --verbose \
     --list \
     --show-rc \
     --keep-daily 30 \
     --keep-weekly 4 \
     --keep-monthly 12 \
     2>&1 | tee "$TMPFILE2"
prune_exit=$?

# Dump the exit codes to /var/log. Icinga2 checks the location to examine the backup results
log_dir="/var/log/borg"
mkdir -p "$log_dir" || (info "Failed to \`mkdir -p $log_dir\`" && global_exit=1)
echo -e "create: $backup_exit\nprune: $prune_exit" > "$log_dir/borg-rc.log"

# use highest exit code as global exit code
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))


# error mail sending
if [ $global_exit != 0 ]; then
    /usr/bin/logger -t backup "Exited abnormally with [$backup_exit][$prune_exit]"
    MAIL="# borg create:\n"
Fjen Undso's avatar
Fjen Undso committed
55
56
    MAIL+=$(cat "$TMPFILE1")
    MAIL+="\n\n"
Fjen Undso's avatar
Fjen Undso committed
57
    MAIL+="# borg prune:\n"
Fjen Undso's avatar
Fjen Undso committed
58
59
    MAIL+=$(cat "$TMPFILE2")
    MAIL+="\n\n"
Fjen Undso's avatar
Fjen Undso committed
60
61
    MAIL+="# borg list:\n"
    MAIL+="$(borg list)\n\n"
Fjen Undso's avatar
Fjen Undso committed
62
    MAIL+="Cheers,\n$HOSTNAME"
Fjen Undso's avatar
Fjen Undso committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    echo -e "$MAIL" | mail -a "Content-Type: text/plain; charset=UTF-8" -s "$HOSTNAME: borgbackup failed!" "$ADMINMAIL"
fi
rm -f "$TMPFILE1" "$TMPFILE2"


if [ ${global_exit} -eq 1 ];
then
    info "Backup and/or Prune finished with a warning"
fi
if [ ${global_exit} -gt 1 ];
then
    info "Backup and/or Prune finished with an error"
fi
exit ${global_exit}