aboutsummaryrefslogtreecommitdiff
path: root/server.sh
blob: d9c06b785428cce50149c7a1b70f2bb446ff74e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/bin/bash

if [ -e "serverconf.sh" ]
then
	source "serverconf.sh"
else
	log_error "No configuration found in PWD. Exiting."
	exit 1
fi

source "backends/tar.sh"
source "backends/bup.sh"
source "backends/borg.sh"

function log_debug() {
	if [ $VERBOSE -ne 0 ]; then
		printf "[DEBUG] $1\n" >&2
	fi
}
log_info() { printf "[INFO] $1\n" ; }
log_error() { printf "[ERROR] $1\n" >&2 ; }

function backup_hook_example {
	bup -d $CUR_BACK_DIR ls -l "$BACKUP_NAME/latest/var/minecraft"
}

function send_cmd () {
	tmux -S $TMUX_SOCKET send -t $TMUX_WINDOW "$1" enter
}

function assert_not_running() {
	if server_running; then
		log_info "It seems a server is already running. If this is not the case,\
			manually attach to the running screen and close it."
		exit 1
	fi
}

function assert_running() {
	if ! server_running; then
		log_info "Server not running"
		exit 1
	fi
}

function server_start() {
	assert_not_running

	if [ ! -f "eula.txt" ]
	then
		log_info "eula.txt not found. Creating and accepting EULA."
		echo "eula=true" > "eula.txt"
	fi

	tmux -S $TMUX_SOCKET new-session -s $TMUX_WINDOW -d \
		$JRE_JAVA $JVM_ARGS -jar $JAR $JAR_ARGS
	pid=`tmux -S $TMUX_SOCKET list-panes -t $TMUX_WINDOW -F "#{pane_pid}"`
	echo $pid > $PIDFILE
	log_info "Started with PID $pid"
	exit
}

function server_stop() {
	# Allow success even if server is not running
	#trap "exit 0" EXIT

	assert_running
	send_cmd "stop"

	local RET=1
	while [ ! $RET -eq 0 ]
	do
		sleep 1
		ps -p $(cat $PIDFILE) > /dev/null
		RET=$?
	done

	log_info "stopped the server"

	rm -f $PIDFILE

	exit
}

function server_attach() {
	assert_running
	tmux -S $TMUX_SOCKET attach -t $TMUX_WINDOW
	exit
}

function server_running() {
	if [ -f $PIDFILE ] && [ "$(cat $PIDFILE)" != "" ]; then
		ps -p $(cat $PIDFILE) > /dev/null
		return
	fi

	false
}

function server_status() {
	if server_running
	then
		log_info "Server is running"
	else
		log_info "Server is not running"
	fi
	exit
}

function players_online() {
	send_cmd "list"
	sleep 1
	while [ $(tail -n 3 "$LOGFILE" | grep -c "There are") -lt 1 ]
	do
		sleep 1
	done

	[ `tail -n 3 "$LOGFILE" | grep -c "There are 0"` -lt 1 ]
}

function backup_backend_run() {
	local cmd
	# could do ${BACKUP_BACKEND}_$1 though
	if [ $BACKUP_BACKEND = "bup" ]; then
		cmd="bup"
	elif [ $BACKUP_BACKEND = "borg" ]; then
		cmd="borg"
	else
		cmd="tar"
	fi
	cmd="${cmd}_$1"
	log_debug "Backup backend command: \"$cmd\""
	eval "$cmd"
}

function init_backup() {
	# even though bup and borg are smart, they will not create a path for a repo
	for backup_dir in ${BACKUP_DIRS[*]}
	do
		if [[ $backup_dir == *:* ]]; then
			local remote="$(echo "$backup_dir" | cut -d: -f1)"
			local remote_dir="$(echo "$backup_dir" | cut -d: -f2)"
			ssh "$remote" "mkdir -p \"$remote_dir\""
		else
			mkdir -p "$backup_dir"
		fi
	done

	backup_backend_run "init"
}

function same_world() {
	delta=$(diff -r "$1" "$2")
	if [ $? -ne 0 ]; then
		return 1
	fi
	if [ -z "$delta" ] ; then
		return 0
	fi
	return 1
}

# checking if latest snapshots are the same as the current world
function test_backup_integrity() {
	local retcode=0
	for backup_dir in ${BACKUP_DIRS[*]}
	do
		local tmpdir=$(mktemp -d);

		# restore most recent backup to a temporary dir
		if ! server_restore "$backup_dir" 0 "$tmpdir" ; then
			log_error "Failed to get latest snapshot from \"$backup_dir\""
			retcode=1
		elif ! same_world "$WORLD_NAME" "$tmpdir/$WORLD_NAME" ; then
			log_error "Latest backup from \"$backup_dir\" differs from current world!"
			retcode=1
		else
			log_info "Backup at \"$backup_dir\" is OK"
		fi

		rm -r "$tmpdir"
	done

	if [ $retcode -ne 0 ] ; then
		log_error "Backup integrity check: FAILED"
	else
		log_info "Backup integrity check: OK"
	fi
	return $retcode
}

function create_backup() {
	init_backup
	backup_backend_run "create_backup"
	test_backup_integrity
}

function server_backup_safe() {
	local force=$1
	log_info "Detected running server. Checking if players online..."
	if [ "$force" != "true" ] && ! players_online; then
		log_info "Players are not online. Not backing up."
		return
	fi

	log_info "Disabling autosave"
	send_cmd "save-off"
	send_cmd "save-all flush"
	log_info "Waiting for save... If froze, run /save-on to re-enable autosave!!"

	sleep 1
	while [ $(tail -n 3 "$LOGFILE" | grep -c "Saved the game") -lt 1 ]
	do
		sleep 1
	done
	sleep 2
	log_info "Done! starting backup..."

	create_backup

	local RET=$?

	log_info "Re-enabling auto-save"
	send_cmd "save-on"

	if [ $RET -eq 0 ]; then
		log_info "Running backup hook"
		$BACKUP_HOOK
	fi
}

function server_backup_unsafe() {
	log_info "No running server detected. Running Backup"

	create_backup
	local status=$?

	if [ $status -eq 0 ]; then
		log_info "Running backup hook"
		$BACKUP_HOOK
	fi
}

function backup_running() {
	systemctl is-active --quiet mc-backup.service
}

function fbackup_running() {
	systemctl is-active --quiet mc-fbackup.service
}

function server_backup() {
	local force=$1

	if [ "$force" = "true" ]; then
		if backup_running; then
			log_info "A backup is running. Aborting..."
			return
		fi
	else
		if fbackup_running; then
			log_info "A force backup is running. Aborting..."
			return
		fi
	fi

	if server_running; then
		server_backup_safe "$force"
	else
		server_backup_unsafe
	fi
}

function server_ls_backups() {
	for backup_dir in ${BACKUP_DIRS[*]}
	do
		log_info "backups in ${backup_dir}:"
		backup_backend_run "ls \"$backup_dir\""
	done
}

# creates a selection dialog
function choose_from() {
	local items=("$@")
	select item in "${items[@]}"; do
		echo "$item"
		return
	done
}

# checks if an item is in the array
function is_in() {
	local item="$1"
	shift
	local array=("$@")

	# these :space: things allow checking that *exactly* this item is in array
	if [[ ${array[*]} =~ (^|[[:space:]])"$item"($|[[:space:]]) ]]; then
		return
	fi
	false
}

function server_restore() {
	local backup_dir
	local snapshot_index
	local dest="$PWD"

	# parameters are only used for testing backups, so thorough checks are not needed
	if [ $# -ge 2 ]; then
		backup_dir="$1"
		snapshot_index=$2
	fi
	if [ $# -eq 3 ]; then
		dest="$3"
	fi

	if [ "$dest" = "$PWD" ]; then
		assert_not_running
	fi

	if [ ${#BACKUP_DIRS[@]} -eq 0 ]; then
		log_error "No backup directories found, abort"
		return 1
	fi


	if [ -z $backup_dir ]; then
		log_info "From where get the snapshot?"
		backup_dir="$(choose_from "${BACKUP_DIRS[@]}")"
	fi
	if ! is_in "$backup_dir" "${BACKUP_DIRS[@]}" ; then
		log_error "No valid backup directory selected, abort"
		return 1
	fi


	local snapshots="$( backup_backend_run "ls \"$backup_dir\"" )"
	log_debug "Snapshots found:"
	log_debug "$snapshots"
	if [ -z "$snapshots" ]; then
		log_error "No snapshots found, abort"
		return 1
	fi
	# convert multiline string to bash array
	snapshots=($(echo "$snapshots"))


	local snapshot
	if [ -z $snapshot_index ]; then
		log_info "Select which snapshot to restore"
		snapshot=$(choose_from "${snapshots[@]}")
	else
		snapshot="${snapshots[snapshot_index]}"
	fi
	if ! is_in "$snapshot" "${snapshots[@]}" ; then
		log_error "No valid snapshot selected, abort"
		return 1
	fi


	log_debug "Restoring snapshot \"$snapshot\" from \"$backup_dir\""

	# if we restore to PWD, we will overwrite the current world, which might be harmful
	local oldworld_name
	if [ "$dest" = "$PWD" ] && [[ -d "$WORLD_NAME" ]]; then
		oldworld_name="${WORLD_NAME}.old.$(date +'%F_%H-%M-%S.%N')"
		log_info "Preserving old world: $(mv -n -v "$PWD/$WORLD_NAME" "$PWD/$oldworld_name")"
	fi


	backup_backend_run "restore \"$backup_dir\" \"$snapshot\" \"$dest\""
	local status=$?


	# if we preseved the current world, but failed to restore the snapshot
	if [ ! -z ${oldworld_name+x} ] && [ $status -ne 0 ]; then
		log_error "Failed to restore snapshot, putting old world back where it was:"
		rm -rv "$PWD/$WORLD_NAME"
		mv -v "$PWD/$oldworld_name" "$PWD/$WORLD_NAME"
		return 1
	fi

	log_debug "Snapshot restored"

	return 0
}

#cd $(dirname $0)

case $1 in
	"start")
		server_start
		;;
	"stop")
		server_stop
		;;
	"attach")
		server_attach
		;;
	"backup")
		server_backup
		;;
	"restore")
		server_restore
		;;
	"status")
		server_status
		;;
	"fbackup")
		server_backup "true"
		;;
	"ls")
		server_ls_backups
		;;
	*)
		echo "Usage: $0 start|stop|attach|status|backup"
		;;
esac