-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.py
96 lines (73 loc) · 1.79 KB
/
daemon.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
import os
import signal
import sys
import time
import logging
from subprocess import Popen
from discord_server import create_server
COMMANDS = ['start', 'stop', 'restart']
def set_saved_pid(pid):
f = open("pid.txt", "w")
f.write(str(pid))
def get_saved_pid():
try:
f = open("pid.txt")
return int(f.read())
except IOError:
return 0
def delete_saved_pid():
try:
os.remove("pid.txt")
except OSError:
pass
def get_started_pid():
pid = get_saved_pid()
try:
os.kill(pid, 0)
except OSError:
return 0
else:
return pid
def kill_process(pid):
os.kill(pid, signal.SIGKILL)
def start():
if not get_started_pid():
p = Popen([
'python3', os.path.abspath(__file__),
'daemon',
])
pid = p.pid
set_saved_pid(pid)
logging.info('Server started (pid {}).'.format(pid))
else:
logging.info('Server already started.')
def stop():
pid = get_saved_pid()
if pid:
try:
kill_process(pid)
logging.info('Server stopped (pid {})'.format(pid))
except Exception as e:
logging.error('Server not started (pid {})'.format(pid))
logging.exception(e)
delete_saved_pid()
else:
logging.info('Server not started')
def restart():
stop()
time.sleep(1)
start()
time.sleep(1)
def daemon():
try:
create_server()
except Exception as e:
logging.exception(e)
if __name__ == "__main__":
num = len(sys.argv)
if sys.argv[1] in (COMMANDS + ['daemon']):
cmd = sys.argv[1]
globals()[cmd]()
else:
logging.info('Error: invalid command')
logging.info('Usage: python daemon.py {%s}.' % '|'.join(COMMANDS))