Add transport provider status to message buffer
[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 _rmr_const = rmr_c_lib.rmr_get_consts
33 _rmr_const.argtypes = []
34 _rmr_const.restype = c_char_p
35
36
37 def _get_constants(cache={}):
38     """
39     Get or build needed constants from rmr
40     TODO: are there constants that end user applications need?
41     """
42     if cache:
43         return cache
44
45     js = _rmr_const()  # read json string
46     cache = json.loads(str(js.decode()))  # create constants value object as a hash
47     return cache
48
49
50 def _get_mapping_dict(cache={}):
51     """
52     Get or build the state mapping dict
53
54     #define RMR_OK              0       // state is good
55     #define RMR_ERR_BADARG      1       // argument passd to function was unusable
56     #define RMR_ERR_NOENDPT     2       // send/call could not find an endpoint based on msg type
57     #define RMR_ERR_EMPTY       3       // msg received had no payload; attempt to send an empty message
58     #define RMR_ERR_NOHDR       4       // message didn't contain a valid header
59     #define RMR_ERR_SENDFAILED  5       // send failed; errno has nano reason
60     #define RMR_ERR_CALLFAILED  6       // unable to send call() message
61     #define RMR_ERR_NOWHOPEN    7       // no wormholes are open
62     #define RMR_ERR_WHID        8       // wormhole id was invalid
63     #define RMR_ERR_OVERFLOW    9       // operation would have busted through a buffer/field size
64     #define RMR_ERR_RETRY       10      // request (send/call/rts) failed, but caller should retry (EAGAIN for wrappers)
65     #define RMR_ERR_RCVFAILED   11      // receive failed (hard error)
66     #define RMR_ERR_TIMEOUT     12      // message processing call timed out
67     #define RMR_ERR_UNSET       13      // the message hasn't been populated with a transport buffer
68     #define RMR_ERR_TRUNC       14      // received message likely truncated
69     #define RMR_ERR_INITFAILED  15      // initialisation of something (probably message) failed
70
71     """
72     if cache:
73         return cache
74
75     rmr_consts = _get_constants()
76     for key in rmr_consts:  # build the state mapping dict
77         if key[:7] in ["RMR_ERR", "RMR_OK"]:
78             en = int(rmr_consts[key])
79             cache[en] = key
80
81     return cache
82
83
84 def _state_to_status(stateno):
85     """
86     convery a msg state to status
87     """
88     sdict = _get_mapping_dict()
89     return sdict.get(stateno, "UNKNOWN STATE")
90
91
92 ##############
93 # PUBLIC API
94 ##############
95
96 # These constants are directly usable by importers of this library
97 # TODO: Are there others that will be useful?
98 RMR_MAX_RCV_BYTES = _get_constants()["RMR_MAX_RCV_BYTES"]
99
100
101 class rmr_mbuf_t(Structure):
102     """
103     Reimplementation of rmr_mbuf_t which is in an unaccessible header file (src/common/include/rmr.h)
104
105     typedef struct {
106        int     state;             // state of processing
107        int     mtype;             // message type
108        int     len;               // length of data in the payload (send or received)
109        unsigned char* payload;    // transported data
110        unsigned char* xaction;    // pointer to fixed length transaction id bytes
111        int sub_id;                // subscription id
112        int      tp_state;         // transport state (a.k.a errno)
113                                   // these things are off limits to the user application
114        void*   tp_buf;            // underlying transport allocated pointer (e.g. nng message)
115        void*   header;            // internal message header (whole buffer: header+payload)
116        unsigned char* id;         // if we need an ID in the message separate from the xaction id
117        int flags;                 // various MFL_ (private) flags as needed
118        int alloc_len;             // the length of the allocated space (hdr+payload)
119     } rmr_mbuf_t;
120
121     We do not include the fields we are not supposed to mess with
122
123      RE PAYLOADs type below, see the documentation for c_char_p:
124        class ctypes.c_char_p
125            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.
126
127     """
128
129     _fields_ = [
130         ("state", c_int),
131         ("mtype", c_int),
132         ("len", c_int),
133         (
134             "payload",
135             POINTER(c_char),
136         ),  # according to th following the python bytes are already unsinged https://bytes.com/topic/python/answers/695078-ctypes-unsigned-char
137         ("xaction", POINTER(c_char)),
138         ("sub_id", c_int),
139         ("tp_state", c_int),
140     ]
141
142
143 # argtypes and restype are important: https://stackoverflow.com/questions/24377845/ctype-why-specify-argtypes
144
145
146 # extern void* rmr_init(char* uproto_port, int max_msg_size, int flags)
147 rmr_init = rmr_c_lib.rmr_init
148 rmr_init.argtypes = [c_char_p, c_int, c_int]
149 rmr_init.restype = c_void_p
150
151
152 # extern void rmr_close(void* vctx)
153 rmr_close = rmr_c_lib.rmr_close
154 rmr_close.argtypes = [c_void_p]
155 # I don't think there's a restype needed here. THe return is simply "return" in the c lib
156
157 # extern int rmr_ready(void* vctx)
158 rmr_ready = rmr_c_lib.rmr_ready
159 rmr_ready.argtypes = [c_void_p]
160 rmr_ready.restype = c_int
161
162 # extern int rmr_set_stimeout(void* vctx, int time)
163 # RE "int time", from the C docs:
164 #        Set send timeout. The value time is assumed to be microseconds.  The timeout is the
165 #        rough maximum amount of time that RMr will block on a send attempt when the underlying
166 #        mechnism indicates eagain or etimeedout.  All other error conditions are reported
167 #        without this delay. Setting a timeout of 0 causes no retries to be attempted in
168 #        RMr code. Setting a timeout of 1 causes RMr to spin up to 10K retries before returning,
169 #        but without issuing a sleep.  If timeout is > 1, then RMr will issue a sleep (1us)
170 #        after every 10K send attempts until the time value is reached. Retries are abandoned
171 #        if NNG returns anything other than NNG_AGAIN or NNG_TIMEDOUT.
172 #
173 #        The default, if this function is not used, is 1; meaning that RMr will retry, but will
174 #        not enter a sleep.  In all cases the caller should check the status in the message returned
175 #        after a send call.
176 rmr_set_stimeout = rmr_c_lib.rmr_set_rtimeout
177 rmr_set_stimeout.argtypes = [c_void_p, c_int]
178 rmr_set_stimeout.restype = c_int
179
180 # extern rmr_mbuf_t* rmr_alloc_msg(void* vctx, int size)
181 rmr_alloc_msg = rmr_c_lib.rmr_alloc_msg
182 rmr_alloc_msg.argtypes = [c_void_p, c_int]
183 rmr_alloc_msg.restype = POINTER(rmr_mbuf_t)
184
185 # extern int rmr_payload_size(rmr_mbuf_t* msg)
186 rmr_payload_size = rmr_c_lib.rmr_payload_size
187 rmr_payload_size.argtypes = [POINTER(rmr_mbuf_t)]
188 rmr_payload_size.restype = c_int
189
190
191 """
192 The following functions all seem to have the same interface
193 """
194
195 # extern rmr_mbuf_t* rmr_send_msg(void* vctx, rmr_mbuf_t* msg)
196 rmr_send_msg = rmr_c_lib.rmr_send_msg
197 rmr_send_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
198 rmr_send_msg.restype = POINTER(rmr_mbuf_t)
199
200 # extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
201 # TODO: the old message (Send param) is actually optional, but I don't know how to specify that in Ctypes.
202 rmr_rcv_msg = rmr_c_lib.rmr_rcv_msg
203 rmr_rcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
204 rmr_rcv_msg.restype = POINTER(rmr_mbuf_t)
205
206 # extern rmr_mbuf_t* rmr_torcv_msg(void* vctx, rmr_mbuf_t* old_msg, int ms_to)
207 # the version of receive for nng that has a timeout (give up after X ms)
208 rmr_torcv_msg = rmr_c_lib.rmr_torcv_msg
209 rmr_torcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t), c_int]
210 rmr_torcv_msg.restype = POINTER(rmr_mbuf_t)
211
212 # extern rmr_mbuf_t*  rmr_rts_msg(void* vctx, rmr_mbuf_t* msg)
213 rmr_rts_msg = rmr_c_lib.rmr_rts_msg
214 rmr_rts_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
215 rmr_rts_msg.restype = POINTER(rmr_mbuf_t)
216
217 # extern rmr_mbuf_t* rmr_call(void* vctx, rmr_mbuf_t* msg)
218 rmr_call = rmr_c_lib.rmr_call
219 rmr_call.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
220 rmr_call.restype = POINTER(rmr_mbuf_t)
221
222
223 # Header field interface
224
225 # extern int rmr_bytes2meid(rmr_mbuf_t* mbuf, unsigned char const* src, int len);
226 rmr_bytes2meid = rmr_c_lib.rmr_bytes2meid
227 rmr_bytes2meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p, c_int]
228 rmr_bytes2meid.restype = c_int
229
230
231 # CAUTION:  Some of the C functions expect a mutable buffer to copy the bytes into;
232 #           if there is a get_* function below, use it to set up and return the
233 #           buffer properly.
234
235 # extern unsigned char*  rmr_get_meid(rmr_mbuf_t* mbuf, unsigned char* dest);
236 rmr_get_meid = rmr_c_lib.rmr_get_meid
237 rmr_get_meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
238 rmr_get_meid.restype = c_char_p
239
240 # extern unsigned char*  rmr_get_src(rmr_mbuf_t* mbuf, unsigned char* dest);
241 rmr_get_src = rmr_c_lib.rmr_get_src
242 rmr_get_src.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
243 rmr_get_src.restype = c_char_p
244
245
246 # GET Methods
247
248
249 def get_payload(ptr_to_rmr_buf_t):
250     """
251     given a rmr_buf_t*, get it's binary payload as a bytes object
252     this magical function came from the answer here: https://stackoverflow.com/questions/55103298/python-ctypes-read-pointerc-char-in-python
253     """
254     sz = ptr_to_rmr_buf_t.contents.len
255     CharArr = c_char * sz
256     return CharArr(*ptr_to_rmr_buf_t.contents.payload[:sz]).raw
257
258
259 def get_xaction(ptr_to_rmr_buf_t):
260     """
261     given a rmr_buf_t*, get it's transaction id
262     """
263     val = cast(ptr_to_rmr_buf_t.contents.xaction, c_char_p).value
264     sz = _get_constants().get("RMR_MAX_XID", 0)
265     return val[:sz]
266
267
268 def message_summary(ptr_to_rmr_buf_t):
269     """
270     Used for debugging mostly: returns a dict that contains the fields of a message
271     """
272     if ptr_to_rmr_buf_t.contents.len > RMR_MAX_RCV_BYTES:
273         return "Malformed message: message length is greater than the maximum possible"
274
275     meid = get_meid(ptr_to_rmr_buf_t)
276     if meid == "\000" * _get_constants().get("RMR_MAX_MEID", 32):  # special case all nils
277         meid = None
278
279     return {
280         "payload": get_payload(ptr_to_rmr_buf_t),
281         "payload length": ptr_to_rmr_buf_t.contents.len,
282         "message type": ptr_to_rmr_buf_t.contents.mtype,
283         "subscription id": ptr_to_rmr_buf_t.contents.sub_id,
284         "transaction id": get_xaction(ptr_to_rmr_buf_t),
285         "message state": ptr_to_rmr_buf_t.contents.state,
286         "message status": _state_to_status(ptr_to_rmr_buf_t.contents.state),
287         "payload max size": rmr_payload_size(ptr_to_rmr_buf_t),
288         "meid": meid,
289         "message source": get_src(ptr_to_rmr_buf_t),
290         "errno": ptr_to_rmr_buf_t.contents.tp_state,
291     }
292
293
294 def set_payload_and_length(byte_str, ptr_to_rmr_buf_t):
295     """
296     use memmove to set the rmr_buf_t payload and content length
297     """
298     memmove(ptr_to_rmr_buf_t.contents.payload, byte_str, len(byte_str))
299     ptr_to_rmr_buf_t.contents.len = len(byte_str)
300
301
302 def generate_and_set_transaction_id(ptr_to_rmr_buf_t):
303     """
304     use memmove to set the rmr_buf_t xaction
305     """
306     uu_id = uuid.uuid1().hex.encode("utf-8")
307     sz = _get_constants().get("RMR_MAX_XID", 0)
308     memmove(ptr_to_rmr_buf_t.contents.xaction, uu_id, sz)
309
310
311 def get_meid(mbuf):
312     """
313     Suss out the managed equipment ID (meid) from the message header.
314     This is a 32 byte field and RMr returns all 32 bytes which if the
315     sender did not set will be garbage.
316     """
317     sz = _get_constants().get("RMR_MAX_MEID", 64)  # size for buffer to fill
318     buf = create_string_buffer(sz)
319     rmr_get_meid(mbuf, buf)
320     return buf.raw.decode()
321
322
323 def get_src(mbuf):
324     """
325     Suss out the message source information (likely host:port).
326     """
327     sz = _get_constants().get("RMR_MAX_SRC", 64)  # size to fill
328     buf = create_string_buffer(sz)
329     rmr_get_src(mbuf, buf)
330     return buf.value.decode()