aboutsummaryrefslogtreecommitdiff
path: root/mcwrapper
blob: 57768c7ee8093b44fb48a1cecf9d57d137f4dffc (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
#!/usr/bin/env python3
import os
import sys
import re
import subprocess
import signal
import time
import datetime
import traceback
from threading import Thread
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
    global conf_source
    print('Warning: User configuration not loaded. Using default.', file=sys.stderr)
    conf = type('default config', (object,), {})

__config_file__ = None
try:
    __config_file__ = os.environ['CONFIG'] # get config file from environment
except KeyError:
        # Find configuration in predefined paths
    for cf in __all_config_files__:
        if os.path.isfile(cf):
            __config_file__ = 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()

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

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

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

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

def __server_start__():
    if conf.verbose_level >= 0:
        print("Wrapper initializing with identifier: " + conf.identifier)
    try:
        os.mkdir(conf.status)
    except FileExistsError:
        pass
    if os.path.isfile(inputPipe):
        if conf.verbose_level >= -1:
            print("Error: Server input pipe already exists. Is another wrapper running?")
        sys.exit(4)
    os.mkfifo(inputPipe, 0o640)
    global statusFile
    statusFile = conf.status + '/status'
    with open(statusFile, 'w') as f:
        f.write(__STATUSSTRINGS__[1])
    global playersFile
    playersFile = conf.status + '/status'
    with open(playersFile, 'w') as f:
        pass
    global playerCount
    playerCount = 0

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

def __parse_line__(line):
    if ': Done' in line:
        print("Server start.")
        with open(statusFile, 'w') as f:
            f.write(__STATUSSTRINGS__[2] + '\n')
    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
    __server_start__()
    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)
    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()
    __server_clean__()

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

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(' 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
    message = []
    for arg in sys.argv[1:]:
        if arg[0] == '-':
            if len(arg) > 2 and arg[1] == '-':
                if arg == '--help':
                    print_help()
                if arg == '--verbose':
                    conf.verbose_level += 1
                if arg == '--quiet':
                    conf.verbose_level += 1
                    continue
            else:
                for l in arg[1:]:
                    if l == 'h':
                        print_help()
                    elif l == 'v':
                        conf.verbose_level += 1
                    elif l == 'q':
                        conf.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

    # Set identifier if provided
    if identifier:
        conf.identifier = identifier
    # Expand configuration for specified identifier
    if not conf.identifier:
        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'

    signal.signal(signal.SIGTERM, __signal_term__)
    signal.signal(signal.SIGINT, __signal_term__)
    mcexec()