-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathg_server.py
187 lines (162 loc) · 5.61 KB
/
g_server.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
import sys
import gevent
from gevent.server import StreamServer
from gevent.subprocess import Popen, call
from sorteddict import SortedDict
from logfile import RotatingFile
import datetime
shutdown = False
manager = None
RUNNING = 1
STOPPED = 0
FATAL = -1
def set_shutdown(flag):
global shutdown
shutdown = flag
class Command(object):
def __init__(self, name, command, **kwargs):
self.name = name
self.command = command
self.log = None
self.stop = STOPPED #0 normal stopped 1 running -1 fatal stopped
self.process = None
for k, v in kwargs.items():
setattr(self, k, v)
self.start_time = None
self.stop_time = None
def is_ok(self):
return self.process and self.process.poll() is None
def do_start(self):
if not self.log:
self.log = RotatingFile(self.logfile,
maxBytes=self.logfile_maxbytes,
backupCount=self.logfile_backups)
if self.is_ok():
msg = self.name + ' has already been started'
else:
self.log.info('start '+self.name)
n = 0
while n < self.startretries:
self.process = Popen(self.command, stdout=self.log, stderr=self.log, shell=True, cwd=self.cwd)
gevent.sleep(self.starting_time)
if self.process.poll() is not None:
#error
self.log.info('start '+self.name+' failed!, times=%d'%n)
n += 1
else:
self.start_time = datetime.datetime.now()
break
#if stopped then status is Fatal
if n == self.startretries:
self.stop = FATAL
msg = self.name + ' started failed'
else:
self.stop = RUNNING
msg = self.name + ' started'
return msg
def do_stop(self):
if self.is_ok():
self.log.info('stop '+self.name)
self.stop = STOPPED
self.stop_time = datetime.datetime.now()
call(['taskkill', '/F', '/T', '/PID', str(self.process.pid)])
self.process = None
msg = self.name + ' stopped'
else:
msg = self.name + ' has already stopped'
return msg
def do_status(self):
if self.is_ok():
status = 'RUNNING'
info = 'pid %d, uptime %s' % (self.process.pid, self.start_time.strftime('%H:%M:%S'))
else:
if self.stop == STOPPED:
status = 'STOPPED'
info = self.stop_time.ctime()
else:
status = 'FATAL'
info = 'Exited too quickly'
msg = '%-20s %-10s %s' % (self.name, status, info)
return msg
def monitor():
while 1:
if shutdown:
manager.shutdown()
return
manager.check()
gevent.sleep(0.5)
class CommandsManager(object):
def __init__(self, Ini):
self.commands = SortedDict()
for k, v in Ini.items():
if k.startswith('program:'):
kwargs = {}
kwargs['name'] = name = k[8:]
kwargs['command'] = v.command
kwargs['cwd'] = v.get('directory', None)
kwargs['logfile'] = v.get('logfile', name+'.log')
kwargs['logfile_maxbytes'] = v.get('logfile_maxbytes', 50*1024*1024)
kwargs['logfile_backups'] = v.get('logfile_backups', 10)
kwargs['startretries'] = v.get('startretries', 3)
kwargs['starting_time'] = v.get('starting_time', 1)
self.commands[name] = Command(**kwargs)
def start(self, command=None):
if not command:
for k, command in self.commands.items():
command.do_start()
else:
cmd = self.commands.get(command, '')
if not cmd:
msg = "Program %s is not found" % command
else:
msg = cmd.do_start()
return msg
def stop(self, command):
cmd = self.commands.get(command, '')
if not cmd:
msg = "Program %s is not found" % command
else:
msg = cmd.do_stop()
return msg
def shutdown(self):
for k, command in self.commands.items():
command.do_stop()
msg = 'shutdown successful'
return msg
def status(self):
s = []
for k, command in self.commands.items():
s.append(command.do_status())
return '\n'.join(s)
def check(self):
for k, p in self.commands.items():
if not p.stop in (STOPPED, FATAL) and not p.is_ok():
p.do_start()
def CommandsHandler(socket, address):
# using a makefile because we want to use readline()
command = socket.recv(1024)
cmds = command.split()
cmd = cmds[0]
if len(cmds) > 1:
args = cmds[1:]
else:
args = ()
func = getattr(manager, cmd, None)
if not func:
socket.send('Command %s is not supported' % cmd)
return
result = func(*args)
socket.send(result)
if cmd == 'shutdown':
sys.exit(0)
def main():
global manager
import pyini
Ini = pyini.Ini('watcher.ini')
manager = CommandsManager(Ini)
manager.start()
gevent.spawn(monitor)
server = StreamServer((Ini.server.host, Ini.server.port), CommandsHandler)
server.serve_forever()
if __name__ == '__main__':
main()