From 92bc6f43c8f625c0374dd4ecae2a28263da9c225 Mon Sep 17 00:00:00 2001 From: Ryan Cavicchioni Date: Mon, 20 Apr 2020 22:29:43 -0500 Subject: [PATCH] add craftbukkit restic hook --- roles/restic/files/hooks/craftbukkit.sh | 116 ++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 roles/restic/files/hooks/craftbukkit.sh diff --git a/roles/restic/files/hooks/craftbukkit.sh b/roles/restic/files/hooks/craftbukkit.sh new file mode 100644 index 0000000..c9e0771 --- /dev/null +++ b/roles/restic/files/hooks/craftbukkit.sh @@ -0,0 +1,116 @@ +#!/bin/bash + +set -e + +SERVICE=craftbukkit.service +VAR_DIR=/var/opt/craftbukkit +WAIT=30 +VERBOSE=${VERBOSE:-4} + +prereq() { + local service=$1 + if ! systemctl list-units --full --all | grep -Fq "$service"; then + printf "%s unit does not exit\n" "$service" + exit 1 + fi +} + +error_exit() { + printf "%s\n" "$1" >&2 + exit 1 +} + +stop_server() { + local unit="${1:-$SERVICE}" + local attempts="${2:-$WAIT}" + + if ! systemctl -q is-enabled "$unit"; then + printf "%s is not enabled, skipping.\n" "$unit" + return 0 + fi + + if ! systemctl -q is-active "$unit"; then + printf "%s is already stopped\n" "$unit" + return 0 + fi + + systemctl -q stop "$unit" + + while systemctl -q is-active "$unit"; do + printf "waiting for %s to stop ... (%s)\n" "$unit" "$attempts" + ((attempts--)) + if ((attempts == 0)); then + return 1 + fi + sleep 1 + done + + return 0 +} + +start_server() { + local unit="${1:-$SERVICE}" + local attempts="${2:-$WAIT}" + + if ! systemctl -q is-enabled "$unit"; then + printf "%s is not enabled, skipping.\n" "$unit" + return 0 + fi + + if systemctl -q is-active "$unit"; then + printf "%s is already started\n" "$unit" + return 0 + fi + + systemctl -q start "$unit" + + while ! systemctl -q is-active "$unit"; do + printf "waiting for %s to start ... (%d)\n" "$unit" "$attempts" + ((attempts--)) + if ((attempts == 0)); then + return 1 + fi + sleep 1 + done + + return 0 +} + + +open_files() { + local dir=${1-$VAR_DIR} + local attempts="${2:-$WAIT}" + + while (($(lsof +D "$dir" | wc -l) > 0)); do + printf "waiting for open files ... (%d)\n" "$attempts" + ((attempts--)) + if ((attempts == 0)); then + return 1 + fi + sleep 1 + done + + return 0 +} + + +main() { + + if [ "$1" == "pre" ]; then + if ! stop_server $SERVICE; then + error_exit "Failed to stop $SERVICE" + fi + + printf "checking for open files\n" + + if ! open_files $VAR_DIR; then + error_exit "Open files exist in $VAR_DIR" + fi + elif [ "$1" == "post" ]; then + if ! start_server $SERVICE; then + error_exit "Failed to start $SERVICE" + fi + fi +} + +main "$@"