aboutsummaryrefslogtreecommitdiff
path: root/mcwrapper
blob: e7802ae6e892c2d3e48d32a231b0eb34dfa60b49 (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
#!/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
#################################################################################
# Load configuration
# This segment is same as in mcmim

__all_config_files__ = (
        'mcwrapper.conf',
        '~/.mcwrapper.conf',
        '~/.config/mcwrapper.conf',
        '/etc/mcwrapper.conf',
        )

def __set_empty_config__():
    global conf
    print('Warning: User configuration not loaded. Using default.', file=sys.stderr)
    conf = type('default config', (object,), {})

def load_conf(config_file):
    global conf
    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
    if not 'server' in vars(conf):
        conf.server = dict()
    if not 'timeout' in vars(conf):
        conf.timeout = 0

#################################################################################

def autoshutdown_enable():
    global shutdownTimeout
    if (conf.timeout > 0):
        if (conf.verbose_level >= 0):
            print("Automatic shutdown after " + str(conf.timeout) +
                " min.")
        shutdownTimeout = Timer(conf.timeout * 60.0, __server_send_stop__)
        shutdownTimeout.start();
    pass

def autoshutdown_disable():
    global shutdownTimeout
    try:
        shutdownTimeout.cancel()
        del shutdownTimeout
        if (conf.verbose_level >= 0):
            print("Automatic shutdown disabled.")
    except NameError:
        pass

#################################################################################

__STATUSSTRINGS__ = {
    0: "Not running",
    1: "Starting",
    2: "Running",
    3: "Stopping",
    }

def __user_join__(username):
    global playersFile
    global players
    if conf.verbose_level >= 0:
        print("User '" + username + "' joined server.")
    with open(playersFile, 'a') as f:
        players.add(username)
        f.write(username + '\n')
    autoshutdown_disable()

def __user_leave__(username):
    global playersFile
    global players
    if conf.verbose_level >= 0:
        print("User '" + username + "' left server.")
    players.remove(username)
    with open(playersFile, 'w') as f:
        f.writelines(players)
        if players:
            f.write('\n')
    if (not players):
        autoshutdown_enable()

def __server_start__():
    if conf.verbose_level >= 0:
        print("Wrapper initializing with identifier: " + conf.identifier)
    try:
        os.mkdir(conf.status)
    except FileExistsError:
        pass
    try:
        os.mkfifo(inputPipe, 0o640)
    except FileExistsError:
        pass
    if os.path.isfile(pidfile):
        with open(pidfile) as f:
            lpid = int(f.readline())
        try:
            os.kill(lpid, 0)
        except OSError:
            if conf.verbose_level >= 0:
                print("Warning: Detected forced termination of previous wrapper instance")
        else:
            if conf.verbose_level >= -1:
                print("Error: Another wrapper is running with given identifier.")
            sys.exit(4)
    with open(statusFile, 'w') as f:
        f.write(__STATUSSTRINGS__[1] + '\n')
    with open(playersFile, 'w') as f:
        pass

def __server_clean__():
    if conf.verbose_level >= 0:
        print("Wrapper clean.")
    try:
        os.remove(inputPipe)
    except FileNotFoundError:
        pass
    try:
        os.remove(statusFile)
    except FileNotFoundError:
        pass
    try:
        os.remove(playersFile)
    except FileNotFoundError:
        pass
    if os.path.isfile(pidfile):
        os.remove(pidfile)

def __parse_line__(line):
    if ': Done' in line:
        print("Server start.")
        with open(statusFile, 'w') as f:
            f.write(__STATUSSTRINGS__[2] + '\n')
        autoshutdown_enable()
    elif ': Stopping the server' in line:
        print("Server stop.")
        with open(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('[')]
        __user_join__(name)
    elif 'left the game' in line:
        name = line[len('[00:00:00] [Server thread/INFO]: '):]
        name = name[:name.index(' ')]
        __user_leave__(name)

#################################################################################

class __InputThread__(Thread):
    def __init__(self, pipeprocess):
        Thread.__init__(self, name='InputThread')
        self.pipeprocess = pipeprocess
        self.stopread = False
    def stopexec(self):
        self.stopread = True
    def wake(self):
        with open(inputPipe, 'w') as f:
            f.write("\n")
            f.flush()
    def run(self):
        with open(inputPipe, 'r') as p:
            while not self.stopread:
                ln = p.readline()
                if ln.rstrip():
                    if conf.verbose_level >= 1:
                        print("Input: " + ln, end="")
                    self.pipeprocess.write(bytes(ln, sys.getdefaultencoding()))
                    self.pipeprocess.flush()
                else:
                    time.sleep(1)

def __server_send_stop__():
    global prc
    prc.stdin.write(bytes("/stop\n", sys.getdefaultencoding()))
    prc.stdin.flush()

def mcexec():
    """Executes cmd and parses output for server status changes.
    """
    global prc
    if type(conf.command) != str:
        conf.command = ' '.join(conf.command)
    if conf.verbose_level >= 1:
        print("Folder: " + conf.directory)
        print("Start command: " + conf.command)
    os.chdir(os.path.expanduser(conf.directory))
    prc = subprocess.Popen(conf.command, stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True,
             start_new_session=False)
    with open(pidfile, "w") as f:
        f.write(str(prc.pid))
    inputThread = __InputThread__(prc.stdin)
    inputThread.start()
    inputThread.wake() # Input thread is stuck in waiting for first line
    for linen in prc.stdout:
        line = linen.decode(sys.getdefaultencoding())
        if conf.verbose_level >= 2:
            print(line.rstrip())
        __parse_line__(line.rstrip())
    inputThread.stopexec()

#################################################################################

def __signal_term__(_signo, _stack_frame):
    __server_send_stop__()

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()

if __name__ == '__main__':
    identifier = None
    use_config = None
    verbose_level = 0
    message = []
    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:
                        sys.exit('Config option is used multiple times')
                    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:
                        sys.exit("Unknown short argument " + l)
                continue
        if identifier == None:
            identifier = arg
            continue
        sys.exit("Unknown argument: " + arg)
    # Parsing args ends

    load_conf(use_config)
    conf.verbose_level += verbose_level
    # Set identifier if provided
    if identifier:
        conf.identifier = identifier
    # Expand configuration for specified identifier
    if 'identifier' not in vars(conf):
        print('Missing server identifier argument!')
        print('')
        print_help()
    try:
        conf.server[conf.identifier]
        vars(conf).update(conf.server[conf.identifier])
    except KeyError:
        sys.exit('Error: No configuration associated with identifier: ' + conf.identifier)
    # Check configurations for server
    if not 'directory' in vars(conf):
        sys.exit('Missing "directory" config for server ' + conf.identifier)
    if not 'command' in vars(conf):
        sys.exit('Missing server start command for server ' + conf.identifier)
    if not 'status' in vars(conf):
        conf.status = '/dev/shm/mcwrapper-' + conf.identifier
    # Set inputPipe
    global inputPipe
    inputPipe = conf.status + '/input_pipe'
    global statusFile
    statusFile = conf.status + '/status'
    global playersFile
    playersFile = conf.status + '/players'
    global pidfile
    pidfile = conf.status + '/server.pid'
    global players
    players = set()

    signal.signal(signal.SIGTERM, __signal_term__)
    signal.signal(signal.SIGINT, __signal_term__)
    __server_start__()
    atexit.register(__server_clean__)
    mcexec()