commit 2c985cc15072fbdc902b615ed9164d5de3837757 Author: Jakub Fojt Date: Sat Jul 4 21:23:36 2020 +0000 First commit Ensure running and autoshutdown scripts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1377554 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.swp diff --git a/autoshutdown.sh b/autoshutdown.sh new file mode 100755 index 0000000..c62ab99 --- /dev/null +++ b/autoshutdown.sh @@ -0,0 +1,79 @@ +#!/bin/sh + +# If exists tmux session +# If Responds to queries + +SERVER_DIR='/home/ubuntu/minecraft/servers/kincls' +TMUX_NAME='minecraft kincls server' +EMPTY_COUNTER="$SERVER_DIR/empty_counter.txt" + +json_parse() { + cat - | python3 -c "import sys, json; print(json.load(sys.stdin)['$1'])" +} + +silent_exitcode() { + $* > /dev/null 2>&1 +} + +empty_count() { + if [ ! -f "$EMPTY_COUNTER" ]; then + # File not existing + echo "0" + else + cat "$EMPTY_COUNTER" + fi +} + +empty_incr() { + c="$(empty_count)" + if [ "$c" -gt 10 ]; then + echo "Server empty for more than 10 minutes, shutting down" + empty_reset # Needs to be 0 next time server starts + tmux send-keys -t "$TMUX_NAME.0" "stop" ENTER + sleep 5 + $(sudo /sbin/shutdown -P +1) + else + echo "Empty count $c. Incrementing" + echo "$((c+1))" > "$EMPTY_COUNTER" + fi +} + +empty_reset() { + echo "Resetting empty counter" + echo 0 > "$EMPTY_COUNTER" +} + +tmux_running() { + tmux ls -F "#{session_name}" | grep -q "$TMUX_NAME" +} + +server_responsive() { + silent_exitcode mcstatus localhost ping +} + +n_logins="$(w -h | wc -l)" +echo "$(date) [$n_logins logins]" + +if tmux_running; then + : #echo "Tmux running" +else + echo "Tmux not running" + empty_incr + exit 1 +fi + +if server_responsive; then + n_players=$(mcstatus localhost json | json_parse player_count) + echo "Server responsive. $n_players players online" + if [ "$n_players" -gt 0 ] || [ "$n_logins" -gt 0 ]; then + # Keep alive if players or ssh sessions active + empty_reset + else + empty_incr + exit 1 + fi +else + echo "Server unresponsive" + empty_incr + exit 1 +fi diff --git a/crontab b/crontab new file mode 100644 index 0000000..ec115f8 --- /dev/null +++ b/crontab @@ -0,0 +1 @@ +* * * * * /home/ubuntu/minecraft/autoshutdown.sh diff --git a/ensure_running.sh b/ensure_running.sh new file mode 100755 index 0000000..f04c8e5 --- /dev/null +++ b/ensure_running.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +cd servers/kincls +tmux new-session -Ad -s "minecraft kincls server" "java -Xmx1024M -Xms1024M -jar server.jar nogui"