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

# access eth0 in the netns test01
ndb.interfaces[{"target": "test01", "ifname": "eth0"}]

# access a route to

# same with a dict selector
ndb.routes[{"dst": "", "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.


class pyroute2.ndb.view.View

The View() object returns RTNL objects on demand:

ifobj1 = ndb.interfaces['eth0']
ifobj2 = ndb.interfaces['eth0']
# ifobj1 != ifobj2
get(*argv, **kwarg)

Return the value for key if key is in the dictionary, else default.

locate(*argv, **kwarg)

This method works like __getitem__(), but the important difference is that it uses only key fields to locate the object in the DB, ignoring all other keys.

It is useful to locate objects that may change attributes during request, like an interface may come up/down, or an address may become primary/secondary, so plain __getitem__() will not match while the object still exists.

exists(key, table=None)

Check if the specified object exists in the database:

ndb.interfaces.exists({'ifname': 'eth0', 'target': 'localhost'})
keys() a set-like object providing a view on D's keys
values() an object providing a view on D's values
items() a set-like object providing a view on D's items