Skip to content

Commit

Permalink
use atomic mv to create backup
Browse files Browse the repository at this point in the history
  • Loading branch information
skillcoder committed Apr 12, 2024
1 parent cf49a4a commit ba9ea5a
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions backup/pvc/bin/backup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ set -eo pipefail
[[ ! $# -eq 1 ]] && echo "Usage: $0 backup_number" && exit 1;
[[ -z "${BACKUP_DIR}" ]] && echo "Required 'BACKUP_DIR' env not set" && exit 1;
[[ -z "${JENKINS_HOME}" ]] && echo "Required 'JENKINS_HOME' env not set" && exit 1;
BACKUP_TMP_DIR=$(mktemp -d)

# create temp dir on the same filesystem with a BACKUP_DIR to be able use atomic mv enstead of copy
BACKUP_TMP_DIR=$(mktemp -d --tmpdir=${BACKUP_DIR})
trap "test -d "${BACKUP_TMP_DIR}" && rm -fr "${BACKUP_TMP_DIR}"" EXIT SIGINT SIGTERM

backup_number=$1
Expand All @@ -23,12 +25,13 @@ tar --zstd -C "${JENKINS_HOME}" -cf "${BACKUP_TMP_DIR}/${backup_number}.tar.zstd

if [[ "$ret" -eq 0 ]]; then
echo "Backup was completed without warnings"
mv "${BACKUP_TMP_DIR}/${backup_number}.tar.zstd" "${BACKUP_DIR}/${backup_number}.tar.zstd"
elif [[ "$ret" -eq 1 ]]; then
echo "Backup was completed with some warnings"
mv "${BACKUP_TMP_DIR}/${backup_number}.tar.zstd" "${BACKUP_DIR}/${backup_number}.tar.zstd"
fi

# atomically create a backup file
mv "${BACKUP_TMP_DIR}/${backup_number}.tar.zstd" "${BACKUP_DIR}/${backup_number}.tar.zstd"

rm -rf "${BACKUP_TMP_DIR}"
[[ ! -s ${BACKUP_DIR}/${backup_number}.tar.zstd ]] && echo "backup file '${BACKUP_DIR}/${backup_number}.tar.zstd' is empty" && exit 1;

Expand Down

0 comments on commit ba9ea5a

Please sign in to comment.