forked from Ahtenus/minecraft-init
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminecraft
731 lines (682 loc) · 21.1 KB
/
minecraft
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
#!/bin/bash
# /etc/init.d/minecraft
### BEGIN INIT INFO
# Provides: minecraft
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Should-Start: $network
# Should-Stop: $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Minecraft server
# Description: Init script for minecraft server.
### END INIT INFO
# Load config file
if [[ -L $0 ]]
then
source $(readlink -e $0 | sed "s:[^/]*$:config:")
else
source $(echo $0 | sed "s:[^/]*$:config:")
fi
if [[ "$SERVICE" == "" ]]
then
echo "Couldn't load config file, please edit config.example and rename it to config"
logger -t minecraft-init "Couldn't load config file, please edit config.example and rename it to config"
exit
fi
ME=$(whoami)
INVOCATION="java -Xmx${MAXHEAP} -Xms${MINHEAP} -XX:ParallelGCThreads=${CPU_COUNT} -jar ${SERVICE} nogui"
as_user() {
if [[ ${ME} == ${USERNAME} ]] ; then
bash -c "$1"
else
su ${USERNAME} -s /bin/bash -c "$1"
fi
}
is_running() {
# Checks for the minecraft servers screen session
# returns true if it exists.
pidfile=${MCPATH}/${SCREEN}.pid
if [[ -f "$pidfile" ]]
then
pid=$(head -1 ${pidfile})
if ps ax | grep -v grep | grep ${pid} | grep "${SCREEN}" > /dev/null
then
return 0
else
if [[ -z "$isInStop" ]]
then
if [[ -z "$roguePrinted" ]]
then
roguePrinted=1
echo "Rogue pidfile found!"
fi
fi
return 1
fi
else
if ps ax | grep -v grep | grep "${SCREEN} ${INVOCATION}" > /dev/null
then
echo "No pidfile found, but server's running."
echo "Re-creating the pidfile."
pid=$(ps ax | grep -v grep | grep "${SCREEN} ${INVOCATION}" | cut -f1 -d' ')
check_permissions
as_user "echo $pid > $pidfile"
return 0
else
return 1
fi
fi
}
datepath() {
# datepath path filending-to-check returned-filending
# Returns an file path with added date between the filename and file ending.
# $1 filepath (not including file ending)
# $2 file ending to check for uniqueness
# $3 file ending to return
if [[ -e $1$(date +%F)$2 ]]
then
echo $1$(date +%FT%T)$3
else
echo $1$(date +%F)$3
fi
}
mc_start() {
servicejar=${MCPATH}/${SERVICE}
if [[ ! -f "$servicejar" ]]
then
echo "Failed to start: Can't find the specified Minecraft jar under $servicejar. Please check your config!"
exit 1
fi
pidfile=${MCPATH}/${SCREEN}.pid
check_permissions
as_user "cd $MCPATH && screen -dmS $SCREEN $INVOCATION"
as_user "screen -list | grep "\.${SCREEN}" | cut -f1 -d'.' | head -n 1 | tr -d -c 0-9 > $pidfile"
#
# Waiting for the server to start
#
seconds=0
until is_running
do
sleep 1
seconds=${seconds}+1
if [[ ${seconds} -eq 5 ]]
then
echo "Still not running, waiting a while longer..."
fi
if [[ ${seconds} -ge 120 ]]
then
echo "Failed to start, aborting."
exit 1
fi
done
echo "$SERVICE is running."
}
mc_command() {
if is_running
then
as_user "screen -p 0 -S $SCREEN -X eval 'stuff \"$(eval echo ${FORMAT})\"\015'"
else
echo "$SERVICE was not running. Not able to run command."
fi
}
mc_saveoff() {
if is_running
then
echo "$SERVICE is running... suspending saves"
mc_command save-off
mc_command save-all
sync
sleep 10
else
echo "$SERVICE was not running. Not suspending saves."
fi
}
mc_saveon() {
if is_running
then
echo "$SERVICE is running... re-enabling saves"
mc_command save-on
else
echo "$SERVICE was not running. Not resuming saves."
fi
}
mc_say() {
if is_running
then
echo "Said: $1"
mc_command "say $1"
else
echo "$SERVICE was not running. Not able to say anything."
fi
}
mc_stop() {
pidfile=${MCPATH}/${SCREEN}.pid
#
# Stops the server
#
echo "Saving worlds..."
mc_command save-all
sleep 10
echo "Stopping server..."
mc_command stop
sleep 0.5
#
# Waiting for the server to shut down
#
seconds=0
isInStop=1
while is_running
do
sleep 1
seconds=${seconds}+1
if [[ ${seconds} -eq 5 ]]
then
echo "Still not shut down, waiting a while longer..."
fi
if [[ ${seconds} -ge 120 ]]
then
logger -t minecraft-init "Failed to shut down server, aborting."
echo "Failed to shut down, aborting."
exit 1
fi
done
as_user "rm $pidfile"
unset isInStop
is_running
echo "$SERVICE is now shut down."
}
mc_reload() {
echo "$SERVICE is running... reloading."
mc_command reload
}
check_backup_settings() {
case "$BACKUPFORMAT" in
tar)
COMPRESSCMD="tar -hcjf"
STORECMD="tar -cpf"
ARCHIVEENDING=".tar.bz2"
STOREDENDING=".tar"
EXCLUDEARG="-X "
;;
zip)
COMPRESSCMD="zip -rq"
STORECMD="zip -rq -0"
ARCHIVEENDING=".zip"
STOREDENDING=".zip"
EXCLUDEARG="-x@"
;;
*)
echo "$BACKUPFORMAT is not a supported backup format"
exit 1
;;
esac
}
get_worlds() {
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
a=1
for NAME in $(ls ${WORLDSTORAGE})
do
if [[ -d ${WORLDSTORAGE}/${NAME} ]]
then
WORLDNAME[$a]=${NAME}
a=${a}+1
fi
done
IFS=${SAVEIFS}
}
mc_whole_backup() {
check_backup_settings
echo "backing up entire setup into $WHOLEBACKUP"
path=$(datepath ${WHOLEBACKUP}/mine_)
locationOfScript=$(dirname "$(readlink -e "$0")")
as_user "mkdir -p $path"
if [[ -r "$locationOfScript/exclude.list" ]]
then
echo "...except the following files and/or dirs:"
cat ${locationOfScript}/exclude.list
exclude="$EXCLUDEARG$locationOfScript/exclude.list"
fi
if [[ "$COMPRESS_WHOLEBACKUP" ]]
then
as_user "$COMPRESSCMD $path/whole-backup$ARCHIVEENDING $MCPATH $exclude"
else
as_user "$STORECMD $path/whole-backup$STOREDENDING $MCPATH $exclude"
fi
}
mc_world_backup() {
#
# Backup the worlds and puts them in a folder for each day (unless $BACKUPSCRIPTCOMPATIBLE is set)
#
check_backup_settings
get_worlds
today="$(date +%F)"
as_user "mkdir -p $BACKUPPATH"
# Check if the backup script compatibility is enabled
if [[ "$BACKUPSCRIPTCOMPATIBLE" ]]
then
# If it is enabled, then delete the old backups to prevent errors
echo "Detected that backup script compatibility is enabled, deleting old backups that are not necessary."
as_user "rm -r $BACKUPPATH/*"
fi
for INDEX in ${!WORLDNAME[@]}
do
echo "Backing up minecraft ${WORLDNAME[$INDEX]}"
if [[ "$WORLDEDITCOMPATIBLE" ]]
# If this is set tars will be created compatible to WorldEdit
then
as_user "mkdir -p $BACKUPPATH/${WORLDNAME[$INDEX]}"
path=$(datepath ${BACKUPPATH}/${WORLDNAME[$INDEX]}/ ${ARCHIVEENDING} ${ARCHIVEENDING})
elif [[ "$BACKUPSCRIPTCOMPATIBLE" ]]
# If is set tars will be put in $BACKUPPATH without any timestamp to be compatible with
# [backup rotation script](https://github.com/adamfeuer/rotate-backups)
then
path=${BACKUPPATH}/${WORLDNAME[$INDEX]}${ARCHIVEENDING}
else
as_user "mkdir -p $BACKUPPATH/${today}"
path=$(datepath ${BACKUPPATH}/${today}/${WORLDNAME[$INDEX]}_ ${ARCHIVEENDING} ${ARCHIVEENDING})
fi
if [[ "$WORLDEDITCOMPATIBLE" ]]
# Don't store the complete path
then
as_user "cd $MCPATH && $COMPRESSCMD $path ${WORLDNAME[$INDEX]}"
else
as_user "$COMPRESSCMD $path $MCPATH/${WORLDNAME[$INDEX]}"
fi
done
}
check_links() {
get_worlds
for INDEX in ${!WORLDNAME[@]}
do
if [[ -L ${MCPATH}/${WORLDNAME[$INDEX]} || ! -a ${MCPATH}/${WORLDNAME[$INDEX]} ]]
then
link=$(ls -l ${MCPATH}/${WORLDNAME[$INDEX]} | awk '{print $11}')
if [[ "$link" != "${WORLDSTORAGE}/${WORLDNAME[$INDEX]}" ]]
then
as_user "rm -f $MCPATH/${WORLDNAME[$INDEX]}"
as_user "ln -s ${WORLDSTORAGE}/${WORLDNAME[$INDEX]} $MCPATH/${WORLDNAME[$INDEX]}"
echo "Created link for ${WORLDNAME[$INDEX]}"
fi
else
echo "Could not process the world named '${WORLDNAME[$INDEX]}'. Please move all worlds to ${WORLDSTORAGE}."
exit 1
fi
done
}
overviewer_start() {
if [[ ! -e ${OVPATH}/overviewer.py ]]
then
if [[ ! "$OVPATH" == "apt" ]]
then
echo "Minecraft-Overviewer is not installed in \"$OVPATH\""
exit 1
else
echo "Using APT repository installed Minecraft-Overviewer"
fi
fi
if [[ ! -e ${OUTPUTMAP} ]]
then
as_user "mkdir -p $OUTPUTMAP"
fi
if [[ -e ${OVCONFIGPATH}/${OVCONFIGNAME} ]]
then
echo "Start generating map with Minecraft-Overviewer..."
if [[ "$OVPATH" == "apt" ]]
then
as_user "overviewer.py --config=$OVCONFIGPATH/$OVCONFIGNAME"
else
as_user "python $OVPATH/overviewer.py --config=$OVCONFIGPATH/$OVCONFIGNAME"
fi
echo "Map generated."
else
echo "No config file found. Start with default config..."
if [[ -z $1 ]] || [[ ! -e ${OVBACKUP}/$1 ]]
then
echo "World \"$1\" not found."
else
echo "Start generating map with Minecraft-Overviewer..."
if [[ "$OVPATH" == "apt" ]]
then
as_user "nice overviewer.py $OVBACKUP/$1 $OUTPUTMAP"
else
as_user "nice python $OVPATH/overviewer.py $OVBACKUP/$1 $OUTPUTMAP"
fi
echo "Map generated."
fi
fi
}
overviewer_copy_worlds() {
#
# Backup the worlds for overviewer
#
get_worlds
for INDEX in ${!WORLDNAME[@]}
do
echo "Copying minecraft ${WORLDNAME[$INDEX]}."
as_user "mkdir -p $OVBACKUP"
as_user "rsync -rt --delete $WORLDSTORAGE/${WORLDNAME[$INDEX]} $OVBACKUP/${WORLDNAME[$INDEX]}"
done
}
whitelist(){
mc_command "whitelist list"
sleep 1s
whitelist=$(tac ${SERVERLOG} | grep -m 1 "White-listed players:")
echo
echo "Currently there are the following players on your whitelist:"
echo
echo ${whitelist:49} | sed 's/, /\n/g'
}
force_exit() { # Kill the server running (messily) in an emergency
echo ""
echo "SIGINIT CALLED - FORCE EXITING!"
pidfile=${MCPATH}/${SCREEN}.pid
rm ${pidfile}
echo "KILLING SERVER PROCESSES!!!"
# Display which processes are being killed
ps aux | grep -e 'java -Xmx' | grep -v grep | awk '{print $2}' | xargs -i echo "Killing PID: " {}
ps aux | grep -e 'SCREEN -dmS minecraft java' | grep -v grep | awk '{print $2}' | xargs -i echo "Killing PID: " {}
ps aux | grep -e '/etc/init.d/minecraft' | grep -v grep | awk '{print $2}' | xargs -i echo "Killing PID: " {}
# Kill the processes
ps aux | grep -e 'java -Xmx' | grep -v grep | awk '{print $2}' | xargs -i kill {}
ps aux | grep -e 'SCREEN -dmS minecraft java' | grep -v grep | awk '{print $2}' | xargs -i kill {}
ps aux | grep -e '/etc/init.d/minecraft' | grep -v grep | awk '{print $2}' | xargs -i kill {}
exit 1
}
get_script_location() {
echo $(dirname "$(readlink -e "$0")")
}
check_permissions() {
as_user "touch $pidfile"
if ! as_user "test -w '$pidfile'" ; then
echo "Check Permissions. Cannot write to $pidfile. Correct the permissions and then execute: $0 status"
fi
}
trap force_exit SIGINT
case "$1" in
start)
# Starts the server
if is_running; then
echo "Server already running."
else
check_links
mc_start
fi
;;
stop)
# Stops the server
if is_running; then
mc_say "SERVER SHUTTING DOWN!"
mc_stop
else
echo "No running server."
fi
;;
restart)
# Restarts the server
if is_running; then
mc_say "SERVER REBOOT IN 10 SECONDS!"
mc_stop
else
echo "No running server, starting it..."
fi
check_links
mc_start
;;
reload)
# Reloads server configuration
if is_running; then
mc_say "Reloading server configuration.."
mc_reload
else
echo "No running server."
fi
;;
whitelist)
if is_running; then
whitelist
else
echo "Server not running."
fi
;;
whitelist-reload)
# Reloads the whitelist
if is_running; then
mc_command "whitelist reload"
else
echo "No running server."
fi
;;
whitelist-add)
# Adds a player to the whitelist
if is_running; then
mc_command "whitelist add $2"
else
echo "No running server."
fi
;;
backup)
# Backups world
if is_running; then
mc_say "Welt wird gesichert..."
mc_saveoff
mc_world_backup
mc_saveon
mc_say "Sicherung abgeschlossen."
else
mc_world_backup
fi
;;
whole-backup)
# Backup everything
if is_running; then
mc_say "VOLLSTÄNDIGES SERVER BACKUP IN 10 SEKUNDEN.";
mc_say "WARNUNG: DER SERVER WIRD HIERFÜR NEU GESTARTET!"
mc_stop
mc_whole_backup
check_links
mc_start
else
mc_whole_backup
fi
;;
save-off)
# Flushes the state of the world to disk, and then disables
# saving until save-on is called (useful if you have your own
# backup scripts).
if is_running; then
mc_saveoff
else
echo "Server was not running, syncing from ram anyway..."
fi
;;
save-on)
# Re-enables saving if it was disabled by save-off.
if is_running; then
mc_saveon
else
echo "No running server."
fi
;;
say)
# Says something to the ingame chat
if is_running; then
shift 1
mc_say "$*"
else
echo "No running server to say anything."
fi
;;
command)
if is_running; then
shift 1
mc_command "$*"
echo "Sent command: $*"
else
echo "No running server to send a command to."
fi
;;
connected)
# Lists connected users
if is_running; then
mc_command list
sleep 1s
# Get server log in reverse order, assume that response to 'list'
# command is already there.
tac ${SERVERLOG} | \
# Extract two lines. 1) containing ASCII color code and comma-separated list
# of player names and 2) the line saying "[...] players online:"
grep --before-context 1 --max-count 1 "players online" | \
# Throw away the latter line.
head -n 1 | \
# Remove any escape character and the following two bytes (color code).
sed 's/[\x01-\x1F\x7F]..//g' | \
# Only pass through lines that still have content (if no player online,
# then nothing's left over after this grep.
grep . | \
# Replace ", " separator with newline char.
sed 's/, /\n/g'
else
echo "No running server."
fi
;;
playercount)
# List number of connected users.
if is_running; then
mc_command list
sleep 1s
# Same as technique as 'connected' command, but count lines.
tac ${SERVERLOG} | \
grep --before-context 1 --max-count 1 "players online" | \
head -n 1 | sed 's/[\x01-\x1F\x7F]..//g' | grep . | sed 's/, /\n/g' | wc -l
else
echo "No running server."
fi
;;
log)
# Display server log using 'cat'.
cat ${SERVERLOG}
;;
last)
# Greps for recently logged in users
echo Recently logged in users:
cat ${SERVERLOG} | awk '/entity|conn/ {sub(/lost/,"disconnected");print $1,$2,$4,$5}'
;;
status)
# Shows server status
if is_running
then
echo "$SERVICE is running."
else
echo "$SERVICE is not running."
fi
;;
links)
check_links
;;
worlds)
get_worlds
for INDEX in ${!WORLDNAME[@]}
do
echo ${WORLDNAME[$INDEX]}
done
;;
overviewer)
if is_running; then
mc_say "Generating overviewer map."
mc_saveoff
overviewer_copy_worlds
mc_saveon
overviewer_start $2
else
overviewer_copy_worlds
overviewer_start $2
fi
;;
screen)
if is_running; then
as_user "script /dev/null -q -c \"screen -rx $SCREEN\""
else
echo "Server is not running. Do you want to start it?"
echo "Please put \"Yes\", or \"No\": "
read START_SERVER
case "$START_SERVER" in
[Yy]|[Yy][Ee][Ss])
check_links
mc_start
as_user "script /dev/null -q -c \"screen -rx $SCREEN\""
;;
[Nn]|[Nn][Oo])
clear
echo "Aborting startup!"
sleep 1
clear
exit 1
;;
*)
clear
echo "Invalid input"
sleep 1
clear
exit 1
;;
esac
fi
;;
kill)
WIDTH=$(stty size | cut -d ' ' -f 2) # Get terminal's character width
pstree | grep MDSImporte | cut -c 1-${WIDTH} # Chop output after WIDTH chars
echo "Killing the server is an EMERGENCY procedure, and should not be used to perform a normal shutdown! All changes younger than 15 minutes could be permanently lost and WORLD CORRUPTION is possible! Are you ABSOLUTELY POSITIVE this is what you want to do?"
echo "Please put \"Yes\", or \"No\": "
read KILL_SERVER
case "$KILL_SERVER" in # Determine which option was specified
[Yy]|[Yy][Ee][Ss]) # If yes, kill the server
echo "KILLING SERVER PROCESSES!!!"
force_exit
exit 1
;;
[Nn]|[Nn][Oo]) # If no, abort and exit 1
echo "Aborting!"
exit 1
;;
*) # If anything else, exit 1
echo "Error: Invalid Input!"
exit 1
;;
esac
;;
help|--help|-h)
cat <<EOF >&2
Usage: $0 COMMAND
Available commands:
start Starts the server
stop Stops the server
kill Kills the server
restart Restarts the server
reload Reloads the server configuration
backup Backups the worlds defined in the script
whole-backup Backups the entire server folder
log Prints the server log
save-off Flushes the world to disk and then disables saving
save-on Re-enables saving if it was previously disabled by save-off
say Prints the given string to the ingame chat
connected Lists connected users
playercount Prints the number of connected users
status Displays server status
links Creates necessary symlinks
last Displays recently connected users
worlds Displays a list of available worlds
overviewer WORLD Creates a map of the WORLD with Minecraft-Overviewer
whitelist Prints the current whitelist
whitelist-add NAME Adds the specified player to the server whitelist
whitelist-reload Reloads the whitelist
screen Shows the server screen
EOF
;;
*)
echo "No such command, see $0 help"
exit 1
;;
esac
exit 0