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