forked from hexparrot/mineos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mineos.py
1546 lines (1310 loc) · 57 KB
/
mineos.py
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python2.7
"""
A python script to manage minecraft servers.
Designed for use with MineOS: http://minecraft.codeemo.com
"""
__author__ = "William Dizon"
__license__ = "GNU GPL v3.0"
__version__ = "0.6.0"
__email__ = "wdchromium@gmail.com"
import os
from conf_reader import config_file
from collections import namedtuple
from distutils.spawn import find_executable
from functools import wraps
def sanitize(fn):
"""Checks that attempted CLI commands have all required fields.
Raises RuntimeError if false.
"""
@wraps(fn)
def wrapper(self, *args, **kwargs):
return_func = fn(self, *args, **kwargs)
if None in self.previous_arguments.values():
raise RuntimeError('Missing value in %s: %s' % (fn.__name__,str(self.previous_arguments)))
return return_func
return wrapper
def server_exists(state):
"""Decorator to ensure that the command being executed
has a created working directory.
Accepts: True/False
Raises RuntimeWarning if expected value != actual value.
"""
def dec(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
if (self.server_name in self.list_servers(self.base)) == state:
fn(self, *args, **kwargs)
else:
if state:
raise RuntimeWarning('Ignoring {%s}: server not found "%s"' % (fn.__name__,self.server_name))
else:
raise RuntimeWarning('Ignoring {%s}: server already exists "%s"' % (fn.__name__,self.server_name))
return wrapper
return dec
def server_up(up):
"""Decorator to ensure attempted command is currently running
Accepts: True/False
Raises RuntimeError if expected state != actual state
"""
def dec(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
if self.up == up:
fn(self, *args, **kwargs)
else:
if up:
raise RuntimeError('Server must be running to perform this action.')
else:
raise RuntimeError('Server may not be running when performing this action.')
return wrapper
return dec
class mc(object):
NICE_VALUE = 10
COMMIT_DELAY = 10
DEFAULT_PATHS = {
'servers': 'servers',
'backup': 'backup',
'archive': 'archive',
'profiles': 'profiles',
'import': 'import'
}
BINARY_PATHS = {
'rdiff-backup': find_executable('rdiff-backup'),
'rsync': find_executable('rsync'),
'screen': find_executable('screen'),
'java': find_executable('java'),
'nice': find_executable('nice'),
'tar': find_executable('tar'),
'kill': find_executable('kill'),
'wget': find_executable('wget'),
}
LOG_PATHS = {
'legacy': 'server.log',
'current': os.path.join('logs', 'latest.log'),
'bungee': 'proxy.log.0',
'forgemod': 'ForgeModLoader-server-0.log'
}
def __init__(self,
server_name,
owner=None,
base_directory=None):
from getpass import getuser
self._server_name = self.valid_server_name(server_name)
self._owner = owner or getuser()
self._base_directory = base_directory or os.path.expanduser("~")
self._set_environment()
try:
self._load_config(generate_missing=True)
except RuntimeError:
pass
else:
if self.server_config.has_option('java', 'java_bin'):
self.upgrade_old_config()
def _set_environment(self):
"""Sets the most common short-hand paths for the minecraft directories
and configuration files.
"""
self.server_properties = None
self.server_config = None
self.profile_config = None
self.env = {
'cwd': os.path.join(self.base, self.DEFAULT_PATHS['servers'], self.server_name),
'bwd': os.path.join(self.base, self.DEFAULT_PATHS['backup'], self.server_name),
'awd': os.path.join(self.base, self.DEFAULT_PATHS['archive'], self.server_name),
'pwd': os.path.join(self.base, self.DEFAULT_PATHS['profiles'])
}
self.env.update({
'sp': os.path.join(self.env['cwd'], 'server.properties'),
'sc': os.path.join(self.env['cwd'], 'server.config'),
'pc': os.path.join(self.base, self.DEFAULT_PATHS['profiles'], 'profile.config'),
'sp_backup': os.path.join(self.env['bwd'], 'server.properties'),
'sc_backup': os.path.join(self.env['bwd'], 'server.config')
})
for server_type, lp in sorted(self.LOG_PATHS.iteritems()):
#implementation detail; sorted() depends on 'current' always preceeding 'legacy',
#to ensure that current is always tested first in the event both logfiles exist.
path = os.path.join(self.env['cwd'], lp)
if os.path.isfile(path):
self.env['log'] = path
self._server_type = server_type
break
else:
self._server_type = 'unknown'
def _load_config(self, load_backup=False, generate_missing=False):
"""Loads server.properties and server.config for a given server.
With load_backup, /backup/ is referred to rather than /servers/.
generate_missing will create one and only one missing configuration
with hard-coded defaults. generate_missing currently should
only be utilized as a fallback when starting a server.
"""
def load_sp():
self.server_properties = config_file(self.env['sp_backup']) if load_backup else config_file(self.env['sp'])
self.server_properties.use_sections(False)
return self.server_properties[:]
def load_sc():
self.server_config = config_file(self.env['sc_backup']) if load_backup else config_file(self.env['sc'])
return self.server_config[:]
def load_profiles():
self.profile_config = config_file(self.env['pc'])
return self.profile_config[:]
load_sc()
load_sp()
load_profiles()
if generate_missing and not load_backup:
if self.server_properties[:] and self.server_config[:]:
pass
elif self.server_properties[:] and not self.server_config[:]:
self._create_sc()
load_sc()
elif self.server_config[:] and not self.server_properties[:]:
self._create_sp()
load_sp()
else:
raise RuntimeError('No config files found: server.properties or server.config')
def upgrade_old_config(self):
"""Checks server.config for obsolete attributes from previous versions"""
def extract():
"""Extracts relevant attributes from old config"""
from ConfigParser import NoOptionError, NoSectionError
from collections import defaultdict
new_config = defaultdict(dict)
kept_attributes = {
'onreboot': ['restore', 'start'],
'java': ['java_tweaks', 'java_xmx', 'java_xms']
}
for section in kept_attributes:
for option in kept_attributes[section]:
try:
new_config[section][option] = self.server_config[section:option]
except (KeyError, NoOptionError, NoSectionError):
pass
return dict(new_config)
self._command_direct('rm -- %s' % self.env['sc'], self.env['cwd'])
self._create_sc(extract())
self._load_config()
@server_exists(True)
def _create_sp(self, startup_values={}):
"""Creates a server.properties file for the server given a dict.
startup_values is expected to have more options than
server.properties should have, so provided startup_values
are only used if they overwrite an option already
hardcoded in the defaults dict.
Expected startup_values should match format of "defaults".
"""
defaults = {
'server-port': 25565,
'max-players': 20,
'level-seed': '',
'gamemode': 0,
'difficulty': 1,
'level-type': 'DEFAULT',
'level-name': 'world',
'max-build-height': 256,
'generate-structures': 'false',
'generator-settings': '',
'server-ip': '0.0.0.0',
}
sanitize_integers = set(['server-port',
'max-players',
'gamemode',
'difficulty'])
for option in sanitize_integers:
try:
defaults[option] = int(startup_values[option])
except (KeyError, ValueError):
continue
for option, value in startup_values.iteritems():
if option not in sanitize_integers:
defaults[option] = value
self._command_direct('touch %s' % self.env['sp'], self.env['cwd'])
with config_file(self.env['sp']) as sp:
sp.use_sections(False)
for key, value in defaults.iteritems():
sp[key] = str(value)
def _create_sc(self, startup_values={}):
"""Creates a server.config file for a server given a dict.
Expected startup_values should match format of "defaults".
"""
defaults = {
'minecraft': {
'profile': '',
},
'crontabs': {
'archive_interval': 0,
'backup_interval': 0,
},
'onreboot': {
'restore': False,
'start': False,
},
'java': {
'java_tweaks': '',
'java_xmx': 256,
'java_xms': 256,
}
}
sanitize_integers = set([('java', 'java_xmx'),
('java', 'java_xms'),
])
d = defaults.copy()
d.update(startup_values)
for section, option in sanitize_integers:
try:
d[section][option] = int(startup_values[section][option])
except (KeyError, ValueError):
d[section][option] = defaults[section][option]
self._command_direct('touch %s' % self.env['sc'], self.env['cwd'])
with config_file(self.env['sc']) as sc:
for section in d:
sc.add_section(section)
for option in d[section]:
sc[section:option] = str(d[section][option])
@server_exists(False)
def create(self, sc={}, sp={}):
"""Creates a server's directories and generates configurations."""
for d in ('cwd', 'bwd', 'awd'):
self._make_directory(self.env[d], True)
sc = sc if type(sc) is dict else {}
sp = sp if type(sp) is dict else {}
self._create_sc(sc)
self._create_sp(sp)
self._load_config()
@server_exists(True)
def modify_config(self, option, value, section=None):
"""Modifies a value in server.properties or server.config"""
if section:
with self.server_config as sc:
sc[section:option] = value
else:
with self.server_properties as sp:
sp[option] = value
def modify_profile(self, option, value, section):
"""Modifies a value in profile.config
Whitelisted values that can be changed.
"""
if option in ['desc']:
with self.profile_config as pc:
pc[section:option] = value
@server_exists(True)
@server_up(False)
def start(self):
"""Checks if a server is running on its bound IP:PORT
and if not, starts the screen+java instances.
"""
if self.port in [s.port for s in self.list_ports_up()]:
if (self.port, self.ip_address) in [(s.port, s.ip_address) for s in self.list_ports_up()]:
raise RuntimeError('Ignoring {start}; server already up at %s:%s.' % (self.ip_address, self.port))
elif self.ip_address == '0.0.0.0':
raise RuntimeError('Ignoring {start}; can not listen on (0.0.0.0) if port %s already in use.' % self.port)
elif any(s for s in self.list_ports_up() if s.ip_address == '0.0.0.0'):
raise RuntimeError('Ignoring {start}; server already listening on ip address (0.0.0.0).')
self._load_config(generate_missing=True)
if not self.profile_current:
self.profile = self.profile
self._command_direct(self.command_start, self.env['cwd'])
@server_exists(True)
@server_up(True)
def kill(self):
"""Kills a server instance by SIGTERM"""
self._command_direct(self.command_kill, self.env['cwd'])
@server_exists(True)
@server_up(True)
def commit(self):
"""Commit a server's memory to disk"""
self._command_stuff('save-all')
@server_exists(True)
def archive(self):
"""Creates a timestamped, gzipped tarball of the server contents."""
self._make_directory(self.env['awd'])
if self.up:
self._command_stuff('save-off')
self._command_direct(self.command_archive, self.env['cwd'])
self._command_stuff('save-on')
else:
self._command_direct(self.command_archive, self.env['cwd'])
@server_exists(True)
def backup(self):
"""Creates an rdiff-backup of a server."""
self._make_directory(self.env['bwd'])
if self.up:
self._command_stuff('save-off')
self._command_stuff('save-all')
self._command_direct(self.command_backup, self.env['cwd'])
self._command_stuff('save-on')
else:
self._command_direct(self.command_backup, self.env['cwd'])
@server_exists(True)
@server_up(False)
def restore(self, step='now', force=False):
"""Overwrites the /servers/ version of a server with the /backup/."""
from subprocess import CalledProcessError
self._load_config(load_backup=True)
if self.server_properties or self.server_config:
force = '--force' if force else ''
self._make_directory(self.env['cwd'])
try:
self._command_direct(self.command_restore(step,force), self.env['cwd'])
except CalledProcessError as e:
raise RuntimeError(e.output)
self._load_config(generate_missing=True)
else:
raise RuntimeError('Ignoring command {restore}; Unable to locate backup')
@server_exists(False)
def import_server(self, path, filename):
""" Extracts an existing archive into the live space.
Might need additional review if run as root by server.py
"""
import tarfile, zipfile
filepath = os.path.join(path, filename)
if tarfile.is_tarfile(filepath):
archive_ = tarfile.open(filepath, mode='r')
members_ = archive_.getnames()
prefix_ = os.path.commonprefix(members_)
elif zipfile.is_zipfile(filepath):
archive_ = zipfile.ZipFile(filepath, 'r')
members_ = archive_.namelist()
prefix_ = os.path.commonprefix(members_)
else:
raise NotImplementedError('Ignoring command {import_server};'
'archive file must be compressed tar or zip')
if any(f for f in members_ if f.startswith('/') or '..' in f):
raise RuntimeError('Ignoring command {import_server};'
'archive contains files with absolute path or ..')
archive_.extractall(self.env['cwd'])
if not os.path.samefile(self.env['cwd'], os.path.join(self.env['cwd'], prefix_)):
prefixed_dir = os.path.join(self.env['cwd'], prefix_)
from distutils.dir_util import copy_tree
copy_tree(prefixed_dir, self.env['cwd'])
from shutil import rmtree
rmtree(prefixed_dir)
self._load_config(generate_missing=True)
@server_exists(True)
def prune(self, step):
"""Removes old rdiff-backup data/metadata."""
self._command_direct(self.command_prune(step), self.env['bwd'])
def prune_archives(self, filename):
"""Removes old archives by filename as a space-separated string."""
self._command_direct(self.command_delete_files(filename), self.env['awd'])
@server_exists(True)
@server_up(False)
def delete_server(self):
"""Deletes server files from system"""
self._command_direct(self.command_delete_server, self.env['pwd'])
def remove_profile(self, profile):
"""Removes a profile found in profile.config at the base_directory root"""
try:
if self.has_ownership(self._owner, self.env['pc']):
from shutil import rmtree
rmtree(os.path.join(self.env['pwd'], profile))
with self.profile_config as pc:
pc.remove_section(profile)
except OSError as e:
from errno import ENOENT
if e.errno == ENOENT:
with self.profile_config as pc:
pc.remove_section(profile)
else:
raise RuntimeError('Ignoring command {remove_profile}; User does not have permissions on this profile')
def define_profile(self, profile_dict):
"""Accepts a dictionary defining how to download and run a piece
of Minecraft server software.
profile_dict = {
'name': 'vanilla',
'type': 'standard_jar',
'url': 'https://s3.amazonaws.com/Minecraft.Download/versions/1.6.2/minecraft_server.1.6.2.jar',
'save_as': 'minecraft_server.jar',
'run_as': 'minecraft_server.jar',
'ignore': '',
}
"""
profile_dict['run_as'] = self.valid_filename(os.path.basename(profile_dict['run_as']))
if profile_dict['type'] == 'unmanaged':
for i in ['save_as', 'url', 'ignore']:
profile_dict[i] = ''
else:
profile_dict['save_as'] = self.valid_filename(os.path.basename(profile_dict['save_as']))
with self.profile_config as pc:
from ConfigParser import DuplicateSectionError
try:
pc.add_section(profile_dict['name'])
except DuplicateSectionError:
pass
for option, value in profile_dict.iteritems():
if option != 'name':
pc[profile_dict['name']:option] = value
def update_profile(self, profile, expected_md5=None):
"""Download's a profile via the provided URL.
If expected_md5 is provided, it can either:
1) reject downloads not matching expected md5
2) avoid unnecessary download if existing md5 == expected md5
"""
self._make_directory(os.path.join(self.env['pwd'], profile))
profile_dict = self.profile_config[profile:]
if profile_dict['type'] == 'unmanaged':
raise RuntimeWarning('No action taken; unmanaged profile')
elif profile_dict['type'] in ['archived_jar', 'standard_jar']:
with self.profile_config as pc:
pc[profile:'save_as'] = self.valid_filename(os.path.basename(pc[profile:'save_as']))
pc[profile:'run_as'] = self.valid_filename(os.path.basename(pc[profile:'run_as']))
old_file_path = os.path.join(self.env['pwd'], profile, profile_dict['save_as'])
try:
old_file_md5 = self._md5sum(old_file_path)
except IOError:
old_file_md5 = None
finally:
if expected_md5 and old_file_md5 == expected_md5:
raise RuntimeWarning('Did not download; expected md5 == existing md5')
new_file_path = os.path.join(self.env['pwd'], profile, profile_dict['save_as'] + '.new')
from subprocess import CalledProcessError
try:
self._command_direct(self.command_wget_profile(profile),
os.path.join(self.env['pwd'], profile))
except CalledProcessError:
self._command_direct(self.command_wget_profile(profile, True),
os.path.join(self.env['pwd'], profile))
new_file_md5 = self._md5sum(new_file_path)
if expected_md5 and expected_md5 != new_file_md5:
raise RuntimeError('Discarding download; expected md5 != actual md5')
elif old_file_md5 == new_file_md5:
os.unlink(new_file_path)
raise RuntimeWarning('Discarding download; new md5 == existing md5')
'''elif self.profile_config[profile:'save_as_md5'] == new_file_md5:
potentially removable.
os.unlink(new_file_path)
raise RuntimeWarning('Discarding download; new md5 == existing md5')'''
if profile_dict['type'] == 'archived_jar':
import zipfile, tarfile
if zipfile.is_zipfile(new_file_path):
with zipfile.ZipFile(new_file_path, mode='r') as zipchive:
zipchive.extractall(os.path.join(self.env['pwd'], profile))
elif tarfile.is_tarfile(new_file_path):
with tarfile.open(new_file_path, mode='r') as tarchive:
tarchive.extractall(os.path.join(self.env['pwd'], profile))
new_run_as = os.path.join(os.path.join(self.env['pwd'], profile, profile_dict['run_as']))
with self.profile_config as pc:
pc[profile:'save_as_md5'] = new_file_md5
pc[profile:'run_as_md5'] = self._md5sum(new_run_as)
os.unlink(new_file_path)
return new_file_md5
elif profile_dict['type'] == 'standard_jar':
from shutil import move
move(new_file_path, old_file_path)
active_md5 = self._md5sum(old_file_path)
with self.profile_config as pc:
pc[profile:'save_as_md5'] = active_md5
pc[profile:'run_as_md5'] = active_md5
return self._md5sum(old_file_path)
else:
raise NotImplementedError("This type of profile is not implemented yet.")
@staticmethod
def server_version(filepath, guess=''):
"""Extract server version from jarfile and fallback
to guessing by URL"""
import zipfile
from xml.dom.minidom import parseString
try:
with zipfile.ZipFile(filepath, 'r') as zf:
files = zf.namelist()
for internal_path in [r'META-INF/maven/org.bukkit/craftbukkit/pom.xml',
r'META-INF/maven/mcpc/mcpc-plus-legacy/pom.xml',
r'META-INF/maven/mcpc/mcpc-plus/pom.xml',
r'META-INF/maven/org.spigotmc/spigot/pom.xml',
r'META-INF/maven/net.md-5/bungeecord-api/pom.xml']:
if internal_path in files:
try:
xml = parseString(zf.read(internal_path))
return xml.getElementsByTagName('version')[0].firstChild.nodeValue
except (IndexError, KeyError, AttributeError):
continue
except IOError:
return ''
else:
import re
match = re.match('https://s3.amazonaws.com/Minecraft.Download/versions/([^/]+)', guess)
try:
return match.group(1)
except AttributeError:
return ''
#actual command execution methods
@staticmethod
def _demote(user_uid, user_gid):
"""Closure for _command_direct and _command_stuff that changes
current user to that of self._owner.pd_{uid,gid}
Usually this will demote, when this script is running as root,
otherwise it will set its gid and uid to itself.
"""
def set_ids():
os.umask(2)
os.setgid(user_gid)
os.setuid(user_uid)
return set_ids
def _command_direct(self, command, working_directory):
"""Opens a subprocess and executes a command as the user
specified in self._owner.
"""
from subprocess import check_output, STDOUT
from shlex import split
return check_output(split(command),
cwd=working_directory,
stderr=STDOUT,
preexec_fn=self._demote(self.owner.pw_uid, self.owner.pw_gid))
@server_exists(True)
@server_up(True)
def _command_stuff(self, stuff_text):
"""Opens a subprocess and stuffs text to an open screen as the user
specified in self._owner.
"""
from subprocess import check_call
from shlex import split
command = """%s -S %d -p 0 -X eval 'stuff "%s\012"'""" % (self.BINARY_PATHS['screen'],
self.screen_pid,
stuff_text)
check_call(split(command),
preexec_fn=self._demote(self.owner.pw_uid, self.owner.pw_gid))
#validation checks
@staticmethod
def valid_server_name(name):
"""Checks if a server name is only alphanumerics, underscores or dots."""
from string import ascii_letters, digits
valid_chars = set('%s%s_.' % (ascii_letters, digits))
if not name:
raise ValueError('Servername must be a string at least 1 length')
elif any(c for c in name if c not in valid_chars):
raise ValueError('Servername contains invalid characters')
elif name.startswith('.'):
raise ValueError('Servername may not start with "."')
return name
@staticmethod
def valid_filename(filename):
"""Checks filename against whitelist-safe characters"""
from string import ascii_letters, digits
valid_chars = set('%s%s-_.' % (ascii_letters, digits))
if not filename:
raise ValueError('Filename is empty')
elif any(c for c in filename if c not in valid_chars):
raise ValueError('Disallowed characters in filename "%s"' % filename)
elif filename.startswith('.'):
raise ValueError('Files should not be hidden: "%s"' % filename)
return filename
''' properties '''
@property
def server_name(self):
"""Returns the name of the server."""
return self._server_name
@property
def base(self):
"""Returns the root path of the server."""
return self._base_directory
@property
def owner(self):
"""Returns pwd named tuple"""
from pwd import getpwnam
return getpwnam(self._owner)
@property
def up(self):
"""Returns True if the server has a running process."""
return any(s.server_name == self.server_name for s in self.list_servers_up())
@property
def java_pid(self):
"""Returns the process id of the server's java instance."""
for server, java_pid, screen_pid, base_dir in self.list_servers_up():
if self.server_name == server:
return java_pid
else:
return None
@property
def screen_pid(self):
"""Returns the process id of the server's screen instance."""
for server, java_pid, screen_pid, base_dir in self.list_servers_up():
if self.server_name == server:
return screen_pid
else:
return None
@property
def profile(self):
"""Returns the profile the server is set to"""
try:
return self.server_config['minecraft':'profile'] or None
except KeyError:
return None
@profile.setter
def profile(self, profile):
"""Sets a profile for a server, checking that the profile
exists as an entry in 'profile.config'"""
try:
self.profile_config[profile:]
except KeyError:
raise KeyError('There is no defined profile "%s" in profile.config' % profile)
else:
with self.server_config as sc:
from ConfigParser import DuplicateSectionError
try:
sc.add_section('minecraft')
except DuplicateSectionError:
pass
finally:
sc['minecraft':'profile'] = str(profile).strip()
self._command_direct(self.command_apply_profile(profile), self.env['cwd'])
@property
def profile_current(self):
"""Checks that the expected md5 of a server jar matches the one
in the LIVE SERVER DIRECTORY (e.g., update newer than executed)
"""
def compare(profile):
return self._md5sum(os.path.join(self.env['pwd'],
profile,
self.profile_config[current:'run_as'])) == \
self._md5sum(os.path.join(self.env['cwd'],
self.profile_config[current:'run_as']))
try:
current = self.profile
if current == 'unmanaged':
path_ = os.path.join(self.env['cwd'], self.profile_config[self.profile:'run_as'])
if not os.path.isfile(path):
raise RuntimeError('%s does not exist' % path_)
else:
return True
return compare(current)
except TypeError:
raise RuntimeError('Server is not assigned a valid profile.')
except IOError as e:
from errno import ENOENT
if e.errno == ENOENT:
self.profile = current
return compare(current)
@property
def port(self):
"""Returns the port value from server.properties at time of instance creation."""
try:
return int(self.server_properties['server-port'])
except (ValueError, KeyError):
''' KeyError: server-port option does not exist
ValueError: value is not an integer
exception Note: when value is absent or not an int, vanilla
adds/replaces the value in server.properties to 25565'''
return 25565
@property
def ip_address(self):
"""Returns the ip address value from server.properties at time of instance creation.
This may return '0.0.0.0' even if that is not the value in the file,
because it is the effective value vanilla minecraft will run at.
"""
return self.server_properties['server-ip'::'0.0.0.0'] or '0.0.0.0'
''' If server-ip is absent, vanilla starts at *,
which is effectively 0.0.0.0 and
also adds 'server-ip=' to server.properties.'''
@property
def memory(self):
"""Returns the amount of memory the java instance is using (VmRSS)"""
def bytesto(num, to, bsize=1024):
"""convert bytes to megabytes, etc.
sample code:
print('mb= ' + str(bytesto(314575262000000, 'm')))
sample output:
mb= 300002347.946
https://gist.github.com/shawnbutts/3906915
"""
a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
r = float(num)
for i in range(a[to]):
r = r / bsize
return r
from procfs_reader import entries
try:
mem_str = dict(entries(self.java_pid, 'status'))['VmRSS']
mem = int(mem_str.split()[0]) * 1024
return '%s MB' % bytesto(mem, 'm')
except IOError:
return '0'
@property
def ping(self):
"""Returns a named tuple using the current Minecraft protocol
to retreive versions, player counts, etc"""
import socket
def server_list_packet():
"""Guesses what version minecraft a live server directory is."""
if self.server_milestone_short in ['1.5', '1.6'] or \
(self.server_type == 'forgemod' and self.server_milestone == 'unknown'):
return '\xfe' \
'\x01' \
'\xfa' \
'\x00\x06' \
'\x00\x6d\x00\x69\x00\x6e\x00\x65\x00\x6f\x00\x73' \
'\x00\x19' \
'\x49' \
'\x00\x09' \
'\x00\x6c\x00\x6f\x00\x63\x00\x61\x00\x6c\x00\x68' \
'\x00\x6f\x00\x73\x00\x74' \
'\x00\x00\x63\xdd'
else:
return '\xfe\x01'
server_ping = namedtuple('ping', ['protocol_version',
'server_version',
'motd',
'players_online',
'max_players'])
if self.server_type == 'bungee':
return server_ping(None,None,'','0',1)
elif self.up:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.ip_address, self.port))
s.send(server_list_packet())
d = s.recv(1024)
s.shutdown(socket.SHUT_RDWR)
except socket.error:
return server_ping(None,None,self.server_properties['motd'::''],
'-1',self.server_properties['max-players'])
finally:
s.close()
assert d[0] == '\xff'
d = d[3:].decode('utf-16be')
assert d[:3] == u'\xa7\x31\x00'
segments = d[3:].split('\x00')
return server_ping(*segments)
else:
if self.server_name in self.list_servers(self.base):
return server_ping(None,None,self.server_properties['motd'::''],
'0',self.server_properties['max-players'])
else:
raise RuntimeWarning('Server not found "%s"' % self.server_name)
@property
def sp(self):
"""Returns the entire server.properties in a dictionary"""
return self.server_properties[:]
@property
def sc(self):
"""Returns the entire server.config in a dictionary"""
return self.server_config[:]
@property
def server_type(self):
"""Returns best guess of server type"""
return self._server_type
@property
def server_milestone(self):
"""Returns best guessed server major and minor versions"""
jar_file = self.valid_filename(self.profile_config[self.profile:'run_as'])
jar_path = os.path.join(self.env['cwd'], jar_file)
return self.server_version(jar_path,
self.profile_config[self.profile:'url']) or 'unknown'
@property
def server_milestone_short(self):
"""Returns short version of server_milestone major/minor"""
import re
try:
version = re.match(r'(\d)\.(\d)', self.server_milestone)
return '%s.%s' % (version.group(1), version.group(2))
except (AttributeError, TypeError):
return '0.0'
@property
def ping_debug(self):
"""Returns helpful debug information for web-ui ping() issues"""
return ' '.join([
self.server_type,
'(%s) -' % self.server_milestone_short,
self.server_milestone,
])
# shell command constructor properties
@property
def previous_arguments(self):
"""Returns the dict used to construct a CLI command
This method only works AFTER running the command_*
and its primary use is to intercept incomplete commands
in a wrapper before execution"""
try:
return self._previous_arguments
except AttributeError:
return {}
@property
@sanitize
def command_start(self):
"""Returns the actual command used to start up a minecraft server."""
required_arguments = {
'screen_name': 'mc-%s' % self.server_name,
'screen': self.BINARY_PATHS['screen'],
'java': self.BINARY_PATHS['java'],
'java_xmx': self.server_config['java':'java_xmx'],
'java_xms': self.server_config['java':'java_xmx'],
'java_tweaks': self.server_config['java':'java_tweaks':''],
'jar_args': 'nogui'
}
try:
jar_file = self.valid_filename(self.profile_config[self.profile:'run_as'])
required_arguments['jar_file'] = os.path.join(self.env['cwd'], jar_file)
required_arguments['jar_args'] = self.profile_config[self.profile:'jar_args':'']
except (TypeError,ValueError):
required_arguments['jar_file'] = None
required_arguments['jar_args'] = None
try:
java_xms = self.server_config['java':'java_xms'].strip()
assert 0 < int(java_xms) <= int(required_arguments['java_xmx'])
required_arguments['java_xms'] = java_xms
except (KeyError,AttributeError,ValueError,AssertionError):
pass
self._previous_arguments = required_arguments
return '%(screen)s -dmS %(screen_name)s ' \
'%(java)s -server -Xmx%(java_xmx)sM -Xms%(java_xms)sM %(java_tweaks)s ' \
'-jar %(jar_file)s %(jar_args)s' % required_arguments
@property
@sanitize
def command_debug(self):