Move rmr python here.
[ric-plt/xapp-frame-py.git] / ricxappframe / rmr / rmr.py
1 # vim: expandtab ts=4 sw=4:
2 # ==================================================================================
3 #       Copyright (c) 2019-2020 Nokia
4 #       Copyright (c) 2018-2020 AT&T Intellectual Property.
5 #
6 #   Licensed under the Apache License, Version 2.0 (the "License");
7 #   you may not use this file except in compliance with the License.
8 #   You may obtain a copy of the License at
9 #
10 #          http://www.apache.org/licenses/LICENSE-2.0
11 #
12 #   Unless required by applicable law or agreed to in writing, software
13 #   distributed under the License is distributed on an "AS IS" BASIS,
14 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 #   See the License for the specific language governing permissions and
16 #   limitations under the License.
17 # ==================================================================================
18 import uuid
19 import json
20 from ctypes import RTLD_GLOBAL, Structure, c_int, POINTER, c_char, c_char_p, c_void_p, memmove, cast
21 from ctypes import CDLL
22 from ctypes import create_string_buffer
23 from ricxappframe.rmr.exceptions import BadBufferAllocation, MeidSizeOutOfRange, InitFailed
24
25 # https://docs.python.org/3.7/library/ctypes.html
26 # https://stackoverflow.com/questions/2327344/ctypes-loading-a-c-shared-library-that-has-dependencies/30845750#30845750
27 # make sure you do a set -x LD_LIBRARY_PATH /usr/local/lib/;
28
29 # even though we don't use these directly, they contain symbols we need
30 rmr_c_lib = CDLL("librmr_si.so", mode=RTLD_GLOBAL)
31
32
33 # Internal Helpers (not a part of public api)
34
35
36 _rmr_const = rmr_c_lib.rmr_get_consts
37 _rmr_const.argtypes = []
38 _rmr_const.restype = c_char_p
39
40
41 def _get_constants(cache={}):
42     """
43     Get or build needed constants from rmr
44     TODO: are there constants that end user applications need?
45     """
46     if cache:
47         return cache
48
49     js = _rmr_const()  # read json string
50     cache = json.loads(str(js.decode()))  # create constants value object as a hash
51     return cache
52
53
54 def _get_mapping_dict(cache={}):
55     """
56     Get or build the state mapping dict
57
58     RMR_OK              0   state is good
59     RMR_ERR_BADARG      1   argument passd to function was unusable
60     RMR_ERR_NOENDPT     2   send/call could not find an endpoint based on msg type
61     RMR_ERR_EMPTY       3   msg received had no payload; attempt to send an empty message
62     RMR_ERR_NOHDR       4   message didn't contain a valid header
63     RMR_ERR_SENDFAILED  5   send failed; errno has nano reason
64     RMR_ERR_CALLFAILED  6   unable to send call() message
65     RMR_ERR_NOWHOPEN    7   no wormholes are open
66     RMR_ERR_WHID        8   wormhole id was invalid
67     RMR_ERR_OVERFLOW    9   operation would have busted through a buffer/field size
68     RMR_ERR_RETRY       10  request (send/call/rts) failed, but caller should retry (EAGAIN for wrappers)
69     RMR_ERR_RCVFAILED   11  receive failed (hard error)
70     RMR_ERR_TIMEOUT     12  message processing call timed out
71     RMR_ERR_UNSET       13  the message hasn't been populated with a transport buffer
72     RMR_ERR_TRUNC       14  received message likely truncated
73     RMR_ERR_INITFAILED  15  initialization of something (probably message) failed
74
75     """
76     if cache:
77         return cache
78
79     rmr_consts = _get_constants()
80     for key in rmr_consts:  # build the state mapping dict
81         if key[:7] in ["RMR_ERR", "RMR_OK"]:
82             en = int(rmr_consts[key])
83             cache[en] = key
84
85     return cache
86
87
88 def _state_to_status(stateno):
89     """
90     Convert a msg state to status
91
92     """
93     sdict = _get_mapping_dict()
94     return sdict.get(stateno, "UNKNOWN STATE")
95
96
97 _RCONST = _get_constants()
98
99
100 ##############
101 # PUBLIC API
102 ##############
103
104
105 # These constants are directly usable by importers of this library
106 # TODO: Are there others that will be useful?
107
108 RMR_MAX_RCV_BYTES = _RCONST["RMR_MAX_RCV_BYTES"]
109 RMRFL_MTCALL = _RCONST.get("RMRFL_MTCALL", 0x02)  # initialization flags
110 RMRFL_NONE = _RCONST.get("RMRFL_NONE", 0x0)
111 RMR_OK = _RCONST["RMR_OK"]  # useful state constants
112 RMR_ERR_TIMEOUT = _RCONST["RMR_ERR_TIMEOUT"]
113 RMR_ERR_RETRY = _RCONST["RMR_ERR_RETRY"]
114
115
116 class rmr_mbuf_t(Structure):
117     """
118     Reimplementation of rmr_mbuf_t which is in an unaccessible header file (src/common/include/rmr.h)
119
120     | typedef struct {
121     |    int     state;          // state of processing
122     |    int     mtype;          // message type
123     |    int     len;            // length of data in the payload (send or received)
124     |    unsigned char* payload; // transported data
125     |    unsigned char* xaction; // pointer to fixed length transaction id bytes
126     |    int sub_id;             // subscription id
127     |    int      tp_state;      // transport state (a.k.a errno)
128     |
129     | these things are off limits to the user application
130     |
131     |    void*   tp_buf;         // underlying transport allocated pointer (e.g. nng message)
132     |    void*   header;         // internal message header (whole buffer: header+payload)
133     |    unsigned char* id;      // if we need an ID in the message separate from the xaction id
134     |    int flags;              // various MFL (private) flags as needed
135     |    int alloc_len;          // the length of the allocated space (hdr+payload)
136     | } rmr_mbuf_t;
137
138     We do not include the fields we are not supposed to mess with
139
140     RE PAYLOADs type below, see the documentation for c_char_p:
141        class ctypes.c_char_p
142            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.
143     """
144
145     _fields_ = [
146         ("state", c_int),
147         ("mtype", c_int),
148         ("len", c_int),
149         (
150             "payload",
151             POINTER(c_char),
152         ),  # according to th following the python bytes are already unsinged https://bytes.com/topic/python/answers/695078-ctypes-unsigned-char
153         ("xaction", POINTER(c_char)),
154         ("sub_id", c_int),
155         ("tp_state", c_int),
156     ]
157
158
159 # argtypes and restype are important: https://stackoverflow.com/questions/24377845/ctype-why-specify-argtypes
160
161
162 _rmr_init = rmr_c_lib.rmr_init
163 _rmr_init.argtypes = [c_char_p, c_int, c_int]
164 _rmr_init.restype = c_void_p
165
166
167 def rmr_init(uproto_port, max_msg_size, flags):
168     """
169     Refer to rmr C documentation for rmr_init
170     extern void* rmr_init(char* uproto_port, int max_msg_size, int flags)
171
172     This python function checks that the context is not None and raises
173     an excption if it is.
174     """
175     mrc = _rmr_init(uproto_port, max_msg_size, flags)
176     if mrc is None:
177         raise InitFailed()
178     return mrc
179
180
181 _rmr_ready = rmr_c_lib.rmr_ready
182 _rmr_ready.argtypes = [c_void_p]
183 _rmr_ready.restype = c_int
184
185
186 def rmr_ready(vctx):
187     """
188     Refer to rmr C documentation for rmr_ready
189     extern int rmr_ready(void* vctx)
190     """
191     return _rmr_ready(vctx)
192
193
194 _rmr_close = rmr_c_lib.rmr_close
195 _rmr_close.argtypes = [c_void_p]
196
197
198 def rmr_close(vctx):
199     """
200     Refer to rmr C documentation for rmr_close
201     extern void rmr_close(void* vctx)
202     """
203     return _rmr_close(vctx)
204
205
206 _rmr_set_stimeout = rmr_c_lib.rmr_set_stimeout
207 _rmr_set_stimeout.argtypes = [c_void_p, c_int]
208 _rmr_set_stimeout.restype = c_int
209
210
211 def rmr_set_stimeout(vctx, time):
212     """
213     Refer to the rmr C documentation for rmr_set_stimeout
214     extern int rmr_set_stimeout(void* vctx, int time)
215     """
216     return _rmr_set_stimeout(vctx, time)
217
218
219 _rmr_alloc_msg = rmr_c_lib.rmr_alloc_msg
220 _rmr_alloc_msg.argtypes = [c_void_p, c_int]
221 _rmr_alloc_msg.restype = POINTER(rmr_mbuf_t)
222
223
224 def rmr_alloc_msg(
225     vctx, size, payload=None, gen_transaction_id=False, mtype=None, meid=None, sub_id=None, fixed_transaction_id=None
226 ):
227     """
228     Refer to the rmr C documentation for rmr_alloc_msg
229     extern rmr_mbuf_t* rmr_alloc_msg(void* vctx, int size)
230     TODO: on next API break, clean up transaction_id ugliness. Kept for now to preserve API.
231
232     if payload is not None, attempts to set the payload
233     if gen_transaction_id is True, it generates and sets a transaction id. Note, fixed_transaction_id supersedes this option
234     if mtype is not None, sets the sbuf's message type
235     if meid is not None, sets the sbuf's meid
236     if sub_id is not None, sets the sbud's subscription id
237     if fixed_transaction_id is set, it deterministically sets the transaction_id. This overrides the option gen_transation_id
238
239     """
240     sbuf = _rmr_alloc_msg(vctx, size)
241     try:
242         # make sure the alloc worked
243         sbuf.contents
244
245         # set specified fields
246         if payload:
247             set_payload_and_length(payload, sbuf)
248
249         if fixed_transaction_id:
250             set_transaction_id(sbuf, fixed_transaction_id)
251         elif gen_transaction_id:
252             generate_and_set_transaction_id(sbuf)
253
254         if mtype:
255             sbuf.contents.mtype = mtype
256
257         if meid:
258             rmr_set_meid(sbuf, meid)
259
260         if sub_id:
261             sbuf.contents.sub_id = sub_id
262
263         return sbuf
264
265     except ValueError:
266         raise BadBufferAllocation
267
268
269 _rmr_realloc_payload = rmr_c_lib.rmr_realloc_payload
270 _rmr_realloc_payload.argtypes = [POINTER(rmr_mbuf_t), c_int, c_int, c_int]  # new_len, copy, clone
271 _rmr_realloc_payload.restype = POINTER(rmr_mbuf_t)
272
273
274 def rmr_realloc_payload(ptr_mbuf, new_len, copy=False, clone=False):
275     """
276     Refer to the rmr C documentation for rmr_realloc_payload().
277     extern rmr_mbuf_t* rmr_realloc_payload(rmr_mbuf_t*, int, int, int)
278     """
279     return _rmr_realloc_payload(ptr_mbuf, new_len, copy, clone)
280
281
282 _rmr_free_msg = rmr_c_lib.rmr_free_msg
283 _rmr_free_msg.argtypes = [c_void_p]
284 _rmr_free_msg.restype = None
285
286
287 def rmr_free_msg(mbuf):
288     """
289     Refer to the rmr C documentation for rmr_free_msg
290     extern void rmr_free_msg(rmr_mbuf_t* mbuf )
291     """
292     if mbuf is not None:
293         _rmr_free_msg(mbuf)
294
295
296 _rmr_payload_size = rmr_c_lib.rmr_payload_size
297 _rmr_payload_size.argtypes = [POINTER(rmr_mbuf_t)]
298 _rmr_payload_size.restype = c_int
299
300
301 def rmr_payload_size(ptr_mbuf):
302     """
303     Refer to the rmr C documentation for rmr_payload_size
304     extern int rmr_payload_size(rmr_mbuf_t* msg)
305     """
306     return _rmr_payload_size(ptr_mbuf)
307
308
309 """
310 The following functions all seem to have the same interface
311 """
312
313 _rmr_send_msg = rmr_c_lib.rmr_send_msg
314 _rmr_send_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
315 _rmr_send_msg.restype = POINTER(rmr_mbuf_t)
316
317
318 def rmr_send_msg(vctx, ptr_mbuf):
319     """
320     Refer to the rmr C documentation for rmr_send_msg
321     extern rmr_mbuf_t* rmr_send_msg(void* vctx, rmr_mbuf_t* msg)
322     """
323     return _rmr_send_msg(vctx, ptr_mbuf)
324
325
326 # TODO: the old message (Send param) is actually optional, but I don't know how to specify that in Ctypes.
327 _rmr_rcv_msg = rmr_c_lib.rmr_rcv_msg
328 _rmr_rcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
329 _rmr_rcv_msg.restype = POINTER(rmr_mbuf_t)
330
331
332 def rmr_rcv_msg(vctx, ptr_mbuf):
333     """
334     Refer to the rmr C documentation for rmr_rcv_msg
335     extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
336     """
337     return _rmr_rcv_msg(vctx, ptr_mbuf)
338
339
340 _rmr_torcv_msg = rmr_c_lib.rmr_torcv_msg
341 _rmr_torcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t), c_int]
342 _rmr_torcv_msg.restype = POINTER(rmr_mbuf_t)
343
344
345 def rmr_torcv_msg(vctx, ptr_mbuf, ms_to):
346     """
347     Refer to the rmr C documentation for rmr_torcv_msg
348     extern rmr_mbuf_t* rmr_torcv_msg(void* vctx, rmr_mbuf_t* old_msg, int ms_to)
349     """
350     return _rmr_torcv_msg(vctx, ptr_mbuf, ms_to)
351
352
353 _rmr_rts_msg = rmr_c_lib.rmr_rts_msg
354 _rmr_rts_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
355 _rmr_rts_msg.restype = POINTER(rmr_mbuf_t)
356
357
358 def rmr_rts_msg(vctx, ptr_mbuf, payload=None, mtype=None):
359     """
360     Refer to the rmr C documentation for rmr_rts_msg
361     extern rmr_mbuf_t*  rmr_rts_msg(void* vctx, rmr_mbuf_t* msg)
362
363     additional features beyond c-rmr:
364         if payload is not None, attempts to set the payload
365         if mtype is not None, sets the sbuf's message type
366     """
367
368     if payload:
369         set_payload_and_length(payload, ptr_mbuf)
370
371     if mtype:
372         ptr_mbuf.contents.mtype = mtype
373
374     return _rmr_rts_msg(vctx, ptr_mbuf)
375
376
377 _rmr_call = rmr_c_lib.rmr_call
378 _rmr_call.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
379 _rmr_call.restype = POINTER(rmr_mbuf_t)
380
381
382 def rmr_call(vctx, ptr_mbuf):
383     """
384     Refer to the rmr C documentation for rmr_call
385     extern rmr_mbuf_t* rmr_call(void* vctx, rmr_mbuf_t* msg)
386     """
387     return _rmr_call(vctx, ptr_mbuf)
388
389
390 _rmr_bytes2meid = rmr_c_lib.rmr_bytes2meid
391 _rmr_bytes2meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p, c_int]
392 _rmr_bytes2meid.restype = c_int
393
394
395 def rmr_set_meid(ptr_mbuf, byte_str):
396     """
397     Refer to the rmr C documentation for rmr_bytes2meid
398     extern int rmr_bytes2meid(rmr_mbuf_t* mbuf, unsigned char const* src, int len);
399
400     Caution:  the meid length supported in an RMR message is 32 bytes, but C applications
401     expect this to be a nil terminated string and thus only 31 bytes are actually available.
402
403     Raises: exceptions.MeidSizeOutOfRang
404     """
405     max = _get_constants().get("RMR_MAX_MEID", 32)
406     if len(byte_str) >= max:
407         raise MeidSizeOutOfRange
408
409     return _rmr_bytes2meid(ptr_mbuf, byte_str, len(byte_str))
410
411
412 # CAUTION:  Some of the C functions expect a mutable buffer to copy the bytes into;
413 #           if there is a get_* function below, use it to set up and return the
414 #           buffer properly.
415
416 # extern unsigned char*  rmr_get_meid(rmr_mbuf_t* mbuf, unsigned char* dest);
417 # 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.
418 # Rather, rmr_get_meid does this for you, and just returns the string.
419 _rmr_get_meid = rmr_c_lib.rmr_get_meid
420 _rmr_get_meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
421 _rmr_get_meid.restype = c_char_p
422
423
424 def rmr_get_meid(ptr_mbuf):
425     """
426     Get the managed equipment ID (meid) from the message header.
427
428     Parameters
429     ----------
430     ptr_mbuf: ctypes c_void_p
431         Pointer to an rmr message buffer
432
433     Returns
434     -------
435     string:
436         meid
437     """
438     sz = _get_constants().get("RMR_MAX_MEID", 32)  # size for buffer to fill
439     buf = create_string_buffer(sz)
440     _rmr_get_meid(ptr_mbuf, buf)
441     return buf.value
442
443
444 _rmr_get_src = rmr_c_lib.rmr_get_src
445 _rmr_get_src.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
446 _rmr_get_src.restype = c_char_p
447
448
449 def rmr_get_src(ptr_mbuf, dest):
450     """
451     Refer to the rmr C documentation for rmr_get_src
452     extern unsigned char*  rmr_get_src(rmr_mbuf_t* mbuf, unsigned char* dest);
453     """
454     return _rmr_get_src(ptr_mbuf, dest)
455
456
457 # Methods that exist ONLY in rmr-python, and are not wrapped methods
458 # In hindsight, I wish i put these in a seperate module, but leaving this here to prevent api breakage.
459
460
461 def get_payload(ptr_mbuf):
462     """
463     Given a rmr_buf_t*, get it's binary payload as a bytes object
464
465     Parameters
466     ----------
467     ptr_mbuf: ctypes c_void_p
468         Pointer to an rmr message buffer
469
470     Returns
471     -------
472     bytes:
473         the message payload
474     """
475     # Logic came from the answer here: https://stackoverflow.com/questions/55103298/python-ctypes-read-pointerc-char-in-python
476     sz = ptr_mbuf.contents.len
477     CharArr = c_char * sz
478     return CharArr(*ptr_mbuf.contents.payload[:sz]).raw
479
480
481 def get_xaction(ptr_mbuf):
482     """
483     given a rmr_buf_t*, get it's transaction id
484
485     Parameters
486     ----------
487     ptr_mbuf: ctypes c_void_p
488         Pointer to an rmr message buffer
489
490     Returns
491     -------
492     bytes:
493         the transaction id
494     """
495     val = cast(ptr_mbuf.contents.xaction, c_char_p).value
496     sz = _get_constants().get("RMR_MAX_XID", 0)
497     return val[:sz]
498
499
500 def message_summary(ptr_mbuf):
501     """
502     Returns a dict that contains the fields of a message
503
504     Parameters
505     ----------
506     ptr_mbuf: ctypes c_void_p
507         Pointer to an rmr message buffer
508
509     Returns
510     -------
511     dict:
512         dict message summary
513     """
514     return {
515         "payload": get_payload(ptr_mbuf) if ptr_mbuf.contents.state == RMR_OK else None,
516         "payload length": ptr_mbuf.contents.len,
517         "message type": ptr_mbuf.contents.mtype,
518         "subscription id": ptr_mbuf.contents.sub_id,
519         "transaction id": get_xaction(ptr_mbuf),
520         "message state": ptr_mbuf.contents.state,
521         "message status": _state_to_status(ptr_mbuf.contents.state),
522         "payload max size": rmr_payload_size(ptr_mbuf),
523         "meid": rmr_get_meid(ptr_mbuf),
524         "message source": get_src(ptr_mbuf),
525         "errno": ptr_mbuf.contents.tp_state,
526     }
527
528
529 def set_payload_and_length(byte_str, ptr_mbuf):
530     """
531     | Set an rmr payload and content length
532     | In place method, no return
533
534     Parameters
535     ----------
536     byte_str: bytes
537         the bytes to set the payload to
538     ptr_mbuf: ctypes c_void_p
539         Pointer to an rmr message buffer
540     """
541     if rmr_payload_size(ptr_mbuf) < len(byte_str):  # existing message payload too small
542         ptr_mbuf = rmr_realloc_payload(ptr_mbuf, len(byte_str), True)
543
544     memmove(ptr_mbuf.contents.payload, byte_str, len(byte_str))
545     ptr_mbuf.contents.len = len(byte_str)
546
547
548 def generate_and_set_transaction_id(ptr_mbuf):
549     """
550     Generate a UUID and Set an rmr transaction id to it
551
552     Parameters
553     ----------
554     ptr_mbuf: ctypes c_void_p
555         Pointer to an rmr message buffer
556     """
557     set_transaction_id(ptr_mbuf, uuid.uuid1().hex.encode("utf-8"))
558
559
560 def set_transaction_id(ptr_mbuf, tid_bytes):
561     """
562     Set an rmr transaction id
563     TODO: on next API break, merge these two functions. Not done now to preserve API.
564
565     Parameters
566     ----------
567     ptr_mbuf: ctypes c_void_p
568         Pointer to an rmr message buffer
569     tid_bytes: bytes
570         bytes of the desired transaction id
571     """
572     sz = _get_constants().get("RMR_MAX_XID", 0)
573     memmove(ptr_mbuf.contents.xaction, tid_bytes, sz)
574
575
576 def get_src(ptr_mbuf):
577     """
578     Get the message source (likely host:port)
579
580     Parameters
581     ----------
582     ptr_mbuf: ctypes c_void_p
583         Pointer to an rmr message buffer
584
585     Returns
586     -------
587     string:
588         message source
589     """
590     sz = _get_constants().get("RMR_MAX_SRC", 64)  # size to fill
591     buf = create_string_buffer(sz)
592     rmr_get_src(ptr_mbuf, buf)
593     return buf.value.decode()