forked from timakro/ddnet-trashmap
-
Notifications
You must be signed in to change notification settings - Fork 2
/
trashmap.py
executable file
·538 lines (476 loc) · 18.1 KB
/
trashmap.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
#!/usr/bin/python3
import os
import time
import json
import signal
import stat
import tempfile
import subprocess
import re
import fcntl
import traceback
CREATE_SERVER = 3
START_SERVER = 4
STOP_SERVER = 5
CHANGE_MAP = 6
CHANGE_VERSION = 7
CHANGE_PASSWORD = 8
CHANGE_RCON = 9
CHANGE_PLAYERLIMIT = 10
DELETE_SERVER = 11
SUGGEST_RCON = 12
ALLOW_RCON = 13
DELETE_RCON = 14
RUNNING = 0
SHUTDOWN = 1
ERROR = 2
EXCEPTION = 3
def mydefault(self, o):
if isinstance(o, subprocess.Popen):
return None
raise TypeError(repr(o) + " is not JSON serializable")
json.JSONEncoder.default = mydefault
def handle(order):
if order["type"] == CREATE_SERVER:
if order["identifier"] not in data["storage"]["servers"]:
createserver(order)
writestorage()
elif order["type"] == START_SERVER:
if order["identifier"] in data["storage"]["servers"]:
startserver(order["identifier"])
elif order["type"] == STOP_SERVER:
if order["identifier"] in data["storage"]["servers"]:
stopserver(order["identifier"])
elif order["type"] == CHANGE_MAP:
if order["identifier"] in data["storage"]["servers"]:
changemap(order["identifier"], order["mapfile"], order["mapname"])
writestorage()
elif order["type"] == CHANGE_PASSWORD:
if order["identifier"] in data["storage"]["servers"]:
if data["storage"]["servers"][order["identifier"]]["running"]:
writefifo(order["identifier"], buildcommand("password", order["password"] if order["password"] else ""))
data["storage"]["servers"][order["identifier"]]["password"] = order["password"]
writestorage()
elif order["type"] == CHANGE_RCON:
if order["identifier"] in data["storage"]["servers"]:
if data["storage"]["servers"][order["identifier"]]["running"]:
writefifo(order["identifier"], buildcommand("sv_rcon_mod_password", order["rcon"]))
data["storage"]["servers"][order["identifier"]]["rcon"] = order["rcon"]
writestorage()
elif order["type"] == CHANGE_VERSION:
if order["identifier"] in data["storage"]["servers"] and not data["storage"]["servers"][order["identifier"]]["running"]:
data["storage"]["servers"][order["identifier"]]["version"] = order["version"]
writestorage()
elif order["type"] == CHANGE_PLAYERLIMIT:
if order["identifier"] in data["storage"]["servers"] and not data["storage"]["servers"][order["identifier"]]["running"]:
data["storage"]["servers"][order["identifier"]]["playerlimit"] = order["playerlimit"]
writestorage()
elif order["type"] == DELETE_SERVER:
if order["identifier"] in data["storage"]["servers"]:
deleteserver(order["identifier"])
writestorage()
elif order["type"] == SUGGEST_RCON:
if order["command"] not in data["storage"]["allowed_rcon"] and order["command"] not in data["storage"]["suggested_rcon"]:
data["storage"]["suggested_rcon"].append(order["command"])
writestorage()
elif order["type"] == ALLOW_RCON:
if order["command"] in data["storage"]["suggested_rcon"]:
data["storage"]["suggested_rcon"].remove(order["command"])
if order["command"] not in data["storage"]["allowed_rcon"]:
data["storage"]["allowed_rcon"].append(order["command"])
writestorage()
elif order["type"] == DELETE_RCON:
if order["command"] in data["storage"]["allowed_rcon"]:
data["storage"]["allowed_rcon"].remove(order["command"])
if order["command"] in data["storage"]["suggested_rcon"]:
data["storage"]["suggested_rcon"].remove(order["command"])
writestorage()
def createserver(order):
if len(data["storage"]["servers"]) >= data["config"]["maxservers"]:
return
# calculate port
ports = [i["port"] for i in data["storage"]["servers"].values()]
port = 8500
while port in ports:
port += 1
# create serverdir and move map
serverdir = os.path.join("/srv/trashmap/servers", order["identifier"])
os.mkdir(serverdir)
os.symlink("/srv/trashmap/srv/init.cfg", os.path.join(serverdir, "init.cfg"))
os.symlink("/srv/trashmap/srv/storage.cfg", os.path.join(serverdir, "storage.cfg"))
os.mkdir(os.path.join(serverdir, "maps"))
os.rename(order["mapfile"], os.path.join(serverdir, "maps", order["mapname"]+".map"))
# add server to memory
data["storage"]["servers"][order["identifier"]] = {
"label": order["label"],
"accesskey": order["accesskey"],
"serverdir": serverdir,
"mapname": order["mapname"],
"password": order["password"],
"rcon": order["rcon"],
"version": order["version"],
"playerlimit": order["playerlimit"],
"userip": order["userip"],
"lifeseconds": 0,
"starttime": None,
"stoptime": 0,
"titletime": 0,
"running": False,
"stopping": False,
"process": None,
"port": port,
"runtimestring": None,
"streamlast": None,
"clientids": None
}
log("Created server", identifier=order["identifier"])
# start server
startserver(order["identifier"])
def startserver(identifier):
if len([1 for i in data["storage"]["servers"].values() if i["running"]]) >= data["config"]["maxrunningservers"]:
return
info = data["storage"]["servers"][identifier]
if info["running"]:
return
# update memory
info["starttime"] = info["lifeseconds"]
info["stoptime"] = None
info["titletime"] = info["lifeseconds"]
info["running"] = True
info["runtimestring"] = buildruntime(identifier)
info["streamlast"] = ""
info["clientids"] = []
# format init commands
commands = []
commands.append(buildcommand("sv_name", buildtitle(identifier)))
commands.append(buildcommand("sv_port", info["port"]))
commands.append(buildcommand("sv_map", info["mapname"]))
commands.append(buildcommand("sv_max_clients", info["playerlimit"]))
commands.append(buildcommand("sv_rcon_mod_password", info["rcon"]))
if info["password"]:
commands.append(buildcommand("password", info["password"]))
commands.append(buildcommand("exec", "banlist.cfg"))
commands.append(buildcommand("exec", "init.cfg"))
for rcon in data["storage"]["allowed_rcon"]:
commands.append(buildcommand("access_level", rcon, 2))
# start server
binary = "/srv/trashmap/srv/DDNet-Server"
if info["version"] == "0.7":
binary = "/srv/trashmap/srv/DDNet7-Server"
process = subprocess.Popen((binary, "".join(commands).encode("utf-8")), cwd=info["serverdir"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
fcntl.fcntl(process.stdout, fcntl.F_SETFL, os.O_RDONLY | os.O_NONBLOCK)
info["process"] = process
log("Started server", identifier=identifier)
def stopserver(identifier):
info = data["storage"]["servers"][identifier]
if not info["running"] or info["stopping"]:
return
# stop server
writefifo(identifier, buildcommand("bans_save", "banlist.cfg") + buildcommand("shutdown"))
# update memory
info["stopping"] = True
log("Stopped server", identifier=identifier)
def deleteserver(identifier):
info = data["storage"]["servers"][identifier]
# stop if still running
if info["running"]:
stopserver(identifier)
# delete files
def rmtree(path):
if os.path.isdir(path):
files = os.listdir(path)
for f in files:
rmtree(os.path.join(path, f))
try: os.rmdir(path)
except: rmtree(path)
elif os.path.exists(path):
try: os.remove(path)
except: rmtree(path)
rmtree(info["serverdir"])
# update memory
del data["storage"]["servers"][identifier]
log("Deleted server", identifier=identifier)
def changemap(identifier, mapfile, mapname):
info = data["storage"]["servers"][identifier]
# remove old map
os.unlink(os.path.join(info["serverdir"], "maps", info["mapname"]+".map"))
# move new map and reload
os.rename(mapfile, os.path.join(info["serverdir"], "maps", mapname+".map"))
if info["running"]:
if info["mapname"] != mapname:
writefifo(identifier, buildcommand("change_map", mapname))
else:
writefifo(identifier, buildcommand("reload"))
# update memory
info["mapname"] = mapname
log("Changed map", identifier=identifier)
def update(identifier):
info = data["storage"]["servers"][identifier]
running = info["process"].poll() == None if info["process"] else False
# update stopping
if info["stopping"]:
if not running:
info["starttime"] = None
info["stoptime"] = info["lifeseconds"]
info["running"] = False
info["stopping"] = False
info["runtimestring"] = None
info["streamlast"] = None
info["clientids"] = None
# check if running
if info["running"]:
# stop server if it crashed
if not running:
stopserver(identifier)
# check if the server has to stop
if info["lifeseconds"]-info["starttime"] >= data["config"]["stophours"]*60*60:
stopserver(identifier)
# update runtime
info["runtimestring"] = buildruntime(identifier)
# read stream
for line in readstream(identifier):
match = re.match("\[.*\]\[server\]: player is ready\. ClientID=([0-9]+) .*", line)
if match:
cid = int(match.group(1))
if cid not in info["clientids"]:
info["clientids"].append(cid)
continue
match = re.match("\[.*\]\[server\]: client dropped\. cid=([0-9]+) .*", line)
if match:
cid = int(match.group(1))
if cid in info["clientids"]:
info["clientids"].remove(cid)
continue
# check if the server has to stop
if info["lifeseconds"]-info["starttime"] >= data["config"]["joinminutes"]*60 and len(info["clientids"]) == 0:
stopserver(identifier)
# update title
if info["lifeseconds"]-info["titletime"] >= data["config"]["titleupdateseconds"]:
writefifo(identifier, buildcommand("sv_name", buildtitle(identifier)))
info["titletime"] = info["lifeseconds"]
else:
# check if the server has to be deleted
if info["lifeseconds"]-info["stoptime"] >= data["config"]["deletedays"]*24*60*60:
deleteserver(identifier)
return
# delete servers with banned user ips
if info["userip"] in data["config"]["bannedips"]:
deleteserver(identifier)
return
info["lifeseconds"] += data["config"]["tickseconds"]
def buildcommand(command, *args):
args = ["\"" + str(arg).replace("\"", "\\\"") + "\"" for arg in args]
commandstr = command + " " + " ".join(args) + ";"
return commandstr
def buildtitle(identifier):
info = data["storage"]["servers"][identifier]
name = "DDNet " + data["config"]["location"] + " Trashmap - " + info["label"] + " (" + info["runtimestring"] + ")"
return name
def buildruntime(identifier):
info = data["storage"]["servers"][identifier]
minutes, seconds = divmod(info["lifeseconds"]-info["starttime"], 60)
hours, minutes = divmod(minutes, 60)
runtime = str(hours) + "h " + str(minutes) + "m " + str(seconds) + "s"
return runtime
def writefifo(identifier, line):
info = data["storage"]["servers"][identifier]
if not info["running"] or info["stopping"]:
return
fifopath = os.path.join(data["storage"]["servers"][identifier]["serverdir"], "fifo")
try:
assert stat.S_ISFIFO(os.stat(fifopath).st_mode)
fifo = os.open(fifopath, os.O_WRONLY | os.O_NONBLOCK)
os.write(fifo, (line+"\n").encode("utf-8"))
os.close(fifo)
except:
log("Failed to write to server fifo", identifier=identifier, warning=True)
def readstream(identifier):
info = data["storage"]["servers"][identifier]
while True:
# read rawstring
try:
rawstring = os.read(info["process"].stdout.fileno(), 256).decode("utf-8")
except: break
if not rawstring:
break
# form lines
lines = rawstring.split("\n")
lines[0] = info["streamlast"] + lines[0]
info["streamlast"] = lines[-1]
lines = lines[:-1]
# yield lines
for line in lines:
yield line
def log(message, identifier=None, warning=False, error=False):
prefix = ""
if warning: prefix = "Warning: "
elif error: prefix = "Error: "
if identifier:
prefix += "[" + identifier + "] "
message = message.split("\n")
message = [(pidstr+" "+prefix if i == 0 else " ")+m+"\n" for i, m in enumerate(message) if m]
try:
logfile.write("".join(message))
logfile.flush()
except: pass
if error:
global status_flag
status_flag = ERROR
def loadconfig(init=False):
try:
config = json.load(open("/srv/trashmap/srv/daemon_config.json"))
if init: log("Loaded config")
else: log("Reloaded config")
return config
except:
if init: log("Failed to load config", error=True)
else: log("Failed to reload config", warning=True)
def loadstorage():
try:
storage = json.load(open("/srv/trashmap/srv/daemon_storage.json"))
log("Loaded storage")
return storage
except:
log("Failed to load storage", error=True)
def writedata(init=False):
try:
tmp_file = tempfile.NamedTemporaryFile(mode="w", prefix="trashmap-", delete=False)
json.dump(data, tmp_file, indent=4)
tmp_file.close()
os.chmod(tmp_file.name, 0o644)
os.rename(tmp_file.name, "/srv/trashmap/srv/daemon_data.json")
if init: log("Created data")
except:
if init: log("Failed to create data", error=True)
else: log("Failed to write data", warning=True)
def writestorage(final=False):
try:
json.dump(data["storage"], open("/srv/trashmap/srv/daemon_storage.json", "w"), indent=4)
if final: log("Wrote final storage")
except:
if final: log("Failed to write final storage", error=True)
else: log("Failed to write storage", warning=True)
def main():
# open logfile
try:
global logfile
logfile = open("/srv/trashmap/srv/daemon_log.txt", "a")
except: pass
global pidstr
pidstr = str(os.getpid())
pidstr = "0" * (5 - len(pidstr)) + pidstr
log("Trashmap daemon started")
# create data and load files
global data
data = {"config":loadconfig(True), "storage":loadstorage()}
writedata(True)
# create and open fifo
try:
oldmask = os.umask(0000)
os.mkfifo("/srv/trashmap/srv/daemon_input.fifo", 0o666)
os.umask(oldmask)
log("Created fifo")
except:
log("Failed to create fifo", warning=True)
try:
global fifo
fifo = os.open("/srv/trashmap/srv/daemon_input.fifo", os.O_RDONLY | os.O_NONBLOCK)
assert stat.S_ISFIFO(os.fstat(fifo).st_mode)
except:
log("Failed to open fifo", error=True)
# main loop
last = ""
while True:
# calculate next run
next_run = time.time() + data["config"]["tickseconds"]
# check for config reload
global config_reload_flag
if config_reload_flag:
new_config = loadconfig()
if new_config:
data["config"] = new_config
config_reload_flag = False
# check for shutdown or error
if status_flag != RUNNING:
shutdown()
break
# handle fifo
while True:
try:
rawstring = os.read(fifo, 256).decode("utf-8")
except: break
if not rawstring:
break
lines = rawstring.split("\n")
lines[0] = last + lines[0]
last = lines[-1]
lines = lines[:-1]
for line in lines:
try:
order = json.loads(line)
except:
log("Failed to json decode fifo input", error=True)
else:
handle(order)
# update servers
for identifier in data["storage"]["servers"].keys():
update(identifier)
# write data to file
writedata()
# sleep for a tick
delta = next_run - time.time()
if delta < 0:
log("Skipped {} ticks".format(delta / -data["config"]["tickseconds"]), warning=True)
else:
time.sleep(delta)
def shutdown():
# stop servers
try:
for identifier in data["storage"]["servers"].keys():
stopserver(identifier)
except: pass
# close and remove fifo
try:
os.close(fifo)
os.unlink("/srv/trashmap/srv/daemon_input.fifo")
log("Removed fifo")
except:
log("Failed to remove fifo", warning=True)
# remove data
try:
os.unlink("/srv/trashmap/srv/daemon_data.json")
log("Removed data")
except:
log("Failed to remove data", warning=True)
# for safety write storage a last time
try:
if data["storage"]:
writestorage(True)
except: pass
# close logfile
if status_flag == SHUTDOWN: log("Trashmap daemon terminated")
elif status_flag == ERROR: log("Trashmap daemon terminated because an error occurred")
elif status_flag == EXCEPTION: log("Trashmap daemon terminated because a python exception occurred")
try:
logfile.close()
except: pass
status_flag = RUNNING
config_reload_flag = False
# set up SIGTERM and SIGINT handlers
def handle_kill(x, y):
global status_flag
status_flag = SHUTDOWN
signal.signal(signal.SIGTERM, handle_kill)
signal.signal(signal.SIGINT, handle_kill)
# set up SIGUSR1 handler
def handle_reload(x, y):
global config_reload_flag
config_reload_flag = True
signal.signal(signal.SIGUSR1, handle_reload)
try:
main()
except:
status_flag = EXCEPTION
log(traceback.format_exc())
shutdown()
raise