-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.py
230 lines (190 loc) · 6.24 KB
/
service.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
#!/usr/bin/env python
# coding: utf-8
"""
service modules defines classes to construct a general service.
TODO: need to be improved.
"""
import abc
import threading
import logging
from collections import deque
import datetime
log = logging.getLogger(__name__)
class ServiceMixin(object):
"""
Service mixin interface.
Inherit this class to implement service.
The service instance will be handle by Service class
"""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def name(self):
pass
@abc.abstractmethod
def run(self, output, *args, **kwargs):
"""
Service entry point. ServiceWrapper will call this method to run service.
:param output: The file-like output buffer which ServiceWrapper will passed in.
Service implementation can use it to write output.
:param args: Arguments passed to run service
:param kwargs: Named key-value arguments passed to run service.
:return:
"""
pass
class ServiceWrapper(object):
__metaclass__ = abc.ABCMeta
def __init__(self, service, *args, **kwargs):
"""
Wrap a service for running in thread.
:param service: An instance of ServiceMixin which holds the object and functions.
:param args: Arguments passed to run service
:param kwargs: Named key-value arguments passed to run service.
:return:
"""
if not isinstance(service, ServiceMixin):
raise ValueError("Service object must be an instance of ServiceMixin")
self._service = service
# self._owner = owner
self._output = OutputBuffer()
self._event = threading.Event()
if 'stop_event' not in kwargs:
kwargs['stop_event'] = self._event
self._t = threading.Thread(target=self.__run_service, args=args, kwargs=kwargs)
self.on_quit = lambda wrapper: log.debug('%s is quiting' % wrapper)
def start(self):
log.debug('Starting service %s ...' % type(self._service).__name__)
self._t.start()
def stop(self):
log.debug('Stopping service %s %d ...' % (self.__class__, self.sid))
self._event.set()
self._t.join()
def flush_output(self):
return self._output.flush()
@property
def service(self):
""" The ServiceMixin instance """
return self._service
# @property
# def owner(self):
# """ Service owner """
# return self._owner
@property
def is_alive(self):
""" Check if service is still running """
return self._t.is_alive()
@property
def sid(self):
""" Service ID """
if self._t:
return self._t.ident
else:
return -1
@property
def name(self):
""" Service Name """
return self._service.name
def __run_service(self, *args, **kwargs):
"""
Run a service.
:param args:
:param kwargs:
:return:
"""
try:
self._service.run(output=self._output, *args, **kwargs)
except Exception as err:
log.exception(err)
finally:
if self.on_quit:
self.on_quit(wrapper=self)
class ServiceManager(object):
_public = None
_private = {}
def __init__(self):
self._services = {}
def start(self, service, *args, **kwargs):
"""
Start a service in.
:param service: An instance of ServiceMixin which holds the object and functions.
:param args: Arguments passed to run service
:param kwargs: Named key-value arguments passed to run service.
:return: The wrapper object of the service.
"""
if not isinstance(service, ServiceMixin):
raise ValueError("Service object must be an instance of ServiceMixin")
wrapper = ServiceWrapper(service, *args, **kwargs)
wrapper.on_quit = self.__on_quit
wrapper.start()
assert wrapper.sid not in self._services
self._services[wrapper.sid] = wrapper
log.debug('Service %s:"%s" started.' % (wrapper.sid, wrapper.name))
return wrapper
def stop(self, sid):
"""
Stop a running service by given service id.
:param sid: Service ID.
:return:
"""
if sid in self._services:
wrapper = self._services.pop(sid)
wrapper.stop()
def __on_quit(self, wrapper):
"""
PostEvent will be triggered when a service quit
:param wrapper: An instance of ServiceMixin which holds the object and functions.
:return:
"""
assert isinstance(wrapper, ServiceWrapper)
if wrapper:
if wrapper.sid in self._services:
self._services.pop(wrapper.sid)
def all(self):
""" all service """
return self._services
@classmethod
def public(cls):
if cls._public is None:
cls._public = ServiceManager()
return cls._public
@classmethod
def private(cls, user):
if user not in cls._private:
cls._private[user] = ServiceManager()
return cls._private[user]
# TODO: OutputBuffer should be thread-safe (is dequeue thread safe?).
class OutputBuffer(object):
"""
OutputBuffer class is a file like class to output MQ Messages.
"""
def __init__(self, maxlen=100):
"""
ctor
:param maxlen: max buffered records (lines, strings and etc.)
:return:
"""
self._queue = deque(maxlen=maxlen)
def __len__(self):
return len(self._queue)
def _write(self, message):
msg = (message, datetime.datetime.utcnow(), )
if self.full():
self._queue.popleft()
self._queue.append(msg)
def write(self, message):
self._write(message)
def writelines(self, lines):
for line in lines:
self._write(line)
def flush(self):
messages = []
for msg in self._queue:
message, tm = msg
messages.insert(0, {
"message": message,
"time": str(tm),
})
return messages
def full(self):
return len(self._queue) >= self._queue.maxlen
def empty(self):
return len(self._queue) <= 0