Compare commits

...

20 commits
v0.0.3 ... main

Author SHA1 Message Date
c8cb561df5 Run on self-hosted runner
Some checks failed
Docker / build (push) Failing after 7s
ShellCheck / shellcheck (push) Successful in 10s
2026-05-22 08:05:25 +01:00
c30ca25a77 Change publishing
Some checks are pending
Docker / build (push) Waiting to run
ShellCheck / shellcheck (push) Waiting to run
2026-05-22 06:57:55 +01:00
642796f85b Fix borg remote path usage 2026-05-21 21:17:20 +01:00
7e7653518e Try fixing CI
Some checks failed
ShellCheck / shellcheck (push) Successful in 11s
Docker / build (push) Failing after 2m48s
2026-03-23 07:41:06 +00:00
31bc548fdd Lint
Some checks failed
ShellCheck / shellcheck (push) Successful in 48s
Docker / build (push) Failing after 28m4s
2026-03-22 17:41:39 +00:00
fd581ef877 Always clean up 2026-03-22 17:41:30 +00:00
bfea98db61 Don't start unhealthy 2026-03-22 17:40:57 +00:00
8bc697a7f4 Migrate to forgejo 2026-03-22 17:40:02 +00:00
5d49069b7b Safer default 2026-03-22 17:39:50 +00:00
202ea7356c Small clean up 2026-03-22 17:39:45 +00:00
99bf0f857f Clean up 2026-03-15 14:21:26 +00:00
c445ea9582 Add checks 2026-03-15 14:21:08 +00:00
909f7fbb6d Fix healtcheck again 2026-01-24 16:15:04 +00:00
40d87a9d32 Respect gitignores 2026-01-24 16:14:50 +00:00
bb1e5fa826 Fix healthcheck 2026-01-24 15:25:56 +00:00
c3280cbd78 Allow backing up non-root of volume 2025-10-12 10:22:35 +01:00
4c327ec98a Fix healthcheck 2025-08-30 11:21:43 +01:00
dd8a61792f Fix healthcheck caching volume 2025-08-09 22:58:53 +01:00
8261031e11 Store health 2025-08-07 19:48:55 +01:00
362b85a20d Format 2025-07-27 14:53:42 +01:00
11 changed files with 157 additions and 129 deletions

View file

@ -0,0 +1,38 @@
name: Docker
on:
push:
branches: [ "main" ]
tags: [ 'v*.*.*' ]
pull_request:
branches: [ "main" ]
env:
REGISTRY: ${{ forgejo.server_url }}
IMAGE_NAME: ${{ forgejo.repository }}
jobs:
build:
runs-on: docker
steps:
- name: Checkout repository
uses: https://code.forgejo.org/actions/checkout@v4
- name: Log into registry
if: forgejo.event_name != 'pull_request'
run: echo "${{ secrets.FORGEJO_TOKEN }}" | docker login ${{ env.REGISTRY }} -u ${{ forgejo.actor }} --password-stdin
- name: Build Docker image
run: |
TAG="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest"
if [ "${{ forgejo.ref_type }}" = "tag" ]; then
VERSION="${{ forgejo.ref_name }}"
docker build -t "$TAG" -t "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}" .
else
docker build -t "$TAG" .
fi
- name: Push Docker image
if: forgejo.event_name != 'pull_request'
run: |
docker push --all-tags "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"

View file

@ -0,0 +1,19 @@
name: ShellCheck
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
shellcheck:
runs-on: docker
steps:
- uses: https://code.forgejo.org/actions/checkout@v4
- name: Install ShellCheck
run: apt-get update && apt-get install -y shellcheck
- name: Run ShellCheck
run: find ./src -name '*.sh' -exec shellcheck {} +

View file

@ -1,90 +0,0 @@
name: Docker
on:
push:
branches: [ "main" ]
# Publish semver tags as releases.
tags: [ 'v*.*.*' ]
pull_request:
branches: [ "main" ]
env:
# Use docker.io for Docker Hub if empty
REGISTRY: ghcr.io
# github.repository as <account>/<repo>
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
# This is used to complete the identity challenge
# with sigstore/fulcio when running outside of PRs.
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Install the cosign tool except on PR
# https://github.com/sigstore/cosign-installer
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0
with:
cosign-release: 'v2.2.4'
# Set up BuildKit Docker container builder to be able to build
# multi-platform images and export cache
# https://github.com/docker/setup-buildx-action
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0
# Login against a Docker registry except on PR
# https://github.com/docker/login-action
- name: Log into registry ${{ env.REGISTRY }}
if: github.event_name != 'pull_request'
uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# Extract metadata (tags, labels) for Docker
# https://github.com/docker/metadata-action
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
# Build and push Docker image with Buildx (don't push on PR)
# https://github.com/docker/build-push-action
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
# Sign the resulting Docker image digest except on PRs.
# This will only write to the public Rekor transparency log when the Docker
# repository is public to avoid leaking data. If you would like to publish
# transparency data even for private images, pass --force to cosign below.
# https://github.com/sigstore/cosign
- name: Sign the published Docker image
if: ${{ github.event_name != 'pull_request' }}
env:
# https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
TAGS: ${{ steps.meta.outputs.tags }}
DIGEST: ${{ steps.build-and-push.outputs.digest }}
# This step uses the identity token to provision an ephemeral certificate
# against the sigstore community Fulcio instance.
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}

View file

@ -8,15 +8,15 @@ RUN apk --no-cache add \
openssh \ openssh \
bash \ bash \
coreutils \ coreutils \
git \
borgbackup=1.4.0-r0 borgbackup=1.4.0-r0
COPY src /src COPY src /src
COPY config/ssh_config /etc/ssh/ COPY config/ssh_config /etc/ssh/
COPY config/exclude.conf /exclude.conf COPY config/exclude.conf /exclude.conf
# Add healthcheck to verify backup completed within allowed time # Add healthcheck to verify backup completed within allowed time
ENV MAX_BACKUP_AGE_SECONDS=86400 ENV MAX_BACKUP_AGE_SECONDS=86400
HEALTHCHECK --interval=10s --timeout=10s --start-period=1h CMD /src/healthcheck.sh HEALTHCHECK --interval=10s --timeout=10s CMD /src/healthcheck.sh
ENTRYPOINT ["sh", "-c", "/src/schedule.sh"] ENTRYPOINT ["sh", "-c", "/src/schedule.sh"]

View file

@ -19,7 +19,7 @@ Over the past 2 years, this backup setup has enabled me to successfully restore
- **Scheduled Backups**: Automates backups according to a defined schedule. - **Scheduled Backups**: Automates backups according to a defined schedule.
- **Log Rotation**: Maintains weekly logs of all backup activities. - **Log Rotation**: Maintains weekly logs of all backup activities.
- **Multi-Repository Backups**: Allows backups to multiple BorgBackup repositories simultaneously. - **Multi-Repository Backups**: Allows backups to multiple BorgBackup repositories simultaneously.
- **Healtcheck**: The healthcheck is based on the time of the last successful backup. - **Healthcheck**: The healthcheck is based on the time of the last successful backup.
### Multi-target backups ### Multi-target backups

View file

@ -1,4 +1,4 @@
Host * Host *
StrictHostKeyChecking no StrictHostKeyChecking accept-new
ServerAliveInterval 30 ServerAliveInterval 30
ServerAliveCountMax 3 ServerAliveCountMax 3

View file

@ -3,7 +3,6 @@ services:
image: ghcr.io/schmelczer/backup-container:latest image: ghcr.io/schmelczer/backup-container:latest
container_name: backup container_name: backup
init: true init: true
tty: true
environment: environment:
- TZ=Europe/London - TZ=Europe/London
- SLEEP_TIME=1h # we will wait an hour between backups - SLEEP_TIME=1h # we will wait an hour between backups
@ -26,11 +25,14 @@ services:
# Used for determining the health of the container # Used for determining the health of the container
- MAX_BACKUP_AGE_SECONDS=86400 # default: 86400 (1d) - MAX_BACKUP_AGE_SECONDS=86400 # default: 86400 (1d)
volumes: volumes:
- /volumes:/source:ro # we backup this folder (which is a BTRFS volume), we mustn't change it, so it's readonly - /:/btrfs-root:ro
- /volumes/backup:/snapshot # we must mount a path to a folder on the BTRFS disk for the snapshot to be put at, this is just a temporary path - /volumes/backup:/snapshot # we must mount a path to a folder on the BTRFS disk for the snapshot to be put at, this is just a temporary path
- /volumes/backup/logs:/backup-logs # we will store the output of the backup commands in this folder - /volumes/backup/logs:/backup-logs # we will store the output of the backup commands in this folder
- borg-cache:/root/.cache/borg # speed up subsequent backups - borg-cache:/root/.cache/borg # speed up subsequent backups
- health-flag:/health # this is used to determine if the backup was successful and when it was last run
- /bulk/backup:/local-backup # this is an example target backup path for BORG_REPO_1 from above - /bulk/backup:/local-backup # this is an example target backup path for BORG_REPO_1 from above
- /volumes/backup/config/id_rsa:/root/.ssh/id_rsa # this is an example for mounting an ssh key for a remote repo (BORG_REPO_0 above) - /volumes/backup/config/id_rsa:/root/.ssh/id_rsa # this is an example for mounting an ssh key for a remote repo (BORG_REPO_0 above)
@ -40,3 +42,4 @@ services:
volumes: volumes:
borg-cache: borg-cache:
health-flag:

View file

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
echo "Starting backup wrapper script at `date`" echo "Starting backup wrapper script at $(date)"
execute_script() { execute_script() {
echo "Executing script with:" echo "Executing script with:"
@ -20,7 +20,7 @@ configure_environment() {
for var in BORG_PASSPHRASE BORG_REPO; do for var in BORG_PASSPHRASE BORG_REPO; do
local indexed_var_name="${var}_${index}" local indexed_var_name="${var}_${index}"
if [[ -n "${!indexed_var_name}" ]]; then if [[ -n "${!indexed_var_name}" ]]; then
export $var="${!indexed_var_name}" export "$var"="${!indexed_var_name}"
else else
all_vars_set=false all_vars_set=false
break break
@ -28,10 +28,12 @@ configure_environment() {
done done
# optional variables # optional variables
for var in BORG_REMOTE_PATH; do local indexed_var_name="BORG_REMOTE_PATH_${index}"
local indexed_var_name="${var}_${index}" if [[ -n "${!indexed_var_name}" ]]; then
export $var="${!indexed_var_name}" export BORG_REMOTE_PATH="${!indexed_var_name}"
done else
unset BORG_REMOTE_PATH
fi
[[ $all_vars_set == true ]] [[ $all_vars_set == true ]]
} }
@ -39,18 +41,30 @@ configure_environment() {
main() { main() {
if [ -n "$BORG_REPO" ]; then if [ -n "$BORG_REPO" ]; then
# fallback case if multi-target backup isn't needed # fallback case if multi-target backup isn't needed
execute_script if execute_script; then
date > /health/backup_completion_time.log
else
echo "Skipping completion log due to backup failure"
fi
else else
local index=0 local index=0
local configurations_found=false local configurations_found=false
local any_failed=false
while configure_environment $index; do while configure_environment $index; do
execute_script || true execute_script || any_failed=true
configurations_found=true configurations_found=true
unset BORG_PASSPHRASE BORG_REMOTE_PATH BORG_REPO unset BORG_PASSPHRASE BORG_REMOTE_PATH BORG_REPO
((index++)) ((index++))
done done
echo "Finished backup script at $(date)"
if [[ $any_failed == false ]]; then
date > /health/backup_completion_time.log # this used by the healtcheck
else
echo "Skipping completion log due to backup failure(s)"
fi
if [[ $configurations_found == false ]]; then if [[ $configurations_found == false ]]; then
echo "No valid configuration found. Please ensure environment variables are set properly." echo "No valid configuration found. Please ensure environment variables are set properly."
fi fi
@ -59,4 +73,4 @@ main() {
main main
echo "Finished backup wrapper script at `date`" echo "Finished backup wrapper script at $(date)"

View file

@ -5,48 +5,80 @@ KEEP_WEEKLY=${KEEP_WEEKLY:-3}
KEEP_MONTHLY=${KEEP_MONTHLY:-48} KEEP_MONTHLY=${KEEP_MONTHLY:-48}
KEEP_YEARLY=${KEEP_YEARLY:-10} KEEP_YEARLY=${KEEP_YEARLY:-10}
echo "Starting backup script at `date`" echo "Starting backup script at $(date)"
export BORG_RSH='ssh -oBatchMode=yes' # https://borgbackup.readthedocs.io/en/stable/usage/notes.html#ssh-batch-mode export BORG_RSH='ssh -oBatchMode=yes' # https://borgbackup.readthedocs.io/en/stable/usage/notes.html#ssh-batch-mode
# break any stale locks in case the script was interrupted # break any stale locks in case the script was interrupted
borg break-lock borg break-lock
borg info # test whether we have a valid repository if ! borg info; then
if [ $? -ne 0 ]; then
echo "Borg info returned a non-zero status. Initializing Borg..." echo "Borg info returned a non-zero status. Initializing Borg..."
borg init --encryption=repokey borg init --encryption=repokey
fi fi
# The above command will fail if the repo hasn't been already initialized, # The above command will fail if the repo hasn't been already initialized,
# so we can ignore the return status. However, if any of the commands below fail, # so we can ignore the return status. However, if any of the commands below fail,
# we want to stop the script immediately. # we want to stop the script immediately.
set -e set -e
if [ -d "/snapshot/source" ]; then cleanup() {
btrfs subvolume delete /snapshot/source if [ -n "${GIT_EXCLUDE_FILE:-}" ] && [ -f "$GIT_EXCLUDE_FILE" ]; then
rm -f "$GIT_EXCLUDE_FILE"
fi
if [ -d "/snapshot/btrfs-root" ]; then
cd /
btrfs subvolume delete /snapshot/btrfs-root || true
fi
}
trap cleanup EXIT
if [ -d "/snapshot/btrfs-root" ]; then
btrfs subvolume delete /snapshot/btrfs-root
fi fi
btrfs subvolume snapshot /source /snapshot btrfs subvolume snapshot /btrfs-root /snapshot
cd "/snapshot/btrfs-root${BACKUP_RELATIVE_PATH:-}"
# Generate exclusions for git-untracked files if enabled
EXCLUDE_ARGS=(--exclude-from /exclude.conf)
if [ "${IGNORE_GIT_UNTRACKED:-false}" = "true" ]; then
echo "Generating exclusions for git-untracked files..."
GIT_EXCLUDE_FILE=$(mktemp)
# Find all git repositories and list their untracked files
find . -name .git -type d | while read -r gitdir; do
repo_dir=$(dirname "$gitdir")
(
cd "$repo_dir"
# Get untracked files (respecting .gitignore)
git ls-files --others --exclude-standard | while read -r file; do
# Output path relative to backup root
echo "${repo_dir#./}/$file"
done
)
done > "$GIT_EXCLUDE_FILE"
excluded_count=$(wc -l < "$GIT_EXCLUDE_FILE")
echo "Found $excluded_count git-untracked files to exclude"
EXCLUDE_ARGS+=(--exclude-from "$GIT_EXCLUDE_FILE")
fi
cd /snapshot/source
borg create --stats \ borg create --stats \
--list \ --list \
--filter=AMCE \ --filter=AMCE \
--files-cache=ctime,size,inode \ --files-cache=ctime,size,inode \
--compression=zstd,12 \ --compression=zstd,12 \
--exclude-from /exclude.conf ::"{hostname}-{now:%Y-%m-%dT%H:%M:%S}" . "${EXCLUDE_ARGS[@]}" ::"{hostname}-{now:%Y-%m-%dT%H:%M:%S}" .
cd - cd -
borg prune --list --stats \ borg prune --list --stats \
--keep-daily=$KEEP_DAILY \ --keep-daily="$KEEP_DAILY" \
--keep-weekly=$KEEP_WEEKLY \ --keep-weekly="$KEEP_WEEKLY" \
--keep-monthly=$KEEP_MONTHLY \ --keep-monthly="$KEEP_MONTHLY" \
--keep-yearly=$KEEP_YEARLY --keep-yearly="$KEEP_YEARLY"
borg compact --threshold=5 --cleanup-commits --verbose --progress borg compact --threshold=5 --cleanup-commits --verbose --progress
btrfs subvolume delete /snapshot/source
echo "Finished backup script at `date`"
date > /backup_completion_time.log # this used by the healtcheck

View file

@ -2,15 +2,26 @@
set -e set -e
if [ -f /backup_completion_time.log ]; then MAX_BACKUP_AGE_SECONDS="${MAX_BACKUP_AGE_SECONDS:-86400}"
if [ -f /health/backup_completion_time.log ]; then
current_time=$(date +%s) current_time=$(date +%s)
backup_time=$(date --file /backup_completion_time.log +%s) backup_time=$(date --file /health/backup_completion_time.log +%s)
age_in_seconds=$((current_time - backup_time)) age_in_seconds=$((current_time - backup_time))
if [ ${age_in_seconds} -lt ${MAX_BACKUP_AGE_SECONDS} ]; then if [ "${age_in_seconds}" -lt "${MAX_BACKUP_AGE_SECONDS}" ]; then
echo "Backup completed within the last ${MAX_BACKUP_AGE_SECONDS} seconds. Healthcheck passed." echo "Backup completed within the last ${MAX_BACKUP_AGE_SECONDS} seconds. Healthcheck passed."
exit 0 exit 0
fi fi
elif [ -f /health/container_start_time.log ]; then
current_time=$(date +%s)
start_time=$(date --file /health/container_start_time.log +%s)
age_in_seconds=$((current_time - start_time))
if [ "${age_in_seconds}" -lt "${MAX_BACKUP_AGE_SECONDS}" ]; then
echo "No backup completed yet, but container started less than ${MAX_BACKUP_AGE_SECONDS} seconds ago. Healthcheck passed."
exit 0
fi
fi fi
echo "Backup not completed within the last ${MAX_BACKUP_AGE_SECONDS} seconds. Healthcheck failed." echo "Backup not completed within the last ${MAX_BACKUP_AGE_SECONDS} seconds. Healthcheck failed."

View file

@ -10,10 +10,11 @@ get_log_file_name() {
echo "/backup-logs/backup_$(date +%Y)_week_$(date +%U).log" echo "/backup-logs/backup_$(date +%Y)_week_$(date +%U).log"
} }
echo "Starting schedule script at `date`" | log_message echo "Starting schedule script at $(date)" | log_message
date > /health/container_start_time.log
while true; do while true; do
exec /src/backup-wrapper.sh 2>&1 | log_message /src/backup-wrapper.sh 2>&1 | log_message
echo "Sleeping for $SLEEP_TIME" | log_message echo "Sleeping for $SLEEP_TIME" | log_message
# Using a simple sleep loop to schedule backups instead of cron to avoid concurrency issues # Using a simple sleep loop to schedule backups instead of cron to avoid concurrency issues