GITv
master
gitv-backup180 lines, 7.8 KB
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
#!/bin/bash
# Snapshot everything GITv needs to come back after losing the server: the repositories (with
# their trash, reflogs, push logs and visibility markers), the SSH keys file, the web sign-in,
# and the server's SSH host keys (so a rebuilt server is the one clients already trust).
#
# Each run writes <backup dir>/gitv/snapshots/<UTC time>/, a plain copy that restores with
# rsync or cp. Files unchanged since the previous snapshot are hard links to it, so a snapshot
# costs only what changed. Each repository is copied under its exclusive lock (pushes hold it
# shared), then checked with git fsck; only a snapshot that passes becomes `latest`.
#
# Settings (environment; the systemd unit sets the backup directory):
#   GITV_BACKUP_DIR            where the volume is mounted        (/mnt/gitv-backup)
#   GITV_BACKUP_KEEP_DAYS      delete snapshots older than this   (30)
#   GITV_BACKUP_REQUIRE_MOUNT  refuse unless the dir is a mount   (1)
#   GITV_BACKUP_LOCK_WAIT      seconds to wait for a push         (900)
#   GITV_BACKUP_SSH_DIR        where the SSH host keys are        (/etc/ssh)
#   GITV_REPOS, GITV_KEYS, GITV_WEB_AUTH as for gitv and gitv-web.
set -euo pipefail
umask 077

dest=${GITV_BACKUP_DIR:-/mnt/gitv-backup}
keep_days=${GITV_BACKUP_KEEP_DAYS:-30}
lock_wait=${GITV_BACKUP_LOCK_WAIT:-900}
repos=${GITV_REPOS:-/srv/gitv/repos}
keys_dir=$(dirname "${GITV_KEYS:-/etc/gitv/authorized_keys}")
web_dir=$(dirname "${GITV_WEB_AUTH:-/var/lib/gitv-web/login}")
ssh_dir=${GITV_BACKUP_SSH_DIR:-/etc/ssh}

say() { echo "gitv-backup: $*" >&2; }
die() { say "$*"; exit 1; }

# An unmounted volume would silently fill the server's own disk instead.
if [[ ${GITV_BACKUP_REQUIRE_MOUNT:-1} == 1 ]] && ! mountpoint -q "$dest"; then
    die "$dest is not a mounted volume; mount the backup volume there first"
fi
[[ -d $repos && ! -L $repos ]] || die "$repos is not a directory"

base=$dest/gitv
snapshots=$base/snapshots
mkdir -p "$snapshots"
chmod 700 "$base"

# One backup at a time.
exec 9>"$base/.lock"
flock -n 9 || die "another backup is running"

# Leftovers from a run that crashed part way.
find "$snapshots" -mindepth 1 -maxdepth 1 -name '*.partial' -exec rm -rf {} +

stamp=$(date -u +%Y-%m-%dT%H%M%SZ)
[[ -e $snapshots/$stamp ]] && die "snapshot $stamp already exists"
snap=$snapshots/$stamp.partial
previous=$(readlink -f "$base/latest" 2>/dev/null || true)
[[ -d $previous ]] || previous=

# copy FROM TO PART [rsync options...]: copy FROM to TO, hard-linking files unchanged since
# the previous snapshot's PART.
copy() {
    local from=$1 to=$2 part=$3
    shift 3
    local link=()
    if [[ -n $previous && -d $previous/$part ]]; then link=(--link-dest="$previous/$part"); fi
    rsync -a --delete "${link[@]}" "$@" "$from" "$to"
}

# Everything but the repositories themselves: owner folders, the trash, anything unexpected.
mkdir -p "$snap/repos"
copy "$repos/" "$snap/repos/" repos --exclude='/*/*.git/' || die "copying $repos failed"

# Each repository under its lock, so no push is caught half way. The lock is taken on a
# descriptor for the directory itself: `flock PATH` would create an empty file at PATH if the
# repository were deleted after the listing, leaving a file that blocks the name for good.
#
# A repository a push holds for longer than lock_wait keeps the previous snapshot's copy (or
# none, if it has never been backed up), so one long push can't cost every other repository
# its backup. The snapshot still becomes `latest`, but the run fails so the operator hears.
count=0
stale=()
missing=()
while IFS= read -r -d '' repo; do
    rel=${repo#"$repos"/}
    if ! { exec {fd}<"$repo"; } 2>/dev/null; then
        say "$rel was deleted during the backup; skipped"
        continue
    fi
    mkdir -p "$snap/repos/$rel"
    link=()
    if [[ -n $previous && -d $previous/repos/$rel ]]; then link=(--link-dest="$previous/repos/$rel"); fi
    locked=0
    flock -E 75 -x -w "$lock_wait" "$fd" || locked=$?
    if ((locked == 75)); then
        exec {fd}<&-
        if [[ -n ${link[*]} ]]; then
            rsync -a "$previous/repos/$rel/" "$snap/repos/$rel/" "${link[@]}" || die "reusing the previous copy of $rel failed"
            say "a push held $rel for over ${lock_wait}s; kept its copy from $(basename "$previous")"
            stale+=("$rel")
            count=$((count + 1))
        else
            rm -rf "${snap:?}/repos/$rel"
            say "a push held $rel for over ${lock_wait}s, and no earlier snapshot has it; not backed up"
            missing+=("$rel")
        fi
        continue
    fi
    ((locked == 0)) || die "couldn't lock $rel"
    copied=0
    rsync -a --delete "${link[@]}" "$repo/" "$snap/repos/$rel/" || copied=$?
    exec {fd}<&-
    if ((copied)); then
        if [[ ! -e $repo ]]; then
            say "$rel was deleted during the backup; skipped"
            rm -rf "${snap:?}/repos/$rel"
            continue
        fi
        die "copying $rel failed"
    fi
    count=$((count + 1))
done < <(find "$repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0 | sort -z)

# The SSH keys and the web sign-in (whose authenticator secret makes this backup sensitive).
for pair in "$keys_dir:etc-gitv" "$web_dir:gitv-web"; do
    from=${pair%:*} to=${pair##*:}
    if [[ -d $from ]]; then
        copy "$from/" "$snap/$to/" "$to" || die "copying $from failed"
    else
        say "warning: $from doesn't exist; not backed up"
    fi
done

# The host keys only (ssh_host_*), not the rest of sshd's configuration. A rebuilt server
# without them greets every client with "REMOTE HOST IDENTIFICATION HAS CHANGED".
if compgen -G "$ssh_dir/ssh_host_*" >/dev/null; then
    copy "$ssh_dir/" "$snap/ssh-host-keys/" ssh-host-keys --include='ssh_host_*' --exclude='*' ||
        die "copying the SSH host keys from $ssh_dir failed"
else
    say "warning: no SSH host keys in $ssh_dir; not backed up"
fi

# Prove the copies are whole: every ref and reflog entry must reach complete history.
failed=0
while IFS= read -r -d '' copy_dir; do
    if ! env -i PATH=/usr/bin:/bin HOME=/nonexistent GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null \
        git -c safe.directory='*' --git-dir="$copy_dir" fsck --no-progress --connectivity-only >/dev/null 2>"$base/fsck.err"; then
        say "fsck failed for ${copy_dir#"$snap"/repos/}: $(head -c 2000 "$base/fsck.err")"
        failed=$((failed + 1))
    fi
done < <(find "$snap/repos" -mindepth 2 -maxdepth 2 -type d -name '*.git' -print0)
rm -f "$base/fsck.err"

{
    echo "snapshot: $stamp"
    echo "host: $(hostname)"
    echo "repositories: $count"
    # Only when there is something to say, so anything scanning for these lines finds problems.
    ((${#stale[@]} == 0)) || echo "stale (a push held them; copied from the previous snapshot): ${stale[*]}"
    ((${#missing[@]} == 0)) || echo "missing (a push held them; never backed up): ${missing[*]}"
    echo "previous: ${previous:+$(basename "$previous")}"
    echo "$(git --version)"
} >"$snap/MANIFEST"

if ((failed)); then
    mv "$snap" "$snapshots/$stamp.failed"
    die "$failed repositories failed verification; kept as $stamp.failed, latest is unchanged"
fi
mv "$snap" "$snapshots/$stamp"
# Made beside `latest` and renamed over it, so a crash never leaves no `latest` at all.
ln -sfn "snapshots/$stamp" "$base/.latest.new"
mv -T "$base/.latest.new" "$base/latest"
say "snapshot $stamp: $count repositories"

# Retention: snapshots older than keep_days, never the newest.
find "$snapshots" -mindepth 1 -maxdepth 1 -type d -mtime +"$keep_days" ! -name "$stamp" -print0 |
    while IFS= read -r -d '' old; do
        rm -rf "$old" && say "removed old snapshot $(basename "$old")"
    done

# Everything else is backed up; now fail, so a held repository shows in `systemctl --failed`.
if ((${#stale[@]} + ${#missing[@]})); then
    die "incomplete: stale ${stale[*]:-none}; missing ${missing[*]:-none} (pushes held them for over ${lock_wait}s)"
fi