Views and objects

Structure

The NDB objects are dictionary-like structures that represent network objects – interfaces, routes, addresses etc. In addition to the usual dictionary API they have some NDB-specific methods, see the RTNL_Object class description below.

The dictionary fields represent RTNL messages fields and NLA names, and the objects are used as argument dictionaries to normal IPRoute methods like link() or route(). Thus everything described for the IPRoute methods is valid here as well.

See also: IPRoute module

E.g.:

# create a vlan interface with IPRoute
with IPRoute() as ipr:
    ipr.link("add",
             ifname="vlan1108",
             kind="vlan",
             link=ipr.link_lookup(ifname="eth0"),
             vlan_id=1108)

# same with NDB:
with NDB(log="stderr") as ndb:
    (ndb
     .interfaces
     .create(ifname="vlan1108",
             kind="vlan",
             link="eth0",
             vlan_id=1108)
     .commit())

Slightly simplifying, if a network object doesn’t exist, NDB will run an RTNL method with “add” argument, if exists – “set”, and to remove an object NDB will call the method with “del” argument.

Accessing objects

NDB objects are grouped into “views”:

  • interfaces

  • addresses

  • routes

  • neighbours

  • rules

  • netns

Views are dictionary-like objects that accept strings or dict selectors:

# access eth0
ndb.interfaces["eth0"]

# access eth0 in the netns test01
ndb.sources.add(netns="test01")
ndb.interfaces[{"target": "test01", "ifname": "eth0"}]

# access a route to 10.4.0.0/24
ndb.routes["10.4.0.0/24"]

# same with a dict selector
ndb.routes[{"dst": "10.4.0.0", "dst_len": 24}]

Objects cache

NDB create objects on demand, it doesn’t create thousands of route objects for thousands of routes by default. The object is being created only when accessed for the first time, and stays in the cache as long as it has any not committed changes. To inspect cached objects, use views’ .cache:

>>> ndb.interfaces.cache.keys()
[(('target', u'localhost'), ('tflags', 0), ('index', 1)),  # lo
 (('target', u'localhost'), ('tflags', 0), ('index', 5))]  # eth3

There is no asynchronous cache invalidation, the cache is being cleaned up every time when an object is accessed.

API

class pyroute2.ndb.objects.RTNL_Object(view, key, iclass, ctxid=None, load=True, master=None, check=True, auth_managers=None)

The common base class for NDB objects – interfaces, routes, rules addresses etc.

set(*argv, **kwarg)

Set a field specified by key to value, and return self. The method is useful to write call chains like that:

(ndb
 .interfaces["eth0"]
 .set('mtu', 1200)
 .set('state', 'up')
 .set('address', '00:11:22:33:44:55')
 .commit())