-
Notifications
You must be signed in to change notification settings - Fork 0
/
rockettm_server.py
162 lines (129 loc) · 4.71 KB
/
rockettm_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
import sys
import os
import logging
import traceback
import importlib
import time
import signal
from multiprocessing import Process, Manager, Event
from redisqueue import RedisQueue
from redis import Redis
from basicevents import run, send, subscribe
from rockettm import tasks
if 'gevent' in sys.modules:
def call(func, apply_max_time, *args, **kwargs):
return func(*args, **kwargs)
print("WARNING: gevent experimental support, is bad plan!")
else:
from timekiller import call
if len(sys.argv) >= 2:
i, f = os.path.split(sys.argv[-1])
sys.path.append(i)
settings = __import__(os.path.splitext(f)[0])
else:
sys.path.append(os.getcwd())
try:
import settings
except:
exit("settings.py not found")
logging.basicConfig(**settings.logger)
for mod in settings.imports:
importlib.import_module(mod)
tasks.ip = settings.RABBITMQ_IP
if not hasattr(settings, 'ROCKETTM_CALLBACK'):
settings.ROCKETTM_CALLBACK = True
if not hasattr(settings, 'ROCKETTM_SERIALIZER'):
settings.ROCKETTM_CALLBACK = "json"
@subscribe('results')
def call_results(json, room='results'):
tasks.send_task('results', room, json)
class Worker(Process):
def __init__(self, event_kill, name, concurrency, ip, max_time=-1):
self.queue_name = name
self.concurrency = concurrency
self.max_time = max_time
self.event_kill = event_kill
self.conn = RedisQueue(Redis(host=ip), self.queue_name)
super(Worker, self).__init__()
def safe_worker(self, func, return_dict, apply_max_time, body):
try:
return_dict['result'] = call(func, apply_max_time,
*body['args'], **body['kwargs'])
return_dict['success'] = True
except:
return_dict['result'] = traceback.format_exc()
return_dict['success'] = False
logging.error(return_dict['result'])
def safe_call(self, func, apply_max_time, body):
# os.setpgrp() # kill non propagate
if 'gevent' not in sys.modules:
return_dict = Manager().dict()
p = Process(target=self.safe_worker, args=(func, return_dict,
apply_max_time, body))
p.start()
p.join()
else:
return_dict = {}
self.safe_worker(func, return_dict, apply_max_time, body)
return return_dict
def callback(self, body):
logging.info("execute %s" % body['event'])
_id = body['args'][0]
if settings.ROCKETTM_CALLBACK:
send('results', {'_id': _id, 'status': 'processing'})
if not body['event'] in tasks.subs:
if settings.ROCKETTM_CALLBACK:
send('results', {'_id': _id,
'result': 'task not defined',
'status': 'finished',
'success': False})
return False
result = []
for func, max_time2 in tasks.subs[body['event']]:
logging.info("exec func: %s, timeout: %s" % (func, max_time2))
if max_time2 != -1:
apply_max_time = max_time2
else:
apply_max_time = self.max_time
result.append(dict(self.safe_call(func, apply_max_time, body)))
success = not any(r['success'] is False for r in result)
send('results', {'_id': _id, 'status': 'finished',
'success': success, 'result': result})
return True
def run(self):
while not self.event_kill.is_set():
try:
task = self.conn.get(timeout=20)
if task:
self.callback(task)
except:
logging.error(traceback.format_exc())
logging.error("connection loss, try reconnect")
time.sleep(5)
event_kill = Event()
finish_tasks = Event()
def main():
# start basicevents
default_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, signal.SIG_IGN)
run(finish_tasks.is_set)
list_process = []
for queue in settings.queues:
for x in range(queue['concurrency']):
p = Worker(event_kill, ip=settings.RABBITMQ_IP, **queue)
logging.info("start process worker: %s queue: %s" % (p,
queue))
list_process.append(p)
p.start()
signal.signal(signal.SIGINT, default_handler)
try:
signal.pause()
except:
print("init stop")
event_kill.set()
for x in list_process:
x.join()
print("finish tasks")
finish_tasks.set()
if __name__ == "__main__":
main()