Python API: Synchronous mode.
[vpp.git] / src / vpp-api / python / vpp_papi / vpp_papi.py
index 6b6b79f..0c40f17 100644 (file)
 
 from __future__ import print_function
 import sys, os, logging, collections, struct, json, threading, glob
+import atexit, Queue
+
 logging.basicConfig(level=logging.DEBUG)
 import vpp_api
 
 def eprint(*args, **kwargs):
+    """Print critical diagnostics to stderr."""
     print(*args, file=sys.stderr, **kwargs)
 
+def vpp_atexit(self):
+    """Clean up VPP connection on shutdown."""
+    if self.connected:
+        eprint ('Cleaning up VPP on exit')
+        self.disconnect()
+
+
+class Empty(object):
+    pass
+
+
+class FuncWrapper(object):
+    def __init__(self, func):
+        self._func = func
+        self.__name__ = func.__name__
+
+    def __call__(self, **kwargs):
+        return self._func(**kwargs)
+
+
 class VPP():
-    def __init__(self, apifiles = None, testmode = False):
+    """VPP interface.
+
+    This class provides the APIs to VPP.  The APIs are loaded
+    from provided .api.json files and makes functions accordingly.
+    These functions are documented in the VPP .api files, as they
+    are dynamically created.
+
+    Additionally, VPP can send callback messages; this class
+    provides a means to register a callback function to receive
+    these messages in a background thread.
+    """
+    def __init__(self, apifiles = None, testmode = False, async_thread = True):
+        """Create a VPP API object.
+
+        apifiles is a list of files containing API
+        descriptions that will be loaded - methods will be
+        dynamically created reflecting these APIs.  If not
+        provided this will load the API files from VPP's
+        default install location.
+        """
         self.messages = {}
         self.id_names = []
         self.id_msgdef = []
         self.buffersize = 10000
         self.connected = False
         self.header = struct.Struct('>HI')
-        self.results = {}
-        self.timeout = 5
-        self.apifile = []
+        self.apifiles = []
+        self.event_callback = None
+        self.message_queue = Queue.Queue()
+        self.read_timeout = 0
+        self.vpp_api = vpp_api
+        if async_thread:
+            self.event_thread = threading.Thread(target=self.thread_msg_handler)
+            self.event_thread.daemon = True
+            self.event_thread.start()
 
         if not apifiles:
             # Pick up API definitions from default directory
             apifiles = glob.glob('/usr/share/vpp/api/*.api.json')
 
         for file in apifiles:
-            self.apifile.append(file)
             with open(file) as apidef_file:
                 api = json.load(apidef_file)
                 for t in api['types']:
@@ -47,25 +94,34 @@ class VPP():
 
                 for m in api['messages']:
                     self.add_message(m[0], m[1:])
+       self.apifiles = apifiles
 
         # Basic sanity check
         if len(self.messages) == 0 and not testmode:
             raise ValueError(1, 'Missing JSON message definitions')
 
+        # Make sure we allow VPP to clean up the message rings.
+        atexit.register(vpp_atexit, self)
 
     class ContextId(object):
+        """Thread-safe provider of unique context IDs."""
         def __init__(self):
             self.context = 0
+           self.lock = threading.Lock()
         def __call__(self):
-            self.context += 1
-            return self.context
+            """Get a new unique (or, at least, not recently used) context."""
+           with self.lock:
+               self.context += 1
+               return self.context
     get_context = ContextId()
 
     def status(self):
+        """Debug function: report current VPP API status to stdout."""
         print('Connected') if self.connected else print('Not Connected')
-        print('Read API definitions from', self.apifile)
+        print('Read API definitions from', ', '.join(self.apifiles))
 
     def __struct (self, t, n = None, e = -1, vl = None):
+        """Create a packing structure for a message."""
         base_types = { 'u8' : 'B',
                        'u16' : 'H',
                        'u32' : 'I',
@@ -113,6 +169,7 @@ class VPP():
         raise ValueError(1, 'Invalid message type: ' + t)
 
     def __struct_type(self, encode, msgdef, buf, offset, kwargs):
+        """Get a message packer or unpacker."""
         if encode:
             return self.__struct_type_encode(msgdef, buf, offset, kwargs)
         else:
@@ -261,7 +318,7 @@ class VPP():
 
     def make_function(self, name, i, msgdef, multipart, async):
         if (async):
-            f = lambda **kwargs: (self._call_vpp_async(i, msgdef, multipart, **kwargs))
+            f = lambda **kwargs: (self._call_vpp_async(i, msgdef, **kwargs))
         else:
             f = lambda **kwargs: (self._call_vpp(i, msgdef, multipart, **kwargs))
         args = self.messages[name]['args']
@@ -270,9 +327,16 @@ class VPP():
         f.__doc__ = ", ".join(["%s %s" % (argtypes[k], k) for k in args.keys()])
         return f
 
+    @property
+    def api(self):
+        if not hasattr(self, "_api"):
+            raise Exception("Not connected, api definitions not available")
+        return self._api
+
     def _register_functions(self, async=False):
         self.id_names = [None] * (self.vpp_dictionary_maxid + 1)
         self.id_msgdef = [None] * (self.vpp_dictionary_maxid + 1)
+        self._api = Empty()
         for name, msgdef in self.messages.iteritems():
             if name in self.vpp_dictionary:
                 if self.messages[name]['crc'] != self.vpp_dictionary[name]['crc']:
@@ -283,13 +347,28 @@ class VPP():
                 self.id_msgdef[i] = msgdef
                 self.id_names[i] = name
                 multipart = True if name.find('_dump') > 0 else False
-                setattr(self, name, self.make_function(name, i, msgdef, multipart, async))
+                f = self.make_function(name, i, msgdef, multipart, async)
+                setattr(self._api, name, FuncWrapper(f))
+
+                # old API stuff starts here - will be removed in 17.07
+                if hasattr(self, name):
+                    raise NameError(
+                        3, "Conflicting name in JSON definition: `%s'" % name)
+                setattr(self, name, f)
+                # old API stuff ends here
 
     def _write (self, buf):
+        """Send a binary-packed message to VPP."""
         if not self.connected:
             raise IOError(1, 'Not connected')
         return vpp_api.write(str(buf))
 
+    def _read (self):
+        if not self.connected:
+            raise IOError(1, 'Not connected')
+
+        return vpp_api.read(self.read_timeout)
+
     def _load_dictionary(self):
         self.vpp_dictionary = {}
         self.vpp_dictionary_maxid = 0
@@ -303,13 +382,8 @@ class VPP():
             self.vpp_dictionary[name] = { 'id' : i, 'crc' : crc }
             self.vpp_dictionary_maxid = max(self.vpp_dictionary_maxid, i)
 
-    def connect(self, name, chroot_prefix = None, async = False):
-        msg_handler = self.msg_handler if not async else self.msg_handler_async
-        if not chroot_prefix:
-            rv = vpp_api.connect(name, msg_handler)
-        else:
-            rv = vpp_api.connect(name, msg_handler, chroot_prefix)
-
+    def connect_internal(self, name, msg_handler, chroot_prefix, rx_qlen, async):
+       rv = vpp_api.connect(name, msg_handler, chroot_prefix, rx_qlen)
         if rv != 0:
             raise IOError(2, 'Connect failed')
         self.connected = True
@@ -321,81 +395,69 @@ class VPP():
         self.control_ping_index = self.vpp_dictionary['control_ping']['id']
         self.control_ping_msgdef = self.messages['control_ping']
 
-    def disconnect(self):
-        rv = vpp_api.disconnect()
-        return rv
-
-    def results_wait(self, context):
-        return (self.results[context]['e'].wait(self.timeout))
+    def connect(self, name, chroot_prefix = None, async = False, rx_qlen = 32):
+        """Attach to VPP.
 
-    def results_prepare(self, context):
-        self.results[context] = {}
-        self.results[context]['e'] = threading.Event()
-        self.results[context]['e'].clear()
-        self.results[context]['r'] = []
+        name - the name of the client.
+        chroot_prefix - if VPP is chroot'ed, the prefix of the jail
+        async - if true, messages are sent without waiting for a reply
+        rx_qlen - the length of the VPP message receive queue between
+        client and server.
+        """
+        msg_handler = self.msg_handler_sync if not async \
+                      else self.msg_handler_async
+        return self.connect_internal(name, msg_handler, chroot_prefix, rx_qlen,
+                                     async)
 
-    def results_clean(self, context):
-        del self.results[context]
+    def connect_sync (self, name, chroot_prefix = None, rx_qlen = 32):
+        """Attach to VPP in synchronous mode. Application must poll for events.
 
-    def msg_handler(self, msg):
-        if not msg:
-            eprint('vpp_api.read failed')
-            return
-
-        i, ci = self.header.unpack_from(msg, 0)
-        if self.id_names[i] == 'rx_thread_exit':
-            return;
+        name - the name of the client.
+        chroot_prefix - if VPP is chroot'ed, the prefix of the jail
+        rx_qlen - the length of the VPP message receive queue between
+        client and server.
+        """
 
-        #
-        # Decode message and returns a tuple.
-        #
-        msgdef = self.id_msgdef[i]
-        if not msgdef:
-            raise IOError(2, 'Reply message undefined')
-
-        r = self.decode(msgdef, msg)
-        if 'context' in r._asdict():
-            if r.context > 0:
-                context = r.context
+        return self.connect_internal(name, None, chroot_prefix, rx_qlen,
+                                     async=False)
 
-        msgname = type(r).__name__
+    def disconnect(self):
+        """Detach from VPP."""
+        rv = vpp_api.disconnect()
+        self.connected = False
+        return rv
 
-        #
-        # XXX: Call provided callback for event
-        # Are we guaranteed to not get an event during processing of other messages?
-        # How to differentiate what's a callback message and what not? Context = 0?
-        #
-        #if not is_waiting_for_reply():
-        if r.context == 0 and self.event_callback:
-            self.event_callback(msgname, r)
-            return
+    def msg_handler_sync(self, msg):
+        """Process an incoming message from VPP in sync mode.
 
-        #
-        # Collect results until control ping
-        #
-        if msgname == 'control_ping_reply':
-            self.results[context]['e'].set()
+        The message may be a reply or it may be an async notification.
+        """
+        r = self.decode_incoming_msg(msg)
+        if r is None:
             return
 
-        if not context in self.results:
-            eprint('Not expecting results for this context', context, r)
-            return
+        # If we have a context, then use the context to find any
+        # request waiting for a reply
+        context = 0
+        if hasattr(r, 'context') and r.context > 0:
+            context = r.context
 
-        if 'm' in self.results[context]:
-            self.results[context]['r'].append(r)
-            return
+        msgname = type(r).__name__
 
-        self.results[context]['r'] = r
-        self.results[context]['e'].set()
+        if context == 0:
+            # No context -> async notification that we feed to the callback
+            self.message_queue.put_nowait(r)
+        else:
+            raise IOError(2, 'RPC reply message received in event handler')
 
-    def msg_handler_async(self, msg):
+    def decode_incoming_msg(self, msg):
         if not msg:
             eprint('vpp_api.read failed')
             return
 
         i, ci = self.header.unpack_from(msg, 0)
         if self.id_names[i] == 'rx_thread_exit':
-            return;
+            return
 
         #
         # Decode message and returns a tuple.
@@ -405,16 +467,45 @@ class VPP():
             raise IOError(2, 'Reply message undefined')
 
         r = self.decode(msgdef, msg)
+
+        return r
+
+    def msg_handler_async(self, msg):
+        """Process a message from VPP in async mode.
+
+        In async mode, all messages are returned to the callback.
+        """
+        r = self.decode_incoming_msg(msg)
+        if r is None:
+            return
+
         msgname = type(r).__name__
 
-        self.event_callback(msgname, r)
+       if self.event_callback:
+           self.event_callback(msgname, r)
 
     def _control_ping(self, context):
-        self._write(self.encode(self.control_ping_msgdef,
-                        { '_vl_msg_id' : self.control_ping_index,
-                          'context' : context}))
+        """Send a ping command."""
+        self._call_vpp_async(self.control_ping_index,
+                            self.control_ping_msgdef,
+                             context=context)
 
     def _call_vpp(self, i, msgdef, multipart, **kwargs):
+        """Given a message, send the message and await a reply.
+
+        msgdef - the message packing definition
+        i - the message type index
+        multipart - True if the message returns multiple
+        messages in return.
+        context - context number - chosen at random if not
+        supplied.
+        The remainder of the kwargs are the arguments to the API call.
+
+        The return value is the message or message array containing
+        the response.  It will raise an IOError exception if there was
+        no response within the timeout window.
+        """
+
         if not 'context' in kwargs:
             context = self.get_context()
             kwargs['context'] = context
@@ -423,18 +514,49 @@ class VPP():
         kwargs['_vl_msg_id'] = i
         b = self.encode(msgdef, kwargs)
 
-        self.results_prepare(context)
+        vpp_api.suspend()
         self._write(b)
 
         if multipart:
-            self.results[context]['m'] = True
+            # Send a ping after the request - we use its response
+            # to detect that we have seen all results.
             self._control_ping(context)
-        self.results_wait(context)
-        r = self.results[context]['r']
-        self.results_clean(context)
-        return r
 
-    def _call_vpp_async(self, i, msgdef, multipart, **kwargs):
+        # Block until we get a reply.
+        rl = []
+        while (True):
+            msg = self._read()
+            if not msg:
+                print('PNEUM ERROR: OH MY GOD')
+                raise IOError(2, 'PNEUM read failed')
+
+            r = self.decode_incoming_msg(msg)
+            msgname = type(r).__name__
+            if not context in r or r.context == 0 or context != r.context:
+                self.message_queue.put_nowait(r)
+                continue
+
+            if not multipart:
+                rl = r
+                break
+            if msgname == 'control_ping_reply':
+                break
+
+            rl.append(r)
+
+        vpp_api.resume()
+
+        return rl
+
+    def _call_vpp_async(self, i, msgdef, **kwargs):
+        """Given a message, send the message and await a reply.
+
+        msgdef - the message packing definition
+        i - the message type index
+        context - context number - chosen at random if not
+        supplied.
+        The remainder of the kwargs are the arguments to the API call.
+        """
         if not 'context' in kwargs:
             context = self.get_context()
             kwargs['context'] = context
@@ -446,5 +568,32 @@ class VPP():
         self._write(b)
 
     def register_event_callback(self, callback):
+        """Register a callback for async messages.
+
+        This will be called for async notifications in sync mode,
+        and all messages in async mode.  In sync mode, replies to
+        requests will not come here.
+
+        callback is a fn(msg_type_name, msg_type) that will be
+        called when a message comes in.  While this function is
+        executing, note that (a) you are in a background thread and
+        may wish to use threading.Lock to protect your datastructures,
+        and (b) message processing from VPP will stop (so if you take
+        a long while about it you may provoke reply timeouts or cause
+        VPP to fill the RX buffer).  Passing None will disable the
+        callback.
+        """
         self.event_callback = callback
 
+    def thread_msg_handler(self):
+        """Python thread calling the user registerd message handler.
+
+        This is to emulate the old style event callback scheme. Modern
+        clients should provide their own thread to poll the event
+        queue.
+        """
+        while True:
+            r = self.message_queue.get()
+            msgname = type(r).__name__
+           if self.event_callback:
+               self.event_callback(msgname, r)