forked from mozilla/briar-patch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPulseBroker.py
352 lines (268 loc) · 11.2 KB
/
PulseBroker.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
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
""" PulseBroker
:copyright: (c) 2012 by Mozilla
:license: MPLv2
Assumes Python v2.6+
Usage
-c --config Configuration file (json format)
default: None
-r --redis Redis server connection string
default: localhost:6379
--redisdb Redis database ID
default: 8
-p --pulse Pulse server connection string
default: None (i.e. Mozilla's Pulse)
-t --topic Pulse topic string
default: #
-d --debug Turn on debug logging
default: False
-l --logpath Path where the log file output is written
default: None
-b --background Fork to a daemon process
default: False
Sample Configuration file
{ 'redis': 'localhost:6379',
'debug': True,
'logpath': '.'
}
Authors:
bear Mike Taylor <[email protected]>
"""
import os
import json
import time
from Queue import Empty
from multiprocessing import Process, Queue, get_logger
import zmq
from releng import initOptions, initLogs, dbRedis
from releng.constants import ID_PULSE_WORKER
from mozillapulse import consumers
appInfo = '[email protected]|briar-patch'
log = get_logger()
eventQueue = Queue()
SERVER_CHECK_INTERVAL = 120 # how often, in minutes, to check for new servers
PING_FAIL_MAX = 1 # how many pings can fail before server is marked inactive
PING_INTERVAL = 120 # ping servers every 2 minutes
MSG_TIMEOUT = 120 # 2 minutes until a pending message is considered expired
def OfflineTest(options):
log.info('Starting Offline message testing')
hArchive = open(options.testfile, 'r+')
for msg in hArchive:
job = json.loads(msg)
pushJob(job)
hArchive.close()
def cbMessage(data, message):
""" cbMessage
Parses the incoming pulse event and create a "job" that will be sent
to a job processing server via ZeroMQ router.
The job is placed into an event queue for async processing.
"""
message.ack()
routingKey = data['_meta']['routing_key']
msgType = routingKey.split('.')[0]
payload = data['payload']
job = {}
job['master'] = data['_meta']['master_name']
job['pulse_key'] = routingKey
job['time'] = data['_meta']['sent']
job['id'] = data['_meta']['message_id']
job['pulse'] = data
if msgType == 'build':
if 'build' in payload:
job['slave'] = payload['build']['slave']
job['event'] = 'build'
pushJob(job)
elif msgType == 'slave':
if 'slave' in payload:
job['slave'] = payload['slave']['name']
job['event'] = 'slave connect'
else:
job['slave'] = payload['slavename']
job['event'] = 'slave disconnect'
pushJob(job)
elif msgType == 'change':
job['event'] = 'source'
pushJob(job)
class zmqService(object):
def __init__(self, serverID, router, db, events):
self.router = router
self.db = db
self.events = events
self.payload = None
self.expires = None
self.sequence = 0
self.errors = 0
self.alive = True
self.lastPing = time.time()
self.id = serverID
self.address = self.id.replace('%s:' % ID_PULSE_WORKER, '')
if ':' not in self.address:
self.address = '%s:5555' % self.address
self.address = 'tcp://%s' % self.address
log.debug('connecting to server %s' % self.address)
self.router.connect(self.address)
time.sleep(0.1)
def isAvailable(self):
return self.alive and self.payload is None
def reply(self, reply):
if options.debug:
log.debug('reply %s' % self.id)
sequenceReply = reply.pop(0)
if options.debug:
log.debug('recv %s [%s]' % (self.id, reply[0]))
self.errors = 0
self.alive = True
self.lastPing = time.time()
self.expires = self.lastPing + MSG_TIMEOUT
if int(sequenceReply) == self.sequence:
self.payload = None
else:
log.error('reply received out of sequence')
def request(self, msg):
if options.debug:
log.debug('request %s' % self.id)
if self.isAvailable():
self.sequence += 1
self.payload = [self.id, str(self.sequence), 'job', msg]
self.expires = time.time() + MSG_TIMEOUT
if options.debug:
log.debug('send %s %d chars [%s]' % (self.id, len(msg), msg[:42]))
self.router.send_multipart(self.payload)
return True
else:
return False
def heartbeat(self):
if self.payload is not None and time.time() > self.expires:
if self.payload[2] == 'ping':
log.warning('server %s has failed to respond to %d ping requests' % (self.id, self.errors))
if self.errors >= PING_FAIL_MAX:
log.error('removing %s from server list' % self.id)
db.sadd('%s:inactive' % ID_PULSE_WORKER, self.id)
else:
self.ping(force=True)
else:
log.warning('server %s has expired request: %s' % (self.id, ','.join(self.payload)))
self.ping()
if time.time() - self.lastPing > PING_INTERVAL:
self.ping()
def ping(self, force=False):
if options.debug:
log.debug('ping %s' % self.id)
if force or self.isAvailable():
self.sequence += 1
self.payload = [self.id, str(self.sequence), 'ping']
self.lastPing = time.time()
self.expires = self.lastPing + MSG_TIMEOUT
self.errors += 1
self.alive = False
self.router.send_multipart(self.payload)
else:
log.warning('ping requested for offline service [%s]' % self.id)
def discoverServers(servers, db, events, router):
for serverID in db.lrange(ID_PULSE_WORKER, 0, -1):
if db.sismember('%s:inactive' % ID_PULSE_WORKER, serverID):
log.warning('server %s found in inactive list, disconnecting' % serverID)
if serverID in servers:
servers[serverID] = None
del servers[serverID]
else:
if serverID not in servers:
log.debug('server %s is new, adding to connect queue' % serverID)
servers[serverID] = zmqService(serverID, router, db, events)
def handleZMQ(options, events, db):
""" handleZMQ
Primary event loop for everything ZeroMQ related
All payloads to be sent onward arrive via the event queue.
Currently it is a very simple implementation of the Freelance
pattern with no server heartbeat checks.
The incoming events are structured as a list that always
begins with the event type.
Job: ('job', "{'payload': 'sample'}")
Heartbeat: ('ping',)
The structure of the message sent between nodes is:
[destination, sequence, control, payload]
all items are sent as strings.
"""
log.info('starting')
servers = {}
lastDiscovery = time.time()
context = zmq.Context()
router = context.socket(zmq.ROUTER)
poller = zmq.Poller()
poller.register(router, zmq.POLLIN)
while True:
available = False
for serverID in servers:
if servers[serverID].isAvailable():
available = True
break
try:
event = events.get(False)
except Empty:
event = None
if event is not None:
if available:
eventType = event[0]
if eventType == 'ping':
ping(servers, event[1])
elif eventType == 'job':
handled = False
for serverID in servers:
if servers[serverID].isAvailable() and servers[serverID].request(event[1]):
handled = True
break
if not handled:
log.error('no active servers to handle request')
# TODO - push archived item to redis
else:
log.warning('unknown event [%s]' % eventType)
else:
log.error('no active servers to handle request')
try:
items = dict(poller.poll(100))
except:
break
if router in items:
reply = router.recv_multipart()
serverID = reply.pop(0)
servers[serverID].reply(reply)
else:
for serverID in servers:
servers[serverID].heartbeat()
if time.time() > lastDiscovery:
discoverServers(servers, db, events, router)
lastDiscovery = time.time() + SERVER_CHECK_INTERVAL
log.info('done')
def pushJob(job):
s = json.dumps(job)
eventQueue.put(('job', s))
_defaultOptions = { 'config': ('-c', '--config', None, 'Configuration file'),
'debug': ('-d', '--debug', True, 'Enable Debug', 'b'),
'appinfo': ('-a', '--appinfo', appInfo, 'Mozilla Pulse app string'),
'background': ('-b', '--background', False, 'daemonize ourselves', 'b'),
'logpath': ('-l', '--logpath', None, 'Path where log file is to be written'),
'redis': ('-r', '--redis', 'localhost:6379', 'Redis connection string'),
'redisdb': ('', '--redisdb', '8', 'Redis database'),
'pulse': ('-p', '--pulse', None, 'Pulse connection string'),
'topic': ('-t', '--topic', '#', 'Mozilla Pulse Topic filter string'),
'testfile': ('', '--testfile', None, 'Offline testing, uses named file instead of Pulse server'),
}
if __name__ == '__main__':
options = initOptions(params=_defaultOptions)
initLogs(options)
log.info('Starting')
log.info('Connecting to datastore')
db = dbRedis(options)
log.info('Creating ZeroMQ handler')
Process(name='zmq', target=handleZMQ, args=(options, eventQueue, db)).start()
if options.testfile:
OfflineTest(options)
else:
log.info('Connecting to Mozilla Pulse with topic "%s"' % options.topic)
pulse = consumers.BuildConsumer(applabel=options.appinfo)
pulse.configure(topic=options.topic, callback=cbMessage)
log.debug('Starting pulse.listen()')
pulse.listen()