-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkers.py
387 lines (279 loc) · 11.3 KB
/
workers.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
"""
Base classes for all the workers in PSMS
"""
import socket
import logging
from conf import settings
from utils import import_class
from kombu.connection import BrokerConnection
from kombu.messaging import Exchange, Queue, Consumer, Producer
from kombu.exceptions import NotBoundError
# this module is borrowed from the Python source code itself as it's not
# yet available in Python 2.6. Still, it won't work in Python 2.4 or less.
from pragmatic_sms.settings.dictconfig import dictConfig
class WorkerError(Exception):
pass
class Worker(object):
"""
Base class of an object declaring exchanges, queues, consumers and
producers then perform a loop to listen for messages.
"""
name = "worker"
def __init__(self):
"""
Attach routes definition to attributes, connect to message broker
and initialize producers that will send messages into the queue.
"""
self.logger = self.get_logger()
self.run = False
self.connection = None
self.channel = None
self.exchanges = self.get_exchanges()
self.queues = self.get_queues()
self.consumers = None
self.producers = None
def get_logger(self):
"""
Override this if you want a custom logger instance. Default
is to use the root logger.
"""
return logging.getLogger()
def is_connected(self):
return bool(self.connection and self.channel)
def get_connection(self):
"""
Return a kombu connection object to the message broker.
You must override this otherwise your worker will fail in
self.connect
"""
raise WorkerError('Not implemented')
def connect(self):
"""
Start the connection manually. You probably don't need this as
it is taken care of automatically if you call self.start()
"""
if not self.is_connected():
self.connection = self.get_connection()
self.channel = self.connection.channel()
self.bind_exchanges()
self.bind_queues()
self.consumers = self.get_consumers()
self.producers = self.get_producers()
self.on_worker_connected()
def main_loop(self, timeout=1, limit=-1):
"""
Start to listen for messages untill one comes or the timeout is
reached.
Use 'limit' for tests when you want to run the worker a given
number of loops before it stop without having to tell him to.
Limit should be an integer representing the number of loops.
This is mainly used for testing purpose and is default to -1,
which is no limit.
"""
self.run = True
self.on_main_loop()
try:
while self.run and limit != 0:
try:
self.connection.drain_events(timeout=timeout)
except socket.timeout:
# this happens when timeout is reached and no message is
# in the queue
limit -= 1
except self.connection.connection_errors, e:
self.logger.error("Error while connecting with Kombu: %s" % e)
raise
except socket.error, e:
self.logger.error("Socket error: %s" % e)
raise
except (KeyboardInterrupt, SystemExit) as e:
self.logger.info("\nStopping %s" % self.name)
try:
self.connection.release()
except AssertionError:
# todo: find why there is this assertion error about state
pass
def start(self, timeout=1, limit=-1, force_purge=False):
"""
Connect the worker to th message broker, purge queues
if required then starts the main loop to listen
and react for messages.
Provide callbacks to perform action before and after the
main loop starts.
Use 'limit' for tests when you want to run the worker a given
number of loops before it stop without having to tell him to.
Limit should be an integer representing the number of loops.
This is mainly used for testing purpose and is default to -1,
which is no limit.
"""
self.on_worker_starts()
self.connect()
self.logger.info('%s is starting' % self.name)
if force_purge:
self.purge()
self.main_loop(timeout, limit)
self.on_worker_stopped()
self.logger.info('%s stopped' % self.name)
def on_worker_starts(self):
"""
Override this if you want to perform an action when the worker start
"""
pass
def on_worker_stopped(self):
"""
Override this if you want to perform an action when the worker
has stoped
"""
pass
def on_main_loop(self):
"""
Action to perform right before entering in the main loop
"""
pass
def on_worker_connected(self):
"""
Override this if you want to perform an action when the worker
has connected to the messag broker
"""
pass
def get_exchanges(self):
"""
Override this to return the exchanges you are going to use
for you worker. It should return a mapping of exchange names
and exchanges object.
"""
pass
def bind_exchanges(self):
"""
Loop on all exchanges in the self.exchanges dictionary and
bind them to the current channel.
Called in self.connect() right after the connection with the
message broker has been established.
Assume there is only one channel and one connection.
"""
for name, exchange in self.exchanges.items():
self.exchanges[name] = exchange(self.channel)
def get_queues(self):
"""
Override this to return the queues you are going to use
for you worker. It should return a mapping of exchange names
and exchanges object.
"""
pass
def bind_queues(self):
"""
Loop on all queues in the self.queues dictionary and
bind them to the current channel.
Called in self.connect() right after the connection with the
message broker has been established.
Assume there is only one channel and one connection.
"""
for name, queue in self.queues.items():
self.queues[name] = queue(self.channel)
self.queues[name].declare()
def get_consumers(self):
"""
Override this to return the consumers you are going to use
for you worker. It should return a mapping of exchange names
and exchanges object.
There are no 'bind_consumers' method as kombu forces you to
instanciate producers already bounded
"""
pass
def get_producers(self):
"""
Override this to return the producers you are going to use
for you worker. It should return a mapping of exchange names
and exchanges object.
There are no 'bind_producers' method as kombu forces you to
instanciate producers already bounded
"""
pass
def purge(self):
"""
Remove message from all queues. Call this if you want to reset
the state of your message queues, like in a unit test.
"""
try:
for name, queue in self.queues.iteritems():
try:
queue.purge()
except AttributeError as e:
# This queue can't be purge because of some reference issue
# I have yet to figure this out but this doesn't seem to prevent
# the system from working rght now and the unit tests pass,
# so fingers crossed...
self.logger.error('Unable to purge queue %s: %s' % (name, e))
except NotBoundError:
raise WorkerError('You cannot call purge on before binding '\
'queues. Either start the worker or call '\
'connect()')
class PSMSWorker(Worker):
"""
Worker classe adapted to PSMS type of processing
"""
name = "PSMS Worker"
persistent = settings.PERSISTENT_MESSAGE_QUEUES
def get_logger(self):
"""
Return a loggger instance configured as described in the settings
file.
"""
dictConfig(settings.LOGGING)
return logging.getLogger('psms')
def get_queues(self):
"""
Return a dict with queues all worker should be able
to use:
- log queue to all the router to receive logs from external process
- undelivered kombo message queues to handle orphan messages
"""
queues = {}
queues['logs'] = Queue('logs',
exchange=self.exchanges['psms'],
routing_key="logs",
durable=False)
queues['undelivered_kombu_message'] = Queue('ae.undeliver',
exchange=self.exchanges['psms'],
routing_key="ae.undeliver",
durable=self.persistent)
return queues
def get_connection(self):
"""
Return a connection instance configured as described in the settings
file.
"""
transport = settings.MESSAGE_BROKER['transport']
transport_options = settings.MESSAGE_BROKER.get("options", {})
return BrokerConnection(transport=transport, **transport_options)
def get_exchanges(self):
"""
Define one exchange only for all messages and log. Routing
will be done only at the routing key level.
"""
# todo: use topic routing ?
# http://packages.python.org/kombu/reference/kombu.entity.html?#kombu.entity.Exchange.type
return {'psms': Exchange("psms", "direct", durable=self.persistent)}
def get_producers(self):
"""
One producer only for all messages, since we have only one exchange.
"""
return {'psms': Producer(self.channel, exchange=self.exchanges['psms'])}
def start(self, timeout=1, limit=-1, force_purge=None):
"""
Ensure force purge if required by the settting file
"""
purge = not getattr(settings, 'PERSISTENT_MESSAGE_QUEUES', True)
if force_purge is not None:
purge = force_purge
return Worker.start(self, timeout, limit, force_purge=purge)
def log(self, lvl, msg, *args, **kwargs):
"""
Push this log message into the log queue so the router
can pop it and print it on the main terminal.
"""
log = {'lvl': lvl, 'msg': msg, 'args': args, 'kwargs': kwargs}
self.producers['psms'].publish(body=log, routing_key="logs")