BorgBackup xoyaz.xyz

BorgBackup xoyaz.xyz

Notes

xoyaz.xyz

Les dossiers à créer

1
2
3
sudo mkdir -p /etc/borgbackup
# dossier sur root
sudo mkdir -p /root/.borg

Le dépôt borg initialisé : xoyaz.xyz

Le flag et le log portent un identifiant tiré du nom du fichier .repository (xoyaz.xyz.repository donne xoyaz.xyz), pour que plusieurs jobs coexistent sur une même machine.

Transférer les fichiers /sharenfs/pc1/.borg/xoyaz.xyz.*

1
2
3
sudo mv xoyaz.xyz.* /root/.borg/
sudo chown root:root -R /root/.borg/
sudo chmod 600  -R /root/.borg/

Environnement : /etc/borgbackup/xoyaz.xyz.env

1
2
3
4
5
6
7
borg_passphrase=/root/.borg/xoyaz.xyz.passphrase
borg_borgssh=/root/.borg/xoyaz.xyz.borgssh
borg_repository=/root/.borg/xoyaz.xyz.repository
borg_exclusions=/root/.borg/xoyaz.xyz.exclusions
borg_infoOVH vps-5351f610 xoyaz.xyz
borg_ntfy_env=/root/ntfy.env
borg_stamp=non

Le service, en root pour pouvoir lire tout / : /etc/systemd/system/borgbackup@.service

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=Borgbackup (%i)
Wants=network-online.target
After=network-online.target
# Portable : ne pas lancer sur batterie (décommenter si souhaité)
#ConditionACPower=true

[Service]
Type=oneshot
EnvironmentFile=/etc/borgbackup/%i.env
ExecStart=/usr/local/bin/borgbackup.sh
Nice=19
IOSchedulingClass=idle

Le timer template, horaire (pour borg_stamp=oui) : /etc/systemd/system/borgbackup@.timer

1
2
3
4
5
6
7
8
9
[Unit]
Description=Borgbackup (%i) : tentative horaire

[Timer]
OnCalendar=
OnCalendar=*-*-* 03:30

[Install]
WantedBy=timers.target

La ligne OnCalendar= vide est indispensable : OnCalendar est une liste, et sans ce reset l’horaire horaire du template resterait actif.

Le script /usr/local/bin/borgbackup.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/bin/bash
# /usr/local/bin/borgbackup.sh — script commun
#
# Variables à exporter avant l'exécution (chemins de fichiers) :
#   borg_passphrase   fichier contenant la passphrase du dépôt
#   borg_borgssh      clé ssh privée
#   borg_repository   fichier contenant l'URL du dépôt
#   borg_exclusions   fichier d'exclusions (--exclude-from)
# Optionnelles :
#   borg_info         libellé affiché dans la notification (défaut : hostname)
#   borg_path         chemin à sauvegarder (défaut : /)
#   borg_ntfy_env     fichier d'env ntfy (défaut : ~/.config/ntfy/ntfy.env)
#   borg_stamp        oui (défaut) : une seule sauvegarde par jour, flag /var/tmp
#                     non : pas de flag, le timer décide de la fréquence

NTFY_ENV="${borg_ntfy_env:-$HOME/.config/ntfy/ntfy.env}"
if [ ! -r "$NTFY_ENV" ]; then
  echo "Fichier ntfy introuvable : $NTFY_ENV" >&2
  exit 2
fi
. "$NTFY_ENV"

INFO="${borg_info:-$(hostname)}"
BORG_PATH="${borg_path:-/}"

# --- notification ntfy -------------------------------------------------------
# usage : notify "titre" "priorité" "tags" < corps
notify() {
  curl -sS -X POST \
    -H "X-Email: $NTFY_EMAIL" \
    -H "Title: $1" \
    -H "Authorization: Bearer $NTFY_TOKEN" \
    -H "Priority: $2" \
    -H "Tags: $3" \
    -H "Content-Type: text/plain; charset=utf-8" \
    --data-binary @- \
    "$NTFY_URL"
}

# --- vérification des 4 variables et des fichiers ----------------------------
missing=""
for v in borg_passphrase borg_borgssh borg_repository borg_exclusions; do
  eval "val=\${$v:-}"
  if [ -z "$val" ]; then
    missing="$missing\nVariable non définie : $v"
  elif [ ! -r "$val" ]; then
    missing="$missing\nFichier introuvable ou illisible : $v=$val"
  fi
done
if [ -n "$missing" ]; then
  printf "Configuration incomplète :$missing\n" | tee /dev/stderr | \
    notify "💻 $INFO : Borgbackup ❌ préparation" "high" "rotating_light"
  exit 2
fi

# --- identifiant dérivé du fichier repository (ex. e6230) --------------------
ID="$(basename "$borg_repository")"
ID="${ID%.repository}"
STAMP="/var/tmp/borg-last-backup-$ID"
FULLLOG="/var/tmp/borg-$ID-last.log"
TODAY=$(date +%F)

# --- flag du jour (borg_stamp=oui par défaut) --------------------------------
STAMP_ON=1
case "${borg_stamp:-oui}" in
  non|NON|no|NO|false|0) STAMP_ON=0 ;;
esac

if [ "$STAMP_ON" -eq 1 ] && [ -f "$STAMP" ] && [ "$(cat "$STAMP")" = "$TODAY" ]; then
  echo "Backup déjà fait aujourd'hui ($TODAY)."
  exit 0
fi

LOG_DIR=$(mktemp -d)
trap 'rm -rf "$LOG_DIR"' EXIT

# --- nature de l'incident selon le code de retour borg -----------------------
rc_nature() {
  rc=$1
  if   [ "$rc" -eq 0 ];   then echo "OK"
  elif [ "$rc" -eq 1 ];   then echo "AVERTISSEMENT (opération terminée, mais avec des warnings)"
  elif [ "$rc" -eq 2 ];   then echo "ERREUR (l'opération a échoué)"
  elif [ "$rc" -ge 128 ]; then echo "INTERROMPU par le signal $((rc - 128))"
  else                         echo "CODE DE RETOUR INATTENDU ($rc)"
  fi
}

# --- exécute une commande, garde sa sortie dans un log, renvoie son rc -------
run_step() {
  logfile=$1; shift
  "$@" 2>&1 | tee "$logfile"
  return "${PIPESTATUS[0]}"
}

# --- détail d'une étape en échec : lignes parlantes + fin du log -------------
step_detail() {
  label=$1; rc=$2; logfile=$3
  echo "❌ $label : $(rc_nature "$rc") [rc=$rc]"
  if [ -s "$logfile" ]; then
    echo "-- Lignes significatives --"
    grep -iE 'error|erreur|fail|warning|exception|traceback|denied|refused|timed out|timeout|connection|lock|passphrase|repository|no such file|not found|space' "$logfile" | tail -n 15
    echo "-- Fin du log --"
    tail -n 10 "$logfile"
  else
    echo "(aucune sortie de borg)"
  fi
  echo
}

# --- préparation -------------------------------------------------------------
t=$(date +%s)

export BORG_PASSPHRASE="$(cat "$borg_passphrase")"
# BatchMode : échoue au lieu de demander un mot de passe ssh
export BORG_RSH="ssh -i $borg_borgssh -o BatchMode=yes -o ServerAliveInterval=60 -o ServerAliveCountMax=5"

BACKUP_DATE="$(date +%Y-%m-%d-%Hh%M)"
BORG_REPOSITORY="$(cat "$borg_repository")"

# --- borg create -------------------------------------------------------------
LOG_CREATE="$LOG_DIR/create.log"
run_step "$LOG_CREATE" \
  borg create -v --stats --exclude-from "$borg_exclusions" \
  "${BORG_REPOSITORY}::${BACKUP_DATE}" "$BORG_PATH"
rc_create=$?

# --- borg prune (sauté si le create a échoué) --------------------------------
LOG_PRUNE="$LOG_DIR/prune.log"
if [ "$rc_create" -le 1 ]; then
  run_step "$LOG_PRUNE" \
    borg prune -v --stats --keep-daily=7 --keep-weekly=1 --keep-monthly=1 \
    "$BORG_REPOSITORY"
  rc_prune=$?
else
  rc_prune=-1
  echo "Prune non exécuté : le borg create a échoué (rc=$rc_create)." > "$LOG_PRUNE"
fi

# --- durée -------------------------------------------------------------------
d=$(( $(date +%s) - t ))
DUREE=$(( d / 3600 ))h$(( (d % 3600) / 60 ))m$(( d % 60 ))s

# --- bilan -------------------------------------------------------------------
# État global : 0 = OK, 1 = avertissement, 2 = échec
if [ "$rc_create" -ge 2 ] || [ "$rc_prune" -ge 2 ] || [ "$rc_prune" -eq -1 ]; then
  status=2
elif [ "$rc_create" -eq 1 ] || [ "$rc_prune" -eq 1 ]; then
  status=1
else
  status=0
fi

# Flag du jour : posé si la sauvegarde est faite (OK ou avertissement)
[ "$STAMP_ON" -eq 1 ] && [ "$status" -le 1 ] && date +%F > "$STAMP"

{
  echo "=== borg create ($BACKUP_DATE) ==="; cat "$LOG_CREATE"
  echo; echo "=== borg prune ==="; cat "$LOG_PRUNE"
} > "$FULLLOG"

# --- titre / priorité / tags (calculés hors pipeline) ------------------------
if [ "$status" -eq 0 ]; then
  title="💻 $INFO : Borgbackup ✔️ en $DUREE"
  prio="low"; tags="white_check_mark"
elif [ "$status" -eq 2 ]; then
  title="💻 $INFO : Borgbackup ❌ ÉCHEC en $DUREE"
  prio="high"; tags="rotating_light"
else
  title="💻 $INFO : Borgbackup ⚠️ avertissement en $DUREE"
  prio="default"; tags="warning"
fi

# --- corps du message --------------------------------------------------------
BODY="$LOG_DIR/body.txt"
{
  if [ "$status" -eq 0 ]; then
    echo "✔️ borg create : OK"
    tail -n 12 "$LOG_CREATE"
    echo
    echo "✔️ borg prune : OK"
  else
    [ "$rc_create" -ne 0 ] && step_detail "borg create" "$rc_create" "$LOG_CREATE"
    if [ "$rc_prune" -eq -1 ]; then
      echo "⏭️ borg prune : non exécuté (échec du create)"
    elif [ "$rc_prune" -ne 0 ]; then
      step_detail "borg prune" "$rc_prune" "$LOG_PRUNE"
    fi
    echo "Log complet : $FULLLOG"
  fi
} > "$BODY"

# --- envoi -------------------------------------------------------------------
head -c 3800 "$BODY" | notify "$title" "$prio" "$tags"

# Code de sortie pour systemd : échec = unité en "failed"
[ "$status" -lt 2 ] || exit 1

À rendre exécutable

1
sudo chmod 755 /usr/local/bin/borgbackup.sh

Activation et suivi :

1
2
3
4
5
6
7
8
# dépôt xoyaz.xyz.repository
sudo chmod 600 /etc/borgbackup/*.env
sudo systemctl daemon-reload
sudo systemctl enable --now borgbackup@xoyaz.xyz.timer

sudo systemctl start borgbackup@xoyaz.xyz.service      # test immédiat
#sudo journalctl -u borgbackup@xoyaz.xyz.service -f
systemctl list-timers 'borgbackup@*'

Pour éviter l’avertissement, excluez les journaux volatils, par exemple avec une règle d’exclusion pour /var/log/journal/