Compare commits

...
Sign in to create a new pull request.

20 commits
master ... dev

Author SHA1 Message Date
Nicolas Chan
07510de420 Mention linger 2020-03-22 20:16:02 -07:00
Nicolas Chan
a569083736 Add more info to chat 2020-03-22 01:53:51 -07:00
Nicolas Chan
3afbdc712f Remove restic stats because it's slow 2020-03-21 22:28:36 -07:00
Nicolas Chan
bbab6535a1 Fix EXIT_IF_NO_SCREEN 2020-03-21 21:13:24 -07:00
Nicolas Chan
9f24441733
Update README.md 2020-03-21 21:09:27 -07:00
Nicolas Chan
7f62b04d34
Update README.md 2020-03-21 21:07:37 -07:00
Nicolas Chan
2d439bf042
Update README.md 2020-03-21 21:05:56 -07:00
Nicolas Chan
5bf452994f
Update README.md 2020-03-21 21:04:58 -07:00
Nicolas Chan
66a77abbca
Update README.md 2020-03-21 21:03:12 -07:00
Nicolas Chan
27ab7e2087
Update README.md 2020-03-21 21:01:15 -07:00
Nicolas Chan
9605352be0
Update README.md 2020-03-21 21:00:42 -07:00
Nicolas Chan
4350eeb9ae Update readme with examples 2020-03-21 20:54:21 -07:00
Nicolas Chan
7e4772006f Add restic backend and update readme 2020-03-21 20:14:33 -07:00
Nicolas Chan
94e894645f Bug fixes for deleting methods 2020-03-21 19:09:49 -07:00
Nicolas Chan
8cf268f40b Fix default to be gzip 2020-03-21 17:34:24 -07:00
Nicolas Chan
2ec8f7f4dc Major refactor to support new backends 2020-03-21 17:33:21 -07:00
Nicolas Chan
5eaae39e73
Add -g option 2019-09-12 13:46:03 -07:00
Nicolas Chan
02985989af
Remove tmpdir copy 2019-08-11 17:56:54 -07:00
Nicolas Chan
7d548ce28e
Add borg executable bit 2019-08-11 17:55:05 -07:00
Nicolas Chan
f005e54965
Add borg backup option 2019-08-11 13:51:30 -07:00
9 changed files with 774 additions and 224 deletions

178
README.md
View file

@ -1,10 +1,25 @@
# Minecraft Backup # Minecraft Backup
Backup script for Linux servers running a Minecraft server in a GNU Screen Backup script for Linux servers running a Minecraft server in a GNU Screen, supporting saving in compressed tar format or to [restic](https://github.com/restic/restic).
### Disclaimer ## Quick Start
Backups are essential to the integrity of your Minecraft world. You should automate regular backups and **check that your backups work**. While this script has been used in production for several years, it is up to you to make sure that your backups work and that you have a reliable backup policy. ```bash
# Download the scripts
git clone https://github.com/nicolaschan/minecraft-backup.git
./minecraft-backup/backup.sh -c -s $SCREEN_NAME -i $WORLD_DIR -o $BACKUP_DIR
```
Please refer to the LICENSE (MIT License) for the full legal disclaimer. ## Why?
### Why not just put `tar` in crontab?
If the Minecraft server is currently running, you need to disable world autosaving, or you will likely get an error like this:
```
tar: /some/path/here/world/region/r.1.11.mca: file changed as we read it
```
This script will take care of disabling and then re-enabling autosaving for you, and also alert players in the chat of successful backups or errors.
This way, you don't have to shut down the server to take backups.
You'll also probably need some way to delete old backups, and this script can handle keeping either a number of most recent backups, or thinning them out based on hour/day/week. It can also use another backend such as [restic](https://github.com/restic/restic).
### Alternatives
This script is developed with vanilla servers in mind. If you are running a server with plugins or mods, then you can probably find a backup plugin/mod to do a similar job.
## Features ## Features
- Create backups of your world folder - Create backups of your world folder
@ -12,18 +27,22 @@ Please refer to the LICENSE (MIT License) for the full legal disclaimer.
- "thin" - keep last 24 hourly, last 30 daily, and use remaining space for monthly backups - "thin" - keep last 24 hourly, last 30 daily, and use remaining space for monthly backups
- "sequential" - delete oldest backup - "sequential" - delete oldest backup
- Choose your own compression algorithm (tested with: `gzip`, `xz`, `zstd`) - Choose your own compression algorithm (tested with: `gzip`, `xz`, `zstd`)
- Able to print backup status and info to the Minecraft chat - Print backup status and info to the Minecraft chat
- Customizable backup backends and Minecraft server interface (currently supports locally managed tar archives or [restic](https://github.com/restic/restic))
## Requirements ## Requirements
- Linux computer (tested on Ubuntu) - Linux computer (tested on Arch Linux)
- GNU Screen (running your Minecraft server) - GNU Screen (running your Minecraft server)
- Minecraft server (tested with Vanilla 1.10.2 only) - Minecraft server
## Installation ## Installation
1. Download the script: `$ wget https://raw.githubusercontent.com/nicolaschan/minecraft-backup/master/backup.sh` ```bash
2. Mark as executable: `$ chmod +x backup.sh` # Download the scripts
3. Use the command line options or configure default values at the top of `backup.sh`: git clone https://github.com/nicolaschan/minecraft-backup.git
```
**NOTE**: You will need to keep `backup.sh` in the same directory as the `src/` directory, since it looks for dependencies in `src/`.
## Usage Options
Command line options: Command line options:
```text ```text
-a Compression algorithm (default: gzip) -a Compression algorithm (default: gzip)
@ -31,6 +50,7 @@ Command line options:
-d Delete method: thin (default), sequential, none -d Delete method: thin (default), sequential, none
-e Compression file extension, exclude leading "." (default: gz) -e Compression file extension, exclude leading "." (default: gz)
-f Output file name (default is the timestamp) -f Output file name (default is the timestamp)
-g Do not backup (exit) if screen is not running (default: always backup)
-h Shows this help text -h Shows this help text
-i Input directory (path to world folder) -i Input directory (path to world folder)
-l Compression level (default: 3) -l Compression level (default: 3)
@ -42,33 +62,147 @@ Command line options:
-v Verbose mode -v Verbose mode
``` ```
Example usage of command line options: ## Example Usage
### One-off Example
```bash ```bash
./backup.sh -c -i /home/server/minecraft-server/world -o /mnt/external-storage/minecraft-backups -s minecraft ./backup.sh -c -s minecraft -i minecraft-server/world -o backups/
```
In this example, we print the status to the Minecraft chat (`-c`), use `minecraft` as the name of the screen, and save a backup of `minecraft-server/world` into `backups/` using the default thinning delete policy for old backups. While this works for performing a single backup, it is _highly_ recommended that you automate your backups.
### Automated with cron
- Edit the crontab:
```bash
crontab -e
```
- Example for hourly backups:
```
00 * * * * /path/to/minecraft-backup/backup.sh -c -s minecraft -i /path/to/minecraft-server/world -o /path/to/backups
```
### Automated using systemd timers
#### Simple example (single server)
`~/.config/systemd/user/minecraft-backup.timer`
```systemd
[Unit]
Description=Run Minecraft backup hourly
[Timer]
OnCalendar=hourly
Persistent=false
Unit=minecraft-backup.service
[Install]
WantedBy=timers.target
```
`~/.config/systemd/user/minecraft-backup.service`
```systemd
[Unit]
Description=Perform Minecraft backup
[Service]
Type=oneshot
ExecStart=/path/to/minecraft-backup/backup.sh -c -s minecraft -i /path/to/world -o /path/to/backups
[Install]
WantedBy=multi-user.target
```
Then you can run the following to enable the timer:
```bash
# enable the timer right now only
systemctl --user start minecraft-backup.timer
# start the timer on reboot
systemctl --user enable minecraft-backup.timer
# see status of timers
systemctl --user list-timers
```
#### Advanced example (with restic and multiple servers)
If you have multiple servers, you can use `@` to create timers on-demand for each server. This assumes the server directories are named the same as the screen name.
To start at boot, you may also need to enable linger:
```bash
loginctl enable-linger "$USER"
```
`~/.config/systemd/user/minecraft-backup.timer`
```systemd
[Unit]
Description=Run Minecraft backup hourly
[Timer]
OnCalendar=hourly
Persistent=false
Unit=minecraft-backup@.service
[Install]
WantedBy=timers.target
```
`~/.config/systemd/user/minecraft-backup@.service`
```systemd
[Unit]
Description=Perform Minecraft backup
[Service]
Type=oneshot
Environment="RESTIC_PASSWORD_FILE=/path/to/restic-password.txt"
ExecStart=/path/to/minecraft-backup/backup-restic.sh -c -s %i -i /path/to/server/%i/world -o /path/to/restic-repo
[Install]
WantedBy=multi-user.target
```
To enable:
```bash
systemctl --user enable minecraft-backup@your_server_name_here
``` ```
This will use show chat messages (`-c`) in the screen called "minecraft" and save a backup of `/home/server/minecraft-server/world` into `/mnt/external-storage/minecraft-backups` using the default thinning delete policy for old backups.
4. Create a cron job to automatically backup:
- Edit the crontab: `$ crontab -e`
- Example for hourly backups: `00 * * * * /path/to/backup.sh`
## Retrieving Backups ## Retrieving Backups
Always test your backups! Backups are in the `tar` format and compressed depending on the option you choose. To restore, first decompress if necessary and then extract using tar. You may be able to do this in one command if `tar` supports your compression option, as is the case with `gzip`: Always test your backups! Backups are in the `tar` format and compressed depending on the option you choose. To restore, first decompress if necessary and then extract using `tar`. You may be able to do this in one command if `tar` supports your compression option, as is the case with `gzip`:
Example: Example:
```bash ```bash
mkdir restored-world mkdir restored-world
cd restored-world # if using gzip:
tar -xzvf /path/to/backups/2019-04-09_02-15-01.tar.gz gzip -cd 2017-07-31_00-00-00.tar.gz | tar xf - -C restored-world
# if using zstd:
zstd -cd 2017-07-31_00-00-00.tar.zst | tar xf - -C restored-world
``` ```
Then you can move your restored world (`restored-world` in this case) to your Minecraft server folder and rename it (usually called `world`) so the Minecraft server uses it. Then you can move your restored world (`restored-world` in this case) to your Minecraft server folder and rename it (usually called `world`) so the Minecraft server uses it.
## Using [restic](https://github.com/restic/restic)
The `backup-restic.sh` script provides a similar interface for restic.
To specify your repository's password, you'll need to export the `$RESTIC_PASSWORD_FILE` or `$RESTIC_PASSWORD_COMMAND` environment variable.
```bash
restic init -r /path/to/restic-repo
touch restic-password.txt # make a new file for your restic password
chmod 600 restic-password.txt # make sure only you can read your password
echo "my_restic-password" > restic-password.txt
export RESTIC_PASSWORD_FILE=$(pwd)/restic_password.txt
/path/to/minecraft-backup/backup-restic.sh -c -s minecraft -i /path/to/minecraft-server/world -o /path/to/restic-repo
```
See above for an example automating this using systemd timers.
## Help ## Help
- Make sure the compression algorithm you specify is installed on your system. (zstd is not installed by default) - Make sure the compression algorithm you specify is installed on your system. (zstd is not always installed by default)
- Make sure your compression algorithm is in the crontab's PATH - Make sure your compression algorithm is in the crontab's PATH
- Make sure cron has permissions for all the files involved and access to the Minecraft server's GNU Screen - Make sure cron has permissions for all the files involved and access to the Minecraft server's GNU Screen
- It's surprising how much space backups can take--make sure you have enough empty space - It's surprising how much space backups can take--make sure you have enough empty space
- `SERVER_DIRECTORY` should be the server directory, not the `world` directory
- Do not put trailing `/` in the `SERVER_DIRECTORY` or `BACKUP_DIRECTORY`
- If "thin" delete method is behaving weirdly, try emptying your backup directory or switch to "sequential" - If "thin" delete method is behaving weirdly, try emptying your backup directory or switch to "sequential"
## Disclaimer
Backups are essential to the integrity of your Minecraft world. You should automate regular backups and **check that your backups work**. It is up to you to make sure that your backups work and that you have a reliable backup policy.
Some backup tips:
- Drives get corrupted or fail! Backup to a _different_ drive than the one your server is running on, so if that drive fails then you have backups.
- _Automate_ backups so you never lose too much progress.
- Check that your backups work from time to time.
Please refer to the LICENSE (MIT License) for the full legal disclaimer.

100
backup-restic.sh Executable file
View file

@ -0,0 +1,100 @@
#!/usr/bin/env bash
# Minecraft server automatic backup management script
# by Nicolas Chan
# https://github.com/nicolaschan/minecraft-backup
# MIT License
#
# For Minecraft servers running in a GNU screen.
# For most convenience, run automatically with cron.
# Default Configuration
SCREEN_NAME="" # Name of the GNU Screen your Minecraft server is running in
SERVER_WORLD="" # Server world directory
BACKUP_DIRECTORY="" # Directory to save backups in
EXIT_IF_NO_SCREEN=false # Skip backup if there is no minecraft screen running
ENABLE_CHAT_MESSAGES=false # Tell players in Minecraft chat about backup status
PREFIX="Backup" # Shows in the chat message
DEBUG=false # Enable debug messages
SUPPRESS_WARNINGS=false # Suppress warnings
OPTIND=1
while getopts 'cghi:o:p:qs:v' FLAG; do
case $FLAG in
a) COMPRESSION_ALGORITHM=$OPTARG ;;
c) ENABLE_CHAT_MESSAGES=true ;;
d) DELETE_METHOD=$OPTARG ;;
e) COMPRESSION_FILE_EXTENSION=".$OPTARG" ;;
f) TIMESTAMP=$OPTARG ;;
g) EXIT_IF_NO_SCREEN=true ;;
h) echo "Minecraft Backup Script: https://github.com/nicolaschan/minecraft-backup.git"
echo "-c Enable chat messages"
echo "-g Do not backup (exit) if screen is not running (default: always backup)"
echo "-h Shows this help text"
echo "-i Input directory (path to world folder)"
echo "-o Output directory"
echo "-p Prefix that shows in Minecraft chat (default: Backup)"
echo "-q Suppress warnings"
echo "-s Minecraft server screen name"
echo "-v Verbose mode"
exit 0
;;
i) SERVER_WORLD=$OPTARG ;;
l) COMPRESSION_LEVEL=$OPTARG ;;
m) MAX_BACKUPS=$OPTARG ;;
o) BACKUP_DIRECTORY=$OPTARG ;;
p) PREFIX=$OPTARG ;;
q) SUPPRESS_WARNINGS=true ;;
s) SCREEN_NAME=$OPTARG ;;
v) DEBUG=true ;;
*) ;;
esac
done
BASE_DIR=$(dirname "$(realpath "$0")")
if ! [[ -d "$BASE_DIR/src" ]]; then
echo -e "The src/ directory needs to be in the same directory as backup.sh because it contains other scripts that backup.sh depends on.\n\
You should download the entire repository:
git clone https://github.com/nicolaschan.com/minecraft-backup.git
"
exit 1
fi
# shellcheck source=src/logging.sh
source "$BASE_DIR/src/logging.sh" \
-q "$SUPPRESS_WARNINGS" \
-v "$DEBUG"
# Check for missing encouraged arguments
if [[ $SCREEN_NAME == "" ]]; then
log-warning "Minecraft screen name not specified (use -s)"
fi
# Check for required arguments
MISSING_CONFIGURATION=false
if [[ $SERVER_WORLD == "" ]]; then
log-fatal "Server world not specified (use -i)"
MISSING_CONFIGURATION=true
fi
if [[ $BACKUP_DIRECTORY == "" ]]; then
log-fatal "Backup directory not specified (use -o)"
MISSING_CONFIGURATION=true
fi
if $MISSING_CONFIGURATION; then
exit 1
fi
"$BASE_DIR/src/core.sh" \
"$BASE_DIR/src/exec-methods/screen.sh" \
-s "$SCREEN_NAME" \
-- \
"$BASE_DIR/src/backup-methods/restic.sh" \
-i "$SERVER_WORLD" \
-o "$BACKUP_DIRECTORY" \
-- \
-c "$ENABLE_CHAT_MESSAGES" \
-g "$EXIT_IF_NO_SCREEN" \
-p "$PREFIX" \
-q "$SUPPRESS_WARNINGS" \
-v "$DEBUG"

243
backup.sh
View file

@ -1,7 +1,8 @@
#!/bin/bash #!/usr/bin/env bash
# Minecraft server automatic backup management script # Minecraft server automatic backup management script
# by Nicolas Chan # by Nicolas Chan
# https://github.com/nicolaschan/minecraft-backup
# MIT License # MIT License
# #
# For Minecraft servers running in a GNU screen. # For Minecraft servers running in a GNU screen.
@ -14,6 +15,7 @@ BACKUP_DIRECTORY="" # Directory to save backups in
MAX_BACKUPS=128 # -1 indicates unlimited MAX_BACKUPS=128 # -1 indicates unlimited
DELETE_METHOD="thin" # Choices: thin, sequential, none; sequential: delete oldest; thin: keep last 24 hourly, last 30 daily, and monthly (use with 1 hr cron interval) DELETE_METHOD="thin" # Choices: thin, sequential, none; sequential: delete oldest; thin: keep last 24 hourly, last 30 daily, and monthly (use with 1 hr cron interval)
COMPRESSION_ALGORITHM="gzip" # Leave empty for no compression COMPRESSION_ALGORITHM="gzip" # Leave empty for no compression
EXIT_IF_NO_SCREEN=false # Skip backup if there is no minecraft screen running
COMPRESSION_FILE_EXTENSION=".gz" # Leave empty for no compression; Precede with a . (for example: ".gz") COMPRESSION_FILE_EXTENSION=".gz" # Leave empty for no compression; Precede with a . (for example: ".gz")
COMPRESSION_LEVEL=3 # Passed to the compression algorithm COMPRESSION_LEVEL=3 # Passed to the compression algorithm
ENABLE_CHAT_MESSAGES=false # Tell players in Minecraft chat about backup status ENABLE_CHAT_MESSAGES=false # Tell players in Minecraft chat about backup status
@ -25,19 +27,22 @@ SUPPRESS_WARNINGS=false # Suppress warnings
DATE_FORMAT="%F_%H-%M-%S" DATE_FORMAT="%F_%H-%M-%S"
TIMESTAMP=$(date +$DATE_FORMAT) TIMESTAMP=$(date +$DATE_FORMAT)
while getopts 'a:cd:e:f:hi:l:m:o:p:qs:v' FLAG; do OPTIND=1
while getopts 'a:bcd:e:f:ghi:l:m:o:p:qs:v' FLAG; do
case $FLAG in case $FLAG in
a) COMPRESSION_ALGORITHM=$OPTARG ;; a) COMPRESSION_ALGORITHM=$OPTARG ;;
c) ENABLE_CHAT_MESSAGES=true ;; c) ENABLE_CHAT_MESSAGES=true ;;
d) DELETE_METHOD=$OPTARG ;; d) DELETE_METHOD=$OPTARG ;;
e) COMPRESSION_FILE_EXTENSION=".$OPTARG" ;; e) COMPRESSION_FILE_EXTENSION=".$OPTARG" ;;
f) TIMESTAMP=$OPTARG ;; f) TIMESTAMP=$OPTARG ;;
h) echo "Minecraft Backup (by Nicolas Chan)" g) EXIT_IF_NO_SCREEN=true ;;
h) echo "Minecraft Backup Script: https://github.com/nicolaschan/minecraft-backup.git"
echo "-a Compression algorithm (default: gzip)" echo "-a Compression algorithm (default: gzip)"
echo "-c Enable chat messages" echo "-c Enable chat messages"
echo "-d Delete method: thin (default), sequential, none" echo "-d Delete method: thin (default), sequential, none"
echo "-e Compression file extension, exclude leading \".\" (default: gz)" echo "-e Compression file extension, exclude leading \".\" (default: gz)"
echo "-f Output file name (default is the timestamp)" echo "-f Output file name (default is the timestamp)"
echo "-g Do not backup (exit) if screen is not running (default: always backup)"
echo "-h Shows this help text" echo "-h Shows this help text"
echo "-i Input directory (path to world folder)" echo "-i Input directory (path to world folder)"
echo "-l Compression level (default: 3)" echo "-l Compression level (default: 3)"
@ -57,22 +62,30 @@ while getopts 'a:cd:e:f:hi:l:m:o:p:qs:v' FLAG; do
q) SUPPRESS_WARNINGS=true ;; q) SUPPRESS_WARNINGS=true ;;
s) SCREEN_NAME=$OPTARG ;; s) SCREEN_NAME=$OPTARG ;;
v) DEBUG=true ;; v) DEBUG=true ;;
*) ;;
esac esac
done done
log-fatal () { BASE_DIR=$(dirname "$(realpath "$0")")
echo -e "\033[0;31mFATAL:\033[0m $*"
} if ! [[ -d "$BASE_DIR/src" ]]; then
log-warning () { echo -e "The src/ directory needs to be in the same directory as backup.sh because it contains other scripts that backup.sh depends on.\n\
echo -e "\033[0;33mWARNING:\033[0m $*" You should download the entire repository:
} git clone https://github.com/nicolaschan.com/minecraft-backup.git
"
exit 1
fi
# shellcheck source=src/logging.sh
source "$BASE_DIR/src/logging.sh" \
-q "$SUPPRESS_WARNINGS" \
-v "$DEBUG"
# Check for missing encouraged arguments # Check for missing encouraged arguments
if ! $SUPPRESS_WARNINGS; then if [[ $SCREEN_NAME == "" ]]; then
if [[ $SCREEN_NAME == "" ]]; then
log-warning "Minecraft screen name not specified (use -s)" log-warning "Minecraft screen name not specified (use -s)"
fi
fi fi
# Check for required arguments # Check for required arguments
MISSING_CONFIGURATION=false MISSING_CONFIGURATION=false
if [[ $SERVER_WORLD == "" ]]; then if [[ $SERVER_WORLD == "" ]]; then
@ -83,192 +96,26 @@ if [[ $BACKUP_DIRECTORY == "" ]]; then
log-fatal "Backup directory not specified (use -o)" log-fatal "Backup directory not specified (use -o)"
MISSING_CONFIGURATION=true MISSING_CONFIGURATION=true
fi fi
if $MISSING_CONFIGURATION; then if $MISSING_CONFIGURATION; then
exit 0 exit 1
fi fi
ARCHIVE_FILE_NAME=$TIMESTAMP.tar$COMPRESSION_FILE_EXTENSION "$BASE_DIR/src/core.sh" \
ARCHIVE_PATH=$BACKUP_DIRECTORY/$ARCHIVE_FILE_NAME "$BASE_DIR/src/exec-methods/screen.sh" \
-s "$SCREEN_NAME" \
# Minecraft server screen interface functions -- \
message-players () { "$BASE_DIR/src/backup-methods/tar.sh" \
local MESSAGE=$1 -a "$COMPRESSION_ALGORITHM" \
local HOVER_MESSAGE=$2 -d "$DELETE_METHOD" \
message-players-color "$MESSAGE" "$HOVER_MESSAGE" "gray" -e "$COMPRESSION_FILE_EXTENSION" \
} -f "$TIMESTAMP" \
execute-command () { -i "$SERVER_WORLD" \
local COMMAND=$1 -l "$COMPRESSION_LEVEL" \
if [[ $SCREEN_NAME != "" ]]; then -m "$MAX_BACKUPS" \
screen -S $SCREEN_NAME -p 0 -X stuff "$COMMAND$(printf \\r)" -o "$BACKUP_DIRECTORY" \
fi -- \
} -c "$ENABLE_CHAT_MESSAGES" \
message-players-error () { -g "$EXIT_IF_NO_SCREEN" \
local MESSAGE=$1 -p "$PREFIX" \
local HOVER_MESSAGE=$2 -q "$SUPPRESS_WARNINGS" \
message-players-color "$MESSAGE" "$HOVER_MESSAGE" "red" -v "$DEBUG"
}
message-players-success () {
local MESSAGE=$1
local HOVER_MESSAGE=$2
message-players-color "$MESSAGE" "$HOVER_MESSAGE" "green"
}
message-players-color () {
local MESSAGE=$1
local HOVER_MESSAGE=$2
local COLOR=$3
if $DEBUG; then
echo "$MESSAGE ($HOVER_MESSAGE)"
fi
if $ENABLE_CHAT_MESSAGES; then
execute-command "tellraw @a [\"\",{\"text\":\"[$PREFIX] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"$MESSAGE\",\"color\":\"$COLOR\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"$HOVER_MESSAGE\"}]}}}]"
fi
}
# Notify players of start
message-players "Starting backup..." "$ARCHIVE_FILE_NAME"
# Parse file timestamp to one readable by "date"
parse-file-timestamp () {
local DATE_STRING=$(echo $1 | awk -F_ '{gsub(/-/,":",$2); print $1" "$2}')
echo $DATE_STRING
}
# Delete a backup
delete-backup () {
local BACKUP=$1
rm $BACKUP_DIRECTORY/$BACKUP
message-players "Deleted old backup" "$BACKUP"
}
# Sequential delete method
delete-sequentially () {
local BACKUPS=($(ls $BACKUP_DIRECTORY))
while [[ $MAX_BACKUPS -ge 0 && ${#BACKUPS[@]} -gt $MAX_BACKUPS ]]; do
delete-backup ${BACKUPS[0]}
BACKUPS=($(ls $BACKUP_DIRECTORY))
done
}
# Functions to sort backups into correct categories based on timestamps
is-hourly-backup () {
local TIMESTAMP=$*
local MINUTE=$(date -d "$TIMESTAMP" +%M)
return $MINUTE
}
is-daily-backup () {
local TIMESTAMP=$*
local HOUR=$(date -d "$TIMESTAMP" +%H)
return $HOUR
}
is-weekly-backup () {
local TIMESTAMP=$*
local DAY=$(date -d "$TIMESTAMP" +%u)
return $((DAY - 1))
}
# Helper function to sum an array
array-sum () {
SUM=0
for NUMBER in $*; do
(( SUM += NUMBER ))
done
echo $SUM
}
# Thinning delete method
delete-thinning () {
# sub-hourly, hourly, daily, weekly is everything else
local BLOCK_SIZES=(16 24 30)
# First block is unconditional
# The next blocks will only accept files whose names cause these functions to return true (0)
local BLOCK_FUNCTIONS=("is-hourly-backup" "is-daily-backup" "is-weekly-backup")
# Warn if $MAX_BACKUPS does not have enough room for all the blocks
TOTAL_BLOCK_SIZE=$(array-sum ${BLOCK_SIZES[@]})
if [[ $TOTAL_BLOCK_SIZE -gt $MAX_BACKUPS ]]; then
if ! $SUPPRESS_WARNINGS; then
log-warning "MAX_BACKUPS ($MAX_BACKUPS) is smaller than TOTAL_BLOCK_SIZE ($TOTAL_BLOCK_SIZE)"
fi
fi
local CURRENT_INDEX=0
local BACKUPS=($(ls -r $BACKUP_DIRECTORY)) # List newest first
for BLOCK_INDEX in ${!BLOCK_SIZES[@]}; do
local BLOCK_SIZE=${BLOCK_SIZES[BLOCK_INDEX]}
local BLOCK_FUNCTION=${BLOCK_FUNCTIONS[BLOCK_INDEX]}
local OLDEST_BACKUP_IN_BLOCK_INDEX=$((BLOCK_SIZE + CURRENT_INDEX)) # Not an off-by-one error because a new backup was already saved
local OLDEST_BACKUP_IN_BLOCK=${BACKUPS[OLDEST_BACKUP_IN_BLOCK_INDEX]}
if [[ $OLDEST_BACKUP_IN_BLOCK == "" ]]; then
break
fi
local OLDEST_BACKUP_TIMESTAMP=$(parse-file-timestamp ${OLDEST_BACKUP_IN_BLOCK:0:19})
local BLOCK_COMMAND="$BLOCK_FUNCTION $OLDEST_BACKUP_TIMESTAMP"
if $BLOCK_COMMAND; then
# Oldest backup in this block satisfies the condition for placement in the next block
if $DEBUG; then
echo "$OLDEST_BACKUP_IN_BLOCK promoted to next block"
fi
else
# Oldest backup in this block does not satisfy the condition for placement in next block
delete-backup $OLDEST_BACKUP_IN_BLOCK
break
fi
((CURRENT_INDEX += BLOCK_SIZE))
done
delete-sequentially
}
# Disable world autosaving
execute-command "save-off"
# Backup world
START_TIME=$(date +"%s")
case $COMPRESSION_ALGORITHM in
"") # No compression
tar -cf $ARCHIVE_PATH -C $SERVER_WORLD .
;;
*) # With compression
tar -cf - -C $SERVER_WORLD . | $COMPRESSION_ALGORITHM -cv -$COMPRESSION_LEVEL - > $ARCHIVE_PATH 2>> /dev/null
;;
esac
sync
END_TIME=$(date +"%s")
# Enable world autosaving
execute-command "save-on"
# Save the world
execute-command "save-all"
# Delete old backups
delete-old-backups () {
case $DELETE_METHOD in
"sequential") delete-sequentially
;;
"thin") delete-thinning
;;
esac
}
# Notify players of completion
WORLD_SIZE_BYTES=$(du -b --max-depth=0 $SERVER_WORLD | awk '{print $1}')
ARCHIVE_SIZE_BYTES=$(du -b $ARCHIVE_PATH | awk '{print $1}')
COMPRESSION_PERCENT=$(($ARCHIVE_SIZE_BYTES * 100 / $WORLD_SIZE_BYTES))
ARCHIVE_SIZE=$(du -h $ARCHIVE_PATH | awk '{print $1}')
BACKUP_DIRECTORY_SIZE=$(du -h --max-depth=0 $BACKUP_DIRECTORY | awk '{print $1}')
TIME_DELTA=$((END_TIME - START_TIME))
# Check that archive size is not null and at least 1024 KB
if [[ "$ARCHIVE_SIZE" != "" && "$ARCHIVE_SIZE_BYTES" -gt 8 ]]; then
message-players-success "Backup complete!" "$TIME_DELTA s, $ARCHIVE_SIZE/$BACKUP_DIRECTORY_SIZE, $COMPRESSION_PERCENT%"
delete-old-backups
else
message-players-error "Backup was not saved!" "Please notify an administrator"
fi

27
src/backup-methods/restic.sh Executable file
View file

@ -0,0 +1,27 @@
#!/bin/env bash
# Backup to restic
OPTIND=1
while getopts 'i:o:' FLAG; do
case $FLAG in
i) SERVER_WORLD=$OPTARG ;;
o) RESTIC_REPO=$OPTARG ;;
*) ;;
esac
done
minecraft-backup-backup () {
restic backup -r "$RESTIC_REPO" "$SERVER_WORLD"
}
minecraft-backup-check () {
local WORLD_SIZE_BYTES
WORLD_SIZE_BYTES=$(du -b --max-depth=0 "$SERVER_WORLD" | awk '{print $1}')
echo "$WORLD_SIZE_BYTES"
}
minecraft-backup-epilog () {
# do nothing
echo -n
}

188
src/backup-methods/tar.sh Executable file
View file

@ -0,0 +1,188 @@
#!/bin/env bash
# Backup to (compressed) tar archives, and automatically delete
OPTIND=1
while getopts 'a:d:e:f:i:l:m:o:' FLAG; do
case $FLAG in
a) COMPRESSION_ALGORITHM=$OPTARG ;;
d) DELETE_METHOD=$OPTARG ;;
e) COMPRESSION_FILE_EXTENSION=$OPTARG ;;
f) TIMESTAMP=$OPTARG ;;
i) SERVER_WORLD=$OPTARG ;;
l) COMPRESSION_LEVEL=$OPTARG ;;
m) MAX_BACKUPS=$OPTARG ;;
o) BACKUP_DIRECTORY=$OPTARG ;;
*) ;;
esac
done
ARCHIVE_FILE_NAME=$TIMESTAMP.tar$COMPRESSION_FILE_EXTENSION
ARCHIVE_PATH=$BACKUP_DIRECTORY/$ARCHIVE_FILE_NAME
mkdir -p "$BACKUP_DIRECTORY"
# Parse file timestamp to one readable by "date"
parse-file-timestamp () {
echo "$1" | awk -F_ '{gsub(/-/,":",$2); print $1" "$2}'
}
# Delete a backup
delete-backup () {
local BACKUP=$1
rm -f "$BACKUP_DIRECTORY/$BACKUP"
echo "Deleted old backup" "$BACKUP"
}
# Sequential delete method
delete-sequentially () {
local BACKUPS_UNSORTED_RAW=("$BACKUP_DIRECTORY"/*)
local BACKUPS_UNSORTED=()
for BACKUP_NAME in "${BACKUPS_UNSORTED_RAW[@]}"; do
local BASENAME
BASENAME=$(basename "$BACKUP_NAME")
BACKUPS_UNSORTED+=("$BASENAME")
done
# List oldest first
# shellcheck disable=SC2207
IFS=$'\n' BACKUPS=($(sort <<<"${BACKUPS_UNSORTED[*]}"))
while [[ $MAX_BACKUPS -ge 0 && ${#BACKUPS[@]} -gt $MAX_BACKUPS ]]; do
delete-backup "${BACKUPS[0]}"
local BACKUPS_UNSORTED_RAW=("$BACKUP_DIRECTORY"/*)
local BACKUPS_UNSORTED=()
for BACKUP_NAME in "${BACKUPS_UNSORTED_RAW[@]}"; do
local BASENAME
BASENAME=$(basename "$BACKUP_NAME")
BACKUPS_UNSORTED+=("$BASENAME")
done
# List oldest first
# shellcheck disable=SC2207
IFS=$'\n' BACKUPS=($(sort <<<"${BACKUPS_UNSORTED[*]}"))
done
}
# Functions to sort backups into correct categories based on timestamps
is-hourly-backup () {
local TIMESTAMP=$*
local MINUTE
MINUTE=$(date -d "$TIMESTAMP" +%M)
return "$MINUTE"
}
is-daily-backup () {
local TIMESTAMP=$*
local HOUR
HOUR=$(date -d "$TIMESTAMP" +%H)
return "$HOUR"
}
is-weekly-backup () {
local TIMESTAMP=$*
local DAY
DAY=$(date -d "$TIMESTAMP" +%u)
return $((DAY - 1))
}
# Helper function to sum an array
array-sum () {
SUM=0
for NUMBER in "$@"; do
(( SUM += NUMBER ))
done
echo $SUM
}
# Thinning delete method
delete-thinning () {
# sub-hourly, hourly, daily, weekly is everything else
local BLOCK_SIZES=(16 24 30)
# First block is unconditional
# The next blocks will only accept files whose names cause these functions to return true (0)
local BLOCK_FUNCTIONS=("is-hourly-backup" "is-daily-backup" "is-weekly-backup")
# Warn if $MAX_BACKUPS does not have enough room for all the blocks
TOTAL_BLOCK_SIZE=$(array-sum "${BLOCK_SIZES[@]}")
if [[ $TOTAL_BLOCK_SIZE -gt $MAX_BACKUPS ]]; then
log-warning "MAX_BACKUPS ($MAX_BACKUPS) is smaller than TOTAL_BLOCK_SIZE ($TOTAL_BLOCK_SIZE)"
fi
local CURRENT_INDEX=0
local BACKUPS_UNSORTED_RAW=("$BACKUP_DIRECTORY"/*)
local BACKUPS_UNSORTED=()
for BACKUP_NAME in "${BACKUPS_UNSORTED_RAW[@]}"; do
local BASENAME
BASENAME=$(basename "$BACKUP_NAME")
BACKUPS_UNSORTED+=("$BASENAME")
done
# List newest first
# shellcheck disable=SC2207
IFS=$'\n' BACKUPS=($(sort -r <<<"${BACKUPS_UNSORTED[*]}"))
for BLOCK_INDEX in "${!BLOCK_SIZES[@]}"; do
local BLOCK_SIZE=${BLOCK_SIZES[BLOCK_INDEX]}
local BLOCK_FUNCTION=${BLOCK_FUNCTIONS[BLOCK_INDEX]}
local OLDEST_BACKUP_IN_BLOCK_INDEX=$((BLOCK_SIZE + CURRENT_INDEX)) # Not an off-by-one error because a new backup was already saved
local OLDEST_BACKUP_IN_BLOCK=${BACKUPS[OLDEST_BACKUP_IN_BLOCK_INDEX]}
if [[ $OLDEST_BACKUP_IN_BLOCK == "" ]]; then
break
fi
local OLDEST_BACKUP_TIMESTAMP
OLDEST_BACKUP_TIMESTAMP=$(parse-file-timestamp "${OLDEST_BACKUP_IN_BLOCK:0:19}")
if ! $BLOCK_FUNCTION "$OLDEST_BACKUP_TIMESTAMP"; then
# Oldest backup in this block does not satisfy the condition for placement in next block
delete-backup "$OLDEST_BACKUP_IN_BLOCK"
break
fi
((CURRENT_INDEX += BLOCK_SIZE))
done
delete-sequentially
}
clean-up () {
# Re-enable world autosaving
execute-command "save-on"
# Save the world
execute-command "save-all"
}
minecraft-backup-backup () {
case $COMPRESSION_ALGORITHM in
"") # No compression
tar -cf "$ARCHIVE_PATH" -C "$SERVER_WORLD" .
;;
*) # With compression
tar -cf - -C "$SERVER_WORLD" . | $COMPRESSION_ALGORITHM -cv -"$COMPRESSION_LEVEL" - > "$ARCHIVE_PATH" 2>> /dev/null
;;
esac
sync
}
minecraft-backup-check () {
WORLD_SIZE_BYTES=$(du -b --max-depth=0 "$SERVER_WORLD" | awk '{print $1}')
ARCHIVE_SIZE_BYTES=$(du -b "$ARCHIVE_PATH" | awk '{print $1}')
BACKUP_DIRECTORY_SIZE=$(du -h --max-depth=0 "$BACKUP_DIRECTORY" | awk '{print $1}')
ARCHIVE_SIZE=$(numfmt --to=iec "$ARCHIVE_SIZE_BYTES")
COMPRESSION_PERCENT=$((ARCHIVE_SIZE_BYTES * 100 / WORLD_SIZE_BYTES))
# Check that archive size is not null and at least 1024 KB
if [[ "$ARCHIVE_SIZE" != "" && "$ARCHIVE_SIZE_BYTES" -gt 8 ]]; then
echo "$ARCHIVE_SIZE/$BACKUP_DIRECTORY_SIZE, $COMPRESSION_PERCENT%"
else
return 1
fi
}
minecraft-backup-epilog () {
case $DELETE_METHOD in
"sequential") delete-sequentially
;;
"thin") delete-thinning
;;
esac
}

181
src/core.sh Executable file
View file

@ -0,0 +1,181 @@
#!/usr/bin/env bash
# This script implements the core functionality, and expects the following
# functions to be defined by the method scripts:
#
# minecraft-backup-execute "$COMMAND"
# where $COMMAND is a command sent to the Minecraft server console
# minecraft-backup-backup
# which performs a backup
# minecraft-backup-check
# minecraft-backup-epilog
# Default Configuration
EXECUTE_METHOD="$1"
shift
EXECUTE_METHOD_OPTIONS=()
while [[ $1 != "--" ]]; do
EXECUTE_METHOD_OPTIONS+=("$1")
shift
done
shift
BACKUP_METHOD="$1"
shift
BACKUP_METHOD_OPTIONS=()
while [[ $1 != "--" ]]; do
BACKUP_METHOD_OPTIONS+=("$1")
shift
done
shift
OPTIND=1
while getopts 'c:g:p:q:v:' FLAG; do
case $FLAG in
c) ENABLE_CHAT_MESSAGES=$OPTARG ;;
g) EXIT_IF_NO_SCREEN=$OPTARG ;;
p) PREFIX=$OPTARG ;;
q) SUPPRESS_WARNINGS=$OPTARG ;;
v) DEBUG=$OPTARG ;;
*) ;;
esac
done
BASE_DIR=$(dirname "$(realpath "$0")")
# shellcheck source=logging.sh
source "$BASE_DIR/logging.sh" \
-q "$SUPPRESS_WARNINGS" \
-v "$DEBUG"
EXECUTE_METHOD_PATH=$EXECUTE_METHOD
BACKUP_METHOD_PATH=$BACKUP_METHOD
assert-all () {
local TEST_CMD=$1
local MESSAGE=$2
shift 2
local ITEMS=("$@")
local RESULT=true
for ITEM in "${ITEMS[@]}"; do
if ! $TEST_CMD "$ITEM"; then
log-fatal "$MESSAGE $ITEM"
RESULT=false
fi
done
if ! $RESULT; then
exit 1
fi
}
assert-files-exist () {
assert-all "test -f" "Script not found:" "$@"
}
assert-files-exist \
"$EXECUTE_METHOD_PATH" \
"$BACKUP_METHOD_PATH"
# shellcheck source=exec-methods/screen.sh
source "$EXECUTE_METHOD_PATH" "${EXECUTE_METHOD_OPTIONS[@]}"
# shellcheck source=backup-methods/tar.sh
source "$BACKUP_METHOD_PATH" "${BACKUP_METHOD_OPTIONS[@]}"
# fn_exists based upon https://stackoverflow.com/q/85880
fn_exists () {
LC_ALL=C type "$1" 2>&1 | grep -q 'function'
}
assert-functions-exist () {
assert-all fn_exists "Function not defined:" "$@"
}
assert-functions-exist \
minecraft-backup-execute \
minecraft-backup-backup \
minecraft-backup-check \
minecraft-backup-epilog
# Minecraft server communication interface functions
execute-command () {
minecraft-backup-execute "$@"
}
message-players () {
message-players-color "gray" "$@"
}
message-players-error () {
message-players-color "red" "$@"
}
message-players-warning () {
message-players-color "yellow" "$@"
}
message-players-success () {
message-players-color "green" "$@"
}
message-players-color () {
local COLOR=$1
local MESSAGE=$2
local HOVER_MESSAGE=$3
log-info "$MESSAGE ($HOVER_MESSAGE)"
if $ENABLE_CHAT_MESSAGES; then
execute-command \
"tellraw @a [\"\",{\"text\":\"[$PREFIX] \",\"color\":\"gray\",\"italic\":true},{\"text\":\"$MESSAGE\",\"color\":\"$COLOR\",\"italic\":true,\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"$HOVER_MESSAGE\"}]}}}]"
fi
}
clean-up () {
# Re-enable world autosaving
execute-command "save-on"
# Save the world
execute-command "save-all"
}
trap-ctrl-c () {
log-warning "Backup interrupted. Attempting to re-enable autosaving"
clean-up
exit 2
}
trap "trap-ctrl-c" 2
# Notify players of start
SHORT_BACKUP_METHOD=$(basename "$BACKUP_METHOD")
message-players "Starting backup..." "$SHORT_BACKUP_METHOD ${BACKUP_METHOD_OPTIONS[*]}"
# Disable world autosaving
execute-command "save-off"
RESULT=$?
if $EXIT_IF_NO_SCREEN && [[ $RESULT != "0" ]]; then
exit $RESULT
fi
# Record start time for performance reporting
START_TIME=$(date +"%s")
minecraft-backup-backup
BACKUP_RESULT=$?
END_TIME=$(date +"%s")
clean-up
TIME_DELTA=$((END_TIME - START_TIME))
CHECK_MESSAGE=$(minecraft-backup-check)
CHECK_RESULT=$?
if [[ $BACKUP_RESULT != "0" ]] || [[ $CHECK_RESULT != "0" ]]; then
message-players-error "Backup failed!" "Please notify an admin."
exit $CHECK_RESULT
fi
message-players-success "Backup complete!" "$TIME_DELTA s, $CHECK_MESSAGE"
EPILOG_MESSAGE=$(minecraft-backup-epilog)
EPILOG_RESULT=$?
if [[ $EPILOG_RESULT != "0" ]]; then
message-players-warning "Backup epilog failed."
fi
if [[ $EPILOG_MESSAGE != "" ]]; then
message-players "$EPILOG_MESSAGE"
fi

21
src/exec-methods/screen.sh Executable file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env bash
# Execute commands on a Minecraft server running in a GNU screen
OPTIND=1
while getopts 's:' FLAG "$@"; do
case $FLAG in
s) SCREEN_NAME=$OPTARG ;;
*) ;;
esac
done
minecraft-backup-execute () {
local COMMAND=$1
if ! screen -S "$SCREEN_NAME" -Q "select" .; then
return 1
fi
if [[ "$SCREEN_NAME" != "" ]]; then
screen -S "$SCREEN_NAME" -p 0 -X stuff "$COMMAND$(printf \\r)"
fi
}

47
src/logging.sh Normal file
View file

@ -0,0 +1,47 @@
#!/usr/bin/env bash
SUPPRESS_WARNINGS=false
DEBUG=true
OPTIND=1
while getopts 'q:v:' FLAG; do
case $FLAG in
q) SUPPRESS_WARNINGS=$OPTARG ;;
v) DEBUG=$OPTARG ;;
*) ;;
esac
done
echo-colored () {
local COLOR_CODE="$1"
shift
local MESSAGE="$*"
if test -t 1 && [ "$(tput colors)" -gt 1 ]; then
# This terminal supports color
echo -ne "\033[${COLOR_CODE}m${MESSAGE}\033[0m"
else
# Output does not support color
echo -n "$MESSAGE"
fi
}
log () {
local COLOR="$1"
local TYPE="$2"
local MESSAGE="$3"
echo-colored "$COLOR" "${TYPE}: "
echo-colored "0" "$MESSAGE"
echo
}
log-fatal () {
>&2 log "0;31" "FATAL" "$*"
}
log-warning () {
if ! $SUPPRESS_WARNINGS; then
>&2 log "0;33" "WARNING" "$*"
fi
}
log-info () {
if $DEBUG; then
log "0;36" "INFO" "$*"
fi
}

View file

@ -6,13 +6,18 @@ ITERATIONS=1000
MINUTE_INTERVAL=30 MINUTE_INTERVAL=30
MINUTES_SINCE_START=0 MINUTES_SINCE_START=0
WORLD=test/world
BACKUP_DIR=test/backups
mkdir -p $WORLD
echo "hello there" > "$WORLD/content.txt"
if [[ $1 != "" ]]; then if [[ $1 != "" ]]; then
ITERATIONS=$1 ITERATIONS=$1
fi fi
for (( c=1; c<=$ITERATIONS; c++ )); do for (( c=1; c<=ITERATIONS; c++ )); do
TIMESTAMP=$(( START_TIMESTAMP + MINUTES_SINCE_START * 60 )) TIMESTAMP=$(( START_TIMESTAMP + MINUTES_SINCE_START * 60 ))
FILE_NAME=$(date -d "@$TIMESTAMP" +%F_%H-%M-%S) FILE_NAME=$(date -d "@$TIMESTAMP" +%F_%H-%M-%S)
./backup.sh -q -i /home/nicolas/privatesurvival/world -o /home/nicolas/backups -f $FILE_NAME ./backup.sh -q -s minecraft -i "$WORLD" -o "$BACKUP_DIR" -f "$FILE_NAME"
(( MINUTES_SINCE_START += MINUTE_INTERVAL )) (( MINUTES_SINCE_START += MINUTE_INTERVAL ))
done done