-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhmb_messaging.py
More file actions
416 lines (350 loc) · 16.5 KB
/
hmb_messaging.py
File metadata and controls
416 lines (350 loc) · 16.5 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#!/usr/bin/env python27
"""Module for sending messages to an httpmsgbus server. """
"""
TO DO?
recv_all() - remove timeout code? rely on requests timeouts?
- change retries semantics to apply to the top level loop?
"""
import requests
import time
import json
import logging
import bson
import numbers
######## Default Logger #####
logger = logging.getLogger("hmb_messaging")
logger.setLevel(logging.INFO)
if not logger.handlers:
# create console handler and set level to warning
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s.%(process)d - %(message)s')
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
#############################
class Hmbsession(object):
def __init__(self, url, param={}, logger=logger, retry_wait=1, use_bson=False, autocreate_queues=False, **kwargs):
"""opens a session with an hmb server at provided url.
param = {
"cid": <string>,
"heartbeat": <int>,
"recv_limit": <int>,
"queue": {
<queue_name>: {
"topics": <list of string>,
"seq": <int>,
"endseq": <int>,
"starttime": <string>,
"endtime": <string>,
"filter": <doc>,
"qlen": <int>,
"oowait": <int>,
"keep": <bool>
},
...
},
}
"""
self.url = url
self.param = param
self.connection_kwargs = kwargs
self._logger = logger
self.retry_wait = retry_wait
self._sid = None
self._oid = ''
self._use_json = not use_bson #flag selecting format of messages: either json or bson
self._autocreate_queues = autocreate_queues #This might sometimes prevent issues over missing queues
"""
if 'queue' in self.param:
# initially set 'keep' to false to get pending data
for q in self.param['queue'].values():
q['keep'] = False
"""
def _open(self):
"""opens the HMB session"""
try:
headers = {"Content-type": "application/json" if self._use_json else "application/bson"}
r = requests.post(self.url + '/open',
data=json.dumps(self.param) if self._use_json else bson.BSON.encode(self.param),
headers=headers, **self.connection_kwargs)
if r.status_code == 400:
raise requests.exceptions.RequestException("bad request: " + r.text.strip())
elif r.status_code == 503:
raise requests.exceptions.RequestException("service unavailable: " + r.text.strip())
r.raise_for_status()
ack = r.json() if self._use_json else bson.BSON(r.content).decode()
self._sid = ack['sid']
self._oid = ''
self.param['cid'] = ack['cid']
qinfo = ack.get('queue',{})
for qname,queue in qinfo.items():
seqnext = queue['seq']
if isinstance(seqnext,numbers.Integral) and qname in self.param['queue']:
if seqnext > self.param['queue'][qname].get('seq',None):
self.param['queue'][qname]['seq'] = seqnext #next message number
#errors or missing queues
for qname,queue in qinfo.items():
error = queue.get('error',None)
if error:
self._logger.warning("hmb server gives an error for queue '%s': %s",qname,error)
#if queue not found then create queue?
if error == u'queue not found' and self._autocreate_queues:
msg = {'type':'TOUCH','queue':qname}
self.send({'0':msg} if self._use_json else msg)
self.param['queue'][qname]['seq'] = 1
self._logger.warning("created (hmb) queue '%s' by sending test message",qname)
self._logger.info("hmbsession opened, sid=%s, cid=%s",ack['sid'], ack['cid'])
self._logger.info("hmbsession parameters are: %r",self.param)
except requests.exceptions.RequestException as e:
errmsg = str(e)
if "service unavailable" in errmsg:
errmsg = "service unavailable: The server is down due to maintenance downtime or capacity problems"
self._logger.warning("hmb error: %s",errmsg)
self._logger.warning("connection to hmb message bus failed")
def info(self):
"""gets info from the hmb server on defined queues, topics and available
data."""
try:
return self._info_request('info')
except requests.exceptions.RequestException as e:
self._logger.error("error getting info: %s",str(e))
return None
def features(self):
"""gets functions and capabilities supported by the server and optionally
the name and version of the server software."""
try:
return self._info_request('features')
except requests.exceptions.RequestException as e:
self._logger.error("error getting features: %s",str(e))
return None
def status(self):
"""gets status of connected clients (sessions)."""
try:
return self._info_request('status')
except requests.exceptions.RequestException as e:
self._logger.error("error getting status: %s",str(e))
return None
def _info_request(self,cmd):
"""gets info, functions and capabilities supported by the server."""
r = requests.get(self.url + '/'+cmd, **self.connection_kwargs)
if r.status_code == 400:
raise requests.exceptions.RequestException("bad request: " + r.text.strip())
elif r.status_code == 503:
raise requests.exceptions.RequestException("service unavailable: " + r.text.strip())
r.raise_for_status()
return r.json()
def set_format(self,use_bson):
"""defines whether connection object should use bson or json
note that this may force the connection to the server to be reestablished.
"""
if not isinstance(use_bson,bool):
raise TypeError("use_bson must be a boolean value")
if self._use_json != use_bson:
#no change to format so do nothing
pass
else:
self._use_json = not use_bson
self._sid = None #mark session as closed
def send_msg(self,mtype,queue,data,topic=None,retries=1,**kwargs):
"""send single message to HMB session.
mtype - message type (string)
queue - destination queue of the message
data - json compatible payload
topic - optional tag for the message
retries - number of times to retry sending message
kwargs - any extra keyvalues to put in the message ie. seq, starttime, endtime
"""
msg = {"type":mtype,
"queue":queue,
"data":data}
if topic: msg["topic"] = topic
for k,v in kwargs.items(): msg["k"] = v
if self._use_json: msg = {0:msg} #json messages always require multi-message format
else: pass #bson messages use a different type of concatenation
self.send(msg,retries)
def send(self,msg,retries=1):
"""send message to HMB session. Handles disconnections and retries
sending the message. The message should have the correct hmb format.
"""
for i in range(retries+1):
try:
if not self._sid:
self._open()
self._send(msg)
except Exception as e:
self._sid = None #mark session as closed
if i == retries:
self._logger.error("hmb error: %s",str(e))
self._logger.error("problem hmb msg: %s", msg) #the first time it probably isn't the message's fault
elif i == 0:
self._logger.info("hmb error: %s",str(e))
self._logger.info("closing connection to hmb message bus lost, retrying")
else:
self._logger.warning("hmb error: %s",str(e))
self._logger.warning("problem hmb msg: %s", msg) #the first time it probably isn't the message's fault
self._logger.warning("closing connection to hmb message bus lost, retrying in %d seconds", self.retry_wait)
time.sleep(self.retry_wait) #don't wait on the first retry
else: #if no exceptions -
break
def _send(self,msg):
"""actually sends message to HMB session"""
r = requests.post(self.url + '/send/' + self._sid,
headers={"Content-type": "application/json" if self._use_json else "application/bson"},
data=json.dumps(msg,allow_nan=False) if self._use_json else bson.BSON.encode(msg),
**self.connection_kwargs)
if r.status_code == 400:
raise requests.exceptions.RequestException("bad request: " + r.text.strip())
elif r.status_code == 503:
raise requests.exceptions.RequestException("service unavailable: " + r.text.strip())
r.raise_for_status()
def recv_all(self,retries=1,timeout=None):
"""receives all messages from an HMB query. This should not be
used for realtime operation."""
starttime = time.time()
starttime -= 0.2 #correction factor so that timeout works as expected.
messages = []
while True:
subset = self.recv(retries=retries)
if not subset: #no messages received
pass #(continue)
elif subset[-1]['type'] != 'EOF':
messages += subset
else:
messages += subset[:-1]
break
if timeout and time.time() > starttime + timeout:
self._sid = None
break
return messages
def recv(self,retries=1):
"""receives messages from HMB session. Request is blocking until the
next heartbeat message if "keep=True" is specified in the connection
parameters for any of the queues.. HEARTBEAT messages are
elimated but EOF messages are kept so that we know when the end of
the stream is reached."""
messages = []
for i in range(retries+1):
try:
if not self._sid:
self._open()
messages = self._recv()
except Exception as e:
self._sid = None #mark session as closed
if i == retries:
self._logger.error("hmb error: %s",str(e))
elif i == 0:
self._logger.info("hmb error: %s",str(e))
self._logger.info("connection to hmb message bus lost, retrying")
else:
self._logger.warning("hmb error: %s",str(e))
self._logger.warning("connection to hmb message bus lost, retrying in %d seconds", self.retry_wait)
time.sleep(self.retry_wait) #don't wait on the first retry
else: #if no exceptions.
break
#else:
# raise
#eliminate HEARTBEAT messages
messages = [m for m in messages if m['type'] not in ('HEARTBEAT',)]
return messages
def _recv(self):
"""actually receive messages from HMB. Request is blocking if "keep=True"
is specified in the connection parameters for any of the queues."""
r = requests.get(self.url + '/recv/' + self._sid + self._oid, **self.connection_kwargs)
if r.status_code == 400:
raise requests.exceptions.RequestException("bad request: " + r.text.strip())
elif r.status_code == 503:
raise requests.exceptions.RequestException("service unavailable: " + r.text.strip())
r.raise_for_status()
if self._use_json:
msgdict = r.json() # can be multiple messages
messages = [msgdict[str(i)] for i in range(len(msgdict))] #convert to list
else: #bson
messages = bson.decode_all(r.content)
#print r.content
#print
#print msgdict
#print
###
seqnum = None
for obj in messages:
#extracts sequence number from messages to ensure future continuity of messages received.
if 'seq' in obj and 'queue' in obj:
seqnum = obj['seq']
if isinstance(seqnum,numbers.Integral):
if seqnum >= self.param['queue'][obj['queue']]['seq']:
self.param['queue'][obj['queue']]['seq'] = seqnum + 1 #next message number
self._oid = '/%s/%d' % (obj['queue'], seqnum)
#closing session if EOF message is last message received
if obj['type'] == 'EOF': #will always be the last message?
self._sid = None #close current session when we reach latest message.
#changing queues to realtime mode
#is this useful?
"""
try:
if obj['type'] == 'EOF':
self._sid = None #close current session when we reach latest message.
for q in self.param['queue'].values():
q['keep'] = True #change session connection parameters to keep session alive
except KeyError:
pass
"""
###
return messages
#############################
def example0():
"""Very basic example of receiving HMB messages"""
# Choose here the bus to subsribe:
#hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule0' # CLOSEST
hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule1' # FASTER
#hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule2' # STRONGEST
#hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule3' # HIGHEST
param = {
'queue': {
'SYSTEM_ALERT': { #choose queue to listen on
'seq': -5, #choose message to start at.
'keep': True #make request blocking
}
}
}
#each message in the queue has a sequence number. Setting:
#seq=-1 => start with next new message
#seq=-2 => start with most recent message
#seq=-3 => start with message before the last message.
#...
#seq=10 => start with the 10th message in the queue
hmbconn = Hmbsession(url=hmbbus, param=param, use_bson=False)
msgs = hmbconn.recv()
for msg in msgs:
logger.info('hmb msg: %r',msg)
def example1():
"""Basic example of receiving HMB messages with some robustness"""
# Choose here the bus to subsribe:
#hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule0' # CLOSEST
hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule1' # FASTER
#hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule2' # STRONGEST
#hmbbus='http://cerf.emsc-csem.org:80/MTtest_rule3' # HIGHEST
param = {
'heartbeat': 10, #sec
'queue': {
'SYSTEM_ALERT': { #choose queue to listen on
'seq': -1, #choose message to start at.
'keep': True, #make request blocking
#'topics': [],
}
}
}
hmbconn = Hmbsession(url=hmbbus, param=param, use_bson=True, retry_wait=2, timeout=(6.05,11), autocreate_queues=True)
#setup timeouts just longer than the heartbeat rate
#set a delay between retries
while True:
msgs = hmbconn.recv(retries=10)
#the method will retry in the event of an error or timeout by reopening a
#new connection to the server and trying again.
#nb. msgs might be empty due to eliminated heartbeat messages
for msg in msgs:
logger.info('hmb msg: %r',msg)
if __name__ == "__main__":
#example0()
example1()