VPP/Python API

From fd.io
< VPP
Revision as of 09:30, 23 February 2018 by GabrielGanne (Talk | contribs)

Jump to: navigation, search

Python binding for the VPP API

The vpp-papi module in vpp-api/python/ provides a Python binding to the VPP API. The Python bindings to the API is auto-generated from JSON API definitions. These JSON definitions must be passed to the VPP class init method. Both individual components and plugins provide API definitions. The JSON files are also generated, from .api files. In a binary installation the JSON API definitions are installed under /usr/share/vpp/api/

Currently there are three classes of VPP API methods:

  1. Simple request / reply. For example the show_version() call the SHOW_VERSION message is the request and the SHOW_VERSION_REPLY is the answer back. By convention replies are named ending with _REPLY.
  2. Dump functions. For example sw_interface_dump() send the SW_INTERFACE_DUMP message and receive a set of messages back. In this example SW_INTERFACE_DETAILS and SW_INTERFACE_SET_FLAGS are (typically) received. The CONTROL_PING/CONTROL_PING_REPLY is used as a method to signal to the client that the last message has been received. By convention the request message have names ending with _DUMP and the replies have names ending in _DETAILS.
  3. Register for events. For example want_stats() sends a WANT_STATS message, get a WANT_STATS_REPLY message back, and the client will then asynchronously receive VNET_INTERFACE_COUNTERS messages.

The API is by default blocking although there is possible to get asynchronous behaviour by setting the function argument async=True.

Each call uses the arguments as specified in the API definitions file (e.g. vpe.api). The "client_index" and "context" fields are handled by the module itself. A call returns a named tuple or a list of named tuples.

Installation

The main VPP build will build the C library (libvppapiclient.so). If VPP is installed via the Linux package system that library will be available on the system. To run within a build directory, set LD_LIBRARY_PATH to point to the location of libvppapiclient.so.

To build the VPP_PAPI Python package (and shared library): This step maybe unnecessary if you have already done it (generally one time)

 
make build
 

The Python package can either be installed in the Python system directory or in a Virtualenv environment. To install the Python component:

cd src/vpp-api/python
sudo python setup.py install
 

To test:

alagalah@thing1:vpp (master)*$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import vpp_papi
>>> 
 

If you run from the development directory in a virtualenv environment, you might have to set LD_LIBRARY_PATH to e.g. build-root/install-vpp_debug-native/vpp-api/lib64/

The Python package can also be installed from the vpp-python-api RPM/DEB. It is then installed in the system default Python library directory.

Step by Step

  1. # install preresquisites
  2. sudo apt-get install python-virtualenv
  3.  
  4. export VPP=~vpp/
  5. cd $VPP
  6.  
  7. # build vpp
  8. make bootstrap build
  9.  
  10. # create virtualenv
  11. virtualenv virtualenv
  12.  
  13. # (optional) install python packages
  14. # ipaddress is used by some scripts
  15. virtualenv/bin/pip install ipaddress
  16. # nice to have to get the tab completion and other CLI niceties
  17. virtualenv/bin/pip install scapy
  18.  
  19. # install vpp python api
  20. pushd $VPP/src/vpp-api/python/
  21. $VPP/virtualenv/bin/python setup.py install
  22. popd
  23.  
  24. # Now set the LD_LIBRARY_PATH such that it points to the directory containing libvppapiclient.so
  25. export LD_LIBRARY_PATH=`find $VPP -name "libvppapiclient.so" -exec dirname {} \; | grep install-vpp | head -n 1`
  26.  
  27. # You will now need two windows :
  28. # one for vpp, and the other for python
  29.  
  30. # VPP
  31. cd $VPP
  32. make run
  33.  
  34. # python
  35. # (as root, as vpp.connect() requires root privileges)
  36. # Note that sudo cannot not preserve LD_LIBRARY_PATH
  37. cd $VPP
  38.  
  39. # you can run a script 
  40. sudo -E LD_LIBRARY_PATH=$LD_LIBRARY_PATH $VPP/virtualenv/bin/python vpp-api/python/tests/vpp_hello_world.py.py
  41.  
  42. # or get a python prompt
  43. sudo -E LD_LIBRARY_PATH=$LD_LIBRARY_PATH $VPP/virtualenv/bin/python

VPP python's hello world

  1. #!/bin/env python
  2. '''
  3. vpp_hello_world.py
  4. '''
  5. from __future__ import print_function
  6.  
  7. import os
  8. import fnmatch
  9.  
  10. from vpp_papi import VPP 
  11.  
  12. # first, construct a vpp instance from vpp json api files
  13. # this will be a header for all python vpp scripts
  14.  
  15. # directory containing all the json api files.
  16. # if vpp is installed on the system, these will be in /usr/share/vpp/api/
  17. vpp_json_dir = os.environ['VPP'] + '/build-root/install-vpp_debug-native/vpp/share/vpp/api/core'
  18.  
  19. # construct a list of all the json api files
  20. jsonfiles = []
  21. for root, dirnames, filenames in os.walk(vpp_json_dir):
  22.     for filename in fnmatch.filter(filenames, '*.api.json'):
  23.         jsonfiles.append(os.path.join(vpp_json_dir, filename))
  24.  
  25. if not jsonfiles:
  26.     print('Error: no json api files found')
  27.     exit(-1)
  28.  
  29. # use all those files to create vpp.
  30. # Note that there will be no vpp method available before vpp.connect()
  31. vpp = VPP(jsonfiles)
  32. r = vpp.connect('papi-example')
  33. print(r)
  34. # None
  35.  
  36. # You're all set.
  37. # You can check the list of available methods by calling dir(vpp)
  38.  
  39. # show vpp version
  40. rv = vpp.api.show_version()
  41. print('VPP version =', rv.version.decode().rstrip('\0x00'))
  42. # VPP version = 17.04-rc0~192-gc5fccc0c
  43.  
  44. # disconnect from vpp
  45. r = vpp.disconnect()
  46. print(r)
  47. # 0
  48.  
  49. exit(r)

Implementation

Note: This is out of date and needs updating; pneum has been replaced by libvppapiclient; the semantics are otherwise mostly the same.

The vpp/api/vpe.api file specifies a set of messages that can be exchanged between VPP and the API client. The semantics of those messages are somewhat up to interpretation and convention.

The language binding is implemented simply by exposing four C calls to Python. Those are:

  int pneum_connect(char *name);
  int pneum_disconnect(void);
  int pneum_read(char **data, int *l);
  int pneum_write(char *data, int len);

In addition there is a Python message handler callback called by the C RX pthread. All message handling and parsing is done in Python.

Architecture

Architecture.png

Packaging:

VPP PAPI Packaging

Examples

Example: Dumping interface table

  1. #!/usr/bin/env python
  2.  
  3. from __future__ import print_function
  4.  
  5. import os
  6. import fnmatch
  7.  
  8. from vpp_papi import VPP 
  9.  
  10.  
  11. vpp_json_dir = '/usr/share/vpp/api/'
  12.  
  13. jsonfiles = []
  14. for root, dirnames, filenames in os.walk(vpp_json_dir):
  15.     for filename in fnmatch.filter(filenames, '*.api.json'):
  16.         jsonfiles.append(os.path.join(vpp_json_dir, filename))
  17.  
  18. if not jsonfiles:
  19.     print('Error: no json api files found')
  20.     exit(-1)
  21.  
  22. vpp = VPP(jsonfiles)
  23.  
  24. r = vpp.connect("test_papi")
  25. print(r)
  26.  
  27. for intf in vpp.sw_interface_dump():
  28.     print(intf.interface_name.decode())
  29.  
  30. exit(vpp.disconnect())

Example: Receive statistics


#!/usr/bin/env python

import struct
import time

import vpp_papi

def papi_event_handler(result):
    if result.vl_msg_id == vpp_papi.VL_API_VNET_INTERFACE_COUNTERS:
        format = '>' + str(int(len(result.data) / 8)) + 'Q'
        counters = struct.unpack(format, result.data)
        print('Counters:', counters)
        return

    print('Unknown message id:', result.vl_msg_id)

r = vpp_papi.connect("test_papi")
vpp_papi.register_event_callback(papi_event_handler)
r = vpp_papi.want_stats(True, 123)

#
# Wait for some stats
#
time.sleep(60)
r = vpp_papi.want_stats(False, pid)
r = vpp_papi.disconnect()

 

API generation

The Python binding is automatically generated from the API definitions. See figure below.

Assumptions

  • A common context field is used as a transaction id, for the client to be able to match replies with requests. Not all messages have context and the API handles that, as long as the CONTROL_PING is used to embed them.
  • The API generates code that will send a CONTROL_PING for _DUMP/_DETAIL message exchanges. It will not do so for CALL/CALL_REPLY style calls, so it is important that those conventions are followed.
  • Some messages, e.g. VNET_INTERFACE_COUNTERS are variable sized, with an unspecified u8 data[0] field and a something like a u32 count or u32 nitems field telling the message specific handler the size of the message. There is no way to automatically generate code to handle this, so the Python API returns these to the caller as a byte string. These can then be handled by message specific code like:
 if result.vl_msg_id == vpp_papi.VL_API_VNET_INTERFACE_COUNTERS:
        format = '>' + str(int(len(result.data) / 8)) + 'Q'
        counters = struct.unpack(format, result.data)
 

Papi.png

Future Improvements / TODOs

Performance: Python essentially runs single threaded. The RX thread will hold the Global Interpreter Lock during callback. Current performance is about 1500 messages/second. An implementation in C gets about 450000 messages/second in comparison.

API: Use Python Async I/O?

Exception / error handling

Handle messages like GET_NODE_GRAPH where the reply is a reference to shared memory.