confd.maapi
index
/lab/build/tailf-src/confddoc.confdbasic.confd-6.4-x86_64/confd_dir/src/confd/pyapi/confd/maapi.py

MAAPI high level module.
 
This module defines a high level interface to the low-level maapi functions.
 
The 'Maapi' class encapsulates a MAAPI connection which upon constructing,
sets up a connection towards ConfD/NCS. An example of setting up a transaction
and manipulating data:
 
import ncs
 
m = ncs.maapi.Maapi()
m.start_user_session('admin', 'test_context')
t = m.start_write_trans()
t.get_elem('/model/data{one}/str')
t.set_elem('testing', '/model/data{one}/str')
t.apply()
 
Another way is to use context managers, which will handle all cleanup
related to transactions, user sessions and socket connections:
 
with ncs.maapi.Maapi() as m:
    with ncs.maapi.Session(m, 'admin', 'test_context'):
        with m.start_write_trans() as t:
            t.get_elem('/model/data{one}/str')
            t.set_elem('testing', '/model/data{one}/str')
            t.apply()
 
Finally, a really compact way of doing this:
 
    with ncs.maapi.single_write_trans('admin', 'test_context') as t:
        t.get_elem('/model/data{one}/str')
        t.set_elem('testing', '/model/data{one}/str')
        t.apply()

 
Modules
       
_confd
contextlib
socket
sys
threading
confd.tm
traceback

 
Classes
       
__builtin__.object
Key
Maapi
Session
Transaction

 
class Key(__builtin__.object)
    Key string encapsulation and helper.
 
  Methods defined here:
__getitem__(self, key)
Get key at index 'key'.
__init__(self, key, enum_cs_nodes=None)
Initialize a key.
 
'key' may be a string or a list of strings.
__iter__(self)
Return a key iterator object.
__len__(self)
Get number of keys.
__repr__(self)
Get internal representation.
__str__(self)
Get string representation.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class Maapi(__builtin__.object)
    Class encapsulating a MAAPI connection.
 
  Methods defined here:
__dir__(self)
Return a list of all available methods in Maapi.
__enter__(self)
Python magic method.
__exit__(self, exc_type, exc_value, tb)
Python magic method.
__getattr__(self, name)
Python magic method.
 
This method will be called whenever an attribute not present here
is accessed. It will try to find a corresponding attribute in the
low-level maapi module which takes a maapi socket as the first
arument and forward the call there.
 
Example (pseudo code):
    import ncs     # high-level module
    import _ncs    # low-level module
 
    maapi = ncs.maapi.Maapi()
 
    Now, these two calls are equal:
        1. maapi.install_crypto_keys()
        1. _ncs.maapi.install_crypto_keys(maapi.msock)
__init__(self, ip='127.0.0.1', port=4565, path=None, load_schemas=True, msock=None)
Setting up a MAAPI socket.
__repr__(self)
Get internal representation.
apply_template(*args, **kwargs)
Apply a template.
attach(self, ctx_or_th, hashed_ns=0, usid=0)
Attach to an existing transaction.
 
'ctx_or_th' may be either a TransCtxRef or a transaction handle.
The 'hashed_ns' argument is basically just there to save a call to
set_namespace(). 'usid' is only used if 'ctx_or_th' is a transaction
handle and if set to 0 the user session id that is the owner of the
transaction will be used.
 
A new Transaction object will be returned.
attach_init(self)
Attach to phase0 for CDB initialization and upgrade.
authenticate(self, user, password, n, src_addr=None, src_port=None, context=None, prot=None)
Authenticate a user using the AAA configuration.
cursor(self, th, path, enum_cs_nodes=None)
Get an iterable list cursor.
destroy_cursor(self, mc)
Destroy cursor.
detach(self, ctx_or_th)
Detach the underlying MAAPI socket.
do_display(self, th, path)
Do display.
 
If the data model uses the YANG when or tailf:display-when
statement, this function can be used to determine if the item
given by the path should be displayed or not.
exists(self, th, path)
Check if path exists.
find_next(self, mc, type, inkeys)
Find next.
 
Update the cursor 'mc' with the key(s) for the list entry designated
by the 'type' and 'inkeys' arguments. This function may be used to
start a traversal from an arbitrary entry in a list. Keys for
subsequent entries may be retrieved with the get_next() function.
When no more keys are found, False is returned.
 
The strategy to use is defined by 'type':
 
    FIND_NEXT - The keys for the first list entry after the one
                indicated by the 'inkeys' argument.
    FIND_SAME_OR_NEXT - If the values in the 'inkeys' array completely
                identifies an actual existing list entry, the keys for
                this entry are requested. Otherwise the same logic as
                for FIND_NEXT above.
get_next(self, mc)
Iterate and get the keys for the next entry in a list.
 
When no more keys are found, False is returned.
get_objects(self, mc, n, nobj)
Get objects.
 
Read at most n values from each nobj lists starting at cursor mc.
Returns a list of Value's.
get_running_db_status(self)
Get running db status.
 
Gets the status of the running db. Returns True if consistent and
False otherwise.
load_schemas(self, use_maapi_socket=False)
Load the schemas to Python (using shared memory if enabled).
 
If 'use_maapi_socket' is set to True, the schmeas are loaded through
the NSO daemon via a MAAPI socket.
query_free_result(self, qrs)
Deallocate QueryResult memory.
 
Deallocated memory inside the QueryResult object 'qrs' returned from
query_result(). It is not necessary to call this method as deallocation
will be done when the Python library garbage collects the QueryResult
object.
safe_create(self, th, path)
Safe version of create.
 
Create a new list entry, a presence container, or a leaf of
type empty in the data tree - if it doesn't already exist.
safe_delete(self, th, path)
Safe version of delete.
 
Delete an existing list entry, a presence container, or an
optional leaf and all its children (if any) from the data
tree. If it exists.
safe_get_elem(self, th, path)
Safe version of get_elem.
 
Read the element at 'path', returns 'None' if it doesn't
exist.
safe_get_object(self, th, n, path)
Safe version of get_object.
 
This function reads at most 'n' values from the list entry or
container specified by the 'path'. Returns 'None' the path is
empty.
set_elem(self, th, value, path)
Set the node at 'path' to 'value'.
 
If 'value' is not of type Value it will be converted to a string
before calling set_elem2() under the hood.
shared_apply_template(*args, **kwargs)
FASTMAP version of apply_template().
shared_copy_tree(*args, **kwargs)
FASTMAP version of copy_tree().
shared_create(*args, **kwargs)
FASTMAP version of create().
shared_insert(*args, **kwargs)
FASTMAP version of insert().
shared_set_elem(*args, **kwargs)
FASTMAP version of set_elem().
 
If 'value' is not of type Value it will be converted to a string
before calling shared_set_elem2() under the hood.
shared_set_values(*args, **kwargs)
FASTMAP version of set_values().
start_read_trans(self, db=2, usid=0, flags=0, vendor=None, product=None, version=None, client_id=None)
Start a read transaction.
 
For details see start_trans().
start_trans(self, rw, db=2, usid=0, flags=0, vendor=None, product=None, version=None, client_id=None)
Start a transaction towards the 'db'.
 
This function starts a new a new transaction towards the given
data store.
 
A new Transaction object will be returned.
start_trans_in_trans(self, th, readwrite, usid=0)
Start a new transaction within a transaction.
 
This function makes it possible to start a transaction with another
transaction as backend, instead of an actual data store. This can be
useful if we want to make a set of related changes, and then either
apply or discard them all based on some criterion, while other changes
remain unaffected. The thandle identifies the backend transaction to
use. If 'usid' is 0, the transaction will be started within the user
session associated with the MAAPI socket, otherwise it will be started
within the user session given by usid. If we call apply() on this
"transaction in a transaction" object, the changes (if any) will be
applied to the backend transaction. To discard the changes, call
finish() without calling apply() first.
 
A new Transaction object will be returned.
start_user_session(self, user, context, groups=[], src_ip='127.0.0.1', src_port=0, proto=1, vendor=None, product=None, version=None, client_id=None)
Start a new user session.
 
This method gives some resonable defaults.
start_write_trans(self, db=2, usid=0, flags=0, vendor=None, product=None, version=None, client_id=None)
Start a write transaction.
 
For details see start_trans().
write_service_log_entry(*args, **kwargs)
Write service log entries.
 
This function makes it possible to write service log entries from
FASTMAP code.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class Session(__builtin__.object)
    Encapsulate a MAAPI user session.
 
Context manager for user sessions. This class makes is easy to use
a single Maapi connection and switch user session along the way.
 
Example:
    with Maapi() as m:
        for user, context, device in devlist:
            with Session(m, user, context):
                with m.start_write_trans() as t:
                    # ...
                    # do something using the correct user session
                    # ...
                    t.apply()
 
  Methods defined here:
__enter__(self)
Python magic method.
__exit__(self, exc_type, exc_value, tb)
Python magic method.
__init__(self, maapi, user, context, groups=[], src_ip='127.0.0.1', src_port=0, proto=1, vendor=None, product=None, version=None, client_id=None)
Initialize a Session object.
 
'maapi' should be a Maapi object. For all other arguments see
Maapi.start_user_session().
close(self)
Close the user session.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class Transaction(__builtin__.object)
    Class that corresponds to a single MAAPI transaction.
 
  Methods defined here:
__dir__(self)
Return a list of all available methods in Transaction.
__enter__(self)
Python magic method.
__exit__(self, exc_type, exc_value, tb)
Python magic method.
__getattr__(self, name)
Python magic method.
 
This method will be called whenever an attribute not present here
is accessed. It will try to find a corresponding attribute in the Maapi
object which takes a transaction handle as the second argument and
forward the call there.
 
Example (pseudo code):
    import ncs     # high-level module
    import _ncs    # low-level module
 
    maapi = ncs.maapi.Maapi()
    trans = maapi.start_read_trans()
 
    Now, these three calls are equal:
        1. trans.get_elem('/path/to/leaf')
        2. maapi.get_elem(trans.th, '/path/to/leaf')
        3. _ncs.maapi.get_elem(maapi.msock, trans.th, '/path/to/leaf')
__init__(self, maapi, th=None, rw=None, db=2, vendor=None, product=None, version=None, client_id=None)
Initialize a Transaction object.
 
When created one may access the maapi and th arguments like this:
 
    trans = Transaction(mymaapi, th=myth)
    trans.maapi # the Maapi object
    trans.th # the transaction handle
 
An instance of this class is also a context manager:
 
    with Transaction(mymaapi, th=myth) as trans:
        # do something here...
 
When exiting the with statement, finish() will be called.
 
If 'th' is left out (or None) a new transaction is started using
the 'db' and 'rw' arguments, otherwise 'db' and 'rw' are ignored.
 
Arguments:
    maapi -- a Maapi object
    th -- a transaction handle or None
    db -- database
    rw -- mode (READ or READ_WRITE)
    vendor -- lock error information (optional)
    product -- lock error information (optional)
    version -- lock error information (optional)
    client_id -- lock error information (optional)
__repr__(self)
Get internal representation.
abort(self)
Abort the transaction.
apply(self, keep_open=True, flags=0)
Apply the transaction.
 
Validates, prepares and eventually commits or aborts the
transaction. If the validation fails and the 'keep_open'
argument is set to True (default), the transaction is left
open and the developer can react upon the validation errors.
commit(self)
Commit the transaction.
finish(self)
Finish the transaction.
 
This will finish the transaction. If the transaction is implemented
by an external database, this will invoke the finish() callback.
prepare(self, flags=0)
Prepare transaction.
 
This function must be called as first part of two-phase commit. After
this function has been called, commit() or abort() must be called.
 
It will invoke the prepare callback in all participants in the
transaction. If all participants reply with OK, the second phase of
the two-phase commit procedure is commenced.
validate(self, unlock, forcevalidation=False)
Validate the transaction.
 
This function validates all data written in the transaction. This
includes all data model constraints and all defined semantic
validation, i.e. user programs that have registered functions under
validation points.
 
If 'unlock' is True, the transaction is open for further editing even
if validation succeeds. If 'unlock' is False and the function succeeds
next function to be called MUST be prepare() or finish().
 
'unlock = True' can be used to implement a 'validate' command which
can be given in the middle of an editing session. The first thing that
happens is that a lock is set. If 'unlock' == False, the lock is
released on success. The lock is always released on failure.
 
The 'forcevalidation' argument should normally be False. It has no
effect for a transaction towards the running or startup data stores,
validation is always performed. For a transaction towards the
candidate data store, validation will not be done unless
'forcevalidation' is True. Avoiding this validation is preferable if
we are going to commit the candidate to running, since otherwise the
validation will be done twice. However if we are implementing a
'validate' command, we should give a True value for 'forcevalidation'.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
Functions
       
StringIO(...)
StringIO([s]) -- Return a StringIO-like stream for reading or writing
connect(ip='127.0.0.1', port=4565, path=None)
Convenience function for connecting to ConfD/NCS.
 
The 'ip' and 'port' arguments are ignored if path is specified.
single_read_trans(*args, **kwds)
Context manager for a single READ transaction.
 
This function connects to ConfD/NCS, starts a user session and finally
starts a new READ transaction.
 
Signature:
def single_read_trans(user, context, groups=[],
                      db=RUNNING, ip='127.0.0.1',
                      port=<CONFD-OR-NCS-PORT>, path=None,
                      src_ip='127.0.0.1', src_port=0, proto=PROTO_TCP,
                      vendor=None, product=None, version=None,
                      client_id=_mk_client_id()):
 
For argument db see Maapi.start_trans(). For arguments user,
context, groups, src_ip, src_port, proto, vendor, product, version and
client_id see Maapi.start_user_session().
For arguments ip, port and path see connect().
single_write_trans(*args, **kwds)
Context manager for a single READ/WRITE transaction.
 
This function connects to ConfD/NCS, starts a user session and finally
starts a new READ/WRITE transaction.
 
Signature:
def single_write_trans(user, context, groups=[],
                       db=RUNNING, ip='127.0.0.1',
                       port=<CONFD-OR-NCS-PORT>, path=None,
                       src_ip='127.0.0.1', src_port=0, proto=PROTO_TCP,
                       vendor=None, product=None, version=None,
                       client_id=_mk_client_id()):
 
For argument db see Maapi.start_trans(). For arguments user,
context, groups, src_ip, src_port, proto, vendor, product, version and
client_id see Maapi.start_user_session().
For arguments ip, port and path see connect().