aboutsummaryrefslogtreecommitdiff
path: root/mcwrapper
blob: fda83fa2948325f3e1de9afe5d5767e9bfb88c27 (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
#!/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()
            self.__autoshutdown_disable__()
    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.status == 2:
            info(self.identifier + ": Input: " + text,  1)
            self.prc.stdin.write(bytes(text, sys.getdefaultencoding()))
            self.prc.stdin.flush()
            return True
        else:
            return False
    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('   --configfile')
    print('       prints used configuration file and exits.')
    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)

def print_conffile():
    if '__file__' in vars(conf):
        print(conf.__file__)
    else:
        print("No configuration file used.")
    sys.exit(_EC_OK)

if __name__ == '__main__':
    identifier = None
    use_config = None
    verbose_level = 0
    print_config_file = False
    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
                elif arg == '--configfile':
                    print_config_file = True
                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)

    if print_config_file:
        print_conffile()

    conf.verbose_level += verbose_level
    # Set identifier if provided
    if identifier:
        conf.identifier = identifier
    elif not "identifier" in vars(conf):
        print_help()

    signal.signal(signal.SIGTERM, __signal_term__)
    signal.signal(signal.SIGINT, __signal_term__)
    atexit.register(wrapper_atexit)

    mcs = MCServer(conf.identifier)
    mcs.start()
    mcs.join()