80617a7f9b4abdee58275f99a990735335052c43
[ric-plt/xapp-frame-py.git] / ricxappframe / rmr / rmr.py
1 # ==================================================================================
2 #       Copyright (c) 2019-2020 Nokia
3 #       Copyright (c) 2018-2020 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 CDLL, POINTER, RTLD_GLOBAL, Structure
20 from ctypes import c_char, c_char_p, c_int, c_void_p, cast, create_string_buffer, memmove
21
22 from ricxappframe.rmr.exceptions import BadBufferAllocation, MeidSizeOutOfRange, InitFailed
23
24 # https://docs.python.org/3.7/library/ctypes.html
25 # https://stackoverflow.com/questions/2327344/ctypes-loading-a-c-shared-library-that-has-dependencies/30845750#30845750
26 # make sure you do a set -x LD_LIBRARY_PATH /usr/local/lib/;
27 rmr_c_lib = CDLL("librmr_si.so", mode=RTLD_GLOBAL)
28
29
30 # Internal Helpers (not a part of public api)
31
32
33 _rmr_const = rmr_c_lib.rmr_get_consts
34 _rmr_const.argtypes = []
35 _rmr_const.restype = c_char_p
36
37
38 def _get_constants(cache={}) -> dict:
39     """
40     Gets constants published by RMR and caches for subsequent calls.
41     TODO: are there constants that end user applications need?
42     """
43     if cache:
44         return cache
45
46     js = _rmr_const()  # read json string
47     cache = json.loads(str(js.decode()))  # create constants value object as a hash
48     return cache
49
50
51 def _get_mapping_dict(cache={}) -> dict:
52     """
53     Builds a state mapping dict from constants and caches for subsequent calls.
54     Relevant constants at this writing include:
55
56     RMR_OK              0   state is good
57     RMR_ERR_BADARG      1   argument passd to function was unusable
58     RMR_ERR_NOENDPT     2   send/call could not find an endpoint based on msg type
59     RMR_ERR_EMPTY       3   msg received had no payload; attempt to send an empty message
60     RMR_ERR_NOHDR       4   message didn't contain a valid header
61     RMR_ERR_SENDFAILED  5   send failed; errno has nano reason
62     RMR_ERR_CALLFAILED  6   unable to send call() message
63     RMR_ERR_NOWHOPEN    7   no wormholes are open
64     RMR_ERR_WHID        8   wormhole id was invalid
65     RMR_ERR_OVERFLOW    9   operation would have busted through a buffer/field size
66     RMR_ERR_RETRY       10  request (send/call/rts) failed, but caller should retry (EAGAIN for wrappers)
67     RMR_ERR_RCVFAILED   11  receive failed (hard error)
68     RMR_ERR_TIMEOUT     12  message processing call timed out
69     RMR_ERR_UNSET       13  the message hasn't been populated with a transport buffer
70     RMR_ERR_TRUNC       14  received message likely truncated
71     RMR_ERR_INITFAILED  15  initialization of something (probably message) failed
72
73     """
74     if cache:
75         return cache
76
77     rmr_consts = _get_constants()
78     for key in rmr_consts:  # build the state mapping dict
79         if key[:7] in ["RMR_ERR", "RMR_OK"]:
80             en = int(rmr_consts[key])
81             cache[en] = key
82
83     return cache
84
85
86 def _state_to_status(stateno: int) -> str:
87     """
88     Converts a msg state integer to a status string.
89     Returns "UNKNOWN STATE" if the int value is not known.
90
91     """
92     sdict = _get_mapping_dict()
93     return sdict.get(stateno, "UNKNOWN STATE")
94
95
96 _RCONST = _get_constants()
97
98
99 ##############
100 # PUBLIC API
101 ##############
102
103
104 # These constants are directly usable by importers of this library
105 # TODO: Are there others that will be useful?
106
107 #: Maximum size message to receive
108 RMR_MAX_RCV_BYTES = _RCONST["RMR_MAX_RCV_BYTES"]
109 #: Multi-threaded initialization flag
110 RMRFL_MTCALL = _RCONST.get("RMRFL_MTCALL", 0x02)  # initialization flags
111 #: Empty flag
112 RMRFL_NONE = _RCONST.get("RMRFL_NONE", 0x0)
113 #: State constant for OK
114 RMR_OK = _RCONST["RMR_OK"]
115 #: State constant for timeout
116 RMR_ERR_TIMEOUT = _RCONST["RMR_ERR_TIMEOUT"]
117 #: State constant for retry
118 RMR_ERR_RETRY = _RCONST["RMR_ERR_RETRY"]
119
120
121 class rmr_mbuf_t(Structure):
122     """
123     Mirrors public members of type rmr_mbuf_t from RMR header file src/common/include/rmr.h
124
125     | typedef struct {
126     |    int     state;          // state of processing
127     |    int     mtype;          // message type
128     |    int     len;            // length of data in the payload (send or received)
129     |    unsigned char* payload; // transported data
130     |    unsigned char* xaction; // pointer to fixed length transaction id bytes
131     |    int sub_id;             // subscription id
132     |    int      tp_state;      // transport state (a.k.a errno)
133     |
134     | these things are off limits to the user application
135     |
136     |    void*   tp_buf;         // underlying transport allocated pointer (e.g. nng message)
137     |    void*   header;         // internal message header (whole buffer: header+payload)
138     |    unsigned char* id;      // if we need an ID in the message separate from the xaction id
139     |    int flags;              // various MFL (private) flags as needed
140     |    int alloc_len;          // the length of the allocated space (hdr+payload)
141     | } rmr_mbuf_t;
142
143     RE PAYLOADs type below, see the documentation for c_char_p:
144        class ctypes.c_char_p
145             Represents the C char * datatype when it points to a zero-terminated string.
146             For a general character pointer that may also point to binary data, POINTER(c_char)
147             must be used. The constructor accepts an integer address, or a bytes object.
148     """
149
150     _fields_ = [
151         ("state", c_int),
152         ("mtype", c_int),
153         ("len", c_int),
154         ("payload", POINTER(c_char)),  # according to the following the python bytes are already unsigned
155                                        # https://bytes.com/topic/python/answers/695078-ctypes-unsigned-char
156         ("xaction", POINTER(c_char)),
157         ("sub_id", c_int),
158         ("tp_state", c_int),
159     ]
160
161
162 # argtypes and restype are important: https://stackoverflow.com/questions/24377845/ctype-why-specify-argtypes
163
164
165 _rmr_init = rmr_c_lib.rmr_init
166 _rmr_init.argtypes = [c_char_p, c_int, c_int]
167 _rmr_init.restype = c_void_p
168
169
170 def rmr_init(uproto_port: c_char_p, max_msg_size: int, flags: int) -> c_void_p:
171     """
172     Prepares the environment for sending and receiving messages.
173     Refer to RMR C documentation for method::
174
175         extern void* rmr_init(char* uproto_port, int max_msg_size, int flags)
176
177     This function raises an exception if the returned context is None.
178
179     Parameters
180     ----------
181     uproto_port: c_char_p
182         Pointer to bytes built from the port number as a string; e.g., b'4550'
183     max_msg_size: integer
184         Maximum message size to receive
185     flags: integer
186         RMR option flags
187
188     Returns
189     -------
190     c_void_p:
191         Pointer to RMR context
192     """
193     mrc = _rmr_init(uproto_port, max_msg_size, flags)
194     if mrc is None:
195         raise InitFailed()
196     return mrc
197
198
199 _rmr_ready = rmr_c_lib.rmr_ready
200 _rmr_ready.argtypes = [c_void_p]
201 _rmr_ready.restype = c_int
202
203
204 def rmr_ready(vctx: c_void_p) -> int:
205     """
206     Checks if a routing table has been received and installed.
207     Refer to RMR C documentation for method::
208
209         extern int rmr_ready(void* vctx)
210
211     Parameters
212     ----------
213     vctx: ctypes c_void_p
214         Pointer to RMR context
215
216     Returns
217     -------
218     1 for yes, 0 for no
219     """
220     return _rmr_ready(vctx)
221
222
223 _rmr_close = rmr_c_lib.rmr_close
224 _rmr_close.argtypes = [c_void_p]
225
226
227 def rmr_close(vctx: c_void_p):
228     """
229     Closes the listen socket.
230     Refer to RMR C documentation for method::
231
232         extern void rmr_close(void* vctx)
233
234     Parameters
235     ----------
236     vctx: ctypes c_void_p
237         Pointer to RMR context
238
239     Returns
240     -------
241     None
242     """
243     _rmr_close(vctx)
244
245
246 _rmr_set_stimeout = rmr_c_lib.rmr_set_stimeout
247 _rmr_set_stimeout.argtypes = [c_void_p, c_int]
248 _rmr_set_stimeout.restype = c_int
249
250
251 def rmr_set_stimeout(vctx: c_void_p, rloops: int) -> int:
252     """
253     Sets the configuration for how RMR will retry message send operations.
254     Refer to RMR C documentation for method::
255
256         extern int rmr_set_stimeout(void* vctx, int rloops)
257
258     Parameters
259     ----------
260     vctx: ctypes c_void_p
261         Pointer to RMR context
262     rloops: int
263         Number of retry loops
264
265     Returns
266     -------
267     0 on success, -1 on failure
268     """
269     return _rmr_set_stimeout(vctx, rloops)
270
271
272 _rmr_alloc_msg = rmr_c_lib.rmr_alloc_msg
273 _rmr_alloc_msg.argtypes = [c_void_p, c_int]
274 _rmr_alloc_msg.restype = POINTER(rmr_mbuf_t)
275
276
277 def rmr_alloc_msg(vctx: c_void_p, size: int,
278                   payload=None, gen_transaction_id=False, mtype=None,
279                   meid=None, sub_id=None, fixed_transaction_id=None):
280     """
281     Allocates and returns a buffer to write and send through the RMR library.
282     Refer to RMR C documentation for method::
283
284         extern rmr_mbuf_t* rmr_alloc_msg(void* vctx, int size)
285
286     Optionally populates the message from the remaining arguments.
287
288     TODO: on next API break, clean up transaction_id ugliness. Kept for now to preserve API.
289
290     Parameters
291     ----------
292     vctx: ctypes c_void_p
293         Pointer to RMR context
294     size: int
295         How much space to allocate
296     payload: bytes
297         if not None, attempts to set the payload
298     gen_transaction_id: bool
299         if True, generates and sets a transaction ID.
300         Note, option fixed_transaction_id overrides this option
301     mtype: bytes
302         if not None, sets the sbuf's message type
303     meid: bytes
304         if not None, sets the sbuf's meid
305     sub_id: bytes
306         if not None, sets the sbuf's subscription id
307     fixed_transaction_id: bytes
308         if not None, used as the transaction ID.
309         Note, this overrides the option gen_transaction_id
310
311     Returns
312     -------
313     c_void_p:
314         Pointer to rmr_mbuf structure
315     """
316     sbuf = _rmr_alloc_msg(vctx, size)
317     try:
318         # make sure the alloc worked
319         sbuf.contents
320
321         # set specified fields
322         if payload:
323             set_payload_and_length(payload, sbuf)
324
325         if fixed_transaction_id:
326             set_transaction_id(sbuf, fixed_transaction_id)
327         elif gen_transaction_id:
328             generate_and_set_transaction_id(sbuf)
329
330         if mtype:
331             sbuf.contents.mtype = mtype
332
333         if meid:
334             rmr_set_meid(sbuf, meid)
335
336         if sub_id:
337             sbuf.contents.sub_id = sub_id
338
339         return sbuf
340
341     except ValueError:
342         raise BadBufferAllocation
343
344
345 _rmr_realloc_payload = rmr_c_lib.rmr_realloc_payload
346 _rmr_realloc_payload.argtypes = [POINTER(rmr_mbuf_t), c_int, c_int, c_int]  # new_len, copy, clone
347 _rmr_realloc_payload.restype = POINTER(rmr_mbuf_t)
348
349
350 def rmr_realloc_payload(ptr_mbuf: c_void_p, new_len: int, copy=False, clone=False):
351     """
352     Allocates and returns a message buffer large enough for the new length.
353     Refer to RMR C documentation for method::
354
355         extern rmr_mbuf_t* rmr_realloc_payload(rmr_mbuf_t*, int, int, int)
356
357     Parameters
358     ----------
359     ptr_mbuf: c_void_p
360         Pointer to rmr_mbuf structure
361     new_len: int
362         Length
363     copy: bool
364         Whether to copy the original paylod
365     clone: bool
366         Whether to clone the original buffer
367
368     Returns
369     -------
370     c_void_p:
371         Pointer to rmr_mbuf structure
372     """
373     return _rmr_realloc_payload(ptr_mbuf, new_len, copy, clone)
374
375
376 _rmr_free_msg = rmr_c_lib.rmr_free_msg
377 _rmr_free_msg.argtypes = [POINTER(rmr_mbuf_t)]
378 _rmr_free_msg.restype = None
379
380
381 def rmr_free_msg(ptr_mbuf: c_void_p):
382     """
383     Releases the message buffer.
384     Refer to RMR C documentation for method::
385
386         extern void rmr_free_msg(rmr_mbuf_t* mbuf )
387
388     Parameters
389     ----------
390     ptr_mbuf: c_void_p
391         Pointer to rmr_mbuf structure
392
393     Returns
394     -------
395     None
396     """
397     if ptr_mbuf is not None:
398         _rmr_free_msg(ptr_mbuf)
399
400
401 _rmr_payload_size = rmr_c_lib.rmr_payload_size
402 _rmr_payload_size.argtypes = [POINTER(rmr_mbuf_t)]
403 _rmr_payload_size.restype = c_int
404
405
406 def rmr_payload_size(ptr_mbuf: c_void_p) -> int:
407     """
408     Gets the number of bytes available in the payload.
409     Refer to RMR C documentation for method::
410
411         extern int rmr_payload_size(rmr_mbuf_t* msg)
412
413     Parameters
414     ----------
415     ptr_mbuf: c_void_p
416         Pointer to rmr_mbuf structure
417
418     Returns
419     -------
420     int:
421         Number of bytes available
422     """
423     return _rmr_payload_size(ptr_mbuf)
424
425
426 """
427 The following functions all seem to have the same interface
428 """
429
430 _rmr_send_msg = rmr_c_lib.rmr_send_msg
431 _rmr_send_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
432 _rmr_send_msg.restype = POINTER(rmr_mbuf_t)
433
434
435 def rmr_send_msg(vctx: c_void_p, ptr_mbuf: POINTER(rmr_mbuf_t)) -> POINTER(rmr_mbuf_t):
436     """
437     Sends the message according to the routing table and returns an empty buffer.
438     Refer to RMR C documentation for method::
439
440         extern rmr_mbuf_t* rmr_send_msg(void* vctx, rmr_mbuf_t* msg)
441
442     Parameters
443     ----------
444     vctx: ctypes c_void_p
445         Pointer to RMR context
446     ptr_mbuf: c_void_p
447         Pointer to rmr_mbuf structure
448
449     Returns
450     -------
451     c_void_p:
452         Pointer to rmr_mbuf structure
453     """
454     return _rmr_send_msg(vctx, ptr_mbuf)
455
456
457 # TODO: the old message (Send param) is actually optional, but I don't know how to specify that in Ctypes.
458 _rmr_rcv_msg = rmr_c_lib.rmr_rcv_msg
459 _rmr_rcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
460 _rmr_rcv_msg.restype = POINTER(rmr_mbuf_t)
461
462
463 def rmr_rcv_msg(vctx: c_void_p, ptr_mbuf: POINTER(rmr_mbuf_t)) -> POINTER(rmr_mbuf_t):
464     """
465     Waits for a message to arrive, and returns it.
466     Refer to RMR C documentation for method::
467
468         extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
469
470     Parameters
471     ----------
472     vctx: ctypes c_void_p
473         Pointer to RMR context
474     ptr_mbuf: c_void_p
475         Pointer to rmr_mbuf structure
476
477     Returns
478     -------
479     c_void_p:
480         Pointer to rmr_mbuf structure
481     """
482     return _rmr_rcv_msg(vctx, ptr_mbuf)
483
484
485 _rmr_torcv_msg = rmr_c_lib.rmr_torcv_msg
486 _rmr_torcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t), c_int]
487 _rmr_torcv_msg.restype = POINTER(rmr_mbuf_t)
488
489
490 def rmr_torcv_msg(vctx: c_void_p, ptr_mbuf: POINTER(rmr_mbuf_t), ms_to: int) -> POINTER(rmr_mbuf_t):
491     """
492     Waits up to the timeout value for a message to arrive, and returns it.
493     Refer to RMR C documentation for method::
494
495         extern rmr_mbuf_t* rmr_torcv_msg(void* vctx, rmr_mbuf_t* old_msg, int ms_to)
496
497     Parameters
498     ----------
499     vctx: ctypes c_void_p
500         Pointer to RMR context
501     ptr_mbuf: c_void_p
502         Pointer to rmr_mbuf structure
503     ms_to: int
504         Time out value in milliseconds
505
506     Returns
507     -------
508     c_void_p:
509         Pointer to rmr_mbuf structure
510     """
511     return _rmr_torcv_msg(vctx, ptr_mbuf, ms_to)
512
513
514 _rmr_rts_msg = rmr_c_lib.rmr_rts_msg
515 _rmr_rts_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
516 _rmr_rts_msg.restype = POINTER(rmr_mbuf_t)
517
518
519 def rmr_rts_msg(vctx: c_void_p, ptr_mbuf: POINTER(rmr_mbuf_t), payload=None, mtype=None) -> POINTER(rmr_mbuf_t):
520     """
521     Sends a message to the originating endpoint and returns an empty buffer.
522     Refer to RMR C documentation for method::
523
524         extern rmr_mbuf_t* rmr_rts_msg(void* vctx, rmr_mbuf_t* msg)
525
526     additional features beyond c-rmr:
527         if payload is not None, attempts to set the payload
528         if mtype is not None, sets the sbuf's message type
529
530     Parameters
531     ----------
532     vctx: ctypes c_void_p
533         Pointer to an RMR context
534     ptr_mbuf: ctypes c_void_p
535         Pointer to an RMR message buffer
536     payload: bytes
537         Payload
538     mtype: bytes
539         Message type
540
541     Returns
542     -------
543     c_void_p:
544         Pointer to rmr_mbuf structure
545     """
546
547     if payload:
548         set_payload_and_length(payload, ptr_mbuf)
549
550     if mtype:
551         ptr_mbuf.contents.mtype = mtype
552
553     return _rmr_rts_msg(vctx, ptr_mbuf)
554
555
556 _rmr_call = rmr_c_lib.rmr_call
557 _rmr_call.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
558 _rmr_call.restype = POINTER(rmr_mbuf_t)
559
560
561 def rmr_call(vctx: c_void_p, ptr_mbuf: POINTER(rmr_mbuf_t)) -> POINTER(rmr_mbuf_t):
562     """
563     Sends a message, waits for a response and returns it.
564     Refer to RMR C documentation for method::
565
566         extern rmr_mbuf_t* rmr_call(void* vctx, rmr_mbuf_t* msg)
567
568     Parameters
569     ----------
570     ptr_mbuf: ctypes c_void_p
571         Pointer to an RMR message buffer
572
573     Returns
574     -------
575     c_void_p:
576         Pointer to rmr_mbuf structure
577     """
578     return _rmr_call(vctx, ptr_mbuf)
579
580
581 _rmr_bytes2meid = rmr_c_lib.rmr_bytes2meid
582 _rmr_bytes2meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p, c_int]
583 _rmr_bytes2meid.restype = c_int
584
585
586 def rmr_set_meid(ptr_mbuf: POINTER(rmr_mbuf_t), byte_str: bytes) -> int:
587     """
588     Sets the managed entity field in the message and returns the number of bytes copied.
589     Refer to RMR C documentation for method::
590
591         extern int rmr_bytes2meid(rmr_mbuf_t* mbuf, unsigned char const* src, int len);
592
593     Caution:  the meid length supported in an RMR message is 32 bytes, but C applications
594     expect this to be a nil terminated string and thus only 31 bytes are actually available.
595
596     Raises: exceptions.MeidSizeOutOfRang
597
598     Parameters
599     ----------
600     ptr_mbuf: ctypes c_void_p
601         Pointer to an RMR message buffer
602     byte_tr: bytes
603         Managed entity ID value
604
605     Returns
606     -------
607     int:
608         number of bytes copied
609     """
610     max = _get_constants().get("RMR_MAX_MEID", 32)
611     if len(byte_str) >= max:
612         raise MeidSizeOutOfRange
613
614     return _rmr_bytes2meid(ptr_mbuf, byte_str, len(byte_str))
615
616
617 # CAUTION:  Some of the C functions expect a mutable buffer to copy the bytes into;
618 #           if there is a get_* function below, use it to set up and return the
619 #           buffer properly.
620
621 # extern unsigned char*  rmr_get_meid(rmr_mbuf_t* mbuf, unsigned char* dest);
622 # 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.
623 # Rather, rmr_get_meid does this for you, and just returns the string.
624 _rmr_get_meid = rmr_c_lib.rmr_get_meid
625 _rmr_get_meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
626 _rmr_get_meid.restype = c_char_p
627
628
629 def rmr_get_meid(ptr_mbuf: POINTER(rmr_mbuf_t)) -> bytes:
630     """
631     Gets the managed entity ID (meid) from the message header.
632     This is a python-friendly version of RMR C method::
633
634         extern unsigned char* rmr_get_meid(rmr_mbuf_t* mbuf, unsigned char* dest);
635
636     Parameters
637     ----------
638     ptr_mbuf: ctypes c_void_p
639         Pointer to an RMR message buffer
640
641     Returns
642     -------
643     bytes:
644         Managed entity ID
645     """
646     sz = _get_constants().get("RMR_MAX_MEID", 32)  # size for buffer to fill
647     buf = create_string_buffer(sz)
648     _rmr_get_meid(ptr_mbuf, buf)
649     return buf.value
650
651
652 _rmr_get_src = rmr_c_lib.rmr_get_src
653 _rmr_get_src.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
654 _rmr_get_src.restype = c_char_p
655
656
657 def rmr_get_src(ptr_mbuf: POINTER(rmr_mbuf_t), dest: c_char_p) -> c_char_p:
658     """
659     Copies the message-source information to the buffer.
660     Refer to RMR C documentation for method::
661
662         extern unsigned char* rmr_get_src(rmr_mbuf_t* mbuf, unsigned char* dest);
663
664     Parameters
665     ----------
666     ptr_mbuf: ctypes POINTER(rmr_mbuf_t)
667         Pointer to an RMR message buffer
668     dest: ctypes c_char_p
669         Pointer to a buffer to receive the message source
670
671     Returns
672     -------
673     string:
674         message-source information
675     """
676     return _rmr_get_src(ptr_mbuf, dest)
677
678
679 # Methods that exist ONLY in rmr-python, and are not wrapped methods
680 # In hindsight, I wish i put these in a separate module, but leaving this here to prevent api breakage.
681
682
683 def get_payload(ptr_mbuf: c_void_p) -> bytes:
684     """
685     Gets the binary payload from the rmr_buf_t*.
686
687     Parameters
688     ----------
689     ptr_mbuf: ctypes c_void_p
690         Pointer to an rmr message buffer
691
692     Returns
693     -------
694     bytes:
695         the message payload
696     """
697     # Logic came from the answer here: https://stackoverflow.com/questions/55103298/python-ctypes-read-pointerc-char-in-python
698     sz = ptr_mbuf.contents.len
699     CharArr = c_char * sz
700     return CharArr(*ptr_mbuf.contents.payload[:sz]).raw
701
702
703 def get_xaction(ptr_mbuf: c_void_p) -> bytes:
704     """
705     Gets the transaction ID from the rmr_buf_t*.
706
707     Parameters
708     ----------
709     ptr_mbuf: ctypes c_void_p
710         Pointer to an rmr message buffer
711
712     Returns
713     -------
714     bytes:
715         the transaction id
716     """
717     val = cast(ptr_mbuf.contents.xaction, c_char_p).value
718     sz = _get_constants().get("RMR_MAX_XID", 0)
719     return val[:sz]
720
721
722 def message_summary(ptr_mbuf: c_void_p) -> dict:
723     """
724     Returns a dict with the fields of an RMR message.
725
726     Parameters
727     ----------
728     ptr_mbuf: ctypes c_void_p
729         Pointer to an rmr message buffer
730
731     Returns
732     -------
733     dict:
734         dict message summary
735     """
736     return {
737         "payload": get_payload(ptr_mbuf) if ptr_mbuf.contents.state == RMR_OK else None,
738         "payload length": ptr_mbuf.contents.len,
739         "message type": ptr_mbuf.contents.mtype,
740         "subscription id": ptr_mbuf.contents.sub_id,
741         "transaction id": get_xaction(ptr_mbuf),
742         "message state": ptr_mbuf.contents.state,
743         "message status": _state_to_status(ptr_mbuf.contents.state),
744         "payload max size": rmr_payload_size(ptr_mbuf),
745         "meid": rmr_get_meid(ptr_mbuf),
746         "message source": get_src(ptr_mbuf),
747         "errno": ptr_mbuf.contents.tp_state,
748     }
749
750
751 def set_payload_and_length(byte_str: bytes, ptr_mbuf: c_void_p):
752     """
753     Sets an rmr payload and content length.
754
755     Parameters
756     ----------
757     byte_str: bytes
758         the bytes to set the payload to
759     ptr_mbuf: ctypes c_void_p
760         Pointer to an rmr message buffer
761
762     Returns
763     -------
764     None
765     """
766     if rmr_payload_size(ptr_mbuf) < len(byte_str):  # existing message payload too small
767         ptr_mbuf = rmr_realloc_payload(ptr_mbuf, len(byte_str), True)
768
769     memmove(ptr_mbuf.contents.payload, byte_str, len(byte_str))
770     ptr_mbuf.contents.len = len(byte_str)
771
772
773 def generate_and_set_transaction_id(ptr_mbuf: c_void_p):
774     """
775     Generates a UUID and sets the RMR transaction id to it
776
777     Parameters
778     ----------
779     ptr_mbuf: ctypes c_void_p
780         Pointer to an rmr message buffer
781     """
782     set_transaction_id(ptr_mbuf, uuid.uuid1().hex.encode("utf-8"))
783
784
785 def set_transaction_id(ptr_mbuf: c_void_p, tid_bytes: bytes):
786     """
787     Sets an RMR transaction id
788     TODO: on next API break, merge these two functions. Not done now to preserve API.
789
790     Parameters
791     ----------
792     ptr_mbuf: ctypes c_void_p
793         Pointer to an rmr message buffer
794     tid_bytes: bytes
795         bytes of the desired transaction id
796     """
797     sz = _get_constants().get("RMR_MAX_XID", 0)
798     memmove(ptr_mbuf.contents.xaction, tid_bytes, sz)
799
800
801 def get_src(ptr_mbuf: c_void_p) -> str:
802     """
803     Gets the message source (likely host:port)
804
805     Parameters
806     ----------
807     ptr_mbuf: ctypes c_void_p
808         Pointer to an rmr message buffer
809
810     Returns
811     -------
812     string:
813         message source
814     """
815     sz = _get_constants().get("RMR_MAX_SRC", 64)  # size to fill
816     buf = create_string_buffer(sz)
817     rmr_get_src(ptr_mbuf, buf)
818     return buf.value.decode()