OVSDB client in Python

After reading Brent’s post on OVSDB, I was inspired to try my hand at interfacing with OVSDB via Python. I highly recommend reading his post to learn more about OVSDB before looking at the code examples below.

Making ovsdb-server listen

The first thing I needed to do was to make the database accept my client. If you’re running OVS version 1.10 or later, you can do this using ovs-appctl:

ovs-appctl -t ovsdb-server ovsdb-server/add-remote ptcp:6632

If you’ve installed OVS on Ubuntu using apt, and its already running, I found this worked for me:

  1. Edit /usr/share/openvswitch/scripts/ovs-ctl
  2. Under #Start ovsdb-server add a line:
  3. set "$@" --remote=ptcp:6632
    
  4. Then restart ovs
  5. sudo service openvswitch-switch restart

Now that we’ve got the server listening to us, we can start to tackle to code.

Python sockets

To connect to the DB, we’ll need to establish a TCP connection on the port we selected above. We’ll use Python sockets for this:

import socket

OVSDB_IP = '127.0.0.1'
OVSDB_PORT = 6632

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((OVSDB_IP, OVSDB_PORT))

This sets up our socket connection, and from here on out we can send things over using s.send() and receive with s.recv()

As an easy test we can try running getting a list of the databases, which is done using JSON-RPC. For this case its pretty simple:

{
 "method :"list_dbs",
 "params": [],
 "id" : 0
}

First we send the query and then we get the response:

import json

list_dbs_query =  {"method":"list_dbs", "params":[], "id": 0}
s.send(json.dumps(list_dbs_query))
response = s.recv(4096)
print response

The number passed to recv is the size of the buffer we want to use to receive. We take the response and put it in a variable which we can print out to see what databases are present. You should get something like this:

{"method":"echo","id":"echo","params":[]}{"id":0,"result":["Open_vSwitch"],"error":null}{"method":"echo","id":"echo","params":[]}

Now we’ve got two way communication going to the database. You’ll see we got an echo, the reply to our query, and another echo. As long as this stays open, we’ll still receive periodic echos from the server. To keep this connection open we’ll need to respond the echo messages we get from the server. I’ll tackle that in my next post.

Advertisements

6 thoughts on “OVSDB client in Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s