1 # ==================================================================================
2 # Copyright (c) 2019 Nokia
3 # Copyright (c) 2018-2019 AT&T Intellectual Property.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 # ==================================================================================
19 from ctypes import RTLD_GLOBAL, Structure, c_int, POINTER, c_char, c_char_p, c_void_p, memmove, cast
20 from ctypes import CDLL
21 from ctypes import create_string_buffer
23 # https://docs.python.org/3.7/library/ctypes.html
24 # https://stackoverflow.com/questions/2327344/ctypes-loading-a-c-shared-library-that-has-dependencies/30845750#30845750
25 # make sure you do a set -x LD_LIBRARY_PATH /usr/local/lib/;
27 # even though we don't use these directly, they contain symbols we need
28 _ = CDLL("libnng.so", mode=RTLD_GLOBAL)
29 rmr_c_lib = CDLL("librmr_nng.so", mode=RTLD_GLOBAL)
32 # Internal Helpers (not a part of public api)
35 _rmr_const = rmr_c_lib.rmr_get_consts
36 _rmr_const.argtypes = []
37 _rmr_const.restype = c_char_p
40 def _get_constants(cache={}):
42 Get or build needed constants from rmr
43 TODO: are there constants that end user applications need?
48 js = _rmr_const() # read json string
49 cache = json.loads(str(js.decode())) # create constants value object as a hash
53 def _get_mapping_dict(cache={}):
55 Get or build the state mapping dict
57 RMR_OK 0 state is good
58 RMR_ERR_BADARG 1 argument passd to function was unusable
59 RMR_ERR_NOENDPT 2 send/call could not find an endpoint based on msg type
60 RMR_ERR_EMPTY 3 msg received had no payload; attempt to send an empty message
61 RMR_ERR_NOHDR 4 message didn't contain a valid header
62 RMR_ERR_SENDFAILED 5 send failed; errno has nano reason
63 RMR_ERR_CALLFAILED 6 unable to send call() message
64 RMR_ERR_NOWHOPEN 7 no wormholes are open
65 RMR_ERR_WHID 8 wormhole id was invalid
66 RMR_ERR_OVERFLOW 9 operation would have busted through a buffer/field size
67 RMR_ERR_RETRY 10 request (send/call/rts) failed, but caller should retry (EAGAIN for wrappers)
68 RMR_ERR_RCVFAILED 11 receive failed (hard error)
69 RMR_ERR_TIMEOUT 12 message processing call timed out
70 RMR_ERR_UNSET 13 the message hasn't been populated with a transport buffer
71 RMR_ERR_TRUNC 14 received message likely truncated
72 RMR_ERR_INITFAILED 15 initialization of something (probably message) failed
78 rmr_consts = _get_constants()
79 for key in rmr_consts: # build the state mapping dict
80 if key[:7] in ["RMR_ERR", "RMR_OK"]:
81 en = int(rmr_consts[key])
87 def _state_to_status(stateno):
89 Convert a msg state to status
92 sdict = _get_mapping_dict()
93 return sdict.get(stateno, "UNKNOWN STATE")
96 _RCONST = _get_constants()
104 # These constants are directly usable by importers of this library
105 # TODO: Are there others that will be useful?
107 RMR_MAX_RCV_BYTES = _RCONST["RMR_MAX_RCV_BYTES"]
108 RMRFL_MTCALL = _RCONST.get("RMRFL_MTCALL", 0x02) # initialization flags
109 RMRFL_NONE = _RCONST.get("RMRFL_NONE", 0x0)
110 RMR_OK = _RCONST["RMR_OK"] # useful state constants
111 RMR_ERR_TIMEOUT = _RCONST["RMR_ERR_TIMEOUT"]
112 RMR_ERR_RETRY = _RCONST["RMR_ERR_RETRY"]
115 class rmr_mbuf_t(Structure):
117 Reimplementation of rmr_mbuf_t which is in an unaccessible header file (src/common/include/rmr.h)
120 | int state; // state of processing
121 | int mtype; // message type
122 | int len; // length of data in the payload (send or received)
123 | unsigned char* payload; // transported data
124 | unsigned char* xaction; // pointer to fixed length transaction id bytes
125 | int sub_id; // subscription id
126 | int tp_state; // transport state (a.k.a errno)
128 | these things are off limits to the user application
130 | void* tp_buf; // underlying transport allocated pointer (e.g. nng message)
131 | void* header; // internal message header (whole buffer: header+payload)
132 | unsigned char* id; // if we need an ID in the message separate from the xaction id
133 | int flags; // various MFL (private) flags as needed
134 | int alloc_len; // the length of the allocated space (hdr+payload)
137 We do not include the fields we are not supposed to mess with
139 RE PAYLOADs type below, see the documentation for c_char_p:
140 class ctypes.c_char_p
141 Represents the C char * datatype when it points to a zero-terminated string. For a general character pointer that may also point to binary data, POINTER(c_char) must be used. The constructor accepts an integer address, or a bytes object.
151 ), # according to th following the python bytes are already unsinged https://bytes.com/topic/python/answers/695078-ctypes-unsigned-char
152 ("xaction", POINTER(c_char)),
158 # argtypes and restype are important: https://stackoverflow.com/questions/24377845/ctype-why-specify-argtypes
161 _rmr_init = rmr_c_lib.rmr_init
162 _rmr_init.argtypes = [c_char_p, c_int, c_int]
163 _rmr_init.restype = c_void_p
166 def rmr_init(uproto_port, max_msg_size, flags):
168 Refer to rmr C documentation for rmr_init
169 extern void* rmr_init(char* uproto_port, int max_msg_size, int flags)
171 return _rmr_init(uproto_port, max_msg_size, flags)
174 _rmr_ready = rmr_c_lib.rmr_ready
175 _rmr_ready.argtypes = [c_void_p]
176 _rmr_ready.restype = c_int
181 Refer to rmr C documentation for rmr_ready
182 extern int rmr_ready(void* vctx)
184 return _rmr_ready(vctx)
187 _rmr_close = rmr_c_lib.rmr_close
188 _rmr_close.argtypes = [c_void_p]
193 Refer to rmr C documentation for rmr_close
194 extern void rmr_close(void* vctx)
196 return _rmr_close(vctx)
199 _rmr_set_stimeout = rmr_c_lib.rmr_set_stimeout
200 _rmr_set_stimeout.argtypes = [c_void_p, c_int]
201 _rmr_set_stimeout.restype = c_int
204 def rmr_set_stimeout(vctx, time):
206 Refer to the rmr C documentation for rmr_set_stimeout
207 extern int rmr_set_stimeout(void* vctx, int time)
209 return _rmr_set_stimeout(vctx, time)
212 _rmr_alloc_msg = rmr_c_lib.rmr_alloc_msg
213 _rmr_alloc_msg.argtypes = [c_void_p, c_int]
214 _rmr_alloc_msg.restype = POINTER(rmr_mbuf_t)
217 def rmr_alloc_msg(vctx, size):
219 Refer to the rmr C documentation for rmr_alloc_msg
220 extern rmr_mbuf_t* rmr_alloc_msg(void* vctx, int size)
222 return _rmr_alloc_msg(vctx, size)
225 _rmr_free_msg = rmr_c_lib.rmr_free_msg
226 _rmr_free_msg.argtypes = [c_void_p]
227 _rmr_free_msg.restype = None
230 def rmr_free_msg(mbuf):
232 Refer to the rmr C documentation for rmr_free_msg
233 extern void rmr_free_msg( rmr_mbuf_t* mbuf )
239 _rmr_payload_size = rmr_c_lib.rmr_payload_size
240 _rmr_payload_size.argtypes = [POINTER(rmr_mbuf_t)]
241 _rmr_payload_size.restype = c_int
244 def rmr_payload_size(ptr_mbuf):
246 Refer to the rmr C documentation for rmr_payload_size
247 extern int rmr_payload_size(rmr_mbuf_t* msg)
249 return _rmr_payload_size(ptr_mbuf)
253 The following functions all seem to have the same interface
256 _rmr_send_msg = rmr_c_lib.rmr_send_msg
257 _rmr_send_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
258 _rmr_send_msg.restype = POINTER(rmr_mbuf_t)
261 def rmr_send_msg(vctx, ptr_mbuf):
263 Refer to the rmr C documentation for rmr_send_msg
264 extern rmr_mbuf_t* rmr_send_msg(void* vctx, rmr_mbuf_t* msg)
266 return _rmr_send_msg(vctx, ptr_mbuf)
269 # TODO: the old message (Send param) is actually optional, but I don't know how to specify that in Ctypes.
270 _rmr_rcv_msg = rmr_c_lib.rmr_rcv_msg
271 _rmr_rcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
272 _rmr_rcv_msg.restype = POINTER(rmr_mbuf_t)
275 def rmr_rcv_msg(vctx, ptr_mbuf):
277 Refer to the rmr C documentation for rmr_rcv_msg
278 extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
280 return _rmr_rcv_msg(vctx, ptr_mbuf)
283 _rmr_torcv_msg = rmr_c_lib.rmr_torcv_msg
284 _rmr_torcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t), c_int]
285 _rmr_torcv_msg.restype = POINTER(rmr_mbuf_t)
288 def rmr_torcv_msg(vctx, ptr_mbuf, ms_to):
290 Refer to the rmr C documentation for rmr_torcv_msg
291 extern rmr_mbuf_t* rmr_torcv_msg(void* vctx, rmr_mbuf_t* old_msg, int ms_to)
293 return _rmr_torcv_msg(vctx, ptr_mbuf, ms_to)
296 _rmr_rts_msg = rmr_c_lib.rmr_rts_msg
297 _rmr_rts_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
298 _rmr_rts_msg.restype = POINTER(rmr_mbuf_t)
301 def rmr_rts_msg(vctx, ptr_mbuf):
303 Refer to the rmr C documentation for rmr_rts_msg
304 extern rmr_mbuf_t* rmr_rts_msg(void* vctx, rmr_mbuf_t* msg)
306 return _rmr_rts_msg(vctx, ptr_mbuf)
309 _rmr_call = rmr_c_lib.rmr_call
310 _rmr_call.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
311 _rmr_call.restype = POINTER(rmr_mbuf_t)
314 def rmr_call(vctx, ptr_mbuf):
316 Refer to the rmr C documentation for rmr_call
317 extern rmr_mbuf_t* rmr_call(void* vctx, rmr_mbuf_t* msg)
319 return _rmr_call(vctx, ptr_mbuf)
322 _rmr_bytes2meid = rmr_c_lib.rmr_bytes2meid
323 _rmr_bytes2meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p, c_int]
324 _rmr_bytes2meid.restype = c_int
327 def rmr_bytes2meid(ptr_mbuf, src, length):
329 Refer to the rmr C documentation for rmr_bytes2meid
330 extern int rmr_bytes2meid(rmr_mbuf_t* mbuf, unsigned char const* src, int len);
332 return _rmr_bytes2meid(ptr_mbuf, src, length)
335 # this is an alias to rmr_bytes2meid using familiar set/get terminoloigy
336 rmr_set_meid = rmr_bytes2meid
338 # CAUTION: Some of the C functions expect a mutable buffer to copy the bytes into;
339 # if there is a get_* function below, use it to set up and return the
342 # extern unsigned char* rmr_get_meid(rmr_mbuf_t* mbuf, unsigned char* dest);
343 # we don't provide direct access to this function (unless it is asked for) because it is not really useful to provide your own buffer.
344 # Rather, rmr_get_meid does this for you, and just returns the string.
345 _rmr_get_meid = rmr_c_lib.rmr_get_meid
346 _rmr_get_meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
347 _rmr_get_meid.restype = c_char_p
350 def rmr_get_meid(ptr_mbuf):
352 Get the managed equipment ID (meid) from the message header.
356 ptr_mbuf: ctypes c_void_p
357 Pointer to an rmr message buffer
364 sz = _get_constants().get("RMR_MAX_MEID", 64) # size for buffer to fill
365 buf = create_string_buffer(sz)
366 _rmr_get_meid(ptr_mbuf, buf)
367 return buf.value.decode() # decode turns into a string
370 _rmr_get_src = rmr_c_lib.rmr_get_src
371 _rmr_get_src.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
372 _rmr_get_src.restype = c_char_p
375 def rmr_get_src(ptr_mbuf, dest):
377 Refer to the rmr C documentation for rmr_get_src
378 extern unsigned char* rmr_get_src(rmr_mbuf_t* mbuf, unsigned char* dest);
380 return _rmr_get_src(ptr_mbuf, dest)
383 # Methods that exist ONLY in rmr-python, and are not wrapped methods
384 # In hindsight, I wish i put these in a seperate module, but leaving this here to prevent api breakage.
387 def get_payload(ptr_mbuf):
389 Given a rmr_buf_t*, get it's binary payload as a bytes object
393 ptr_mbuf: ctypes c_void_p
394 Pointer to an rmr message buffer
401 # Logic came from the answer here: https://stackoverflow.com/questions/55103298/python-ctypes-read-pointerc-char-in-python
402 sz = ptr_mbuf.contents.len
403 CharArr = c_char * sz
404 return CharArr(*ptr_mbuf.contents.payload[:sz]).raw
407 def get_xaction(ptr_mbuf):
409 given a rmr_buf_t*, get it's transaction id
413 ptr_mbuf: ctypes c_void_p
414 Pointer to an rmr message buffer
421 val = cast(ptr_mbuf.contents.xaction, c_char_p).value
422 sz = _get_constants().get("RMR_MAX_XID", 0)
426 def message_summary(ptr_mbuf):
428 Returns a dict that contains the fields of a message
432 ptr_mbuf: ctypes c_void_p
433 Pointer to an rmr message buffer
440 if ptr_mbuf.contents.len > RMR_MAX_RCV_BYTES:
441 return "Malformed message: message length is greater than the maximum possible"
444 "payload": get_payload(ptr_mbuf),
445 "payload length": ptr_mbuf.contents.len,
446 "message type": ptr_mbuf.contents.mtype,
447 "subscription id": ptr_mbuf.contents.sub_id,
448 "transaction id": get_xaction(ptr_mbuf),
449 "message state": ptr_mbuf.contents.state,
450 "message status": _state_to_status(ptr_mbuf.contents.state),
451 "payload max size": rmr_payload_size(ptr_mbuf),
452 "meid": rmr_get_meid(ptr_mbuf),
453 "message source": get_src(ptr_mbuf),
454 "errno": ptr_mbuf.contents.tp_state,
458 def set_payload_and_length(byte_str, ptr_mbuf):
460 | Set an rmr payload and content length
461 | In place method, no return
466 the bytes to set the payload to
467 ptr_mbuf: ctypes c_void_p
468 Pointer to an rmr message buffer
470 memmove(ptr_mbuf.contents.payload, byte_str, len(byte_str))
471 ptr_mbuf.contents.len = len(byte_str)
474 def generate_and_set_transaction_id(ptr_mbuf):
476 | Generate a UUID and Set an rmr transaction id to it
477 | In place method, no return
481 ptr_mbuf: ctypes c_void_p
482 Pointer to an rmr message buffer
484 uu_id = uuid.uuid1().hex.encode("utf-8")
485 sz = _get_constants().get("RMR_MAX_XID", 0)
486 memmove(ptr_mbuf.contents.xaction, uu_id, sz)
489 def get_src(ptr_mbuf):
491 Get the message source (likely host:port)
495 ptr_mbuf: ctypes c_void_p
496 Pointer to an rmr message buffer
503 sz = _get_constants().get("RMR_MAX_SRC", 64) # size to fill
504 buf = create_string_buffer(sz)
505 rmr_get_src(ptr_mbuf, buf)
506 return buf.value.decode()