bc6523708aadcfeda364958969b895dbcf36e699
[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, pythonapi
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 def _errno():
93     """Suss out the C error number value which might be useful in understanding
94     an underlying reason when RMr returns a failure.
95     """
96     return c_int.in_dll(pythonapi, "errno").value
97
98
99 ##############
100 # PUBLIC API
101 ##############
102
103 # These constants are directly usable by importers of this library
104 # TODO: Are there others that will be useful?
105 RMR_MAX_RCV_BYTES = _get_constants()["RMR_MAX_RCV_BYTES"]
106
107
108 class rmr_mbuf_t(Structure):
109     """
110     Reimplementation of rmr_mbuf_t which is in an unaccessible header file (src/common/include/rmr.h)
111
112     typedef struct {
113        int     state;             // state of processing
114        int     mtype;             // message type
115        int     len;               // length of data in the payload (send or received)
116        unsigned char* payload;    // transported data
117        unsigned char* xaction;    // pointer to fixed length transaction id bytes
118        int sub_id;                // subscription id
119                                   // these things are off limits to the user application
120        void*   tp_buf;            // underlying transport allocated pointer (e.g. nng message)
121        void*   header;            // internal message header (whole buffer: header+payload)
122        unsigned char* id;         // if we need an ID in the message separate from the xaction id
123        int flags;                 // various MFL_ (private) flags as needed
124        int alloc_len;             // the length of the allocated space (hdr+payload)
125     } rmr_mbuf_t;
126
127     We do not include the fields we are not supposed to mess with
128
129      RE PAYLOADs type below, see the documentation for c_char_p:
130        class ctypes.c_char_p
131            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.
132
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     ]
146
147
148 # argtypes and restype are important: https://stackoverflow.com/questions/24377845/ctype-why-specify-argtypes
149
150
151 # extern void* rmr_init(char* uproto_port, int max_msg_size, int flags)
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 # extern void rmr_close(void* vctx)
158 rmr_close = rmr_c_lib.rmr_close
159 rmr_close.argtypes = [c_void_p]
160 # I don't think there's a restype needed here. THe return is simply "return" in the c lib
161
162 # extern int rmr_ready(void* vctx)
163 rmr_ready = rmr_c_lib.rmr_ready
164 rmr_ready.argtypes = [c_void_p]
165 rmr_ready.restype = c_int
166
167 # extern int rmr_set_stimeout(void* vctx, int time)
168 # RE "int time", from the C docs:
169 #        Set send timeout. The value time is assumed to be microseconds.  The timeout is the
170 #        rough maximum amount of time that RMr will block on a send attempt when the underlying
171 #        mechnism indicates eagain or etimeedout.  All other error conditions are reported
172 #        without this delay. Setting a timeout of 0 causes no retries to be attempted in
173 #        RMr code. Setting a timeout of 1 causes RMr to spin up to 10K retries before returning,
174 #        but without issuing a sleep.  If timeout is > 1, then RMr will issue a sleep (1us)
175 #        after every 10K send attempts until the time value is reached. Retries are abandoned
176 #        if NNG returns anything other than NNG_AGAIN or NNG_TIMEDOUT.
177 #
178 #        The default, if this function is not used, is 1; meaning that RMr will retry, but will
179 #        not enter a sleep.  In all cases the caller should check the status in the message returned
180 #        after a send call.
181 rmr_set_stimeout = rmr_c_lib.rmr_set_rtimeout
182 rmr_set_stimeout.argtypes = [c_void_p, c_int]
183 rmr_set_stimeout.restype = c_int
184
185 # extern rmr_mbuf_t* rmr_alloc_msg(void* vctx, int size)
186 rmr_alloc_msg = rmr_c_lib.rmr_alloc_msg
187 rmr_alloc_msg.argtypes = [c_void_p, c_int]
188 rmr_alloc_msg.restype = POINTER(rmr_mbuf_t)
189
190 # extern int rmr_payload_size(rmr_mbuf_t* msg)
191 rmr_payload_size = rmr_c_lib.rmr_payload_size
192 rmr_payload_size.argtypes = [POINTER(rmr_mbuf_t)]
193 rmr_payload_size.restype = c_int
194
195
196 """
197 The following functions all seem to have the same interface
198 """
199
200 # extern rmr_mbuf_t* rmr_send_msg(void* vctx, rmr_mbuf_t* msg)
201 rmr_send_msg = rmr_c_lib.rmr_send_msg
202 rmr_send_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
203 rmr_send_msg.restype = POINTER(rmr_mbuf_t)
204
205 # extern rmr_mbuf_t* rmr_rcv_msg(void* vctx, rmr_mbuf_t* old_msg)
206 # TODO: the old message (Send param) is actually optional, but I don't know how to specify that in Ctypes.
207 rmr_rcv_msg = rmr_c_lib.rmr_rcv_msg
208 rmr_rcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
209 rmr_rcv_msg.restype = POINTER(rmr_mbuf_t)
210
211 # extern rmr_mbuf_t* rmr_torcv_msg(void* vctx, rmr_mbuf_t* old_msg, int ms_to)
212 # the version of receive for nng that has a timeout (give up after X ms)
213 rmr_torcv_msg = rmr_c_lib.rmr_torcv_msg
214 rmr_torcv_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t), c_int]
215 rmr_torcv_msg.restype = POINTER(rmr_mbuf_t)
216
217 # extern rmr_mbuf_t*  rmr_rts_msg(void* vctx, rmr_mbuf_t* msg)
218 rmr_rts_msg = rmr_c_lib.rmr_rts_msg
219 rmr_rts_msg.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
220 rmr_rts_msg.restype = POINTER(rmr_mbuf_t)
221
222 # extern rmr_mbuf_t* rmr_call(void* vctx, rmr_mbuf_t* msg)
223 rmr_call = rmr_c_lib.rmr_call
224 rmr_call.argtypes = [c_void_p, POINTER(rmr_mbuf_t)]
225 rmr_call.restype = POINTER(rmr_mbuf_t)
226
227
228 # Header field interface
229
230 # extern int rmr_bytes2meid(rmr_mbuf_t* mbuf, unsigned char const* src, int len);
231 rmr_bytes2meid = rmr_c_lib.rmr_bytes2meid
232 rmr_bytes2meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p, c_int]
233 rmr_bytes2meid.restype = c_int
234
235
236 # CAUTION:  Some of the C functions expect a mutable buffer to copy the bytes into;
237 #           if there is a get_* function below, use it to set up and return the
238 #           buffer properly.
239
240 # extern unsigned char*  rmr_get_meid(rmr_mbuf_t* mbuf, unsigned char* dest);
241 rmr_get_meid = rmr_c_lib.rmr_get_meid
242 rmr_get_meid.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
243 rmr_get_meid.restype = c_char_p
244
245 # extern unsigned char*  rmr_get_src(rmr_mbuf_t* mbuf, unsigned char* dest);
246 rmr_get_src = rmr_c_lib.rmr_get_src
247 rmr_get_src.argtypes = [POINTER(rmr_mbuf_t), c_char_p]
248 rmr_get_src.restype = c_char_p
249
250
251 # GET Methods
252
253
254 def get_payload(ptr_to_rmr_buf_t):
255     """
256     given a rmr_buf_t*, get it's binary payload as a bytes object
257     this magical function came from the answer here: https://stackoverflow.com/questions/55103298/python-ctypes-read-pointerc-char-in-python
258     """
259     sz = ptr_to_rmr_buf_t.contents.len
260     CharArr = c_char * sz
261     return CharArr(*ptr_to_rmr_buf_t.contents.payload[:sz]).raw
262
263
264 def get_xaction(ptr_to_rmr_buf_t):
265     """
266     given a rmr_buf_t*, get it's transaction id
267     """
268     val = cast(ptr_to_rmr_buf_t.contents.xaction, c_char_p).value
269     sz = _get_constants().get("RMR_MAX_XID", 0)
270     return val[:sz]
271
272
273 def message_summary(ptr_to_rmr_buf_t):
274     """
275     Used for debugging mostly: returns a dict that contains the fields of a message
276     """
277     if ptr_to_rmr_buf_t.contents.len > RMR_MAX_RCV_BYTES:
278         return "Malformed message: message length is greater than the maximum possible"
279
280     meid = get_meid(ptr_to_rmr_buf_t)
281     if meid == "\000" * _get_constants().get("RMR_MAX_MEID", 32):  # special case all nils
282         meid = None
283
284     return {
285         "payload": get_payload(ptr_to_rmr_buf_t),
286         "payload length": ptr_to_rmr_buf_t.contents.len,
287         "message type": ptr_to_rmr_buf_t.contents.mtype,
288         "subscription id": ptr_to_rmr_buf_t.contents.sub_id,
289         "transaction id": get_xaction(ptr_to_rmr_buf_t),
290         "message state": ptr_to_rmr_buf_t.contents.state,
291         "message status": _state_to_status(ptr_to_rmr_buf_t.contents.state),
292         "payload max size": rmr_payload_size(ptr_to_rmr_buf_t),
293         "meid": meid,
294         "message source": get_src(ptr_to_rmr_buf_t),
295         "errno": _errno(),
296     }
297
298
299 def set_payload_and_length(byte_str, ptr_to_rmr_buf_t):
300     """
301     use memmove to set the rmr_buf_t payload and content length
302     """
303     memmove(ptr_to_rmr_buf_t.contents.payload, byte_str, len(byte_str))
304     ptr_to_rmr_buf_t.contents.len = len(byte_str)
305
306
307 def generate_and_set_transaction_id(ptr_to_rmr_buf_t):
308     """
309     use memmove to set the rmr_buf_t xaction
310     """
311     uu_id = uuid.uuid1().hex.encode("utf-8")
312     sz = _get_constants().get("RMR_MAX_XID", 0)
313     memmove(ptr_to_rmr_buf_t.contents.xaction, uu_id, sz)
314
315
316 def get_meid(mbuf):
317     """
318     Suss out the managed equipment ID (meid) from the message header.
319     This is a 32 byte field and RMr returns all 32 bytes which if the
320     sender did not set will be garbage.
321     """
322     sz = _get_constants().get("RMR_MAX_MEID", 64)  # size for buffer to fill
323     buf = create_string_buffer(sz)
324     rmr_get_meid(mbuf, buf)
325     return buf.raw.decode()
326
327
328 def get_src(mbuf):
329     """
330     Suss out the message source information (likely host:port).
331     """
332     sz = _get_constants().get("RMR_MAX_SRC", 64)  # size to fill
333     buf = create_string_buffer(sz)
334     rmr_get_src(mbuf, buf)
335     return buf.value.decode()