Skip to content

VPP Python_API

Dave Wallace edited this page Apr 21, 2026 · 1 revision

Contents

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. from __future__ import print_function
    
  4. from vpp_papi import VPPApiClient
    
  5. import fnmatch
    
  6. import os
    
  7.  
    
  8. # this is 25.02-rc0~196-g098d0c594 version test
    
  9. vpp_json_dir = '/opt/vpp/build-root/install-vpp_debug-native/vpp/share/vpp/api/core'
    
  10.  
    
  11. jsonfiles = []
    
  12. for root, dirnames, filenames in os.walk(vpp_json_dir):
    
  13.     for filename in fnmatch.filter(filenames, '*.api.json'):
    
  14.         jsonfiles.append(os.path.join(vpp_json_dir, filename))
    
  15.  
    
  16. if not jsonfiles:
    
  17.     print('Error: no json api files found')
    
  18.     exit(-1)
    
  19.  
    
  20.  
    
  21. # use all those files to create vpp.
    
  22. # Note that there will be no vpp method available before vpp.connect()
    
  23. vpp = VPPApiClient(apidir=vpp_json_dir, apifiles=jsonfiles)
    
  24. r = vpp.connect('papi-example')
    
  25. print(r)
    
  26. # None
    
  27.  
    
  28. # You're all set.
    
  29. # You can check the list of available methods by calling dir(vpp)
    
  30.  
    
  31. # show vpp version
    
  32. rv = vpp.api.show_version()
    
  33. if isinstance(rv.version, bytes):
    
  34.     version_str = rv.version.decode().rstrip('\x00')
    
  35. else:
    
  36.     version_str = rv.version.rstrip('\x00')
    
  37.  
    
  38. print('VPP version =', version_str)
    
  39.  
    
  40. # disconnect from vpp
    
  41. r = vpp.disconnect()
    
  42. print(r)
    
  43.  
    
  44. 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 VPPApiClient
    
  9.  
    
  10.  
    
  11. vpp_json_dir = '/usr/share/vpp/api/core/'
    
  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 = VPPApiClient(apifiles=jsonfiles)
    
  23.  
    
  24. r = vpp.connect("test_papi")
    
  25. print(r)
    
  26.  
    
  27. for intf in vpp.api.sw_interface_dump():
    
  28.     if isinstance(intf.interface_name, bytes):
    
  29.         print(intf.interface_name.decode())
    
  30.     else:
    
  31.         print(intf.interface_name)
    
  32.  
    
  33. exit(vpp.disconnect())
    

Example: Receive statistics

  1. #!/usr/bin/env python
    
  2.  
    
  3. from vpp_papi import VPPApiClient
    
  4. import os
    
  5. import sys
    
  6. import fnmatch
    
  7. import time
    
  8. def papi_event_handler(msgname, result):
    
  9.   print(msgname)
    
  10.   print(result)
    
  11.  
    
  12. vpp_json_dir = os.environ['VPP'] + '/build-root/install-vpp_debug-native/vpp/share/vpp/api/core'
    
  13.  
    
  14. # construct a list of all the json api files
    
  15. jsonfiles = []
    
  16. for root, dirnames, filenames in os.walk(vpp_json_dir):
    
  17.     for filename in fnmatch.filter(filenames, '*.api.json'):
    
  18.         jsonfiles.append(os.path.join(vpp_json_dir, filename))
    
  19. if not jsonfiles:
    
  20.     print('Error: no json api files found')
    
  21.     exit(-1)
    
  22. # use all those files to create vpp.
    
  23. vpp = VPPApiClient(apifiles=jsonfiles)
    
  24. r = vpp.connect("test_papi")
    
  25. print(r)
    
  26.  
    
  27. async=True
    
  28. r=vpp.register_event_callback(papi_event_handler)
    
  29. r = vpp.api.want_interface_events(enable_disable=1, pid=os.getpid())
    
  30. print(r)
    
  31. # Wait for some stats
    
  32. time.sleep(60)
    
  33. r = vpp.api.want_interface_events(enable_disable=False)
    
  34. r = vpp.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.

VPP Wiki

Home

Attachments

Clone this wiki locally