#!/bin/bash # Backup Gitea database in a Kubernetes environment # Usage: backup-database [OPTIONS] # `gitea dump` is a mess that we should not touch. We write our own backup scripts instead. # usage() { >&2 printf "Usage: %s \n" "${0}" >&2 printf "Options:\n" >&2 printf "\t-e \t Specify the environment file to use\n" exit "${1:-1}" } # Get options while getopts ":e:" option; do case "${option}" in e) if ! [ -f "${OPTARG}" ]; then >&2 printf "Error: Specified environment file does not exist: '%s'.\n" "${OPTARG}" elif ! [ -r "${OPTARG}" ]; then >&2 printf "Error: Specified environment file is not readable: '%s'.\n" "${OPTARG}" fi env_file="${OPTARG}" ;; *) >&2 printf "Error: Invalid option: '%s'.\n" "${option}" usage ;; esac done shift $(( OPTIND - 1 )) # Check arguments. if [ $# -ne 1 ]; then >&2 printf "Error: You need to specify a destination.\n" usage elif ! [ -d "${1}" ]; then >&2 printf "Error: Specified destination does not exist or is not readable : '%s'.\n" "${1}" usage else destination="${1}" fi namespace="ix-gitea-2" # Retrieve container names base_container="$( k3s kubectl get pods --namespace "${namespace}" | cut -f1 -d' ' | grep -E 'gitea-2-[0-9a-z]{10}-[0-9a-z]{5}' )" database_container="$( k3s kubectl get pods --namespace "${namespace}" | cut -f1 -d' ' | grep 'gitea-2-cnpg-main-2' )" if ! [[ -n "${base_container}" && -n "${database_container}" ]]; then >&2 printf "Error: Not all containers could be found.\n" exit 2 fi # Abort entire script if any command fails set -e # Enable maintenance mode # Flush queues k3s kubectl exec "${base_container}" --namespace "${namespace}" -- gitea manager flush-queues # TODO Pause queues # Database backup # Filename for database backup. database_backupfile="gitea-sqlbkp_$( date +'%Y%m%d' ).bak" host_database_backupfile="${destination}/${database_backupfile}" # Backup the database >&2 echo 'Backing up database' k3s kubectl exec "${database_container}" --namespace "${namespace}" -- env $(cat "${env_file:=.env}" | xargs) pg_dump 'gitea' -cwv -h 'localhost' -U 'gitea' > "${host_database_backupfile}" # Disable maintenance mode # TODO Continue queues # Double check # gitea doctor --all --log-file /tmp/doctor.log # TODO printf "Done.\n"