Greatly improve test coverage
[ric-plt/lib/rmr.git] / src / bindings / rmr-python / rmr / rmr.py
1 # ==================================================================================
2 #       Copyright (c) 2019 Nokia
3 #       Copyright (c) 2018-2019 AT&T Intellectual Property.
4 #
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
8 #
9 #          http://www.apache.org/licenses/LICENSE-2.0
10 #
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 # ==================================================================================
17 import uuid
18 import json
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
22
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/;
26
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)
30
31
32 # Internal Helpers (not a part of public api)
33
34
35 _rmr_const = rmr_c_lib.rmr_get_consts
36 _rmr_const.argtypes = []
37 _rmr_const.restype = c_char_p
38
39
40 def _get_constants(cache={}):
41     """
42     Get or build needed constants from rmr
43     TODO: are there constants that end user applications need?
44     """
45     if cache:
46         return cache
47
48     js = _rmr_const()  # read json string
49     cache = json.loads(str(js.decode()))  # create constants value object as a hash
50     return cache
51
52
53 def _get_mapping_dict(cache={}):
54     """
55     Get or build the state mapping dict
56
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  initialisation of something (probably message) failed
73
74     """
75     if cache:
76         return cache
77
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])
82             cache[en] = key
83
84     return cache
85
86
87 def _state_to_status(stateno):
88     """
89     Convert a msg state to status
90
91     """
92     sdict = _get_mapping_dict()
93     return sdict.get(stateno, "UNKNOWN STATE")
94
95
96 ##############
97 # PUBLIC API
98 ##############
99
100
101 # These constants are directly usable by importers of this library
102 # TODO: Are there others that will be useful?
103 RMR_MAX_RCV_BYTES = _get_constants()["RMR_MAX_RCV_BYTES"]
104
105
106 class rmr_mbuf_t(Structure):
107     """
108     Reimplementation of rmr_mbuf_t which is in an unaccessible header file (src/common/include/rmr.h)
109
110     | typedef struct {
111     |    int     state;          // state of processing
112     |    int     mtype;          // message type
113     |    int     len;            // length of data in the payload (send or received)
114     |    unsigned char* payload; // transported data
115     |    unsigned char* xaction; // pointer to fixed length transaction id bytes
116     |    int sub_id;             // subscription id
117     |    int      tp_state;      // transport state (a.k.a errno)
118     |
119     | these things are off limits to the user application
120     |
121     |    void*   tp_buf;         // underlying transport allocated pointer (e.g. nng message)
122     |    void*   header;         // internal message header (whole buffer: header+payload)
123     |    unsigned char* id;      // if we need an ID in the message separate from the xaction id
124     |    int flags;              // various MFL (private) flags as needed
125     |    int alloc_len;          // the length of the allocated space (hdr+payload)
126     | } rmr_mbuf_t;
127
128     We do not include the fields we are not supposed to mess with
129
130     RE PAYLOADs type below, see the documentation for c_char_p:
131        class ctypes.c_char_p
132            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.
133     """
134
135     _fields_ = [
136         ("state", c_int),
137         ("mtype", c_int),
138         ("len", c_int),
139         (
140             "payload",
141             POINTER(c_char),
142         ),  # according to th following the python bytes are already unsinged https://bytes.com/topic/python/answers/695078-ctypes-unsigned-char
143         ("xaction", POINTER(c_char)),
144         ("sub_id", c_int),
145         ("tp_state", c_int),
146     ]
147
148
149 # argtypes and restype are important: https://stackoverflow.com/questions/24377845/ctype-why-specify-argtypes
150
151
152 _rmr_init = rmr_c_lib.rmr_init
153 _rmr_init.argtypes = [c_char_p, c_int, c_int]
154 _rmr_init.restype = c_void_p
155
156
157 def rmr_init(uproto_port, max_msg_size, flags):
158     """
159     Refer to rmr C documentation for rmr_init
160     extern void* rmr_init(char* uproto_port, int max_msg_size, int flags)
161     """
162     return _rmr_init(uproto_port, max_msg_size, flags)
163
164
165 _rmr_ready = rmr_c_lib.rmr_ready
166 _rmr_ready.argtypes = [c_void_p]
167 _rmr_ready.restype = c_int
168
169
170 def rmr_ready(vctx):
171     """
172     Refer to rmr C documentation for rmr_ready
173     extern int rmr_ready(void* vctx)
174     """
175     return _rmr_ready(vctx)
176
177
178 _rmr_close = rmr_c_lib.rmr_close
179 _rmr_close.argtypes = [c_void_p]
180
181
182 def rmr_close(vctx):
183     """
184     Refer to rmr C documentation for rmr_close
185     extern void rmr_close(void* vctx)
186     """
187     return _rmr_close(vctx)
188
189
190 _rmr_set_stimeout = rmr_c_lib.rmr_set_stimeout
191 _rmr_set_stimeout.argtypes = [c_void_p, c_int]
192 _rmr_set_stimeout.restype = c_int
193
194
195 def rmr_set_stimeout(vctx, time):
196     """
197     Refer to the rmr C documentation for rmr_set_stimeout
198     extern int rmr_set_stimeout(void* vctx, int time)
199     """
200     return _rmr_set_stimeout(vctx, time)
201
202
203 _rmr_alloc_msg = rmr_c_lib.rmr_alloc_msg
204 _rmr_alloc_msg.argtypes = [c_void_p, c_int]
205 _rmr_alloc_msg.restype = POINTER(rmr_mbuf_t)
206
207
208 def rmr_alloc_msg(vctx, size):
209     """
210     Refer to the rmr C documentation for rmr_alloc_msg
211     extern rmr_mbuf_t* rmr_alloc_msg(void* vctx, int size)
212     """
213     return _rmr_alloc_msg(vctx, size)
214
215
216 _rmr_payload_size = rmr_c_lib.rmr_payload_size
217 _rmr_payload_size.argtypes = [POINTER(rmr_mbuf_t)]
218 _rmr_payload_size.restype = c_int
219
220
221 def rmr_payload_size(ptr_mbuf):
222     """
223     Refer to the rmr C documentation for rmr_payload_size
224     extern int rmr_payload_size(rmr_mbuf_t* msg)
225     """
226     return _rmr_payload_size(ptr_mbuf)
227
228
229 """
230 The following functions all seem to have the same interface
231 """
232
233 _rmr_send_msg = rmr_c_lib.rmr_send_msg
234 _rmr_send_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
235 _rmr_send_msg.restype = POINTER(rmr_mbuf_t)
236
237
238 def rmr_send_msg(vctx, ptr_mbuf):
239     """
240     Refer to the rmr C documentation for rmr_send_msg
241     extern rmr_mbuf_t* rmr_send_msg(void* vctx, rmr_mbuf_t* msg)
242     """
243     return _rmr_send_msg(vctx, ptr_mbuf)
244
245
246 # TODO: the old message (Send param) is actually optional, but I don't know how to specify that in Ctypes.
247 _rmr_rcv_msg = rmr_c_lib.rmr_rcv_msg
248 _rmr_rcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
249 _rmr_rcv_msg.restype = POINTER(rmr_mbuf_t)
250
251
252 def rmr_rcv_msg(vctx, ptr_mbuf):
253     """
254     Refer to the rmr C documentation for rmr_rcv_msg
255     extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
256     """
257     return _rmr_rcv_msg(vctx, ptr_mbuf)
258
259
260 _rmr_torcv_msg = rmr_c_lib.rmr_torcv_msg
261 _rmr_torcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t), c_int]
262 _rmr_torcv_msg.restype = POINTER(rmr_mbuf_t)
263
264
265 def rmr_torcv_msg(vctx, ptr_mbuf, ms_to):
266     """
267     Refer to the rmr C documentation for rmr_torcv_msg
268     extern rmr_mbuf_t* rmr_torcv_msg(void* vctx, rmr_mbuf_t* old_msg, int ms_to)
269     """
270     return _rmr_torcv_msg(vctx, ptr_mbuf, ms_to)
271
272
273 _rmr_rts_msg = rmr_c_lib.rmr_rts_msg
274 _rmr_rts_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
275 _rmr_rts_msg.restype = POINTER(rmr_mbuf_t)
276
277
278 def rmr_rts_msg(vctx, ptr_mbuf):
279     """
280     Refer to the rmr C documentation for rmr_rts_msg
281     extern rmr_mbuf_t*  rmr_rts_msg(void* vctx, rmr_mbuf_t* msg)
282     """
283     return _rmr_rts_msg(vctx, ptr_mbuf)
284
285
286 _rmr_call = rmr_c_lib.rmr_call
287 _rmr_call.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
288 _rmr_call.restype = POINTER(rmr_mbuf_t)
289
290
291 def rmr_call(vctx, ptr_mbuf):
292     """
293     Refer to the rmr C documentation for rmr_call
294     extern rmr_mbuf_t* rmr_call(void* vctx, rmr_mbuf_t* msg)
295     """
296     return _rmr_call(vctx, ptr_mbuf)
297
298
299 _rmr_bytes2meid = rmr_c_lib.rmr_bytes2meid
300 _rmr_bytes2meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p, c_int]
301 _rmr_bytes2meid.restype = c_int
302
303
304 def rmr_bytes2meid(ptr_mbuf, src, length):
305     """
306     Refer to the rmr C documentation for rmr_bytes2meid
307     extern int rmr_bytes2meid(rmr_mbuf_t* mbuf, unsigned char const* src, int len);
308     """
309     return _rmr_bytes2meid(ptr_mbuf, src, length)
310
311
312 # this is an alias to rmr_bytes2meid using familiar set/get terminoloigy
313 rmr_set_meid = rmr_bytes2meid
314
315
316 # CAUTION:  Some of the C functions expect a mutable buffer to copy the bytes into;
317 #           if there is a get_* function below, use it to set up and return the
318 #           buffer properly.
319
320
321 _rmr_get_meid = rmr_c_lib.rmr_get_meid
322 _rmr_get_meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
323 _rmr_get_meid.restype = c_char_p
324
325
326 def rmr_get_meid(ptr_mbuf, dest):
327     """
328     Refer to the rmr C documentation for rmr_get_meid
329     extern unsigned char*  rmr_get_meid(rmr_mbuf_t* mbuf, unsigned char* dest);
330     """
331     return _rmr_get_meid(ptr_mbuf, dest)
332
333
334 _rmr_get_src = rmr_c_lib.rmr_get_src
335 _rmr_get_src.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
336 _rmr_get_src.restype = c_char_p
337
338
339 def rmr_get_src(ptr_mbuf, dest):
340     """
341     Refer to the rmr C documentation for rmr_get_src
342     extern unsigned char*  rmr_get_src(rmr_mbuf_t* mbuf, unsigned char* dest);
343     """
344     return _rmr_get_src(ptr_mbuf, dest)
345
346
347 # Methods that exist ONLY in rmr-python, and are not wrapped methods
348 # In hindsight, I wish i put these in a seperate module, but leaving this here to prevent api breakage.
349
350
351 def get_payload(ptr_mbuf):
352     """
353     Given a rmr_buf_t*, get it's binary payload as a bytes object
354
355     Parameters
356     ----------
357     ptr_mbuf: ctypes c_void_p
358         Pointer to an rmr message buffer
359
360     Returns
361     -------
362     bytes:
363         the message payload
364     """
365     # Logic came from the answer here: https://stackoverflow.com/questions/55103298/python-ctypes-read-pointerc-char-in-python
366     sz = ptr_mbuf.contents.len
367     CharArr = c_char * sz
368     return CharArr(*ptr_mbuf.contents.payload[:sz]).raw
369
370
371 def get_xaction(ptr_mbuf):
372     """
373     given a rmr_buf_t*, get it's transaction id
374
375     Parameters
376     ----------
377     ptr_mbuf: ctypes c_void_p
378         Pointer to an rmr message buffer
379
380     Returns
381     -------
382     bytes:
383         the transaction id
384     """
385     val = cast(ptr_mbuf.contents.xaction, c_char_p).value
386     sz = _get_constants().get("RMR_MAX_XID", 0)
387     return val[:sz]
388
389
390 def message_summary(ptr_mbuf):
391     """
392     Returns a dict that contains the fields of a message
393
394     Parameters
395     ----------
396     ptr_mbuf: ctypes c_void_p
397         Pointer to an rmr message buffer
398
399     Returns
400     -------
401     dict:
402         dict message summary
403     """
404     if ptr_mbuf.contents.len > RMR_MAX_RCV_BYTES:
405         return "Malformed message: message length is greater than the maximum possible"
406
407     meid = get_meid(ptr_mbuf)
408     if meid == "\000" * _get_constants().get("RMR_MAX_MEID", 32):  # special case all nils
409         meid = None
410
411     return {
412         "payload": get_payload(ptr_mbuf),
413         "payload length": ptr_mbuf.contents.len,
414         "message type": ptr_mbuf.contents.mtype,
415         "subscription id": ptr_mbuf.contents.sub_id,
416         "transaction id": get_xaction(ptr_mbuf),
417         "message state": ptr_mbuf.contents.state,
418         "message status": _state_to_status(ptr_mbuf.contents.state),
419         "payload max size": rmr_payload_size(ptr_mbuf),
420         "meid": meid,
421         "message source": get_src(ptr_mbuf),
422         "errno": ptr_mbuf.contents.tp_state,
423     }
424
425
426 def set_payload_and_length(byte_str, ptr_mbuf):
427     """
428     | Set an rmr payload and content length
429     | In place method, no return
430
431     Parameters
432     ----------
433     byte_str: bytes
434         the bytes to set the payload to
435     ptr_mbuf: ctypes c_void_p
436         Pointer to an rmr message buffer
437     """
438     memmove(ptr_mbuf.contents.payload, byte_str, len(byte_str))
439     ptr_mbuf.contents.len = len(byte_str)
440
441
442 def generate_and_set_transaction_id(ptr_mbuf):
443     """
444     | Generate a UUID and Set an rmr transaction id to it
445     | In place method, no return
446
447     Parameters
448     ----------
449     ptr_mbuf: ctypes c_void_p
450         Pointer to an rmr message buffer
451     """
452     uu_id = uuid.uuid1().hex.encode("utf-8")
453     sz = _get_constants().get("RMR_MAX_XID", 0)
454     memmove(ptr_mbuf.contents.xaction, uu_id, sz)
455
456
457 def get_meid(ptr_mbuf):
458     """
459     | Get the managed equipment ID (meid) from the message header.
460     | This is a 32 byte field and RMr returns all 32 bytes which if the sender did not set will be garbage.
461
462     Parameters
463     ----------
464     ptr_mbuf: ctypes c_void_p
465         Pointer to an rmr message buffer
466
467     Returns
468     -------
469     string:
470         meid
471     """
472     sz = _get_constants().get("RMR_MAX_MEID", 64)  # size for buffer to fill
473     buf = create_string_buffer(sz)
474     rmr_get_meid(ptr_mbuf, buf)
475     return buf.raw.decode()
476
477
478 def get_src(ptr_mbuf):
479     """
480     Get the message source (likely host:port)
481
482     Parameters
483     ----------
484     ptr_mbuf: ctypes c_void_p
485         Pointer to an rmr message buffer
486
487     Returns
488     -------
489     string:
490         meid
491     """
492     sz = _get_constants().get("RMR_MAX_SRC", 64)  # size to fill
493     buf = create_string_buffer(sz)
494     rmr_get_src(ptr_mbuf, buf)
495     return buf.value.decode()