NDB¶
An experimental module that may obsolete IPDB.
Examples:
from pyroute2 import NDB
from pprint import pprint
ndb = NDB()
# ...
for line ndb.routes.csv():
print(line)
# ...
for record in ndb.interfaces.summary():
print(record)
# ...
pprint(ndb.interfaces['eth0'])
# ...
pprint(ndb.interfaces[{'target': 'localhost',
'ifname': 'eth0'}])
#
# change object parameters
#
eth0 = ndb.interfaces['eth0']
eth0['state'] = 'up'
eth0.commit()
#
# create objects
#
test0 = ndb.interfaces.add(ifname='test0', kind='dummy')
test0.commit()
# ...
test0.remove()
test0.commit()
#
# it is mandatory to call close()
#
ndb.close()
Difference with IPDB¶
NDB is designed to work with multiple event sources and with loads of network objects.
Multiple sources:
from pyroute2 import (NDB,
IPRoute,
NetNS,
RemoteIPRoute)
sources = {'localhost': IPRoute(),
'debian.test': RemoteIPRoute(protocol='ssh',
hostname='192.168.122.54',
username='netops'),
'openbsd.test': RemoteIPRoute(protocol='ssh',
hostname='192.168.122.60',
username='netops'),
'netns0': NetNS('netns0'),
'docker': NetNS('/var/run/docker/netns/f2d2ba3e5987')}
# NDB supports the context protocol, close() is called automatically
with NDB(sources=sources) as ndb:
# ...
NDB stores all the data in an SQL database and creates objects on demand. Statements like ndb.interfaces[‘eth0’] create a new object every time you run this statement. Thus:
with NDB() as ndb:
#
# This will NOT work, as every line creates a new object
#
ndb.interfaces['eth0']['state'] = 'up'
ndb.interfaces['eth0'].commit()
#
# This works
#
eth0 = ndb.interfaces['eth0'] # get the reference
eth0['state'] = 'up'
eth0.commit()
#
# The same with a context manager
#
with ndb.interfaces['eth0'] as eth0:
eth0['state'] = 'up'
# ---> <--- the context manager runs commit() at __exit__()
DB providers¶
NDB supports different DB providers, now they are SQLite3 and PostgreSQL. PostgreSQL access requires psycopg2 module:
from pyroute2 import NDB
# SQLite3 -- simple in-memory DB
ndb = NDB(db_provider='sqlite3')
# SQLite3 -- same as above
ndb = NDB(db_provider='sqlite3',
db_spec=':memory:')
# SQLite3 -- file DB
ndb = NDB(db_provider='sqlite3',
db_spec='test.db')
# PostgreSQL -- local DB
ndb = NDB(db_provider='psycopg2',
db_spec={'dbname': 'test'})
# PostgreSQL -- remote DB
ndb = NDB(db_provider='psycopg2',
db_spec={'dbname': 'test',
'host': 'db1.example.com'})