Difference between revisions of "VPP/Python API"

From fd.io
< VPP
Jump to: navigation, search
(Architecture)
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.)
 
(22 intermediate revisions by 7 users not shown)
Line 2: Line 2:
 
== Python binding for the VPP API ==
 
== 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. The main API definition is in vpp/vpp-api/vpe.api. Plugins and other components may provide their own API definitions, and those are distributed as separate Python packages.
+
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:
 
Currently there are three classes of VPP API methods:
Line 16: Line 16:
  
 
== Installation ==
 
== Installation ==
The main VPP build will build the C library (libpneum.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 libpneum.so.
+
The main VPP build will build the C library (<code>libvppapiclient.so</code>). 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 <code>libvppapiclient.so</code>.
  
 
To build the VPP_PAPI Python package (and shared library):
 
To build the VPP_PAPI Python package (and shared library):
<nowiki>
+
This step maybe unnecessary if you have already done it (generally one time)
make build-vpp-api
+
 
 +
  <nowiki>
 +
make build
 
  </nowiki>
 
  </nowiki>
  
Line 26: Line 28:
 
To install the Python component:
 
To install the Python component:
 
  <nowiki>
 
  <nowiki>
cd vpp-api/python
+
cd src/vpp-api/python
python setup.py install
+
sudo python setup.py install
 
  </nowiki>
 
  </nowiki>
  
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/
+
To test:
 +
<nowiki>
 +
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
 +
>>>
 +
</nowiki>
 +
 
 +
If you run from the development directory in a virtualenv environment, you might have to set LD_LIBRARY_PATH to e.g. <code>build-root/install-vpp_debug-native/vpp-api/lib64/</code>
 +
 
 +
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 ==
 +
<syntaxhighlight lang="bash" line='line'>
 +
# 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
 +
</syntaxhighlight>
 +
 
 +
VPP python's hello world
 +
<syntaxhighlight lang="python" line='line'>
 +
#!/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
  
The Python package can also be installed from the vpp-python-api RPM. It is then installed in the default Python library directory.
+
exit(r)
 +
</syntaxhighlight>
  
 
== Implementation ==
 
== Implementation ==
  
 +
<b>Note: This is out of date and needs updating; <code>pneum</code> has been replaced by <code>libvppapiclient</code>; the semantics are otherwise mostly the same.</b>
  
 
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 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:
 
The language binding is implemented simply by exposing four C calls to Python. Those are:
 +
<syntaxhighlight lang="C">
 
   int pneum_connect(char *name);
 
   int pneum_connect(char *name);
 
   int pneum_disconnect(void);
 
   int pneum_disconnect(void);
 
   int pneum_read(char **data, int *l);
 
   int pneum_read(char **data, int *l);
 
   int pneum_write(char *data, int len);
 
   int pneum_write(char *data, int len);
 +
</syntaxhighlight>
  
 
In addition there is a Python message handler callback called by the C RX pthread. All message handling and parsing is done in Python.
 
In addition there is a Python message handler callback called by the C RX pthread. All message handling and parsing is done in Python.
Line 54: Line 169:
  
 
[[File:Screen Shot 2016-09-21 at 12.02.05.png||300px|VPP PAPI Packaging]]
 
[[File:Screen Shot 2016-09-21 at 12.02.05.png||300px|VPP PAPI Packaging]]
 +
== Examples ==
  
 
=== Example: Dumping interface table ===
 
=== Example: Dumping interface table ===
The example is in "vpp-api-client/python/examply.py" and there are unit tests in "vpp-api-client/python/test_papi.py".
 
  
<nowiki>
+
<syntaxhighlight lang="python" line='line'>
 
#!/usr/bin/env python
 
#!/usr/bin/env python
  
import vpp_papi
+
from __future__ import print_function
  
r = vpp_papi.connect("test_papi")
+
import os
 +
import fnmatch
  
t = vpp_papi.show_version()
+
from vpp_papi import VPP  
print('VPP version:', t.version.decode())
+
  
t = vpp_papi.sw_interface_dump(0, b'ignored')
 
  
if t:
+
vpp_json_dir = '/usr/share/vpp/api/core/'
    print('List of interfaces')
+
    for interface in t:
+
        if interface.vl_msg_id == vpp_papi.vpe.VL_API_SW_INTERFACE_DETAILS:
+
            print(interface.interface_name.decode())
+
r = vpp_papi.disconnect()
+
</nowiki>
+
  
== Examples ==
+
jsonfiles = []
=== Example: Receive statistics ===
+
for root, dirnames, filenames in os.walk(vpp_json_dir):
<nowiki>
+
    for filename in fnmatch.filter(filenames, '*.api.json'):
 +
        jsonfiles.append(os.path.join(vpp_json_dir, filename))
  
#!/usr/bin/env python
+
if not jsonfiles:
 +
    print('Error: no json api files found')
 +
    exit(-1)
  
import struct
+
vpp = VPP(jsonfiles)
import time
+
  
import vpp_papi
+
r = vpp.connect("test_papi")
 +
print(r)
  
def papi_event_handler(result):
+
for intf in vpp.api.sw_interface_dump():
     if result.vl_msg_id == vpp_papi.VL_API_VNET_INTERFACE_COUNTERS:
+
     print(intf.interface_name.decode())
        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)
+
exit(vpp.disconnect())
 +
</syntaxhighlight>
  
r = vpp_papi.connect("test_papi")
+
=== Example: Receive statistics ===
vpp_papi.register_event_callback(papi_event_handler)
+
r = vpp_papi.want_stats(True, 123)
+
  
#
+
<syntaxhighlight lang="python" line='line'>
# Wait for some stats
+
#!/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)
 
time.sleep(60)
r = vpp_papi.want_stats(False, pid)
+
r = vpp.api.want_per_interface_simple_stats(enable_disable=False)
r = vpp_papi.disconnect()
+
r = vpp.disconnect()
  
</nowiki>
+
</syntaxhighlight>
  
 
== API generation ==
 
== API generation ==

Latest revision as of 15:25, 18 April 2019

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/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 = VPP(jsonfiles)
  23.  
  24. r = vpp.connect("test_papi")
  25. print(r)
  26.  
  27. for intf in vpp.api.sw_interface_dump():
  28.     print(intf.interface_name.decode())
  29.  
  30. exit(vpp.disconnect())

Example: Receive statistics

  1. #!/usr/bin/env python
  2.  
  3. from vpp_papi import VPP
  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 = VPP(jsonfiles)
  24. r = vpp.connect("test_papi")                                                                                                                                                                              
  25. print(r)
  26.  
  27. async=True                                                                                                                                                                                                
  28. r=vpp.register_event_callback(papi_event_handler)
  29. pid=os.getpid()
  30. sw_ifs = [1,2,3,4,5,6,7]                                                                                                                                                                                  
  31. r = vpp.api.want_per_interface_simple_stats(enable_disable=True, sw_ifs=sw_ifs, num=len(sw_ifs), pid=pid)
  32. print(r)
  33. # Wait for some stats                                                                                                                                                                                    
  34. time.sleep(60)
  35. r = vpp.api.want_per_interface_simple_stats(enable_disable=False)
  36. 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.