Difference between revisions of "VPP/Python API"
(Updated stats example) |
Aijayadams (Talk | contribs) m (API definition jsons are now separated by core and plugin, appending filename to base path /usr/share/vpp/api/core/ does not yield the correct path.) |
||
(One intermediate revision by one other user not shown) | |||
Line 184: | Line 184: | ||
− | vpp_json_dir = '/usr/share/vpp/api/' | + | vpp_json_dir = '/usr/share/vpp/api/core/' |
jsonfiles = [] | jsonfiles = [] | ||
Line 200: | Line 200: | ||
print(r) | print(r) | ||
− | for intf in vpp.sw_interface_dump(): | + | for intf in vpp.api.sw_interface_dump(): |
print(intf.interface_name.decode()) | print(intf.interface_name.decode()) | ||
Latest revision as of 15:25, 18 April 2019
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:
- 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.
- 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.
- 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
# install preresquisites
sudo apt-get install python-virtualenv
export VPP=~vpp/
cd $VPP
# build vpp
make bootstrap build
# create virtualenv
virtualenv virtualenv
# (optional) install python packages
# ipaddress is used by some scripts
virtualenv/bin/pip install ipaddress
# nice to have to get the tab completion and other CLI niceties
virtualenv/bin/pip install scapy
# install vpp python api
pushd $VPP/src/vpp-api/python/
$VPP/virtualenv/bin/python setup.py install
popd
# Now set the LD_LIBRARY_PATH such that it points to the directory containing libvppapiclient.so
export LD_LIBRARY_PATH=`find $VPP -name "libvppapiclient.so" -exec dirname {} \; | grep install-vpp | head -n 1`
# You will now need two windows :
# one for vpp, and the other for python
# VPP
cd $VPP
make run
# python
# (as root, as vpp.connect() requires root privileges)
# Note that sudo cannot not preserve LD_LIBRARY_PATH
cd $VPP
# you can run a script
sudo -E LD_LIBRARY_PATH=$LD_LIBRARY_PATH $VPP/virtualenv/bin/python vpp-api/python/tests/vpp_hello_world.py.py
# or get a python prompt
sudo -E LD_LIBRARY_PATH=$LD_LIBRARY_PATH $VPP/virtualenv/bin/python
VPP python's hello world
#!/bin/env python
'''
vpp_hello_world.py
'''
from __future__ import print_function
import os
import fnmatch
from vpp_papi import VPP
# first, construct a vpp instance from vpp json api files
# this will be a header for all python vpp scripts
# directory containing all the json api files.
# if vpp is installed on the system, these will be in /usr/share/vpp/api/
vpp_json_dir = os.environ['VPP'] + '/build-root/install-vpp_debug-native/vpp/share/vpp/api/core'
# construct a list of all the json api files
jsonfiles = []
for root, dirnames, filenames in os.walk(vpp_json_dir):
for filename in fnmatch.filter(filenames, '*.api.json'):
jsonfiles.append(os.path.join(vpp_json_dir, filename))
if not jsonfiles:
print('Error: no json api files found')
exit(-1)
# use all those files to create vpp.
# Note that there will be no vpp method available before vpp.connect()
vpp = VPP(jsonfiles)
r = vpp.connect('papi-example')
print(r)
# None
# You're all set.
# You can check the list of available methods by calling dir(vpp)
# show vpp version
rv = vpp.api.show_version()
print('VPP version =', rv.version.decode().rstrip('\0x00'))
# VPP version = 17.04-rc0~192-gc5fccc0c
# disconnect from vpp
r = vpp.disconnect()
print(r)
# 0
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
Packaging:
Examples
Example: Dumping interface table
#!/usr/bin/env python
from __future__ import print_function
import os
import fnmatch
from vpp_papi import VPP
vpp_json_dir = '/usr/share/vpp/api/core/'
jsonfiles = []
for root, dirnames, filenames in os.walk(vpp_json_dir):
for filename in fnmatch.filter(filenames, '*.api.json'):
jsonfiles.append(os.path.join(vpp_json_dir, filename))
if not jsonfiles:
print('Error: no json api files found')
exit(-1)
vpp = VPP(jsonfiles)
r = vpp.connect("test_papi")
print(r)
for intf in vpp.api.sw_interface_dump():
print(intf.interface_name.decode())
exit(vpp.disconnect())
Example: Receive statistics
#!/usr/bin/env python
from vpp_papi import VPP
import os
import sys
import fnmatch
import time
def papi_event_handler(msgname, result):
print(msgname)
print(result)
vpp_json_dir = os.environ['VPP'] + '/build-root/install-vpp_debug-native/vpp/share/vpp/api/core'
# construct a list of all the json api files
jsonfiles = []
for root, dirnames, filenames in os.walk(vpp_json_dir):
for filename in fnmatch.filter(filenames, '*.api.json'):
jsonfiles.append(os.path.join(vpp_json_dir, filename))
if not jsonfiles:
print('Error: no json api files found')
exit(-1)
# use all those files to create vpp.
vpp = VPP(jsonfiles)
r = vpp.connect("test_papi")
print(r)
async=True
r=vpp.register_event_callback(papi_event_handler)
pid=os.getpid()
sw_ifs = [1,2,3,4,5,6,7]
r = vpp.api.want_per_interface_simple_stats(enable_disable=True, sw_ifs=sw_ifs, num=len(sw_ifs), pid=pid)
print(r)
# Wait for some stats
time.sleep(60)
r = vpp.api.want_per_interface_simple_stats(enable_disable=False)
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)
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.