#!/usr/bin/env python3 import os import sys import re import subprocess import signal import time import datetime import traceback import atexit from threading import Thread from threading import Timer import importlib.machinery as imp ################################################################################# # Exit codes and prints helpers _EC_OK = 0 _EC_ARG_UNKNOWN = 1 _EC_ARG_MULTIPLE_CONFIG = 2 _EC_MISSING_CONFIGURATION = 10 _EC_SERVER_RUNNING = 11 def info(message, minverbose = 0): "Prints message to stdout if minverbose >= verbose_level" try: if conf.verbose_level >= minverbose: print(message) except NameError: print(message) def warning(message, minverbose = -1): "Prints message to stderr if minverbose >= verbose_level" try: if conf.verbose_level >= minverbose: print(message, file=sys.stderr) except NameError: print(message, file=sys.stderr) def error(message, minverbose = -2, ec = -1): "Prints message to stderr if minverbose >= verbose_level" try: if conf.verbose_level >= minverbose: print(message, file=sys.stderr) except NameError: print(message, file=sys.stderr) # TODO rather throw exception and handle it globally sys.exit(ec) ################################################################################# # Load configuration __all_config_files__ = ( 'mcwrapper.conf', '~/.mcwrapper.conf', '~/.config/mcwrapper.conf', '/etc/mcwrapper.conf', ) def load_conf(config_file): "Load config_file to conf variable. Or if it has value None, search on default paths" global conf def __set_empty_config__(): global conf warning('User configuration not loaded. Using default.') conf = type('default config', (object,), {}) if config_file == None: # Find configuration in predefined paths for cf in __all_config_files__: if os.path.isfile(os.path.expanduser(cf)): config_file = os.path.expanduser(cf) break if config_file == None: # If no configuration find. Set empty config __set_empty_config__() else: # else load configuration try: conf = imp.SourceFileLoader("conf", config_file).load_module() except Exception: traceback.print_exc() __set_empty_config__() # Set additional runtime configuration variables if not 'verbose_level' in vars(conf): conf.verbose_level = 0 def conf_setserver(server): "Check and set configuration for server specified as agument." try: srv = vars(conf)[server]; except KeyError: error("No configuration class found for server: " + server, ec = _EC_MISSING_CONFIGURATION) if not 'timeout' in vars(srv): srv.timeout = 0 if not 'directory' in vars(srv): error('Missing "directory" config for server ' + server, ec = _EC_MISSING_CONFIGURATION) if not 'command' in vars(srv): error('Missing server start command for server ' + server, ec = _EC_MISSING_CONFIGURATION) if not 'statusdir' in vars(srv): srv.statusdir = '/dev/shm/mcwrapper-' + server return srv ################################################################################# # Minecraft server _mcservers = [] __STATUSSTRINGS__ = { 0: "Not running", 1: "Starting", 2: "Running", 3: "Stopping", } class MCServer: def __init__(self, identifier): _mcservers.append(self) self.identifier = identifier self.players = set() self.status = 0 self.conf = conf_setserver(identifier) self.inputPipe = self.conf.statusdir + '/input_pipe' self.statusFile = self.conf.statusdir + '/status' self.playersFile = self.conf.statusdir + '/players' self.pidfile = self.conf.statusdir + '/server.pid' if type(self.conf.command) != str: self.conf.command = ' '.join(self.conf.command) info(self.identifier + ": Server wrapper initializing") info(self.identifier + ": Folder: " + self.conf.directory, 1) info(self.identifier + ": Start command: " + self.conf.command, 1) try: os.mkdir(self.conf.statusdir) except FileExistsError: pass try: os.mkfifo(self.inputPipe, 0o640) except FileExistsError: pass if os.path.isfile(self.pidfile): with open(self.pidfile) as f: lpid = int(f.readline()) try: os.kill(lpid, 0) except OSError: warning(self.identifier + ": Detected forced termination of " "previous server wrapper instance.") else: error(self.identifier + ": Another wrapper is running with given identifier.", -1, _EC_SERVER_RUNNING) with open(self.statusFile, 'w') as f: f.write(__STATUSSTRINGS__[0] + '\n') with open(self.playersFile, 'w') as f: pass self.inputThread = __MCServerInputThread__(self) self.outpuThread = __MCServerOutputThread__(self) def __del__(self): info(self.identifier + ": Server wrapper clean.") _mcservers.remove(self) try: os.remove(self.inputPipe) except FileNotFoundError: pass try: os.remove(self.statusFile) except FileNotFoundError: pass try: os.remove(self.playersFile) except FileNotFoundError: pass if os.path.isfile(self.pidfile): os.remove(self.pidfile) def start(self): "Start Minecraft server" self.prc = subprocess.Popen(self.conf.command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, start_new_session=False, cwd=os.path.expanduser(self.conf.directory)) with open(self.pidfile, "w") as f: f.write(str(self.prc.pid)) self.status = 1 with open(self.statusFile, 'w') as f: f.write(__STATUSSTRINGS__[1] + '\n') if self.inputThread.is_alive() or self.outpuThread.is_alive(): # TODO throw exception return self.inputThread.start() self.inputThread.wake() # Input thread is stuck in waiting for first line self.outpuThread.start() def stop(self): if self.running(): self.prc.stdin.write(bytes("/stop\n", sys.getdefaultencoding())) self.prc.stdin.flush() def running(self): "Returns True if mc server is running. Othervise False." if self.status != 0: return True else: return False def write_to_terminal(self, text): "Write to server terminal. If server not running it does nothing" if self.running(): info(self.identifier + ": Input: " + ln, 1) self.prc.write(bytes(line, sys.getdefaultencoding())) self.prc.flush() def join(self): "Join execution untill server exits." self.outpuThread.join() self.inputThread.join() def __autoshutdown_enable__(self): if (self.conf.timeout > 0): info(self.identifier + ": Automatic shutdown after " + str(self.conf.timeout) + " min.") self.shutdownTimeout = Timer(self.conf.timeout * 60.0, self.stop) self.shutdownTimeout.start(); def __autoshutdown_disable__(self): try: self.shutdownTimeout.cancel() del self.shutdownTimeout info(self.identifier + ": Automatic shutdown disabled.") except AttributeError: pass def __user_join__(self, username): info(self.identifier + ": User '" + username + "' joined server.") with open(self.playersFile, 'a') as f: self.players.add(username) f.write(username + '\n') self.__autoshutdown_disable__() def __user_leave__(self, username): info(self.identifier + ": User '" + username + "' left server.") self.players.remove(username) with open(self.playersFile, 'w') as f: f.writelines(self.players) if self.players: f.write('\n') if (not self.players): self.__autoshutdown_enable__() def __parse_line__(self, line): if ': Done' in line: info(self.identifier + ": Server start.") self.status = 2 with open(self.statusFile, 'w') as f: f.write(__STATUSSTRINGS__[2] + '\n') self.__autoshutdown_enable__() elif ': Stopping the server' in line: info(self.identifier + ": Server stop.") self.status = 3 with open(self.statusFile, 'w') as f: f.write(__STATUSSTRINGS__[3] + '\n') elif 'logged in with entity id' in line: name = line[len('[00:00:00] [Server thread/INFO]: '):] name = name[:name.index('[')] self.__user_join__(name) elif 'left the game' in line: name = line[len('[00:00:00] [Server thread/INFO]: '):] name = name[:name.index(' ')] self.__user_leave__(name) class __MCServerOutputThread__(Thread): def __init__(self, mcserver): Thread.__init__(self, name='MCServerOutputThread:' + mcserver.identifier) self.mcserver = mcserver self.__stopread__ = False def stop(self): self.stopread = True def run(self): for linen in self.mcserver.prc.stdout: line = linen.decode(sys.getdefaultencoding()) info(self.mcserver.identifier + ": " + line.rstrip(), 2) self.mcserver.__parse_line__(line.rstrip()) self.mcserver.inputThread.stop() self.mcserver.status = 0 with open(self.mcserver.statusFile, 'w') as f: f.write(__STATUSSTRINGS__[0] + '\n') class __MCServerInputThread__(Thread): def __init__(self, mcserver): Thread.__init__(self, name='MCServerInputThread:' + mcserver.identifier) self.mcserver = mcserver self.stopread = False def stop(self): self.stopread = True def wake(self): with open(self.mcserver.inputPipe, 'w') as f: f.write("\n") f.flush() def run(self): with open(self.mcserver.inputPipe, 'r') as p: while not self.stopread: ln = p.readline().rstrip() if ln: self.mcserver.write_to_terminal(ln + "\n") else: time.sleep(3) ################################################################################# def wrapper_atexit(): "This is called when wrapper is exiting" for srv in _mcservers: del srv def wrapper_toexit(): "This function is called when system signalizes that mcwrapper should exit" for srv in _mcservers: srv.stop() def __signal_term__(_signo, _stack_frame): wrapper_toexit() def print_help(): print('mcwrapper [arguments...] IDENTIFIER') print(' This script is executing Minecraft server and reads its output. From output is') print(' extracted server status and list of online players.') print('') print(' arguments') print(' -h, --help') print(' Prints this help text.') print(' -v, --verbose') print(' Increase verbose level of output.') print(' -q, --quiet') print(' Decrease verbose level of output.') print(' --config CONFIG_FILE') print(' Specify configuration file to be used.') print(' IDENTIFIER') print(' Identifier for new server. This allows multiple servers running with this') print(' wrapper. Identifier is word without spaces and preferably without special') print(' characters.') sys.exit(_EC_OK) if __name__ == '__main__': identifier = None use_config = None verbose_level = 0 i = 1 while i < len(sys.argv): arg = sys.argv[i] i += 1 if arg[0] == '-': if len(arg) > 2 and arg[1] == '-': if arg == '--help': print_help() elif arg == '--verbose': verbose_level += 1 elif arg == '--quiet': verbose_level += 1 elif arg == '--config': if use_config != None: error('Config option is used multiple times', ec = _EC_ARG_MULTIPLE_CONFIG) else: use_config = sys.argv[i] i += 1 continue else: for l in arg[1:]: if l == 'h': print_help() elif l == 'v': verbose_level += 1 elif l == 'q': verbose_level -= 1 else: error("Unknown short argument " + l, ec = _EC_ARG_UNKNOWN) continue if identifier == None: identifier = arg continue error("Unknown argument: " + arg, ec = _EC_ARG_UNKNOWN) # Parsing args ends load_conf(use_config) conf.verbose_level += verbose_level # Set identifier if provided if identifier: conf.identifier = identifier signal.signal(signal.SIGTERM, __signal_term__) signal.signal(signal.SIGINT, __signal_term__) atexit.register(wrapper_atexit) mcs = MCServer(conf.identifier) mcs.start() mcs.join()