Class Maapi
- All Implemented Interfaces:
Closeable,AutoCloseable
This class implements the Management Agent API (MAAPI).
The purpose of the class is twofold:
MAAPI can be used to implement our own proprietary management agent.
- We can also use Maapi to attach to already existing transactions, for example when we wish to implement semantic validation of data elements or implement a CLI wizard.
Example:
// int port = Conf.PORT for ConfD or Conf.NCS_PORT for NCS
// Setup socket to server
Socket s = new Socket("localhost", port);
// Start MAAPI session for admin user, originating from localhost
Maapi maapi = new Maapi(s);
maapi.startUserSession("admin",
"maapi",
new String[] { "admin" },
new SocketAddress(InetAddress.getLocalHost(), 0),
MaapiUserSessionFlag.PROTO_TCP);
// Start a read transaction towards the running configuration.
int tid = maapi.startTrans(Conf.DB_RUNNING, Conf.MODE_READ);
// Set the namespace for the upcoming data operations
maapi.setNamespace(tid, "http://tail-f.com/test/mtest/1.0");
// Read the maxLeaseTime setting in the running configuration.
ConfObject r = maapi.getElem(tid, "/mtest/servers/server{www}/ip");
// Done, the transaction and user session is automatically
// ended when the socket is closed.
s.close();
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classstatic enumTo be used in:reportProgress(int,Verbosity,String)reportServiceProgress(int,Verbosity,String,ConfPath) -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intFlags to use in:applyTrans(int,boolean,int)prepareTrans(int,int)static final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intFlag to use in initUpgrade() -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new instance ofMaapisupplying a established open socket to ConfD/NCS daemon.Maapi(SocketAddress address) Creates a new instance ofMaapisupplying an address to the ConfD/NCS server. -
Method Summary
Modifier and TypeMethodDescriptionvoidaaaReload(boolean synchronous) When the ConfD/NCS AAA tree is populated by an external data provider, this method can be used by the data provider to notify ConfD/NCS when there is a change to the AAA data.voidabortTrans(int tid) Abort a transaction specified by transaction handletid.voidNote, This method is only applicable for Confd.voidapplyTrans(int tid, boolean keepOpen) Apply a current transaction with transaction handletid.voidapplyTrans(int tid, boolean keepOpen, int flags) Apply a current transaction with transaction handletidwith additional flags (NCS Specific).applyTransParams(int tid, boolean keepOpen, CommitParams params) Apply a current transaction with transaction handletidwith additional NCS specific parameters.voidattach(int tid, int nsi) Same asattach(int, int, int)with the exception that the User session id is implicit for the attached transaction.voidattach(int tid, int nsi, int usid) Attach to a current transaction.voidSame asattach(int, String, int)with the exception that the User session id is implicit for the attached transaction.voidAttach to a current transaction.intAttach to transaction available in phase0.authenticate(String user, String passwd) If we are implementing a proprietary Management Agent with MAAPI API, the methodstartUserSession(String,String,String[],SocketAddress, MaapiUserSessionFlag)requires the application to tell ConfD/NCS which groups the user are member of.authenticate2(String user, String passwd, InetAddress srcAddr, int srcPort, String context, MaapiUserSessionFlag proto) If we are implementing a proprietary Management Agent with MAAPI API, the methodstartUserSession(String,String,String[],SocketAddress, MaapiUserSessionFlag)requires the application to tell ConfD/NCS which groups the user are member of.voidThis function cancels a pending confirmed commit.voidcandidateAbortCommitPersistent(String persistId) Cancel an ongoing persistent commit with the cookie given by persistId.voidThis function copies the candidate to running.voidcandidateCommitInfo(String label, String comment) This method can be used to set the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running.voidcandidateCommitInfo(String persistId, String label, String comment) This method can be used to set the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running.voidcandidateCommitPersistent(String persistId) Confirm an ongoing persistent commit with the cookie given by persistId.voidcandidateConfirmedCommit(int t) This method also copies the candidate into running.voidcandidateConfirmedCommitInfo(int timeoutsecs, String label, String comment) This method does the same ascandidateConfirmedCommitPersistent(int, java.lang.String, java.lang.String), but allows for setting the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running.voidcandidateConfirmedCommitInfo(int timeoutsecs, String persist, String persistId, String label, String comment) This method does the same ascandidateConfirmedCommitPersistent(int, java.lang.String, java.lang.String), but allows for setting the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running.voidcandidateConfirmedCommitPersistent(int timeoutsecs, String persist, String persistId) This method can be used to start or extend a persistent confirmed commit, see the Tail-f Commit Capability section in the NETCONF Server chapter in the User Guide.voidThis function copies running into candidate.voidThis function validates the candidate.voidThis function mimics the behavior of the UNIX "cd" command.voidSame asclearOpCache(ConfPath), with the only difference that if clears all cached data from "/" and down.voidclearOpCache(ConfPath path) Request clearing of the operational data cache (see the Operational Data the User Guide).voidCLIAccounting(String user, int usid, String cmd) Generate an audit log entry in the CLI audit log.CLICmdToPath(int th, String cmd) Given a C- or I-style command, this method tries to determine the corresponding namespace and path in the schema.CLICmdToPath(String cmd) Equivalent toCLICmdToPath(int, String)with the first parameter set to -1 (ie, the command is not interpreted in the context of any particular transaction)CLIDiffCmd(int thandle, int thandleOld, ConfPath path) Get the diff between two transactions as C-/I-style CLI commands.CLIPathCmd(int th, EnumSet<CLIPathCmdFlag> flags, String fmt, Object... args) Returns a string representing the C/I style CLI command that can be associated with the given path.Prompts user for a string.Prompts user for a string.CLIPromptOneOf(int usid, String prompt, String[] choice) Prompt user for one of the strings given in the choice parameter.CLIPromptOneOf(int usid, String prompt, String[] choice, int timeout) Prompt user for one of the strings given in the choice parameter.CLIReadEOF(int usid, boolean echo) Read a multi line string from the CLI.CLIReadEOF(int usid, boolean echo, int timeout) Read a multi line string from the CLI.voidWrite to the CLI.voidclose()voidcommitTrans(int tid) Commit a transaction specified by transaction handletid.voidNote, This method is only applicable for Confd.intChecks whether a confirmed commit is pending.voidcopy(int thfrom, int thto) If we open two transactions from the same user sessions but towards different data stores, such as one transaction towards the candidate and one towards running, we can copy all data from one data store to the other with this method.voidSimilar tocopy(int, int), but does a replacing copy only of the subtree rooted at the path given bypathvoidCopies running to startup.voidThis function is used to copy an entire subtree in the configuration from one point to another.voidcopyTree(int, boolean, ConfPath, ConfPath)Equivalent tocopyTree(int, boolean, ConfPath, ConfPath)with useSharedCreate set to false i.e., for use outside fastmap, without 'shared' create/setvoidCreate an entity in the XML tree.voidCreate a new list entry in the XML tree.voidDeletes a node and all its children from the XML data tree.voidDeletes a node and all its children from the XML data tree.voiddeleteAll(int th, MaapiDeleteAllFlag how) This function can be used to delete "all" configuration data within a transaction.voiddeleteConfig(int db) This function empties a data store.ConfObject[][]This method dereferences a leafref and returns a list of the objects the leafref "points" to.voiddetach(int tid) Detaches an attached MAAPI socket.voiddiffIterate(int tid, MaapiDiffIterate iter) Iterates through the transaction diff.voiddiffIterate(int tid, MaapiDiffIterate iter, Object initstate, String fmt, Object... args) Iterates through the transaction diff.voiddiffIterate(int tid, MaapiDiffIterate iter, String fmt, Object... args) Iterates through the transaction diff.voiddiffIterate(int tid, Object initstate, EnumSet<DiffIterateFlags> flags, MaapiDiffIterate iter, ConfPath path) Iterates through the transaction diff.voiddisconnectRemote(String address) Disconnect all remote connections between CONFD_IPC_PORT (see the IPC section in the Advanced Topics chapter in the User Guide) and address.voiddisconnectSockets(int[] sockets) This function is an alternative todisconnectRemote()that can be useful in particular when using the "External IPC" functionality (see "Using a different IPC mechanism" in the ConfD IPC section in the Advanced Topics chapter in the User Guide).booleanIf 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 in fmt should be displayed or not.End progress span.voidEnds the current user session on thisMaapiinstance.voidevent(int tid, Maapi.Verbosity verbosity, String msg, ConfPath path, Attributes attributes) Create a progress event.booleanBoolean function which return 1 or 0 if a path defines an existing element in the XML data tree.booleanfindNext(MaapiCursor c, ConfFindNextType type, ConfKey key) The findNext method makes it possible to jump forward to an element in the model at a position defined by the MaapiCursor After the findNext call the same MaapiCursor can be used in subsequent getNext calls.voidfinishTrans(int tid) Finish the transaction specified by transaction handletid.getAttrs(int tid, ConfAttributeType[] attribs, String fmt, Object... args) Retrieve attributes for a configuration node.String[]getAuthorizationInfo(int usid) This method retrieves authorization info for a user session, i.e.static ArrayList<ConfNamespace>static ArrayList<ConfNamespace>getAutoNsList(List<ConfNamespace> defaultNsList) static Map<Integer,ConfNamespace> static Map<String,List<ConfNamespace>> This returns the current 'case' for a 'choice' construct.getCLIInteraction(int usid) Get CLIInteraction object which enables communication with the user via the CLI.getCwd(int tid) Returns the current position as previously set by Maapi.cd(), Maapi.pushd(), or Maapi.popd() as a String.getCwdPath(int tid) Returns the current position like Maapi.getCwd(), but as a ConfPath instead of as a String.This reads a value from the path in fmt and returns the result.getMountId(int tid, ConfPath path) intReturns the usid associated with thisMaapiIterates and gets the keys for the next element pinpointed by theMaapiCursorinitially retrieved bynewCursor(int, String, Object...).Get a list of the installed namespaces retrieved from the loadedMaapiSchemas.intgetNumberOfInstances(int tid, ConfPath path) intgetNumberOfInstances(int tid, String fmt, Object... arguments) Return the number of instances in a list.This reads a container object or a list entry object from the path in fmt and returns the result.List<ConfObject[]>getObjects(MaapiCursor c, int numOfObjects, int numOfInstances) Get several list instances with one request.intgetRollbackId(int tid) Get rollback id for committed transaction specified by transaction handletid.intQuery ConfD/NCS for its consistency state.static MaapiSchemasReturns the currently loaded schema.static InetAddressgetSource(SocketAddress address) getTransParams(int tid) Get commit parameters for a transaction.getUserSession(int usid) Return aMaapiUserSessiongiven by theusid.getUserSessionIdentification(int usid) This method can be used to retrieve additional identification information for a user session (if available - ie., if it has been provided by the northbound client).getUserSessionOpaque(int usid) If the user session has "opaque" information provided by the northbound client (see the -O option inconfd_cli), the opaque information can be retrieved using this method.int[]Return all user sessions id's currently connected to ConfD/NCS.<T extends ConfXMLParam>
T[]Read an arbitrary set of sub-elements of a container element.<T extends ConfXMLParam>
T[]Read an arbitrary set of sub-elements of a container element.<T extends List<ConfXMLParam>>
TRead an arbitrary set of sub-elements of a container element.<T extends List<ConfXMLParam>>
TRead an arbitrary set of sub-elements of a container element.voidHide all nodes belonging to a hide group in a transaction that started withMaapiFlag.HIDE_ALL_HIDEGROUPSflag.voidinit()voidinitUpgrade(int timeoutsecs, int flags) Note, This method is only applicable for Confd.voidThis function inserts a new element in an ordered list of elements.voidbooleanReturns true if candidate has been modified, i.e if there are pending non committed changes to the candidate data store.intisLockSet(int db) This methods checks if a lock is taken or not.booleanReturns true if running has been modified since the last copy to startup, false if it has not been modified.voiditerate(int tid, Object initstate, EnumSet<ConfIterateFlags> flags, MaapiIterate iter, ConfPath path) Iterates through all the data in a transaction.voidkillUserSession(int usid) Ends another users session, effectively logging out that user.voidloadConfig(int tid, EnumSet<MaapiConfigFlag> flags, String filename) This function loads a configuration from filename into the server.voidloadConfigCmds(int tid, EnumSet<MaapiConfigFlag> flags, String cmds, String fmt, Object... arguments) This function loads a configuration from a string into the server.loadConfigStream(int tid, EnumSet<MaapiConfigFlag> flags) Load configuration from aOuputStreaminto ConfD/NCS.Load Schemas method that downloads all schemas from server into a MaapiSchemas container, from which specified schemas can be accessed and traversed.loadSchemas(String[] namespaceURIs) Load Schemas method that downloads a specified number of schemas the server into a MaapiSchemas container, from which specified schemas can be accessed and transversed.voidlock(int db) This function is used to take a lock on one of the databases.intlockPartial(int db, String xpath) Same aslockPartial(int,String[])except only one xpath expression is given.intlockPartial(int db, String[] xpaths) It is possible to manipulate partial locks on the databases, i.e.voidThis function moves an existing object.voidThis function moves an existing objectvoidmoveOrdered(int tid, MoveWhereFlag where, ConfKey tokey, String fmt, Object... arguments) For a list with the YANG ordered-by user statement, this function can be used to change the order of entries, by moving one entry to a new position.voidncsApplyTemplate(int tid, String template, ConfPath rootIKP, Properties variables, boolean createShared) voidncsApplyTemplate(int tid, String template, ConfPath rootIKP, Properties variables, String document, boolean createShared) String[]ncsGetTemplateVariables(String template) booleanRunopwith a new read-write transaction against the RUNNING datastore.booleanncsRunWithRetry(MaapiRetryableOp op, int maxNumRetries, CommitParams commitParams) Runopwith a new read-write transaction against the RUNNING datastore.booleanncsRunWithRetry(MaapiRetryableOp op, int maxNumRetries, CommitParams commitParams, int usid, EnumSet<MaapiFlag> flags) Runopwith a new read-write transaction against the RUNNING datastore.voidnetconfSSHCallHome(ConfObject host, int port) Request that ConfD daemon initiates a NETCONF SSH Call Home connection (see RFC 8071) to the NETCONF client running on host.voidnetconfSSHCallHomeOpaque(ConfObject host, String opaque, int port) Request that ConfD daemon initiates a NETCONF SSH Call Home connection (see RFC 8071) to the NETCONF client running on host.Creates a cursor for a list specified bypathCreates a cursor for a list specified byfmt.newCursorWithFilter(int tid, String filter, ConfPath path) Creates a cursor for a list specified bypathwith an XPath filter specified byfilter.newCursorWithFilter(int tid, String filter, String fmt, Object... arguments) Creates a cursor for a list specified byfmtwith an XPath filter specified byfilter.voidperformUpgrade(String[] loadpathdirs) Note, This method is only applicable for Confd.voidpopd(int tid) Pops the top position of the directory stack and changes directoryvoidprepareTrans(int tid) Prepares the transaction specified by transaction handletid.voidprepareTrans(int tid, int flags) Prepares the transaction specified by transaction handletid.voidprioMessage(String to, String message) Send a high priority message to a specific user, a specific user session or all users depending on the to parameter.voidBehaves like cd() with the exception that we can subsequently call popd() and return to the previous position in the XML data tree.<T extends ResultType>
QueryResult<T>queryStart(int tid, String expr, String context, int chunkSize, int offset, List<String> select, Class<T> cls) Initiate (or starts) a new XPath query attached to the transaction given intid.<T extends ResultType>
QueryResult<T>queryStart(int tid, String expr, String context, int chunkSize, int offset, List<String> select, List<String> sort, boolean reverseSortOrder, Class<T> cls) Initiate (or starts) a new XPath query attached to the transaction given inth.voidRequest that the daemon reloads its configuration files.This method throws away any old MaapiSchemas container and downloads a new from the server.reloadSchemas(String[] namespaceURIs) This method throws away any old MaapiSchemas container and downloads a new from the server.voidRequest that the daemon closes and re-opens its log filesvoidreportProgress(int tid, Maapi.Verbosity verbosity, String msg) Report progress of an action or transaction.requestAction(ConfXMLParam[] params, int nshash, String fmt, Object... arguments) Same asrequestAction(ConfXMLParam[], String, Object...)Since actions are not associated with transactions, the namespace hashnshashmust be provided and the path to the action, i.e.requestAction(ConfXMLParam[] params, String fmt, Object... arguments) Invokes an action defined in the data model annotated withtailf:action(see tailf_yang_extensions(5)).requestAction(List<ConfXMLParam> params, int nshash, String fmt, Object... arguments) requestAction(List<ConfXMLParam> params, String fmt, Object... arguments) Same asrequestAction(ConfXMLParam[], String, Object...)with the difference that theparamsisListinstead ofConfXMLParamarray.requestActionTh(int tid, ConfXMLParam[] params, String fmt, Object... arguments) Same asrequestAction(ConfXMLParam[], String, Object...)with the difference that the fmt is not required to have a namespace prefix in the root tag.requestActionTh(int tid, List<ConfXMLParam> params, String fmt, Object... arguments) voidrevert(int tid) Remove all changes in the transaction.rollbackConfig(int tid, String fmt, String... args) This function can be used to save the equivalent of a rollback file for a given configuration before it is committed (or a subtree thereof) in curly bracket format.voidsafeCreate(int tid, ConfPath path) Create a new list entity in the XML tree.voidsafeCreate(int tid, String fmt, Object... arguments) Create a new entity in the XML tree.voidsafeDelete(int tid, String fmt, Object... arguments) Deletes a node and all its children from the XML data tree.safeGetElem(int tid, ConfPath path) Reads a value from thepathspecifiedsafeGetElem(int tid, String fmt, Object... arguments) This reads a value from the path in fmt and returns the result.safeGetObject(int tid, String fmt, Object... arguments) This is a variant of getObject() that returns null if the object doesn't existsaveConfig(int tid, EnumSet<MaapiConfigFlag> flags) Save the entire config in different formats.saveConfig(int tid, EnumSet<MaapiConfigFlag> flags, ConfPath path) Save the subtree in different formats.saveConfig(int tid, EnumSet<MaapiConfigFlag> flags, String fmt, Object... args) Save the subtree in different formats, with ability to XPath Filtering.voidsetAttr(int tid, ConfAttributeValue attr, String fmt, Object... args) Set an attribute for a configuration node.voidsetComment(int tid, String comment) Set the "Comment" that is stored in the rollback file when a transaction towards running is committed.booleansetDelayedWhen(int tid, boolean on) This function enables/disables the "delayed when" mode of a transaction.voidsetElem(int tid, ConfObject value, ConfPath path) Set value to a leaf node.voidsetElem(int tid, ConfObject value, String fmt, Object... arguments) Set value to a leaf node.voidSet value to a leaf node.voidSet value to a leaf node.voidThis method can modify some aspects of the read/write session, see MaapiFlag The flags are an Enumset ofMaapiFlagvoidSet the "Label" that is stored in the rollback file when a transaction towards running is committed.voidsetNamespace(int tid, int nsid) voidsetNamespace(int tid, String ns) Before can invoke any of read or write functions, we must indicate which namespace we are going to use.voidsetNextUserSessionId(int usid) Set the user session id that will be assigned to the next user session started.voidsetObject(int tid, ConfObject[] values, String fmt, Object... arguments) This writes a container object or a list entry object from the path in fmt and returns the result.voidsetReadOnlyMode(boolean flag) Control if the node should accept write transactionsvoidsetRunningDbStatus(int status) Explicitly sets the systems notion of the consistency state.voidsetUserSession(int usid) Associate this Maapi instance with an already existing user session.voidsetValues(int tid, ConfXMLParam[] params, ConfPath path) Set arbitrary sub-elements of a container element in one bulk operation.voidsetValues(int tid, ConfXMLParam[] params, String fmt, Object... arguments) Set arbitrary sub-elements of a container element in one bulk operation.voidsetValues(int tid, List<ConfXMLParam> params, ConfPath path) Set arbitrary sub-elements of a container element in one bulk operation.voidsetValues(int tid, List<ConfXMLParam> params, String fmt, Object... arguments) Set arbitrary sub-elements of a container element in one bulk operation.voidsharedCreate(int tid, ConfPath path) This is the variant of create() to use from FASTMAP code.voidsharedCreate(int tid, String fmt, Object... arguments) voidsharedSetElem(int tid, ConfObject value, ConfPath path) Set value to a leaf node from NCS FastMap code.voidsharedSetElem(int tid, ConfObject value, String fmt, Object... arguments) Set value to a leaf node from NCS FastMap code This method is the equivalent of setElem() except that it can only be called from NCS FastMap service code.voidsharedSetElem(int tid, String value, String fmt, Object... arguments) Set value to a leaf node from NCS FastMap code.voidsharedSetValues(int tid, ConfXMLParam[] params, ConfPath path) Set arbitrary sub-elements of a container element in one bulk operation from NCS FastMap code.voidsharedSetValues(int tid, ConfXMLParam[] params, String fmt, Object... arguments) Set arbitrary sub-elements of a container element in one bulk operation from NCS FastMap code.voidsharedSetValues(int tid, List<ConfXMLParam> params, ConfPath path) Set arbitrary sub-elements of a container element in one bulk operation from NCS FastMap code.voidsharedSetValues(int tid, List<ConfXMLParam> params, String fmt, Object... arguments) Set arbitrary sub-elements of a container element in one bulk operation from NCS FastMap code.voidsnmpaReload(boolean synchronous) When the ConfD/NCS SNMP Agent config tree is implemented by an external data provider, this method can be used by the data provider to notify ConfD/NCS when there is a change to the data.voidsnmpSendNotification(String notifName, String notifyTarget, String ctxName, SnmpVarbind[] varbinds) Send SNMP notification.voidstartPhase(int phase) Once the ConfD/NCS daemon has been started in phase0 it is possible to use this function to tell the daemon to proceed to startPhase 1 or 2.voidstartPhase(int phase, boolean synchronous) Once the ConfD/NCS daemon has been started in phase0 it is possible to use this function to tell the daemon to proceed to start phase 1 or 2.startSpan(int tid, Maapi.Verbosity verbosity, String msg, ConfPath path, Attributes attributes, Span[] links) Create a progress span.intstartTrans(int dbname, int mode) Start a new transaction towards the specified databasedbnamewith a transaction modemode.intstartTrans(int dbname, int mode, String vendor, String product, String version, String clientId) intstartTrans2(int dbname, int mode, int usid) Start a new transaction towards database within an existing user session specified byusid.intstartTransFlags(int dbname, int mode, int usid, EnumSet<MaapiFlag> flags) Start a new transaction towards the specified databasedbnamewith a transaction modemodewith additionalflagsto control read/write sessions.intstartTransInTrans(int mode, int usid, int tid) Start a new transaction within an existing user session and another transaction as backendvoidstartUserSession(String user, String context) voidstartUserSession(String user, String context, String[] groups) voidstartUserSession(String user, String context, String[] groups, SocketAddress source) voidstartUserSession(String user, String context, String[] groups, SocketAddress source, MaapiUserSessionFlag proto) Establish a new user session on thisMaapiinstance.voidstartUserSession(String user, String context, String[] groups, SocketAddress source, MaapiUserSessionFlag proto, String vendor, String product, String version, String clientId) voidstartUserSession(String user, InetAddress source, String context, String[] groups, MaapiUserSessionFlag proto) Deprecated.voidstartUserSession(String user, InetAddress source, String context, String[] groups, MaapiUserSessionFlag proto, String vendor, String product, String version, String clientId) voidstop()Requests that the daemon stops, returns when daemon has stopped.voidstop(boolean synchronous) Stops the daemon.voidsysMessage(String to, String message) Send a message to a specific user, a specific user session or all users depending on the to parameter.toString()voidunhideGroup(int tid, String groupName) Unhide all nodes belonging to a hide group in a transaction that started withMaapiFlag.HIDE_ALL_HIDEGROUPSflag.voidunlock(int db) This function releases a lock previously acquired using the lock() method.voidunlockPartial(int lockId) This methods releases a lock previously acquired using the lockPartial() method.voiduserMessage(String to, String message, String sender) Send a message to a specific user, a specific user session or all users depending on the to parameter.String[]validateToken(String token, InetAddress srcAddr, int srcPort, String context, MaapiUserSessionFlag proto) If external token validation (see /confdConfig/aaa/externalValidation) is in use, this method can be used to ask ConfD/NSO to validate such a token.voidvalidateTrans(int tid, boolean unlock, boolean force) Validates a transaction specified by transaction handletidvoidwaitStart(int phase) Wait until the daemon has completed a certain start phase.voidWait until the daemon is fully started, i.e.xpath2kpath(String xpath) Convert a XPath path to a ConfPath object.xpath2kpath_th(int tid, String xpath) voidxpathEval(int tid, MaapiXPathEvalResult xpatheval, MaapiXPathEvalTrace xpathtrace, String expr, Object initstate, String fmt, Object... arguments) Evaluated the xpath expression as supplied in byexpr.xpathEvalExpr(int tid, String expr, MaapiXPathEvalTrace xpathtrace, String fmt, Object... arg) Evaluate the xpath expression given inexprparameter and return the result as a string.
-
Field Details
-
IA_CLIENT_MAAPI
public static final int IA_CLIENT_MAAPI- See Also:
-
MAAPI_UPGRADE_KILL_ON_TIMEOUT
public static final int MAAPI_UPGRADE_KILL_ON_TIMEOUTFlag to use in initUpgrade()- See Also:
-
COMMIT_NCS_NO_REVISION_DROP
public static final int COMMIT_NCS_NO_REVISION_DROPFlags to use in:applyTrans(int,boolean,int)prepareTrans(int,int)- See Also:
-
COMMIT_NCS_NO_DEPLOY
public static final int COMMIT_NCS_NO_DEPLOY- See Also:
-
COMMIT_NCS_NO_NETWORKING
public static final int COMMIT_NCS_NO_NETWORKING- See Also:
-
COMMIT_NCS_NO_OUT_OF_SYNC_CHECK
public static final int COMMIT_NCS_NO_OUT_OF_SYNC_CHECK- See Also:
-
COMMIT_NCS_NO_OVERWRITE_WRITE_SET_ONLY
public static final int COMMIT_NCS_NO_OVERWRITE_WRITE_SET_ONLY- See Also:
-
COMMIT_NCS_USE_LSA
public static final int COMMIT_NCS_USE_LSA- See Also:
-
COMMIT_NCS_NO_LSA
public static final int COMMIT_NCS_NO_LSA- See Also:
-
COMMIT_NCS_RECONCILE_KEEP_NON_SERVICE_CONFIG
public static final int COMMIT_NCS_RECONCILE_KEEP_NON_SERVICE_CONFIG- See Also:
-
COMMIT_NCS_RECONCILE_DISCARD_NON_SERVICE_CONFIG
public static final int COMMIT_NCS_RECONCILE_DISCARD_NON_SERVICE_CONFIG- See Also:
-
COMMIT_NCS_RECONCILE_ATTACH_NON_SERVICE_CONFIG
public static final int COMMIT_NCS_RECONCILE_ATTACH_NON_SERVICE_CONFIG- See Also:
-
COMMIT_NCS_RECONCILE_DETACH_NON_SERVICE_CONFIG
public static final int COMMIT_NCS_RECONCILE_DETACH_NON_SERVICE_CONFIG- See Also:
-
COMMIT_NCS_CONFIRM_NETWORK_STATE
public static final int COMMIT_NCS_CONFIRM_NETWORK_STATE- See Also:
-
COMMIT_NCS_CONFIRM_NETWORK_STATE_RE_EVALUATE_POLICIES
public static final int COMMIT_NCS_CONFIRM_NETWORK_STATE_RE_EVALUATE_POLICIES- See Also:
-
COMMIT_NCS_NO_OVERWRITE_WRITE_AND_FULL_READ_SET
public static final int COMMIT_NCS_NO_OVERWRITE_WRITE_AND_FULL_READ_SET- See Also:
-
COMMIT_NCS_NO_OVERWRITE_WRITE_AND_SERVICE_READ_SET
public static final int COMMIT_NCS_NO_OVERWRITE_WRITE_AND_SERVICE_READ_SET- See Also:
-
-
Constructor Details
-
Maapi
Creates a new instance ofMaapisupplying a established open socket to ConfD/NCS daemon. Since the ConfD/NCS daemon expects initialization within 5 seconds after a new socket is established this constructor should be called directly for a new socket. For instance:// int port = Conf.PORT for ConfD or Conf.NCS_PORT for NCS Maapi maapi = new Maapi(new Socket("localhost", port));When establishing a connection to ConfD/NCS the
MaapiSchemaswill be loaded once automatically by the library.If encrypted communication towards ConfD/NCS is desired, an environment variable "CONFD_IPC_ACCESS_FILE" or "NCS_IPC_ACCESS_FILE" need to be set. This variable is expected to point to a file containing a secret salt. example: export CONFD_IPC_ACCESS_FILE=./secret_file.txt An alternative to the environment variable is to set an java system property with the same name pointing to the file.
- Parameters:
socket- A socket connected to ConfD/NCS.- Throws:
ConfException- If ConfD/NCS refuses to establish connection the reason could be obtained throughThrowable.getMessage()ConfException- signals problem connecting to ConfD/NCS
-
Maapi
Creates a new instance ofMaapisupplying an address to the ConfD/NCS server.When establishing a connection to ConfD/NCS the
MaapiSchemaswill be loaded once automatically by the library.If encrypted communication towards ConfD/NCS is desired, an environment variable "CONFD_IPC_ACCESS_FILE" or "NCS_IPC_ACCESS_FILE" need to be set. This variable is expected to point to a file containing a secret salt. example: export CONFD_IPC_ACCESS_FILE=./secret_file.txt An alternative to the environment variable is to set an java system property with the same name pointing to the file.
- Parameters:
address- An address to connect to- Throws:
ConfException- If ConfD/NCS refuses to establish connection the reason could be obtained throughThrowable.getMessage()IOException- signals I/O exception when creating the underlying socketConfException- signals problems creating the underlying socket or connecting to ConfD/NCS
-
-
Method Details
-
init
- Throws:
ConfException
-
getNsList
Get a list of the installed namespaces retrieved from the loadedMaapiSchemas. The underlying socket is not required to be open for this operation.- Returns:
- list of namespaces
-
startUserSession
- Throws:
IOExceptionConfException
-
startUserSession
public void startUserSession(String user, String context, String[] groups) throws IOException, ConfException - Throws:
IOExceptionConfException
-
startUserSession
public void startUserSession(String user, String context, String[] groups, SocketAddress source) throws IOException, ConfException - Throws:
IOExceptionConfException
-
startUserSession
public void startUserSession(String user, String context, String[] groups, SocketAddress source, MaapiUserSessionFlag proto) throws IOException, ConfException Establish a new user session on thisMaapiinstance.Once we have created a
Maapicommunication instance, we must also establish a user session.It is up to the user of the
Maapiclass to authenticate users.Maapican be used to to perform the actual authentication through a call toauthenticate(String,String)but authentication may very well occur through some other external means.Thus, when we use this function to create a user session, we must provide all relevant information about the user. If we wish to execute read/write transactions over the MAAPI interface, we must first have an established user session.
A user session corresponds to a NETCONF manager who has just established an authenticated SSH connection, but not yet sent any NETCONF commands on the SSH connection.
The
userstring is the login name of the user. The user name is used when setting up the AAA environment for the session.The
srcipaddress specifies from where did the session originate.The
contextparameter can be any string which is precisely thecontextstring which will be used to authorize all data access through the AAA system. Each AAA rule has a context string which must match in order for a AAA rule to match. (See the AAA chapter in the User Guide).Using the string "system" for context has special significance:
- The session is exempt from all max sessions limits in the configuration file.
- There will be no authorization checks done by the AAA system.
- The session is not logged in the audit log.
- The session is not shown in
'confd --status'or'ncs --status', nor'show users'in CLI etc. - The session may be started already in start phase 0. (However read-write transactions can not be started until phase 1)
It is not possible to create new user sessions until the system has reached start phase 2 with the above exception of a session with the context set to "system".
The
photoparameter specifies the protocol used by the user for connecting to the device. Can be one ofMaapiUserSessionFlag.PROTO_SSH,MaapiUserSessionFlag.PROTO_CONSOLE,MaapiUserSessionFlag.PROTO_TCP, andMaapiUserSessionFlag.PROTO_SSL- Parameters:
user- Login name of usercontext- The context string parameter stated discussed above.groups- An array of AAA groups that the user belongs to.source- source address where the user session originateproto- Protocol used by the user for connecting to the device..- Throws:
MaapiException- If ConfD/NCS could not create a new session based on the parameters. To get detailed message useThrowable.getMessage()IOException- signals I/O exception on the underlying socketConfException
-
startUserSession
@Deprecated public void startUserSession(String user, InetAddress source, String context, String[] groups, MaapiUserSessionFlag proto) throws IOException, ConfException Deprecated.- Throws:
IOExceptionConfException
-
startUserSession
@Deprecated public void startUserSession(String user, InetAddress source, String context, String[] groups, MaapiUserSessionFlag proto, String vendor, String product, String version, String clientId) throws IOException, ConfException Deprecated.- Throws:
IOExceptionConfException
-
startUserSession
public void startUserSession(String user, String context, String[] groups, SocketAddress source, MaapiUserSessionFlag proto, String vendor, String product, String version, String clientId) throws IOException, ConfException - Throws:
IOExceptionConfException
-
endUserSession
Ends the current user session on thisMaapiinstance.If the
Maapisocket is closed, the user session is automatically ended.- Throws:
MaapiException- If there is no current session on thisMaapiinstanceIOException- Signals I/O exception on the underlying socketConfException
-
killUserSession
Ends another users session, effectively logging out that user.- Parameters:
usid- ID of session to terminate- Throws:
MaapiException- If the session with theIDdid not existsIOException- Signals I/O exception on the underlying socketConfException
-
getUserSession
Return aMaapiUserSessiongiven by theusid.- Parameters:
usid- ID of session to retrieve- Throws:
MaapiException- If the user session with the givenIDdoes not exitsIOException- Signals I/O exception on the underlying socketConfException
-
getUserSessions
Return all user sessions id's currently connected to ConfD/NCS.- Throws:
MaapiException- -IOException- Signals I/O exception on the underlying socketConfException
-
getMyUserSession
Returns the usid associated with thisMaapi- Throws:
MaapiException- If no user session exists on thisMaapisocketIOException- Signals some I/O exception on the underlying socketConfException
-
getUserSessionIdentification
This method can be used to retrieve additional identification information for a user session (if available - ie., if it has been provided by the northbound client).- Parameters:
usid- Session id- Returns:
- A
MaapiUserSessionIdobject with the fields vendor, product, version and clientId. - Throws:
ConfExceptionIOExceptionMaapiException
-
getUserSessionOpaque
If the user session has "opaque" information provided by the northbound client (see the -O option inconfd_cli), the opaque information can be retrieved using this method.- Parameters:
usid- User session id- Throws:
ConfExceptionIOException
-
setNextUserSessionId
Set the user session id that will be assigned to the next user session started. The given value is silently forced to be in the range 100 .. 2^31-1. This function can be used to ensure that session ids for user sessions started by northbound agents or via MAAPI are unique across a ConfD/NSO restart.- Parameters:
usid- The session id to assign for the next user session- Throws:
ConfExceptionIOException
-
validateToken
public String[] validateToken(String token, InetAddress srcAddr, int srcPort, String context, MaapiUserSessionFlag proto) throws ConfException, IOException If external token validation (see /confdConfig/aaa/externalValidation) is in use, this method can be used to ask ConfD/NSO to validate such a token.- Parameters:
token- The token to validatesrcAddr- source addresssrcPort- source portcontext- contextproto- extra information passed to the token validation executable (see /confdConfig/aaa/externalValidation/includeExtra)- Throws:
ConfExceptionIOException
-
startTrans
Start a new transaction towards the specified databasedbnamewith a transaction modemode.The main purpose of MAAPI is to provide read and write access into the transaction manager. Regardless of whether data is kept in CDB or in some* (or several) external data bases, the same API is used to access data.
ConfD/NCS acts as a mediator and multiplexes the different commands to the code which is responsible for each individual data element.
This function creates a new transaction towards a specified data base. If successful, it returns a new transaction identifier, a tid which must be used as a parameter in most of the
Maapimethods which manipulate the transaction.We will drive this transaction forward through the different states a transaction goes through. If an external database is used, and it has registered callback functions for the different transaction states, those callbacks will be called when we in MAAPI invoke the different MAAPI transaction manipulation functions. For example when we call
startTranstheinitcallback will be invoked in all external databases. If data is kept in CDB, the system will handle everything internally.The parameter
dbnameis supplied using on ofConf.DB_STARTUP,Conf.DB_RUNNING,Conf.DB_CANDIDATETransaction mode
modeis supplied usingConf.MODE_READ, to start a read only transactionConf.MODE_READ_WRITEto start a read write transaction.A read only transaction will incur less resource usage, thus if no writes will be done (e.g. the purpose of the transaction is only to read operational data), it is best to use
Conf.MODE_READ.There are also some cases where starting a read-write transaction is not allowed, e.g. if we start a transaction towards the running data store is set to "writable-through-candidate" in confd.conf/ncs.conf, or if ConfD/NCS is running in HA secondary mode.
- Parameters:
dbname- Database that the transaction should operate on.mode- Read or write mode.- Throws:
MaapiException- If the transaction could not be started see theThrowable.getMessage()IOException- Signals I/O exception on the underlying socketConfException
-
startTrans
public int startTrans(int dbname, int mode, String vendor, String product, String version, String clientId) throws IOException, ConfException - Throws:
IOExceptionConfException
-
startTrans2
Start a new transaction towards database within an existing user session specified byusid.If we want to start new transactions inside actions, we can use this function to execute the new transaction within the existing user session.
See
startTrans(int,int)for available options ondbnameand modemode.- Parameters:
dbname- Database that the transaction should operate onmode- Read or write modeusid- The user session id- Throws:
MaapiException- If the transaction could not be started see theThrowable.getMessage()IOException- Signals I/O exception on the underlying socketConfException
-
startTransFlags
public int startTransFlags(int dbname, int mode, int usid, EnumSet<MaapiFlag> flags) throws IOException, ConfException Start a new transaction towards the specified databasedbnamewith a transaction modemodewith additionalflagsto control read/write sessions.This method makes it possible to provide flags that can otherwise be used with
setFlags(int,EnumSet)already when starting a transaction, as well as setting theMaapiFlag.HIDE_INACTIVEandMaapiFlag.HIDE_ALL_HIDEGROUPSflag that can only be used with this function. Otherwise its has functionality equivalent to Maapi.startTrans2().- Parameters:
dbname- Database that the transaction should operate on. Possible values are STARTUP, RUNNING, CANDIDATEmode- Read or write mode. Possible values are READ and READ_WRITEusid- User session idflags- EnumSet of MaapiFlag values.- Throws:
IOExceptionConfException
-
startTransInTrans
Start a new transaction within an existing user session and another transaction as backend- Parameters:
mode- Read or write mode. Possible values are READ and READ_WRITEusid- User session idtid- Backend transaction id- Throws:
MaapiExceptionIOExceptionConfException
-
finishTrans
Finish the transaction specified by transaction handletid.If the transaction is implemented by an external database, this will invoke the
finishcallback.- Parameters:
tid- Transaction id of transaction to terminate.- Throws:
MaapiExceptionIOExceptionConfException
-
attach
Attach to a current transaction.While a transaction is executing, we have a number of situations where we wish to invoke user Java code which can interact in the transaction. One such situation is when we wish to write semantic validation code which is invoked in the validation phase of a transaction.
This code needs to execute within the context of the executing transaction, it must thus have access to the "shadow" storage where all not-yet-committed data is kept.
This method attaches to a existing transaction. See user guide chapter "Semantic Validation" for example code.
Another situation where we wish to attach to the executing transaction is when we are using the notifications API and subscribe to notification of type
NOTIF_COMMIT_DIFFand wish to read the committed diffs from the transaction.- Parameters:
tid- Transaction identifiernsi- Namespace identifier. Use 0 if we don't care which namespace is the default to choose if path elements are not properly prefixed.usid- Usid- Throws:
MaapiExceptionIOExceptionConfException
-
attach
Same asattach(int, int, int)with the exception that the User session id is implicit for the attached transaction.- Parameters:
tid- Transaction identifiernsi- Namespace identifier. Use 0 if we don't care which namespace is the default to choose if path elements are not properly prefixed.- Throws:
IOExceptionConfException
-
attach
Attach to a current transaction.While a transaction is executing, we have a number of situations where we wish to invoke user Java code which can interact in the transaction. One such situation is when we wish to write semantic validation code which is invoked in the validation phase of a transaction.
This code needs to execute within the context of the executing transaction, it must thus have access to the "shadow" storage where all not-yet-committed data is kept.
This method attaches to a existing transaction. See user guide chapter "Semantic Validation" for example code.
Another situation where we wish to attach to the executing transaction is when we are using the notifications API and subscribe to notification of type
NOTIF_COMMIT_DIFFand wish to read the committed diffs from the transaction.- Parameters:
tid- Transaction identifierns- Namespace identifierusid- Usid- Throws:
MaapiExceptionIOExceptionConfException
-
attach
Same asattach(int, String, int)with the exception that the User session id is implicit for the attached transaction.- Parameters:
tid- Transaction identifierns- Namespace identifier- Throws:
IOExceptionConfException
-
attachInit
Attach to transaction available in phase0.This method is used to attach the Maapi socket to the special transaction available in phase0 used for CDB initialization and upgrade.
- Returns:
- the transaction handle for the init transaction
- Throws:
IOExceptionConfException
-
detach
Detaches an attached MAAPI socket. This method is typically called in thefinishphase in validation code. An attached MAAPI socket will be automatically detached when the transaction terminates. This method performs an explicit detach.- Parameters:
tid- Transaction Identifier- Throws:
MaapiExceptionIOExceptionConfException
-
applyTrans
Apply a current transaction with transaction handletid.Invoking the transaction methods in exactly the right order can be a bit complicated.
The right order to invoke the methods is:
Usually we do not require this fine grained control over the two-phase commit protocol. It is easier to use
applyTranswhich validates, prepares and eventually aborts or commits.A call to
applyTransmust also eventually be followed by a call tofinishTrans(int)which will terminate the transaction. For a readonly transaction, i.e. one started withConf.MODE_READ, or for a read-write transaction where we haven't actually done any writes, we do not need to call any of the validate/prepare/commit/abort or apply methods, since there is nothing for them to do. CallingfinishTransto terminate the transaction is sufficient.The parameter
keepopencan optionally be set to true, then the changes to the transaction are not discarded if validation fails. This feature is typically used by management applications that wish to present the validation errors to an operator and allow the operator to fix the validation errors and then later retry the apply sequence.- Parameters:
tid- Transaction id of transaction to commitkeepOpen- If validation fails should the transaction be kept open or not- Throws:
ConfException- If the transaction is in badstate, for example ifapplyTransis called twice.IOException
-
applyTrans
Apply a current transaction with transaction handletidwith additional flags (NCS Specific).Some NCS specific flags can be used:
COMMIT_NCS_NO_REVISION_DROPmeans that NCS will not run its data model revision algorithm, thus requiring all participating managed devices to have all parts of the data models for all data contained in this transaction, i.e., this flag forces NCS to never silently drop any data set operations towards a device.COMMIT_NCS_NO_DEPLOYmeans that NCS will commit without running the FASTMAP algorithm, i.e, write the service instance data without activating the service(s). The service(s) can later be re-deployed to write the changes of the service(s) to the network.COMMIT_NCS_NO_NETWORKINGmeans that the NCS device manager will not see these changes. Even if transaction manipulates data below /devices/device/config, nothing will be sent to the managed devices. Thus this is a way to manipulate CDB in NCS without generating any southbound traffic.COMMIT_NCS_NO_OUT_OF_SYNC_CHECKmeans that NCS will continue with the transaction even if NCS detects that a device's configuration is out of sync. The device's sync state is assumed to be unknown after such commit and the stored transaction id value is cleared.COMMIT_NCS_NO_OVERWRITE_WRITE_SET_ONLYmeans that NCS will check that the data that should be modified has not changed on the device compared to NCS's view of the data. This is fine-granular sync check; NCS verifies that NCS and the device is in sync regarding the data that will be modified. If they are not in sync, the transaction is aborted.COMMIT_NCS_NO_OVERWRITE_WRITE_AND_FULL_READ_SETmeans that NCS will check that the data that should be modified or any data read when computing the device modifications has not changed on the device compared to NCS's view of the data. This is fine-granular sync check; NCS verifies that NCS and the device is in sync regarding the data that will be modified. If they are not in sync, the transaction is aborted.COMMIT_NCS_NO_OVERWRITE_WRITE_AND_SERVICE_READ_SETmeans that NCS will check that the data that should be modified or any data read by services run in the transaction has not changed on the device compared to NCS's view of the data. This is fine-granular sync check; NCS verifies that NCS and the device is in sync regarding the data that will be modified. If they are not in sync, the transaction is aborted.COMMIT_NCS_USE_LSAmeans that NCS will force handling LSA nodes as such.COMMIT_NCS_NO_LSAmeans that NCS will not handle any of the LSA nodes as such. These nodes will be handled as any other device.COMMIT_NCS_RECONCILE_KEEP_NON_SERVICE_CONFIGmeans that all data which existed before the service was created will now be owned by the service. When the service is removed that data will also be removed. In technical terms the reference count will be decreased by one for everything which existed. Note that this flag has no effect on initial service creation. Any manually configured data that exists below in the configuration tree will be kept.COMMIT_NCS_RECONCILE_DISCARD_NON_SERVICE_CONFIGmeans that all data which existed before the service was created will now be owned by the service. When the service is removed that data will also be removed. In technical terms the reference count will be decreased by one for everything which existed. Note that this flag has no effect on initial service creation. Any manually configured data that exists below in the configuration tree will be discarded.The flags are bits and can be ORed together.
- Parameters:
tid- Transaction id of transaction to commitkeepOpen- If validation fails should the transaction be kept open or notflags- Bitwise ORed flags- Throws:
MaapiExceptionIOExceptionConfException
-
applyTransParams
public ApplyResult applyTransParams(int tid, boolean keepOpen, CommitParams params) throws IOException, ConfException Apply a current transaction with transaction handletidwith additional NCS specific parameters.- Parameters:
tid- Transaction id of transaction to commitkeepOpen- If validation fails should the transaction be kept open or notparams- Commit parameters, seeCommitParams- Returns:
- An instance of
DryRunResultif dry-run was requested. An instance ofCommitQueueResultif commit through commit queue was requested. Otherwise an instance ofApplyResult. - Throws:
IOExceptionConfException
-
ncsRunWithRetry
Runopwith a new read-write transaction against the RUNNING datastore. In case of a conflict, retry runningop.Equivalent of ncsRunWithRetry(op, 10, new CommitParams()).
See
ncsRunWithRetry- Throws:
IOExceptionConfException
-
ncsRunWithRetry
public boolean ncsRunWithRetry(MaapiRetryableOp op, int maxNumRetries, CommitParams commitParams) throws IOException, ConfException Runopwith a new read-write transaction against the RUNNING datastore. In case of a conflict, retry runningop.Equivalent of ncsRunWithRetry(op, maxNumRetries, commitParams, EnumSet.noneOf(MaapiFlag.class)).
See
ncsRunWithRetry(MaapiRetryableOp, int, CommitParams, int, EnumSet)- Throws:
IOExceptionConfException
-
ncsRunWithRetry
public boolean ncsRunWithRetry(MaapiRetryableOp op, int maxNumRetries, CommitParams commitParams, int usid, EnumSet<MaapiFlag> flags) throws IOException, ConfException Runopwith a new read-write transaction against the RUNNING datastore. In case of a conflict, retry runningop.Run
opwith a new read-write transaction, applying it if op returns true. Theopis only retried in case of transaction conflicts. Each retry is run using a new transaction.The last conflict exception is thrown in case the maximum number of retries is reached.
- Parameters:
op- Object implementing the com.tailf.maapi.MaapiRetryableOp interfacemaxNumRetries- Maximum number of retries runningopin case of a conflictcommitParams- Commit parameters, seeCommitParamsusid- User session idflags- Enumset ofMaapiFlag- Returns:
- false if the maximum number of retries is reached
- Throws:
IOExceptionConfException
-
getTransParams
Get commit parameters for a transaction.- Parameters:
tid- Transaction id of transaction to get commit parameters for- Returns:
- the commit parameters
- Throws:
IOExceptionConfException
-
getRollbackId
Get rollback id for committed transaction specified by transaction handletid.This methods returns the fixed rollback id of the rollback file created during commit of the transaction. If rollbacks are disabled or no rollback was created this returns -1.
- Parameters:
tid- Transaction Identifier- Throws:
MaapiExceptionIOExceptionConfException
-
validateTrans
Validates a transaction specified by transaction handletidThis method validates all data written in the transaction. This includes all XML checks, checking for uniqueness and dangling pointers. It also includes all defined semantic validation, i.e. user programs that have registered functions under validation points. (See user manual chapter Semantic Validation).
If this method throws an exception due to a validation error, the transaction is still open for further editing. If unlock is true, the transaction is open for further editing even if validation succeeds. If unlock is false and the method returns, the next method to be called MUST be
prepareTrans(int)orfinishTrans(int).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 = true, the lock is released on success. The lock is always released on failure. The force parameter 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 force true. Avoiding this validation is preferable if we are going to commit the candidate to running e.g with
candidateCommit(), since otherwise the validation will be done twice. However if we are implementing a 'validate' command, we should set force = true- Parameters:
tid- Transaction Identifierunlock- if true the transaction is open for further editingforce- if true validation will performed also for candidate data store- Throws:
MaapiExceptionIOExceptionConfException
-
prepareTrans
Prepares the transaction specified by transaction handletid. This method must be called as first part of two-phase commit. After this method has been calledcommitTransorabortTransmust 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.
- Parameters:
tid- Transaction Identifier- Throws:
MaapiExceptionIOExceptionConfException
-
prepareTrans
Prepares the transaction specified by transaction handletid. This method must be called as first part of two-phase commit. After this method has been calledcommitTransorabortTransmust 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.
For a definition of the flags, see
applyTrans(int,boolean)- Parameters:
tid- Transaction Identifierflags- Bitwise ORed flags- Throws:
MaapiExceptionIOExceptionConfException
-
commitTrans
Commit a transaction specified by transaction handletid. Final step of a two-phase commit.validateTrans(int,boolean,boolean)andprepareTransmust be called prior tocommitTrans- Parameters:
tid- Transaction Identifier- Throws:
MaapiExceptionIOExceptionConfException
-
abortTrans
Abort a transaction specified by transaction handletid. Called if a two-phase commit should be aborted after having performedvalidateTransorprepareTrans.- Parameters:
tid- Transaction Identifier- Throws:
MaapiExceptionIOExceptionConfException
-
diffIterate
Iterates through the transaction diff.For all diffs in the transaction the supplied
MaapiDiffIterate.iterate(ConfObject[],DiffIterateOperFlag, ConfObject,ConfObject,Object)(callback) method will be called.This method can be called from an attached MAAPI session. The purpose of the function is to iterate through the transaction diff. It can typically be used in conjunction with the notification API when we subscribe to NOTIF_COMMIT_DIFF events.
For all diffs in the transaction the supplied callback function
iteratewill be called. Theiteratecallback receives the keypath which uniquely identifies which element in the XML tree that is affected, the operation, and an optional value.iterateis called for each modified list entry, and for each modified leaf node. If the node is a list entry, op is one ofMOP_CREATED,MOP_DELETEDorMOP_MODIFIEDIf the node is a leaf node, op is one ofMOP_DELETEDorMOP_VALUE_SET.If
iteratereturnsITER_STOP, no more iteration is done. IfiteratereturnsITER_RECURSEiteration continues with all children to the node. IfiteratereturnsITER_CONTINUEiteration ignores the children to the node (if any), and continues with the node's sibling.The different commit messages are not subjected to AAA checks, i.e. regardless of which path we have and which context was used to create the MAAPI socket, all changed values are sent on the socket.
- Parameters:
tid- Transaction handleiter- A MaapiDiffIterate object- Throws:
MaapiException- Failed diffIterateIOException- Failed to read/write maapi socketConfException
-
diffIterate
public void diffIterate(int tid, MaapiDiffIterate iter, String fmt, Object... args) throws IOException, ConfException Iterates through the transaction diff.For all diffs in the transaction the supplied
MaapiDiffIterate.iterate(ConfObject[],DiffIterateOperFlag, ConfObject,ConfObject,Object)(callback) method will be called.This method can be called from an attached MAAPI session. The purpose of the function is to iterate through the transaction diff. It can typically be used in conjunction with the notification API when we subscribe to NOTIF_COMMIT_DIFF events.
For all diffs in the transaction the supplied callback function
iteratewill be called. Theiteratecallback receives the keypath which uniquely identifies which element in the XML tree that is affected, the operation, and an optional value.iterateis called for each modified list entry, and for each modified leaf node. If the node is a list entry, op is one ofMOP_CREATED,MOP_DELETEDorMOP_MODIFIEDIf the node is a leaf node, op is one ofMOP_DELETEDorMOP_VALUE_SET.If
iteratereturnsITER_STOP, no more iteration is done. IfiteratereturnsITER_RECURSEiteration continues with all children to the node. IfiteratereturnsITER_CONTINUEiteration ignores the children to the node (if any), and continues with the node's sibling.The different commit messages are not subjected to AAA checks, i.e. regardless of which path we have and which context was used to create the MAAPI socket, all changed values are sent on the socket.
- Parameters:
tid- Transaction handleiter- A MaapiDiffIterate object- Throws:
MaapiException- Failed diffIterateIOException- Failed to read/write maapi socketConfException
-
diffIterate
public void diffIterate(int tid, MaapiDiffIterate iter, Object initstate, String fmt, Object... args) throws IOException, ConfException Iterates through the transaction diff.For all diffs in the transaction the supplied
MaapiDiffIterate.iterate(ConfObject[],DiffIterateOperFlag, ConfObject,ConfObject,Object)(callback) method will be called.This method can be called from an attached MAAPI session. The purpose of the function is to iterate through the transaction diff. It can typically be used in conjunction with the notification API when we subscribe to NOTIF_COMMIT_DIFF events.
For all diffs in the transaction the supplied callback function
iteratewill be called. Theiteratecallback receives the keypath which uniquely identifies which element in the XML tree that is affected, the operation, and an optional value.iterateis called for each modified list entry, and for each modified leaf node. If the node is a list entry, op is one ofMOP_CREATED,MOP_DELETEDorMOP_MODIFIEDIf the node is a leaf node, op is one ofMOP_DELETEDorMOP_VALUE_SET.If
iteratereturnsITER_STOP, no more iteration is done. IfiteratereturnsITER_RECURSEiteration continues with all children to the node. IfiteratereturnsITER_CONTINUEiteration ignores the children to the node (if any), and continues with the node's sibling.The different commit messages are not subjected to AAA checks, i.e. regardless of which path we have and which context was used to create the MAAPI socket, all changed values are sent on the socket.
- Parameters:
tid- Transaction handleiter- A MaapiDiffIterate object- Throws:
MaapiException- Failed diffIterateIOException- Failed to read/write maapi socketConfException
-
diffIterate
public void diffIterate(int tid, Object initstate, EnumSet<DiffIterateFlags> flags, MaapiDiffIterate iter, ConfPath path) throws IOException, ConfException Iterates through the transaction diff.For all diffs in the transaction the supplied
MaapiDiffIterate.iterate(ConfObject[],DiffIterateOperFlag, ConfObject,ConfObject,Object)(callback) method will be called.This method can be called from an attached MAAPI session. The purpose of the function is to iterate through the transaction diff. It can typically be used in conjunction with the notification API when we subscribe to NOTIF_COMMIT_DIFF events.
For all diffs in the transaction the supplied callback function
iteratewill be called. Theiteratecallback receives the keypath which uniquely identifies which element in the XML tree that is affected, the operation, and an optional value.iterateis called for each modified list entry, and for each modified leaf node. If the node is a list entry, op is one ofMOP_CREATED,MOP_DELETEDorMOP_MODIFIEDIf the node is a leaf node, op is one ofMOP_DELETEDorMOP_VALUE_SET. If the flags argument is set toDiffIterateFlags.ITER_WANT_ATTRalso attribute changes will be iterated over with opMOP_ATTR_SETand new and old values asConfAttributeValueIf
iteratereturnsITER_STOP, no more iteration is done. IfiteratereturnsITER_RECURSEiteration continues with all children to the node. IfiteratereturnsITER_CONTINUEiteration ignores the children to the node (if any), and continues with the node's sibling.The different commit messages are not subjected to AAA checks, i.e. regardless of which path we have and which context was used to create the MAAPI socket, all changed values are sent on the socket.
- Parameters:
tid- Transaction handleinitstate- arbitrary object passed to the iteratorflags- set ofDiffIterateFlagsflags that controls the iteration, for Maapi onlyDiffIterateFlags.ITER_WANT_ATTRis supportediter- A MaapiDiffIterate objectpath- ConfPath- Throws:
MaapiException- Failed diffIterateIOException- Failed to read/write maapi socketConfException
-
iterate
public void iterate(int tid, Object initstate, EnumSet<ConfIterateFlags> flags, MaapiIterate iter, ConfPath path) throws IOException, ConfException Iterates through all the data in a transaction.For all data elements in the transaction the supplied
MaapiIterate.iterate(ConfObject[],ConfObject, ConfAttributeValue[],Object)(callback) method will be called.This method can be called from an attached MAAPI session.
The
iteratecallback receives the keypath which uniquely identifies which element in the XML tree that is affected, the operation, and an optional value.iterateis called for each list entry, and for each leaf node. If the node is a list entry, op is one ofMOP_CREATED,MOP_DELETEDorMOP_MODIFIEDIf the node is a leaf node, op is one ofMOP_DELETEDorMOP_VALUE_SET. If the flags argument is set toConfIterateFlags.ITER_WANT_ATTRalso attribute changes will be iterated over with opMOP_ATTR_SETand new and old values asConfAttributeValueIf
iteratereturnsITER_STOP, no more iteration is done. IfiteratereturnsITER_RECURSEiteration continues with all children to the node. IfiteratereturnsITER_CONTINUEiteration ignores the children to the node (if any), and continues with the node's sibling.The different commit messages are not subjected to AAA checks, i.e. regardless of which path we have and which context was used to create the MAAPI socket, all changed values are sent on the socket.
- Parameters:
tid- Transaction handleinitstate- arbitrary object passed to the iteratorflags- set ofConfIterateFlagsflags that controls the iteration, for Maapi onlyConfIterateFlags.ITER_WANT_ATTRis supportediter- A MaapiIterate objectpath- ConfPath- Throws:
IOExceptionConfException
-
setLabel
Set the "Label" that is stored in the rollback file when a transaction towards running is committed. Setting the "Label" for transactions via candidate can be done when the candidate is committed to running, by using thecandidateCommitInfo(java.lang.String, java.lang.String)method. For a confirmed commit, the "Label" must also be given via thecandidateConfirmedCommitInfo(int, java.lang.String, java.lang.String)method.- Parameters:
tid- Transaction Identifierlabel- Label- Throws:
MaapiExceptionIOExceptionConfException
-
setComment
Set the "Comment" that is stored in the rollback file when a transaction towards running is committed. Setting the "Comment" for transactions via candidate can be done when the candidate is committed to running, by using thecandidateCommitInfo(java.lang.String, java.lang.String)method. For a confirmed commit, the "Comment" must also be given via thecandidateConfirmedCommitInfo(int, java.lang.String, java.lang.String)method.- Parameters:
tid- Transaction Identifiercomment- Comment- Throws:
MaapiExceptionIOExceptionConfException
-
setNamespace
Before can invoke any of read or write functions, we must indicate which namespace we are going to use. It is possible to change the namespace several times during a transaction.The ns string is the namespace URL
- Parameters:
tid- Transaction Identifierns- Namespace uri- Throws:
MaapiExceptionIOExceptionConfException
-
setNamespace
- Throws:
IOExceptionConfException
-
cd
This function mimics the behavior of the UNIX "cd" command. It changes our working position in the XML tree. If we are worried about performance, it is more efficient to invoke cd() to some position in the XML tree and there perform a series of operations using relative paths than it is to perform the equivalent series of operations using absolute paths.The cd() function is also very useful when writing generic code for accessing parts of the configuration tree.
- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
MaapiExceptionIOExceptionConfException
-
pushd
Behaves like cd() with the exception that we can subsequently call popd() and return to the previous position in the XML data tree.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
MaapiExceptionIOExceptionConfException
-
popd
Pops the top position of the directory stack and changes directory- Parameters:
tid- Transaction Identifier- Throws:
MaapiExceptionIOExceptionConfException
-
exists
Boolean function which return 1 or 0 if a path defines an existing element in the XML data tree.- Parameters:
tid- Transaction Identifierpath- ConfPath instance- Throws:
MaapiExceptionIOExceptionConfException
-
exists
- Throws:
IOExceptionConfException
-
getNumberOfInstances
public int getNumberOfInstances(int tid, String fmt, Object... arguments) throws IOException, ConfException Return the number of instances in a list. The path must lead to a list in the the model.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
MaapiExceptionIOExceptionConfException
-
getNumberOfInstances
- Throws:
IOExceptionConfException
-
getElem
public ConfValue getElem(int tid, String fmt, Object... arguments) throws IOException, ConfException This reads a value from the path in fmt and returns the result. The path must lead to a leaf element in the XML data tree.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
MaapiExceptionIOExceptionConfException
-
getElem
- Throws:
IOExceptionConfException
-
safeGetElem
Reads a value from the
pathspecifiedThe path must lead to a leaf element in the data tree.
This is a equivalent method of
getElem(int,String,Object[])method which returns null if the element doesn't exist instead of throwing a exception.- Parameters:
tid- transaction handlepath- leaf element in data tree- Throws:
ConfExceptionIOException
-
safeGetElem
public ConfValue safeGetElem(int tid, String fmt, Object... arguments) throws IOException, ConfException This reads a value from the path in fmt and returns the result. The path must lead to a leaf element in the XML data tree. This is a variant of the getElem() method which returns null if the element doesn't exist- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
MaapiExceptionIOExceptionConfException
-
getObject
public ConfObject[] getObject(int tid, String fmt, Object... arguments) throws IOException, ConfException This reads a container object or a list entry object from the path in fmt and returns the result. The path must lead to a a list entry or a container element in the XML data tree. The return value is an array of ConfObjects that describe the entire structure. All plain values in the structure, such as strings, ints ip addresses are represented as ConfValue instances. If the structure contains containers, they are represented as ConfTag instances. Finally, optional leafs and containers in the structure that are missing are represented as ConfTypeDescriptor instances with type set to ConfObject.J_NOEXISTS.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Returns:
- An array of ConfObject which describes the object.
- Throws:
MaapiExceptionIOExceptionConfException
-
safeGetObject
public ConfObject[] safeGetObject(int tid, String fmt, Object... arguments) throws IOException, ConfException This is a variant of getObject() that returns null if the object doesn't exist- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Returns:
- An array of ConfObject which describes the object.
- Throws:
MaapiExceptionIOExceptionConfException
-
setObject
public void setObject(int tid, ConfObject[] values, String fmt, Object... arguments) throws IOException, ConfException This writes a container object or a list entry object from the path in fmt and returns the result. The path must lead to a a list entry or a container element in the XML data tree. The values to set is an array of ConfObjects that describe the entire structure. All plain values in the structure, such as strings, ints ip addresses are represented as ConfValue instances. If the structure contains containers, they are represented as ConfTag instances. Finally, optional leafs and containers in the structure that are missing are represented as ConfTypeDescriptor instances with type set to ConfObject.J_NOEXISTS.- Parameters:
tid- Transaction Identifiervalues-fmt- path stringarguments- optional parameters for substitution in fmt- Throws:
MaapiExceptionIOExceptionConfException
-
setValues
public void setValues(int tid, List<ConfXMLParam> params, ConfPath path) throws IOException, ConfException Set arbitrary sub-elements of a container element in one bulk operation. If the container element itself, or any sub-elements that are specified as existing, do not exist before this call, they will be created, otherwise the existing values will be updated. Both non-optional and optional elements may be omitted from the array, and all omitted elements are left unchanged.- Parameters:
tid-params-path-- Throws:
IOExceptionConfException
-
setValues
public void setValues(int tid, List<ConfXMLParam> params, String fmt, Object... arguments) throws IOException, ConfException Set arbitrary sub-elements of a container element in one bulk operation. If the container element itself, or any sub-elements that are specified as existing, do not exist before this call, they will be created, otherwise the existing values will be updated. Both non-optional and optional elements may be omitted from the array, and all omitted elements are left unchanged.- Parameters:
params-fmt-arguments-- Throws:
IOExceptionConfException
-
setValues
public void setValues(int tid, ConfXMLParam[] params, String fmt, Object... arguments) throws IOException, ConfException Set arbitrary sub-elements of a container element in one bulk operation. If the container element itself, or any sub-elements that are specified as existing, do not exist before this call, they will be created, otherwise the existing values will be updated. Both non-optional and optional elements may be omitted from the array, and all omitted elements are left unchanged.- Parameters:
tid-params-fmt-arguments-- Throws:
IOExceptionConfException
-
setValues
public void setValues(int tid, ConfXMLParam[] params, ConfPath path) throws IOException, ConfException Set arbitrary sub-elements of a container element in one bulk operation. If the container element itself, or any sub-elements that are specified as existing, do not exist before this call, they will be created, otherwise the existing values will be updated. Both non-optional and optional elements may be omitted from the array, and all omitted elements are left unchanged.- Parameters:
tid-params-path-- Throws:
IOExceptionConfException
-
getValues
public <T extends List<ConfXMLParam>> T getValues(int tid, T params, String fmt, Object... arguments) throws IOException, ConfException Read an arbitrary set of sub-elements of a container element.The
paramslist must be pre-populated based on the specification of theConfXMLParamarray structure format. WhereConfXMLParamValuevalue element set byConfXMLParamValue.setValue(ConfObject)method is given as follow:ConfNoExistsmeans that the value should be read from the transaction and stored in the array.ConfXMLParamStart,ConfXMLParamStopare used as per the specification.- Keys to select list entries can be given with their values.
All elements have the same position in the array after the call, In order to simplify extraction of the values - this means that optional elements that were requested but didn't exist will have
ConfNoExists(as a theConfXMLParam.getValue()return value in the corresponding position in aConfXMLParamValue) rather than being omitted from the array. However requesting a list entry that doesn't exist will throw a exception indicating that the instance does not exits.- Type Parameters:
T- the type list holding the structure- Parameters:
tid- transaction handlearguments- optional parameter for substitution in fmtparams- pre-populated structure of the elements to be extracted- Throws:
MaapiException- If the the call failed for some reason see theThrowable.getMessage()for details.IOException- Signals I/O exception of some kindConfException- See Also:
-
getValues
public <T extends List<ConfXMLParam>> T getValues(int tid, T params, ConfPath path) throws IOException, ConfException Read an arbitrary set of sub-elements of a container element.The
paramslist must be pre-populated based on the specification of theConfXMLParamarray structure format. WhereConfXMLParamValuevalue element set byConfXMLParamValue.setValue(ConfObject)method is given as follow:ConfNoExistsmeans that the value should be read from the transaction and stored in the array.ConfXMLParamStart,ConfXMLParamStopare used as per the specification.- Keys to select list entries can be given with their values.
All elements have the same position in the array after the call, In order to simplify extraction of the values - this means that optional elements that were requested but didn't exist will have
ConfNoExists(as a theConfXMLParam.getValue()return value in the corresponding position in aConfXMLParamValue) rather than being omitted from the array. However requesting a list entry that doesn't exist will throw a exception indicating that the instance does not exits.- Type Parameters:
T- the type list holding the structure- Parameters:
tid- transaction handlepath- the path pointing to the location of extractionparams- pre-populated structure of the elements to be extracted- Throws:
MaapiException- If the the call failed for some reason see theThrowable.getMessage()for details.IOException- Signals I/O exception of some kindConfException- See Also:
-
getValues
public <T extends ConfXMLParam> T[] getValues(int tid, T[] params, String fmt, Object... arguments) throws IOException, ConfException Read an arbitrary set of sub-elements of a container element.The
paramsarray must be pre-populated based on the specification of theConfXMLParamarray structure format. WhereConfXMLParamValuevalue element set byConfXMLParamValue.setValue(ConfObject)method is given as follow:ConfNoExistsmeans that the value should be read from the transaction and stored in the array.ConfXMLParamStart,ConfXMLParamStopare used as per the specification.- Keys to select list entries can be given with their values.
All elements have the same position in the array after the call, In order to simplify extraction of the values - this means that optional elements that were requested but didn't exist will have
ConfNoExists(as a theConfXMLParam.getValue()return value in the corresponding position in aConfXMLParamValue) rather than being omitted from the array. However requesting a list entry that doesn't exist will throw a exception indicating that the instance does not exits.- Type Parameters:
T- type of the elements contained in the structure- Parameters:
tid- transaction handleparams- pre-populated structure of the elements to be extractedfmt- path stringarguments- optional parameter for substitution in fmt- Throws:
MaapiException- If the the call failed for some reason see theThrowable.getMessage()for details.IOException- Signals I/O exception of some kindConfException- See Also:
-
getValues
public <T extends ConfXMLParam> T[] getValues(int tid, T[] params, ConfPath path) throws IOException, ConfException Read an arbitrary set of sub-elements of a container element.The
paramsarray must be pre-populated based on the specification of theConfXMLParamarray structure format. WhereConfXMLParamValuevalue element set byConfXMLParamValue.setValue(ConfObject)method is given as follow:ConfNoExistsmeans that the value should be read from the transaction and stored in the array.ConfXMLParamStart,ConfXMLParamStopare used as per the specification.- Keys to select list entries can be given with their values.
All elements have the same position in the array after the call, In order to simplify extraction of the values - this means that optional elements that were requested but didn't exist will have
ConfNoExists(as a theConfXMLParam.getValue()return value in the corresponding position in aConfXMLParamValue) rather than being omitted from the array. However requesting a list entry that doesn't exist will throw a exception indicating that the instance does not exits.- Type Parameters:
T- type of the elements contained in the structure- Parameters:
tid- transaction handleparams- pre-populated structure of the elements to be extractedpath- the path pointing to the location of extraction- Throws:
MaapiException- If the the call failed for some reason see theThrowable.getMessage()for details.IOException- Signals I/O exception of some kindConfException- See Also:
-
newCursor
public MaapiCursor newCursor(int tid, String fmt, Object... arguments) throws IOException, ConfException Creates a cursor for a list specified by
fmt.The
MaapiCursoris used to iterate over the keys of a list.When we wish to iterate over key entries we must first create a cursor.
The cursor instance is subsequently used in
getNext(MaapiCursor)to retrieve the next key instance in the list. When the cursor retrieves null the whole list has been iterated.An exhausted cursor cannot be reset.
For example, if we have the following YANG model:
module mtest { namespace "http://tail-f.com/test/mtest/1.0"; prefix mtest; import ietf-inet-types { prefix inet; } container servers { list server { key name; max-elements 64; leaf name { type string; } leaf ip { type inet:ip-address; mandatory true; } leaf port { type inet:port-number; mandatory true; } } } }Example usage:
MaapiCursor c = maapi.newCursor(tid, "/mtest:mtest/servers/server"); ConfKey x; while ((x = maapi.getNext(c)) != null) { ConfValue nameValue = maapi.getElem(tid, "/mtest:mtest/servers/server{%x}/name", x); ConfValue ipValue = maapi.getElem(tid, "/mtest:mtest/servers/server{%x}/ip", x); ConfValue portValue = maapi.getElem(tid, "/mtest:mtest/servers/server{%x}/port",x); }- Parameters:
tid- current transaction idfmt- path of the list to be iteratedarguments- optional parameters for substitution in fmt- Throws:
IOExceptionConfException
-
newCursor
Creates a cursor for a list specified by
pathThe
MaapiCursoris used to iterate over the keys of a list.When we wish to iterate over key entries we must first create a cursor.
The cursor instance is subsequently used in
getNext(MaapiCursor)to retrieve the next key instance in the list. When the cursor retrieves null the whole list has been iterated and the cursor can not be reset.- Parameters:
tid- current transaction idpath- path of the list to be iterated- Throws:
IOExceptionConfException
-
newCursorWithFilter
public MaapiCursor newCursorWithFilter(int tid, String filter, String fmt, Object... arguments) throws IOException, ConfException Creates a cursor for a list specified by
fmtwith an XPath filter specified byfilter.The
MaapiCursoris used to iterate over the keys a list.When we wish to iterate over key entries we must first create a cursor.
The cursor instance is subsequently used in
getNext(MaapiCursor)to retrieve the next key instance in the list. When the cursor retrieves null the whole list has been iterated and the cursor can not be reset.If
filteris not null, only keys of elements matching the filter will be included in the iteration. Iffilteris null, this method behaves just asnewCursor(int, String, Object...)Given the same example model as in
newCursor(int, String, Object...)one could iterate over servers on the 10.x.x.x network with port numbers above 8000 using the following cursor call:MaapiCursor c = maapi.newCursorWithFilter(tid, "starts-with(ip, \"10.\") and port > 8000", "/mtest:mtest/servers/server");- Parameters:
tid- current transaction idfilter- XPath filter for filtering the listfmt- path of the list to be iteratedarguments- optional parameters for substitution in fmt- Throws:
IOExceptionConfException
-
newCursorWithFilter
public MaapiCursor newCursorWithFilter(int tid, String filter, ConfPath path) throws IOException, ConfException Creates a cursor for a list specified by
pathwith an XPath filter specified byfilter.The
MaapiCursoris used to iterate over the keys of a list.When we wish to iterate over key entries we must first create a cursor.
The cursor instance is subsequently used in
getNext(MaapiCursor)to retrieve the next key instance in the list. When the cursor retrieves null the whole list has been iterated and the cursor can not be reset.If
filteris not null, only keys of elements matching the filter will be included in the iteration. Iffilteris null, this method behaves just asnewCursor(int, ConfPath)- Parameters:
tid- current transaction idfilter- XPath filter for filtering the listpath- path of the list to be iterated- Throws:
IOExceptionConfException
-
getNext
Iterates and gets the keys for the next element pinpointed by theMaapiCursorinitially retrieved bynewCursor(int, String, Object...). With the key(s) it is possible to navigate further down the model.For example, to read the port element from the 'server' example model, we would do:
MaapiCursor c = maapi.newCursor(tid, "/mtest:mtest/servers/server"); ConfKey x = maapi.getNext(c); while (x != null) { ConfObject p; p = maapi.getElem(tid, "/mtest:mtest/servers/server{%x}/port", x); // .... x = maapi.getNext(c); }- Parameters:
c- MaapiCursor- Returns:
- ConfKey for the retrieved element
- Throws:
IOExceptionConfException
-
findNext
public ConfKey findNext(MaapiCursor c, ConfFindNextType type, ConfKey key) throws IOException, ConfException The findNext method makes it possible to jump forward to an element in the model at a position defined by the MaapiCursor After the findNext call the same MaapiCursor can be used in subsequent getNext calls.- Parameters:
c- MaapiCursor for pathtype- ConfFindNextType if same element as key or element after key should be retrievedkey- ConfKey for the searched element- Returns:
- ConfKey for the retrieved element or null if not found
- Throws:
IOExceptionConfException
-
getObjects
public List<ConfObject[]> getObjects(MaapiCursor c, int numOfObjects, int numOfInstances) throws IOException, ConfException Get several list instances with one request. A prerequisite is that a MaapiCursor must have been initialized for the list and supplied as an argument to this call. For each list instance the argument numOfObjects controls the maximum number of elements that will be retrieved. The objects are added in schema order. The numOfInstances argument controls the maximum number of list instances that should be retrived. If the list is empty or the cursor have already iterated through all list instances then the returned list will be empty.- Parameters:
c- MaapiCursor on current listnumOfObjects- Number of object retrieved from a list instancenumOfInstances- Number of list instances retrieved in this call- Returns:
- List<ConfObject[]> containing list instances.
- Throws:
IOExceptionConfException
-
setElem
public void setElem(int tid, ConfObject value, String fmt, Object... arguments) throws IOException, ConfException Set value to a leaf node.There two different methods to set a value to a leaf node. One where the value is a string and one where the value to set is a
ConfObject. The string version is useful when we have implemented a management agent where the user enters values as strings.The version with
ConfObjectis useful when we are setting values which we have just read from various API methods that returnsConfObject.- Parameters:
tid- Transaction Identifiervalue-fmt- path stringarguments- optional parameters for substitution in fmt- Throws:
IOExceptionConfException
-
setElem
Set value to a leaf node.There two different methods to set a value to a leaf node. One where the value is a string and one where the value to set is a
ConfObject. The string version is useful when we have implemented a management agent where the user enters values as strings.The version with
ConfObjectis useful when we are setting values which we have just read from various API methods that returnsConfObject.- Parameters:
tid- Transaction Identifiervalue-path-- Throws:
IOExceptionConfException
-
setElem
public void setElem(int tid, String value, String fmt, Object... arguments) throws IOException, ConfException Set value to a leaf node.There two different methods to set a value to a leaf node. One where the value is a string and one where the value to set is a
ConfObject. The string version is useful when we have implemented a management agent where the user enters values as strings.The version with
ConfObjectis useful when we are setting values which we have just read from various API methods that returnsConfObject.- Parameters:
tid- Transaction Identifiervalue-fmt- path stringarguments- optional parameters for substitution in fmt- Throws:
IOExceptionConfException
-
setElem
Set value to a leaf node.There two different methods to set a value to a leaf node. One where the value is a string and one where the value to set is a
ConfObject. The string version is useful when we have implemented a management agent where the user enters values as strings.The version with
ConfObjectis useful when we are setting values which we have just read from various API methods that returnsConfObject.- Parameters:
tid- Transaction Identifiervalue-path- ConfPath instance- Throws:
IOExceptionConfException
-
create
Create a new list entry in the XML tree. For examplemaapi.create(tid, "/servers/server{www}");If we are creating a new server element as above, we must also populate all other XML elements below, which do not have a default value in the YANG model. Thus we must also:maapi.setElem(tid, "80", "/servers/server{www}/port");before we try to commit the data.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
ConfException- if the object already existsIOException
-
create
Create an entity in the XML tree. Things that can be created are liste entries, presence containers and leaves with type empty.maapi.create(tid, "/servers/server{www}");If we are creating a new server element as above, we must also populate all other XML elements below which do not have a default value in the YANG model. Thus, assuming 'port' is mandatory we must also:maapi.setElem(tid, "80", "/servers/server{www}/port");before we try to commit the data.- Parameters:
tid- Transaction Identifierpath-- Throws:
ConfException- if the object already existsIOException
-
safeCreate
Create a new entity in the XML tree. This is variant of the create() method that doesn't throw an exception if the object already exists.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
ConfExceptionIOException
-
safeCreate
Create a new list entity in the XML tree. This is variant of the create() method that doesn't throw an exception if the object already exists.- Parameters:
tid- Transaction Identifierpath-- Throws:
ConfExceptionIOException
-
delete
Deletes a node and all its children from the XML data tree.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
ConfExceptionIOException
-
delete
Deletes a node and all its children from the XML data tree.- Parameters:
tid- Transaction Identifierpath-- Throws:
ConfExceptionIOException
-
deleteAll
This function can be used to delete "all" configuration data within a transaction. The flaghowspecifies the extent of "all":MAAPI_DEL_SAFEDelete everything except namespaces that were exported to none (with tailf:export none). Toplevel nodes that cannot be deleted due to AAA rules are silently left in place, but descendant nodes will still be deleted if the AAA rules allow it.MAAPI_DEL_EXPORTEDDelete everything except namespaces that were exported to none (with tailf:export none). AAA rules are ignored, i.e. nodes are deleted even if the AAA rules don't allow it.MAAPI_DEL_ALLDelete everything. AAA rules are ignored.- Parameters:
th- Transaction handlehow- One of the flags in MaapiDeleteAllFlag, specifying 'how' to delete all- Throws:
ConfExceptionIOException
-
safeDelete
Deletes a node and all its children from the XML data tree.Version of
deletethat doesn't throw an exception if the element doesn't exist- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
ConfExceptionIOException
-
insert
- Throws:
IOExceptionConfException
-
insert
public void insert(int tid, boolean createBackPointer, String fmt, Object... arguments) throws IOException, ConfException This function inserts a new element in an ordered list of elements. The key must be of type integer, and have the attribute <indexedView>. If the inserted element already exists, all element following the element will be reordered.- Parameters:
tid- Transaction IdentifiercreateBackPointer- When we insert items into lists that are managed by FastMap code, we always want to set this parameter to true. Since we insert into the list, effectively changing the keys the FastMap diff-sets must be updated accordingly.fmt- path stringarguments- optional parameters for substitution in fmt- Throws:
ConfExceptionIOException
-
move
public void move(int tid, ConfKey tokey, String fmt, Object... arguments) throws IOException, ConfException This function moves an existing object. Renames the object using the new instance key tokey.- Parameters:
tid- Transaction Identifiertokey-fmt- path stringarguments- optional parameters for substitution in fmt- Throws:
ConfExceptionIOException
-
move
public void move(int tid, String tokey, String fmt, Object... arguments) throws IOException, ConfException This function moves an existing objectRenames the object using the new instance key tokey represented as a string.
- Parameters:
tid- Transaction Identifiertokey-fmt- path stringarguments- optional parameters for substitution in fmt- Throws:
ConfExceptionIOException
-
moveOrdered
public void moveOrdered(int tid, MoveWhereFlag where, ConfKey tokey, String fmt, Object... arguments) throws IOException, ConfException For a list with the YANG ordered-by user statement, this function can be used to change the order of entries, by moving one entry to a new position. When new entries in such a list are created with Maapi.create(), they are always placed last in the list. The path given by fmt and the remaining arguments identifies the entry to move, and the new position is given by the where argument: MoveWhereFlag.MOVE_FIRST Move the entry first in the list. The tokey arguments is ignored, and can be given as NULL. MoveWhereFlag.MOVE_LAST Move the entry last in the list. The tokey arguments is ignored, and can be given as NULL. MoveWhereFlag.MOVE_BEFORE Move the entry to the position before the entry given by the tokey argument. MoveWhereFlag.MOVE_AFTER Move the entry to the position after the entry given by the tokey argument.- Parameters:
tid- current transactionwhere- MoveWhereFlag movement flagtokey- key as base for relative movementsfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
IOExceptionConfException
-
getCase
public ConfTag getCase(int tid, String choice, String fmt, Object... arguments) throws IOException, ConfException This returns the current 'case' for a 'choice' construct.When we use the YANG choice statement in the data model, this method can be used to find the currently selected case, avoiding useless getElem() etc requests for nodes that belong to other cases. The
fmtarguments give the path to the list entry or container where the choice is defined, and choice is the name of the choice.The case value is returned as ConfTag.For a choice without a mandatory true statement where no case is currently selected, the function will fail with ERR_NOEXISTS if the choice doesn't have a default case. If it has a default case, it will be returned unless the
MaapiFlag.NO_DEFAULTSflag is in effect @see MaapiFlag if the flag is set, the value returned will have typeConfTagDefault.NOTE: The method will suppress all ERR_NOEXISTS errors this means that the method will not throw exception when ERR_NOEXISTS occurs it will print a warning message and return null.
- Parameters:
tid- current transaction handlechoice- name of the choicefmt- path string to the container or list where the choice is definedarguments- optional parameters for substitution in fmt- Returns:
- ConfTag representing the current selected case or null if the case could not be determine. If NO_DEFAULTS flag is used and the default case is selected, then ConfTagDefault instance is returned.
- Throws:
MaapiExceptionIOExceptionConfException
-
getCase
- Throws:
IOExceptionConfException
-
revert
Remove all changes in the transaction.- Parameters:
tid-- Throws:
IOExceptionConfException
-
copyTree
copyTree(int, boolean, ConfPath, ConfPath)Equivalent tocopyTree(int, boolean, ConfPath, ConfPath)with useSharedCreate set to false i.e., for use outside fastmap, without 'shared' create/set- Throws:
IOExceptionConfException
-
copyTree
public void copyTree(int tid, boolean useSharedCreate, ConfPath from, ConfPath to) throws IOException, ConfException This function is used to copy an entire subtree in the configuration from one point to another. When we use this function in fastmap code, we usually want to set the useSharedCreate parameter to true.- Parameters:
tid- Transaction IdentifieruseSharedCreate-from-to-- Throws:
ConfExceptionIOException
-
lock
This function is used to take a lock on one of the databases.Only one entity may own the lock at any given time.
You do not have to acquire the lock before you read or write to a transaction.
This lock is also taken by the CLI when the user enters exclusive mode. Depending on the configuration different locks will be taken, ie, if the system has been configured to have a candidate, and a writable running configuration then both a lock on running and a lock on the candidate database will be acquired.
The following locks are acquired when you enter configure exclusive mode in the CLI:
If the system is configured with a startup db, and no writable running or candidate: lock startup
If the system is configured with a writable running and no startup or candidate db: lock running
If the system is configured with a writable running and a startup db, and no candidate: lock running and startup.
If the system is configured with a writable running and a candidate db, and no startup: lock running and candidate.
- Parameters:
db- Database to lock. Possible values are STARTUP, RUNNING, and CANDIDATE- Throws:
ConfExceptionIOException
-
unlock
This function releases a lock previously acquired using the lock() method.- Parameters:
db- Database to unlock. Possible values are STARTUP, RUNNING, and CANDIDATE- Throws:
ConfExceptionIOException
-
lockPartial
It is possible to manipulate partial locks on the databases, i.e. locks on a specified set of leaves and/or subtrees. The specification of what to lock is given via the xpaths array, which is populated with xpath string expressions. If the lock succeeds, lockPartial() returns a lock identifier, which is used in the unlockPartial() call.- Parameters:
db- Databasexpaths- Array of xpath expressions to lock- Returns:
- A lock identifier which is used for unlockPartial()
- Throws:
ConfExceptionIOException
-
lockPartial
Same aslockPartial(int,String[])except only one xpath expression is given.- Throws:
IOExceptionConfException
-
unlockPartial
This methods releases a lock previously acquired using the lockPartial() method.- Parameters:
lockId- The previously specified lock identifier- Throws:
ConfExceptionIOException
-
deref
public ConfObject[][] deref(int tid, String fmt, Object... arguments) throws IOException, ConfException This method dereferences a leafref and returns a list of the objects the leafref "points" to. I.e it returns an array of keypaths. If the leafref points to a single key, the list will be of length 1. If the leafref points to either a normal leaf, or to a list key element in a list with multiple keys, the list may be longer that 1. The path must lead to a leafref element in the XML data tree.- Parameters:
tid- Transaction Identifierfmt- path stringarguments- optional parameters for substitution in fmt- Throws:
MaapiExceptionIOExceptionConfException
-
isLockSet
This methods checks if a lock is taken or not. if integer /= 0 is returned it is the usid of the lock owner- Parameters:
db- Database to check. Possible values areConf.DB_STARTUP,Conf.DB_RUNNING, andConf.DB_CANDIDATE- Throws:
ConfExceptionIOException
-
candidateValidate
This function validates the candidate. The function should only be used when the candidate is not owned by ConfD, i.e. when the candidate is owned by an external database.- Throws:
ConfExceptionIOException
-
deleteConfig
This function empties a data store.- Throws:
ConfExceptionIOException
-
candidateCommit
This function copies the candidate to running. It is also used to confirm a previous call to candidateConfirmedCommit(), i.e. to prevent the automatic rollback if a confirmed commit is not confirmed.- Throws:
ConfExceptionIOException
-
candidateConfirmedCommit
This method also copies the candidate into running. However if a call to candidateCommit() is not done within a given timeout an automatic rollback will occur.- Parameters:
t- Timeout in seconds- Throws:
ConfExceptionIOException
-
candidateReset
This function copies running into candidate.- Throws:
ConfExceptionIOException
-
candidateAbortCommit
This function cancels a pending confirmed commit.- Throws:
ConfExceptionIOException
-
confirmedCommitInProgress
Checks whether a confirmed commit is pending. Returns the ID of the user session currently having a pending confirmed commit operation in progress or 0 if no operation is in progress.- Throws:
ConfExceptionIOException
-
candidateConfirmedCommitPersistent
public void candidateConfirmedCommitPersistent(int timeoutsecs, String persist, String persistId) throws IOException, ConfException This method can be used to start or extend a persistent confirmed commit, see the Tail-f Commit Capability section in the NETCONF Server chapter in the User Guide.The
persistparameter sets the cookie for the persistent confirmed commit, while thepersistIdgives the cookie for an already ongoing persistent confirmed commit. This gives the following possibilities:persist = "cookie", persistId = nullStart a persistent confirmed commit with the cookie "cookie", or extend an already ongoing non-persistent confirmed commit and turn it into a persistent confirmed commit.persist = "newcookie", persistId = "oldcookie"Extend an ongoing persistent confirmed commit that uses the cookie "oldcookie" and change the cookie to "newcookie".persist = null, persistId = "cookie"Extend an ongoing persistent confirmed commit that uses the cookie "oldcookie" and turn it into a non-persistent confirmed commit.persist = null, persistId = nullDoes the same ascandidateConfirmedCommit(int).
persist = "cookie", persistId = null, and to extend it withpersist = "cookie", persistId = "cookie". Throws ConfException- Parameters:
timeoutsecs- timeout for the confirmed commitpersist- value for a new persistent confirmed commitpersistId- value for an already ongoing persistent confirmed commit- Throws:
IOExceptionConfException- If error. If theerrorCodefor theConfExceptionisConfException.ERR_NOEXISTSit means that there is an ongoing persistent confirmed commit, butpersistIddid not give the right cookie for it.
-
candidateConfirmedCommitInfo
public void candidateConfirmedCommitInfo(int timeoutsecs, String label, String comment) throws IOException, ConfException This method does the same ascandidateConfirmedCommitPersistent(int, java.lang.String, java.lang.String), but allows for setting the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running. To set only the "Label", give comment as null, and to set only the "Comment", give label as null. Note: To ensure that the "Label" and/or "Comment" are stored in the rollback file in all cases when doing a confirmed commit, they must be given both with the confirmed commit (using this method) and with the confirming commit (usingcandidateCommitInfo(java.lang.String, java.lang.String)).- Parameters:
timeoutsecs- timeout for the confirmed commitlabel- value for "Label" in the rollback filecomment- value for "Comment" in the rollback file- Throws:
IOExceptionConfException- If error. If theerrorCodefor theConfExceptionisConfException.ERR_NOEXISTSit means that there is an ongoing persistent confirmed commit, butpersistIddid not give the right cookie for it.
-
candidateConfirmedCommitInfo
public void candidateConfirmedCommitInfo(int timeoutsecs, String persist, String persistId, String label, String comment) throws IOException, ConfException This method does the same ascandidateConfirmedCommitPersistent(int, java.lang.String, java.lang.String), but allows for setting the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running. To set only the "Label", give comment as null, and to set only the "Comment", give label as null. Note: To ensure that the "Label" and/or "Comment" are stored in the rollback file in all cases when doing a confirmed commit, they must be given both with the confirmed commit (using this method) and with the confirming commit (usingcandidateCommitInfo(java.lang.String, java.lang.String)).- Parameters:
timeoutsecs- timeout for the confirmed commitpersist- value for a new persistent confirmed commitpersistId- value for an already ongoing persistent confirmed commitlabel- value for "Label" in the rollback filecomment- value for "Comment" in the rollback file- Throws:
IOExceptionConfException- If error. If theerrorCodefor theConfExceptionisConfException.ERR_NOEXISTSit means that there is an ongoing persistent confirmed commit, butpersistIddid not give the right cookie for it.
-
candidateAbortCommitPersistent
Cancel an ongoing persistent commit with the cookie given by persistId. (If persistId is null, it does the same ascandidateAbortCommit().- Parameters:
persistId- cookie for ongoing persistent confirmed commit- Throws:
IOExceptionConfException- If error. If theerrorCodefor theConfExceptionisConfException.ERR_NOEXISTSit means that there is an ongoing persistent confirmed commit, butpersistIddid not give the right cookie for it.
-
candidateCommitPersistent
Confirm an ongoing persistent commit with the cookie given by persistId. (If persistId is null, it does the same ascandidateCommit(). Throws ConfException if error. If the errorCode for the ConfException is ConfException.ERR_NOEXISTS it means that there is an ongoing persistent confirmed commit, but persist_id did not give the right cookie for it.- Parameters:
persistId-- Throws:
IOExceptionConfException- If error. If theerrorCodefor theConfExceptionisConfException.ERR_NOEXISTSit means that there is an ongoing persistent confirmed commit, butpersistIddid not give the right cookie for it.
-
candidateCommitInfo
This method can be used to set the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running. To set only the "Label", give comment as null, and to set only the "Comment", give label as null. If no confirmed commit is ongoing, persistId must not be given, and the method does a normal candidate commit, likecandidateCommit(). Otherwise the method will confirm the ongoing confirmed commit. For a persistent confirmed commit, the cookie can be given by persistId if needed. Note: To ensure that the "Label" and/or "Comment" are stored in the rollback file in all cases when doing a confirmed commit, they must be given both with the confirmed commit (usingcandidateConfirmedCommitInfo(int, java.lang.String, java.lang.String)) and with the confirming commit (using this method).- Parameters:
label- value for "Label" in the rollback filecomment- value for "Comment" in the rollback file- Throws:
IOExceptionConfException- If error. If theerrorCodefor theConfExceptionisConfException.ERR_NOEXISTSit means that there is an ongoing persistent confirmed commit, butpersistIddid not give the right cookie for it.
-
candidateCommitInfo
public void candidateCommitInfo(String persistId, String label, String comment) throws IOException, ConfException This method can be used to set the "Label" and/or "Comment" that is stored in the rollback file when the candidate is committed to running. To set only the "Label", give comment as null, and to set only the "Comment", give label as null. If no confirmed commit is ongoing, persistId must not be given, and the method does a normal candidate commit, likecandidateCommit(). Otherwise the method will confirm the ongoing confirmed commit. For a persistent confirmed commit, the cookie can be given by persistId if needed. Note: To ensure that the "Label" and/or "Comment" are stored in the rollback file in all cases when doing a confirmed commit, they must be given both with the confirmed commit (usingcandidateConfirmedCommitInfo(int, java.lang.String, java.lang.String)) and with the confirming commit (using this method).- Parameters:
persistId- value for an already ongoing persistent confirmed commitlabel- value for "Label" in the rollback filecomment- value for "Comment" in the rollback file- Throws:
IOExceptionConfException- If error. If theerrorCodefor theConfExceptionisConfException.ERR_NOEXISTSit means that there is an ongoing persistent confirmed commit, butpersistIddid not give the right cookie for it.
-
copyRunningToStartup
Copies running to startup.- Throws:
ConfExceptionIOException
-
copy
If we open two transactions from the same user sessions but towards different data stores, such as one transaction towards the candidate and one towards running, we can copy all data from one data store to the other with this method.- Parameters:
thfrom-thto-- Throws:
ConfExceptionIOException
-
copyPath
Similar tocopy(int, int), but does a replacing copy only of the subtree rooted at the path given bypath- Parameters:
fromTh-toTh-path-- Throws:
ConfExceptionIOException
-
authenticate
public MaapiAuthentication authenticate(String user, String passwd) throws IOException, ConfException If we are implementing a proprietary Management Agent with MAAPI API, the methodstartUserSession(String,String,String[],SocketAddress, MaapiUserSessionFlag)requires the application to tell ConfD/NCS which groups the user are member of.ConfD/NCS itself has the capability to authenticate users. It is possible for a MAAPI application to let ConfD/NCS authenticate the user, as per the AAA configuration in the system configuration file
- Parameters:
user-passwd-- Throws:
ConfExceptionIOException
-
authenticate2
public MaapiAuthentication authenticate2(String user, String passwd, InetAddress srcAddr, int srcPort, String context, MaapiUserSessionFlag proto) throws IOException, ConfException If we are implementing a proprietary Management Agent with MAAPI API, the methodstartUserSession(String,String,String[],SocketAddress, MaapiUserSessionFlag)requires the application to tell ConfD/NCS which groups the user are member of.ConfD/NCS itself has the capability to authenticate users. It is possible for a MAAPI application to let ConfD/NCS authenticate the user, as per the AAA configuration in the system configuration file
- Parameters:
user-passwd-srcAddr-srcPort-context-proto-- Throws:
ConfExceptionIOException
-
getAuthorizationInfo
This method retrieves authorization info for a user session, i.e. the groups that the user has been assigned to.- Throws:
IOExceptionConfException
-
getRunningDbStatus
Query ConfD/NCS for its consistency state.If a transaction fails in the
commitphase, the configuration database is in in a possibly inconsistent state. This method queries ConfD/NCS on the consistency state.- Returns:
- 1 if the configuration is consistent and 0 otherwise.
- Throws:
ConfExceptionIOException
-
setRunningDbStatus
Explicitly sets the systems notion of the consistency state.- Throws:
ConfExceptionIOException
-
requestAction
public ConfXMLParam[] requestAction(ConfXMLParam[] params, String fmt, Object... arguments) throws IOException, ConfException Invokes an action defined in the data model annotated withtailf:action(see tailf_yang_extensions(5)).The input parameters is specified as
ConfXMLParamas the input arrayparamwhich corresponds to the input section of the action.The output parameters returned from the method call returns a array of
ConfXMLParamwhich corresponds to the output section of the action. Consider the following yang model:module cs { namespace "http://example.com/test/cs/1.0"; prefix cs; import tailf-common { prefix tailf; } typedef math_op { type enumeration { enum add; enum sub; enum mul; enum div; enum square; } } container system { list computer { key name; leaf name { type string; } tailf:action math { tailf:actionpoint math_cs; input { list operation { min-elements 1; max-elements 3; leaf number { type int32; mandatory true; } leaf type { type math_op; mandatory true; } leaf-list operands { type int16; } } } output { container result { presence ""; leaf number { type int32; mandatory true; } leaf type { type math_op; mandatory true; } leaf value { type int16; mandatory true; } } } } } } }The following is a example of how to assemble the action parameters into and array of ConfXMLParam and its subclasses:ConfNamespace n = new cs(); ConfXMLParam[] params = new ConfXMLParam[] { new ConfXMLParamStart(n, cs.cs_operation_), new ConfXMLParamValue(n, cs.cs_number_, new ConfInt32(13)), new ConfXMLParamValue(n, cs.cs_type_, new ConfEnumeration(0)), new ConfXMLParamValue(n, cs.cs_operands_, new ConfList(new ConfObject[] { new ConfInt16(13), new ConfInt16(25) })), new ConfXMLParamStop(n, cs.cs_operation_)};Using this we can call the action:Maapi maapi = Maapi(socket); maapi.setNamespace( maapi.startUserSession("admin", "maapi", new String[] { "admin" }, new SocketAddress(InetAddress.getLocalHost(), 0)); //Invokes the specified action with input arguments params //and returns the output parameters ConfXMLParam[] res = maapi.requestAction(params, "/system/computer{fred}/math");The path given by
fmtand the varargs list is the full path to the action, i.e. the final element must be the name of the action element in the YANG model.Since actions are not associated with transactions, the namespace must be provided and the path must be absolute transactions, the namespace must be provided and the path must be absolute - but see
requestActionTh(int,ConfXMLParam[],String,Object...).The
Maapiinstance must have an established user session before issue this method call.- Parameters:
params- action input parametersfmt- path string, this must be an absolute path with its root element prefixed .i.e "/prefix:tagname/...."arguments- optional parameters for substitution in fmt- Returns:
- array of ConfXMLParam as the output parameters
- Throws:
ConfException- If the methods invocation fails for some reason. The errorCode or message could be obtain throughgetErrorCode,getMessage()IOException- Signals that a I/O exception has occurred on the stream to ConfD/NCS
-
requestAction
public ConfXMLParam[] requestAction(List<ConfXMLParam> params, String fmt, Object... arguments) throws IOException, ConfException Same asrequestAction(ConfXMLParam[], String, Object...)with the difference that theparamsisListinstead ofConfXMLParamarray.The
Maapiinstance must have an established user session before issue this method call.- Parameters:
params- action input parameters asListfmt- path string, this must be an absolute path with its root element prefixed .i.e "/prefix:tagname/...."arguments- optional parameters for substitution in fmt- Returns:
- array of
ConfXMLParamas the output parameters - Throws:
ConfException- If the methods invocation fails for some reason. The errorCode or message could be obtain throughgetErrorCode,getMessage()IOException- Signals that a I/O exception has occurred on the stream to ConfD/NCS
-
requestAction
public ConfXMLParam[] requestAction(ConfXMLParam[] params, int nshash, String fmt, Object... arguments) throws IOException, ConfException Same asrequestAction(ConfXMLParam[], String, Object...)Since actions are not associated with transactions, the namespace hashnshashmust be provided and the path to the action, i.e. the final element must be the name of the action in the data model. absolute - but seerequestActionTh(int,ConfXMLParam[],String,Object...).- Parameters:
params- action parametersnshash- hashvalue for root namespace for the path represented by thefmtargumentfmt- path stringarguments- optional parameters for substitution in fmt- Returns:
- array of ConfXMLParam
- Throws:
ConfExceptionIOException
-
requestAction
public ConfXMLParam[] requestAction(List<ConfXMLParam> params, int nshash, String fmt, Object... arguments) throws IOException, ConfException - Throws:
IOExceptionConfException
-
requestActionTh
public ConfXMLParam[] requestActionTh(int tid, ConfXMLParam[] params, String fmt, Object... arguments) throws IOException, ConfException Same asrequestAction(ConfXMLParam[], String, Object...)with the difference that the fmt is not required to have a namespace prefix in the root tag. The root namespace is instead retrieved from the transaction indicated by the tid argument. Also, the user session of the transaction owner is used for the action invocation. This function may be convenient in some cases where actions are invoked in conjunction with a transaction, and it must be used if the action needs to access the transaction store.- Parameters:
tid- current transaction handleparams- action parametersfmt- path stringarguments- optional parameters for substitution in fmt- Returns:
- array of ConfXMLParam
- Throws:
IOExceptionConfException
-
requestActionTh
public ConfXMLParam[] requestActionTh(int tid, List<ConfXMLParam> params, String fmt, Object... arguments) throws IOException, ConfException - Throws:
IOExceptionConfException
-
snmpSendNotification
public void snmpSendNotification(String notifName, String notifyTarget, String ctxName, SnmpVarbind[] varbinds) throws ConfException Send SNMP notification.Sends a notification to the management targets defined for 'notifyTarget' in the snmpNotifyTable in SNMP-NOTIFICATION-MIB from the specified context. If no NotifyName is specified (or if it is ""), the notification is sent to all management targets.
- Parameters:
notifName- Notification namenotifyTarget- Notification target namectxName- Context name.varbinds- An array of variable bindings- Throws:
ConfException
-
CLIPrompt
Prompts user for a string.The echo parameter is used to control if the input should be echoed or not. If set to 'true' all input will be visible and if set to 'false' only stars will be shown instead of the actual characters entered by the user. The resulting string will be returned.
This function is intended to be called from inside an action callback when invoked from the CLI.
- Parameters:
usid- ID of sessionprompt- Prompt stringecho- If the answer should be echoed or not- Throws:
ConfExceptionIOException
-
CLIPrompt
public String CLIPrompt(int usid, String prompt, boolean echo, int timeout) throws ConfException, IOException Prompts user for a string.The echo parameter is used to control if the input should be echoed or not. If set to 'true' all input will be visible and if set to 'false' only stars will be shown instead of the actual characters entered by the user. The resulting string will be returned.
This function is intended to be called from inside an action callback when invoked from the CLI.
- Parameters:
usid- ID of sessionprompt- Prompt stringecho- If the answer should be echoed or nottimeout- Idle timeout in seconds- Throws:
ConfExceptionIOException
-
CLIPromptOneOf
public String CLIPromptOneOf(int usid, String prompt, String[] choice) throws ConfException, IOException Prompt user for one of the strings given in the choice parameter.For example:
String res = maapi.CLIPromptOneOf(usid, "Do you want to proceed (yes/no): ", new String[] { "yes", "no" });For example:Do you want to proceed (yes/no): maybe The value must be one of: yes,no. Do you want to proceed (yes/no):This function is intended to be called from inside an action callback when invoked from the CLI.- Parameters:
usid- ID of sessionprompt- Prompt stringchoice- An array of choices to accept from user- Throws:
ConfExceptionIOException
-
CLIPromptOneOf
public String CLIPromptOneOf(int usid, String prompt, String[] choice, int timeout) throws ConfException, IOException Prompt user for one of the strings given in the choice parameter.For example:
String res = maapi.CLIPromptOneOf(usid, "Do you want to proceed (yes/no): ", new String[] { "yes", "no" }, 60);For example:Do you want to proceed (yes/no): maybe The value must be one of: yes,no. Do you want to proceed (yes/no):This function is intended to be called from inside an action callback when invoked from the CLI.- Parameters:
usid- ID of sessionprompt- Prompt stringchoice- An array of choices to accept from usertimeout- Idle timeout in seconds- Throws:
ConfExceptionIOException
-
CLIReadEOF
Read a multi line string from the CLI.The user has to end the input using ctrl-D. The entered characters will be returned. The echo parameters controls if the entered characters should be echoed or not. If set to 'true' the answer will be visible and if set to 'false' stars will be echoed instead.
This method is intended to be called from inside an action call- back when invoked from the CLI.
- Throws:
ConfExceptionIOException
-
CLIReadEOF
Read a multi line string from the CLI.The user has to end the input using ctrl-D. The entered characters will be returned. The echo parameters controls if the entered characters should be echoed or not. If set to 'true' the answer will be visible and if set to 'false' stars will be echoed instead.
This function is intended to be called from inside an action call- back when invoked from the CLI.
- Throws:
ConfExceptionIOException
-
CLIWrite
Write to the CLI.This method is intended to be called from inside an action callback when invoked from the CLI.
- Parameters:
usid- ID of sessionbuf- Text to write to CLI- Throws:
ConfExceptionIOException
-
CLIAccounting
Generate an audit log entry in the CLI audit log.- Parameters:
user- username of sessionusid- ID of sessioncmd- Text to write to the audit log- Throws:
ConfExceptionIOException
-
CLIDiffCmd
public String CLIDiffCmd(int thandle, int thandleOld, ConfPath path) throws ConfException, IOException Get the diff between two transactions as C-/I-style CLI commands.- Parameters:
thandle- Transaction attached to MaapithandleOld- Another transactionpath- path- Throws:
ConfExceptionIOException
-
CLICmdToPath
Equivalent toCLICmdToPath(int, String)with the first parameter set to -1 (ie, the command is not interpreted in the context of any particular transaction)- Throws:
ConfExceptionIOException
-
CLICmdToPath
Given a C- or I-style command, this method tries to determine the corresponding namespace and path in the schema. Returns aCLICmdToPathResultobject, containing the resulting namespace and the data-model path.If the string cannot be interpreted as a path an exception is thrown, indicating that the string is either an operational mode command, a configuration mode command, or just badly formatted. The string is interpreted in the context of the current running configuration.
- Parameters:
th- transaction handlecmd- The command to interpret- Throws:
ConfExceptionIOException
-
CLIPathCmd
public String CLIPathCmd(int th, EnumSet<CLIPathCmdFlag> flags, String fmt, Object... args) throws ConfException, IOException Returns a string representing the C/I style CLI command that can be associated with the given path.- Parameters:
th- Transaction handleflags- Flags can be given as: EMIT_PARENTS to enable the commands to reach the submode for the path to be emitted. DELETE to emit the command to delete the given path. NON_RECURSIVE to prevent that all children to a container or list item are displayed.fmt- path to be formatted as CLI command- Throws:
ConfExceptionIOException
-
setReadOnlyMode
Control if the node should accept write transactions- Parameters:
flag- Mode- Throws:
ConfExceptionIOException
-
loadSchemas
Load Schemas method that downloads all schemas from server into a MaapiSchemas container, from which specified schemas can be accessed and traversed.When loaded the
MaapiSchemasobject is stored locally and new calls to this method will return the same instance.- Returns:
- MaapiSchemas object which is container for all downloaded schemas
- Throws:
MaapiException- if loading failsConfException
-
loadSchemas
Load Schemas method that downloads a specified number of schemas the server into a MaapiSchemas container, from which specified schemas can be accessed and transversed.When loaded the MaapiSchemas object is stored locally and new calls to this method will return the same instance.
- Parameters:
namespaceURIs- string array of URIs for the schemas to load- Returns:
- MaapiSchemas object which is container for all downloaded schemas
- Throws:
MaapiException- if loading failsConfException
-
getSchemas
Returns the currently loaded schema.- Returns:
- null if no schemas has been loaded.
-
reloadSchemas
This method throws away any old MaapiSchemas container and downloads a new from the server.Hence each call of this method will interact with the server.
- Returns:
- MaapiSchemas object which is container for all downloaded schemas
- Throws:
MaapiExceptionConfException
-
reloadSchemas
This method throws away any old MaapiSchemas container and downloads a new from the server.Which namespaces are loaded is specified and do not need to be the same as the earlier loaded that is viped out. This method can therefore unload old schemas and add loading of new schemas.
- Parameters:
namespaceURIs- string array of URIs for the schemas to load- Returns:
- MaapiSchemas object which is container for all downloaded schemas
- Throws:
MaapiExceptionConfException
-
setUserSession
Associate this Maapi instance with an already existing user session.This can be used instead
startUserSession(String, String, String[], SocketAddress, MaapiUserSessionFlag)when we really do not want to start a new user session, e.g. if we want to call an action on behalf of a given user session- Parameters:
usid- user session id- Throws:
MaapiExceptionConfExceptionIOException
-
loadConfigStream
public MaapiOutputStream loadConfigStream(int tid, EnumSet<MaapiConfigFlag> flags) throws ConfException, IOException Load configuration from aOuputStreaminto ConfD/NCS.This method loads a configuration from a
OutputStreaminto the server.The tid parameter is a transaction id. Thus the application must create and also apply the transaction. By default the complete configuration (as allowed by the user of the current transaction) is deleted before the file is loaded.
To merge the contents of the file use the
MaapiConfigFlag.MAAPI_CONFIG_MERGEflag. TheMaapiConfigFlag.MAAPI_CONFIG_WITH_OPERflag can be used together withMaapiConfigFlag.MAAPI_CONFIG_XMLto mean that any operational data in the file should be ignored (instead of producing an error).The other flags parameters are the same as for
saveConfig(int, EnumSet, String, Object...)- Parameters:
tid- transaction id for started transactionflags- One ofMAAPI_CONFIG_XML,MAAPI_CONFIG_J,MAAPI_CONFIG_C,MAAPI_CONFIG_WITH_DEFAULTS,MAAPI_CONFIG_SHOW_DEFAULTS,MAAPI_CONFIG_C_IOS,MAAPI_CONFIG_MERGEorMAAPI_CONFIG_WITH_OPER- Returns:
- OutputStream to write data to.
- Throws:
MaapiExceptionConfExceptionIOException
-
loadConfig
public void loadConfig(int tid, EnumSet<MaapiConfigFlag> flags, String filename) throws ConfException, IOException This function loads a configuration from filename into the server. The tid parameter is a transaction id. Thus the application must create and also apply the transaction. By default the complete configuration (as allowed by the user of the current transaction) is deleted before the file is loaded. To merge the contents of the file use the MAAPI_CONFIG_MERGE flag. The MAAPI_CONFIG_WITH_OPER flag can be used together with MAAPI_CONFIG_XML to mean that any operational data in the file should be ignored (instead of producing an error). The other flags parameters are the same as forsaveConfig(int, EnumSet, String, Object...)- Parameters:
tid- transaction id for started transactionflags- One ofMAAPI_CONFIG_XML,MAAPI_CONFIG_J,MAAPI_CONFIG_C,MAAPI_CONFIG_WITH_DEFAULTS,MAAPI_CONFIG_SHOW_DEFAULTS,MAAPI_CONFIG_C_IOS,MAAPI_CONFIG_MERGEorMAAPI_CONFIG_WITH_OPERfilename- name of the configuration file relative directory where ConfD/NCS started.- Throws:
MaapiExceptionConfExceptionIOException
-
loadConfigCmds
public void loadConfigCmds(int tid, EnumSet<MaapiConfigFlag> flags, String cmds, String fmt, Object... arguments) throws IOException, ConfException This function loads a configuration from a string into the server. By default the complete configuration (as allowed by the user of the current transaction) is deleted before the file is loaded. To merge the contents of the file use the MAAPI_CONFIG_MERGE flag. The MAAPI_CONFIG_WITH_OPER flag can be used together with MAAPI_CONFIG_XML to mean that any operational data in the file should be ignored (instead of producing an error). The other flags parameters are the same as forsaveConfig(int, EnumSet, String, Object...)- Parameters:
tid- transaction id for started transactionflags- One ofMAAPI_CONFIG_XML,MAAPI_CONFIG_J,MAAPI_CONFIG_C,MAAPI_CONFIG_WITH_DEFAULTS,MAAPI_CONFIG_SHOW_DEFAULTS,MAAPI_CONFIG_C_IOS,MAAPI_CONFIG_MERGEorMAAPI_CONFIG_WITH_OPERcmds- string representing the configuration to be loadedfmt- path relative to which the configuration should be loaded- Throws:
ConfExceptionIOException
-
saveConfig
public MaapiInputStream saveConfig(int tid, EnumSet<MaapiConfigFlag> flags, ConfPath path) throws ConfException, IOException Save the subtree in different formats.Retrieves an InputStreamfrom a given path specified byfmtwithflagsparameter which controls the format as follows:Flag Description Raw-XML MaapiConfigFlag.XML_FORMAT,MaapiConfigFlag.MAAPI_CONFIG_XMLThe configuration format is XML Pretty-XML MaapiConfigFlag.XML_PRETTY,MaapiConfigFlag.MAAPI_CONFIG_XML_PRETTYThe configuration format is pretty printed XML Juniper CLI format MaapiConfigFlag.MAAPI_CONFIG_J,MaapiConfigFlag.JUNIPER_CLI_FORMATThe configuration is in curly brace Juniper CLI format Cisco XR CLI format MaapiConfigFlag.MAAPI_CONFIG_C_IOS,MaapiConfigFlag.CISCO_XR_FORMATThe configuration is in Cisco XR style format Cisco IOS CLI format MaapiConfigFlag.MAAPI_CONFIG_C_IOS,MaapiConfigFlag.CISCO_IOS_FORMATThe configuration is in Cisco IOS style format The provided path indicates from where the configuration is to be rooted. If for example fmt is "/aaa:aaa/authentication/users" we only dump a part of the AAA data. It must be a prefix pre pended keypath.
By default, the treatment of nodes with a
tailf:hiddenstatement depends on the state of the transaction. For a transaction started via MAAPI, no nodes are hidden, while for a transaction started by another northbound agent (e.g. CLI) and attached to, the nodes that are hidden are the same as in that agent session. The default can be overridden by using one of the flagsMaapiConfigFlag.MAAPI_CONFIG_HIDE_ALLandMaapiConfigFlag.MAAPI_CONFIG_UNHIDE_ALL.By default, the NCS service-meta-data attributes (refcounter, backpointer, and original-value) are not included in the configuration. The flag
MaapiConfigFlag.MAAPI_CONFIG_WITH_SERVICE_METAcan be used to request that these attributes should be included.The library will initialize a new socket to the end point specified by the initial socket (which was created during initialization of this Maapi instance) thus it is up to the use
- Parameters:
tid- transaction id of the current transactionflags- format parameters (see the table above ) with additionalMAAPI_CONFIG_WITH_DEFAULTS,MAAPI_CONFIG_SHOW_DEFAULTSfor controlling the defaultsMAAPI_CONFIG_READ_WRITE_ACCESS_ONLYfor saving only nodes for which the user has read_write accesspath- path indicating where the configuration to be rooted- Returns:
- MaapiInputStream On success
- Throws:
ConfException- If the methods invocation fails for some reason. The errorCode or message could be obtain throughgetErrorCode,getMessage()IOException- Signals that a I/O exception has occurred on the stream to ConfD/NCS
-
saveConfig
public MaapiInputStream saveConfig(int tid, EnumSet<MaapiConfigFlag> flags) throws ConfException, IOException Save the entire config in different formats.Retrieves an InputStreamwithflagsparameter which controls the format as follows:Flag Description Raw-XML MaapiConfigFlag.XML_FORMAT,MaapiConfigFlag.MAAPI_CONFIG_XMLThe configuration format is XML Pretty-XML MaapiConfigFlag.XML_PRETTY,MaapiConfigFlag.MAAPI_CONFIG_XML_PRETTYThe configuration format is pretty printed XML Juniper CLI format MaapiConfigFlag.MAAPI_CONFIG_J,MaapiConfigFlag.JUNIPER_CLI_FORMATThe configuration is in curly brace Juniper CLI format Cisco XR CLI format MaapiConfigFlag.MAAPI_CONFIG_C_IOS,MaapiConfigFlag.CISCO_XR_FORMATThe configuration is in Cisco XR style format Cisco IOS CLI format MaapiConfigFlag.MAAPI_CONFIG_C_IOS,MaapiConfigFlag.CISCO_IOS_FORMATThe configuration is in Cisco IOS style format By default, the treatment of nodes with a
tailf:hiddenstatement depends on the state of the transaction. For a transaction started via MAAPI, no nodes are hidden, while for a transaction started by another northbound agent (e.g. CLI) and attached to, the nodes that are hidden are the same as in that agent session. The default can be overridden by using one of the flagsMaapiConfigFlag.MAAPI_CONFIG_HIDE_ALLandMaapiConfigFlag.MAAPI_CONFIG_UNHIDE_ALL.Entire configuration is dumped, except that namespaces with restricted export (from 'confdc/ncsc --export') are treated as follows:
When the
MAAPI_CONFIG_XMLorMAAPI_CONFIG_XML_PRETTYformats are used, the context of the user session that started the transaction is used to select namespaces with restricted export. If the "system" context is used, all namespaces are selected, regardless of export restriction.When one of the CLI formats is used, the context used to select namespaces with restricted export is always "CLI".
The library will initialize a new socket to the end point specified by the initial socket (which was created during initialization of this Maapi instance) thus it is up to the use
- Parameters:
tid- transaction id of the current transactionflags- format parameters (see the table above ) with additionalMAAPI_CONFIG_WITH_DEFAULTS,MAAPI_CONFIG_SHOW_DEFAULTSfor controlling the defaults- Returns:
- MaapiInputStream On success
- Throws:
ConfException- If the methods invocation fails for some reason. The errorCode or message could be obtain throughgetErrorCode,getMessage()IOException- Signals that a I/O exception has occurred on the stream to ConfD/NCS- See Also:
-
saveConfig
public MaapiInputStream saveConfig(int tid, EnumSet<MaapiConfigFlag> flags, String fmt, Object... args) throws ConfException, IOException Save the subtree in different formats, with ability to XPath Filtering.Retrieves an InputStreamfrom a given path specified byfmtwithflagsparameter which controls the format as follows:Flag Description Raw-XML MaapiConfigFlag.XML_FORMAT,MaapiConfigFlag.MAAPI_CONFIG_XMLThe configuration format is XML Pretty-XML MaapiConfigFlag.XML_PRETTY,MaapiConfigFlag.MAAPI_CONFIG_XML_PRETTYThe configuration format is pretty printed XML Juniper CLI format MaapiConfigFlag.MAAPI_CONFIG_J,MaapiConfigFlag.JUNIPER_CLI_FORMATThe configuration is in curly brace Juniper CLI format Cisco XR CLI format MaapiConfigFlag.MAAPI_CONFIG_C_IOS,MaapiConfigFlag.CISCO_XR_FORMATThe configuration is in Cisco XR style format Cisco IOS CLI format MaapiConfigFlag.MAAPI_CONFIG_C_IOS,MaapiConfigFlag.CISCO_IOS_FORMATThe configuration is in Cisco IOS style format The provided path indicates from where the configuration is to be rooted. If for example fmt is "/aaa:aaa/authentication/users" we only dump a part of the AAA data. It must be a prefix pre pended keypath.
By default, the treatment of nodes with a
tailf:hiddenstatement depends on the state of the transaction. For a transaction started via MAAPI, no nodes are hidden, while for a transaction started by another northbound agent (e.g. CLI) and attached to, the nodes that are hidden are the same as in that agent session. The default can be overridden by using one of the flagsMaapiConfigFlag.MAAPI_CONFIG_HIDE_ALLandMaapiConfigFlag.MAAPI_CONFIG_UNHIDE_ALL.For
MAAPI_CONFIG_XMLandMAAPI_CONFIG_XML_PRETTYit is alternatively possible to give an XPath filter, by including the flagMaapiConfigFlag.MAAPI_CONFIG_XPATH.The library will initialize a new socket to the end point specified by the initial socket (which was created during initialization of this Maapi instance) thus it is up to the user to close the returning InputStream after reading the configuration.
- Parameters:
tid- transaction id of the current transactionflags- format parameters (see the table above ) with additionalMAAPI_CONFIG_WITH_DEFAULTS,MAAPI_CONFIG_SHOW_DEFAULTSfor controlling the defaultsfmt- path indicating where the configuration to be rootedargs- variable argument list for c-style parameters in fmt- Returns:
- MaapiInputStream On success the library will initialize a new socket which is intended to be closed after usage of this method by the user
- Throws:
ConfException- If the methods invocation fails for some reason. The errorCode or message could be obtain throughgetErrorCode,getMessage()IOException- Signals that a I/O exception has occurred on the stream to ConfD/NCS- See Also:
-
rollbackConfig
This function can be used to save the equivalent of a rollback file for a given configuration before it is committed (or a subtree thereof) in curly bracket format. The provided path indicates where we want the configuration to be rooted. It must be a prefix pre pended keypath. If fmt is null, a rollback config for the entire configuration is dumped. If for example fmt is "/aaa:aaa/authentication/users" we create a rollback config for a part of the AAA data. It is not possible to extract non-config data using this function. The data is returned as a MaapiInputStream that is used to download the configuration @see MaapiInputStream- Parameters:
tid- transaction id for current transactionfmt- path indicating where the configuration to be rootedargs- variable argument list for c-style parameters in fmtPath- Returns:
- MaapiInputStream
- Throws:
MaapiException
-
isCandidateModified
Returns true if candidate has been modified, i.e if there are pending non committed changes to the candidate data store. false if it has not been modified.- Returns:
- boolean
- Throws:
IOExceptionConfException
-
reportProgress
public void reportProgress(int tid, Maapi.Verbosity verbosity, String msg) throws IOException, ConfException Report progress of an action or transaction.- Parameters:
tid- transaction handleverbosity- at which verbosity level the message should be reportedmsg- the message to report- Throws:
IOExceptionConfException
-
event
public void event(int tid, Maapi.Verbosity verbosity, String msg, ConfPath path, Attributes attributes) throws IOException, InvalidParameterException, ConfException Create a progress event. This is the low level method that communicates with the progress trace framework to create events. It is recommended to useProgressTrace.event(java.lang.String)instead.- Parameters:
tid- the transasction IDverbosity- the verbosity of the messagemsg- the message contentpath- the path of the serviceattributes- attribute of the event- Throws:
IOExceptionConfExceptionInvalidParameterException
-
startSpan
public Span startSpan(int tid, Maapi.Verbosity verbosity, String msg, ConfPath path, Attributes attributes, Span[] links) throws IOException, InvalidParameterException, ConfException Create a progress span. This is the low level method that communicates with the progress trace framework to create spans. It is recommended to useProgressTrace.startSpan(java.lang.String)instead.- Parameters:
tid- the transasction IDverbosity- the verbosity of the messagemsg- the message contentpath- the path of the serviceattributes- attribute of the eventlinks- lists of spans that this span links to- Throws:
IOExceptionConfExceptionInvalidParameterException
-
endSpan
End progress span. This is the low level method that communicates with the progress trace framework to end spans. It is recommended to useProgressTrace.endSpan(com.tailf.progress.Span)instead.- Parameters:
span- the span returned fromstartSpan(int,com.tailf.maapi.Maapi.Verbosity,java.lang.String,com.tailf.conf.ConfPath,com.tailf.progress.Attributes,com.tailf.progress.Span[])annotation- annotation of the ending span- Throws:
IOExceptionConfException
-
ncsTemplates
- Throws:
IOExceptionConfException
-
ncsApplyTemplate
public void ncsApplyTemplate(int tid, String template, ConfPath rootIKP, Properties variables, boolean createShared) throws IOException, ConfException - Throws:
IOExceptionConfException
-
ncsApplyTemplate
public void ncsApplyTemplate(int tid, String template, ConfPath rootIKP, Properties variables, String document, boolean createShared) throws IOException, ConfException - Throws:
IOExceptionConfException
-
ncsGetTemplateVariables
- Throws:
IOExceptionConfException
-
initUpgrade
Note, This method is only applicable for Confd. For NCS, the In-service Data Model Upgrades are directly correlated to NCS packages and have more high-level support. This is the first of three functions that must be called in sequence to perform an in-service data model upgrade, i.e. replace fxs files etc without restarting the server. See the In-service Data Model Upgrade chapter in the Confd User Guide for a detailed description of this procedure. This function initializes the upgrade procedure. The timeoutsecs parameter specifies a maximum time to wait for users to voluntarily exit from "configure mode" sessions in CLI and Web UI. If transactions are still active when the timeout expires, the function throw an ConfException. If the flag MAAPI_UPGRADE_KILL_ON_TIMEOUT was given via the flags parameter, such transactions will instead be forcibly terminated, allowing the initialization to complete successfully.- Parameters:
timeoutsecs- specifies a maximum time to wait for users to exitflags- bitflags for control of upgrade behavior- Throws:
IOExceptionConfException
-
performUpgrade
Note, This method is only applicable for Confd. For NCS, the In-service Data Model Upgrades are directly correlated to NCS packages and have more high-level support. When initUpgrade() has completed successfully, this function must be called to instruct the server to load the new data model files. The loadpathdirs parameter is an array of n strings that specify the directories to load from.- Parameters:
loadpathdirs- array of directories- Throws:
IOExceptionConfException
-
commitUpgrade
Note, This method is only applicable for Confd. For NCS, the In-service Data Model Upgrades are directly correlated to NCS packages and have more high-level support. When also performUpgrade() has completed successfully, this function must be called to make the upgrade permanent. This includes committing the CDB upgrade transaction when CDB is used, and we can thus get all the different exceptions that can otherwise result from applyTrans(). When commitUpgrade() has completed successfully, the program driving the upgrade must also make sure that the loadpath elements in confd.conf reference the new directories.- Throws:
IOExceptionConfException
-
abortUpgrade
Note, This method is only applicable for Confd. For NCS, the In-service Data Model Upgrades are directly correlated to NCS packages and have more high-level support. Calling this function at any point before the call of commitUpgrade() will abort the upgrade. Note! abortUpgrade() should NOT be called if any of the three previous functions fail - in that case, the server will do an internal abort of the upgrade.- Throws:
IOExceptionConfException
-
getAttrs
public ConfAttributeValue[] getAttrs(int tid, ConfAttributeType[] attribs, String fmt, Object... args) throws IOException, ConfException Retrieve attributes for a configuration node. These attributes are currently supported: ConfAttributeType.TAGS (values are ConfList of ConfBuf) ConfAttributeType.ANNOTATION (value is ConfBuf) ConfAttributeType.INACTIVE (not used) ConfAttributeType.ORIGIN (value is ConfIdentityRef) The attribs parameter is an array of ConfAttributeType objects, specifying the wanted attributes - if the array is empty or attribs is null, all attributes are retrieved. If no attributes are found, the returned ConfAttributeValue array is empty otherwise the result array is populated.- Parameters:
tid- current transactionattribs- array of ConfAttributeType denoting attributes to retrievefmt- path indicating node to retrieve attributes fromargs- variable argument list for c-style parameters in fmtPath- Returns:
- ConfAttributeValue[]
- Throws:
IOExceptionConfException
-
setAttr
public void setAttr(int tid, ConfAttributeValue attr, String fmt, Object... args) throws IOException, ConfException Set an attribute for a configuration node. See getAttrs() above for the supported attributes. if the attribute should be removed the ConfAttributeValue should be set attr.isRemoveValue()- Parameters:
tid- current transactionattr- ConfAttributeValue object denoting the attribute to setfmt- path indicating node to retrieve attributes fromargs- variable argument list for c-style parameters in fmtPath- Throws:
IOExceptionConfException
-
setFlags
This method can modify some aspects of the read/write session, see MaapiFlag The flags are an Enumset ofMaapiFlag- Parameters:
tid- current transactionflags- Enumset ofMaapiFlag- Throws:
IOExceptionConfException
-
getCwd
Returns the current position as previously set by Maapi.cd(), Maapi.pushd(), or Maapi.popd() as a String. Note that what is returned is a pretty-printed version of the internal representation of the current position, it will be the shortest unique way to print the path but it might not exactly match the string given to Maapi.cd()- Parameters:
tid- current transaction- Returns:
- String
- Throws:
IOExceptionConfException
-
getCwdPath
Returns the current position like Maapi.getCwd(), but as a ConfPath instead of as a String.- Parameters:
tid- current transaction- Returns:
- ConfPath
- Throws:
IOExceptionConfException
-
isRunningModified
Returns true if running has been modified since the last copy to startup, false if it has not been modified.- Returns:
- boolean
- Throws:
IOExceptionConfException
-
doDisplay
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 in fmt should be displayed or not.- Parameters:
tid- current transactionfmt- path stringargs- optional parameters for substitution in fmt- Returns:
- boolean
- Throws:
IOExceptionConfException
-
userMessage
Send a message to a specific user, a specific user session or all users depending on the to parameter. If set to a user name, then message will be delivered to all CLI and Web UI sessions by that user. If set to an integer string, eg "10", then message will be delivered to that specific user session, CLI or Web UI. If set to "all" then all users will get the message.- Parameters:
to- username, integer string session no or "all" for all usersmessage- string message to sendsender- string- Throws:
IOExceptionConfException
-
sysMessage
Send a message to a specific user, a specific user session or all users depending on the to parameter. If set to a user name, then message will be delivered to all CLI and Web UI sessions by that user. If set to an integer string, eg "10", then message will be delivered to that specific user session, CLI or Web UI. If set to "all" then all users will get the message. No formatting of the message is performed as opposed to the user message where a timestamp and sender information is added to the message.- Parameters:
to- username, integer string session no or "all" for all usersmessage- string message to send- Throws:
IOExceptionConfException
-
prioMessage
Send a high priority message to a specific user, a specific user session or all users depending on the to parameter. If set to a user name, then message will be delivered to all CLI and Web UI sessions by that user. If set to an integer string, eg "10", then message will be delivered to that specific user session, CLI or Web UI. If set to "all" then all users will get the message. No formatting of the message is performed as opposed to the user message where a timestamp and sender information is added to the message. The message will not be delayed until the user terminates any ongoing command but will be output directly to the terminal without delay. Messages sent using the maapi_sys_message and maapi_user_message, on the other hand, are not displayed in the middle of some other output but delayed until the any ongoing commands have terminated.- Parameters:
to- username, integer string session no or "all" for all usersmessage- string message to send- Throws:
IOExceptionConfException
-
disconnectRemote
Disconnect all remote connections between CONFD_IPC_PORT (see the IPC section in the Advanced Topics chapter in the User Guide) and address. Since clients, e.g. CDB readers/subscribers, are connected using TCP it is also possible to do this remotely over a network. However since TCP does not offer a fast and reliable way of detecting that the other end has disappeared the server can get stuck waiting for a reply from such a disconnected client. In some environments there will be an alternative supervision method that can detect when a remote host is unavailable, and in that situation this function can be used to instruct the server to drop all remote connections to a particular host. The address parameter is an IP address as a string. On success, the function returns the number of connections that were closed. Note, the server will close all its sockets with remote address address, except HA connections.- Parameters:
address-- Throws:
IOExceptionConfException
-
disconnectSockets
This function is an alternative todisconnectRemote()that can be useful in particular when using the "External IPC" functionality (see "Using a different IPC mechanism" in the ConfD IPC section in the Advanced Topics chapter in the User Guide). In this case ConfD does not have any knowledge of the remote address of the IPC connections, and thusdisconnectRemote()is not applicable.disconnectSockets()instead takes an array of file descriptor numbers as the parameter. ConfD will close all connected sockets whose local file descriptor number is included that array.- Parameters:
sockets- The array of socket file descriptors to close- Throws:
IOExceptionMaapiExceptionConfException
-
getCLIInteraction
Get CLIInteraction object which enables communication with the user via the CLI. This function is intended to be called from inside an action callback when invoked from the CLI.- Parameters:
usid- user session id- Returns:
- CLIInteraction
-
xpath2kpath
Convert a XPath path to a ConfPath object. The XPath expression must be an "instance identifier", i.e. all elements and keys must be fully specified. Namespace prefixes are optional, unless required to resolve ambiguities (e.g. when multiple namespaces have the same root element).- Parameters:
xpath-- Returns:
- ConfPath
- Throws:
IOExceptionConfException
-
xpath2kpath_th
- Throws:
IOExceptionConfException
-
xpathEval
public void xpathEval(int tid, MaapiXPathEvalResult xpatheval, MaapiXPathEvalTrace xpathtrace, String expr, Object initstate, String fmt, Object... arguments) throws IOException, ConfException Evaluated the xpath expression as supplied in by
For each node in the resulting node set theexpr.result(ConfObject[],ConfValue,Object)method of @see MaapiXPathEvalResult is called with the keypath (asConfObject[]) to the resulting node as the first argument, and, if the node is a leaf and has a value (asConfValue), the value of that node as the second argument otherwise it will return the string "undefined".The expression will be evaluated using the root node as the context node, unless a path to an existing node is given as the fmt argument.
For each invocation the
resultmethod should returnITER_CONTINUEto tell the xpath evaluator to continue with the next resulting node. To stop the evaluation the result can returnITER_STOPinstead. TheMaapiXPathEvalTraceimplementation of a methodtrace(String)that takes a single string as argument.If supplied (optional) it will be invoked when the xpath evaluator has trace output for the current expression.
Theinitstateparameter can be used for any user supplied opaque data (i.e. whatever is supplied as initstate is passed as state to theresultmethod for each invocation).- Parameters:
tid- Transaction handlexpatheval- A implementation ofMaapiXPathEvalResultcallback methodxpathtrace- A implementation ofMaapiXPathEvalTraceor null if no trace is wantedexpr- The XPath expressionfmt- Path string (context node) root if not suppliedarguments- Optional parameters for substitution in fmt- Throws:
MaapiException- Failed MaapiXPathEvaluateIOException- Failed to read/write maapi socketConfException
-
xpathEvalExpr
public String xpathEvalExpr(int tid, String expr, MaapiXPathEvalTrace xpathtrace, String fmt, Object... arg) throws IOException, ConfException Evaluate the xpath expression given inexprparameter and return the result as a string.It is possible to supply a path
fmt(optional) which will be treated as the initial context node when evaluatingexpr.If the path is relative, this is treated as the starting point, and this is also the node that
current()will return when used in the xpath expression.If null is given, the current maapi position is used (set by
cd(int,String,Object...))The
MaapiXPathEvalTraceimplementation of the methodtrace(String)which takes a single string as argument (optional) will be invoked if supplied (optional) when the xpath implementation has trace output for the current expression.- Parameters:
tid- Transaction handleexpr- The xpath expressionxpathtrace- A implementation ofMaapiXPathEvalTraceor null if no trace is wanted A implementation ofMaapiXPathEvalTraceor null if no trace is wantedfmt- Path string (context node) root if not suppliedarg- Optional parameters for substitution in fmt- Throws:
ConfException- Failed MaapiXPathEvaluateIOException- Failed to read/write maapi socket
-
netconfSSHCallHome
Request that ConfD daemon initiates a NETCONF SSH Call Home connection (see RFC 8071) to the NETCONF client running on host.- Parameters:
host- The ip address or hostname of the clientport- The port the client listens to- Throws:
IOExceptionConfException
-
netconfSSHCallHomeOpaque
public void netconfSSHCallHomeOpaque(ConfObject host, String opaque, int port) throws IOException, ConfException Request that ConfD daemon initiates a NETCONF SSH Call Home connection (see RFC 8071) to the NETCONF client running on host.- Parameters:
host- The ip address or hostname of the clientopaque- String passed to an external SSH Call Home sessionport- The port the client listens to- Throws:
IOExceptionConfException
-
aaaReload
When the ConfD/NCS AAA tree is populated by an external data provider, this method can be used by the data provider to notify ConfD/NCS when there is a change to the AAA data. I.e. it is an alternative to executing the commandconfd --clear-aaa-cacheorncs --clear-aaa-cache.- Parameters:
synchronous- Whether to wait for the daemon to complete reloading the AAA data before returning.- Throws:
IOExceptionConfException
-
snmpaReload
When the ConfD/NCS SNMP Agent config tree is implemented by an external data provider, this method can be used by the data provider to notify ConfD/NCS when there is a change to the data.- Parameters:
synchronous- Whether to wait for the daemon to complete reloading the data before returning.- Throws:
IOExceptionConfException
-
startPhase
Once the ConfD/NCS daemon has been started in phase0 it is possible to use this function to tell the daemon to proceed to start phase 1 or 2.- Parameters:
phase- Which start phase to proceed to, 1 or 2synchronous- Whether to wait for the daemon to complete the transition to the requested start phase or return immediately.- Throws:
IOExceptionConfException
-
startPhase
Once the ConfD/NCS daemon has been started in phase0 it is possible to use this function to tell the daemon to proceed to startPhase 1 or 2. Upon return the daemon has completed the transition.- Parameters:
phase- Which start phase to proceed to, 1 or 2- Throws:
IOExceptionConfException
-
waitStart
Wait until the daemon has completed a certain start phase.- Parameters:
phase- Which start phase to wait for: 0, 1, or 2- Throws:
IOExceptionConfException
-
waitStarted
Wait until the daemon is fully started, i.e. has completed start phase 2.- Throws:
IOExceptionConfException
-
reloadConfig
Request that the daemon reloads its configuration files. The daemon will also close and re-open its log-files.- Throws:
IOExceptionConfException
-
reopenLogs
Request that the daemon closes and re-opens its log files- Throws:
IOExceptionConfException
-
stop
Stops the daemon. Upon return the connection to the daemon will be closed.- Parameters:
synchronous- Whether to wait for the daemon to stop- Throws:
IOExceptionConfException
-
stop
Requests that the daemon stops, returns when daemon has stopped.- Throws:
IOExceptionConfException
-
getSocket
-
close
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException
-
getAutoNsList
- Returns:
- the currently auto generated namespace list.
-
getAutoNsMap
- Returns:
- the currently auto generated namespace map keyed on the namespace hash.
-
getAutoNsPrefixMap
- Returns:
- the currently auto generated namespace prefix map. The namespace prefix map maps namespace prefixes to namespaces.
-
getAutoNsList
- Returns:
- the currently auto generated namespace list or supplied default if no auto generated exists.
-
queryStart
public <T extends ResultType> QueryResult<T> queryStart(int tid, String expr, String context, int chunkSize, int offset, List<String> select, List<String> sort, boolean reverseSortOrder, Class<T> cls) throws IOException, ConfException Initiate (or starts) a new XPath query attached to the transaction given inth.If successful a
QueryResultis returned which represents a query result.The XPath
exprstring parameter is a primary XPath expression which must evaluate to a node-set, the "results". For each node in the results node-set every "select" expression is evaluated with the result node as its context. For example, given the YANG snippet:list interface { key name; unique number; leaf name { type string; } leaf number { type uint32; mandatory true; } leaf enabled { type boolean; default true; } ... }and given that we want to find the name and number of all enabled interfaces - the expr could be"/interface[enabled='true']", and the select expressions would be{ "name","number" }.Note that the select expressions can have any valid XPath expression, so if you wanted to find out an interfaces name, and whether its number is even or not, the expressions would be:
{ "name", "(number mod 2) == 0" }.The
selectparameter determining what to include in the result.The
chunksizeis the possibility to return the result in groups of a particular size. This option determines the fetch frequency for a iterator.The "chunk" retrieval is done by the
QueryResult.iterator()iterator which process result locally and when it needs more data it retrieve the next chunk (if available).The
offsetis the number of the first result in this chunk (i.e. for the first chunk it will be 1).If the underlying database supports multiple "tables" there is usually also support for "join" (the ability to make a filter span several tables), in ConfD/NCS this is usually not an issue - reference to "other" tables are naturally done using leafref, and thus it is possible to filter on "foreign keys" (to use SQL terminology).
- Parameters:
tid- transaction handleexpr- XPath expressioncontext- A context nodechunkSize- Result chunksize to fetchoffset- The offset to start fetchselect- A list of XPath "select" expressionssort- A list of XPath exressions used for sortingreverseSortOrder- Set this to true to get items in the reverse order (only if "sort" is specified)cls- Result type- Returns:
- A QueryResult where resulting nodes and values could be fetched.
- Throws:
IOException- if the underlying socket or input stream is closed for some reasonConfException- if the XPath parser encounters error for some reason
-
queryStart
public <T extends ResultType> QueryResult<T> queryStart(int tid, String expr, String context, int chunkSize, int offset, List<String> select, Class<T> cls) throws IOException, ConfException Initiate (or starts) a new XPath query attached to the transaction given intid.Runs an XPath query with default sort order
If successful a
QueryResultis returned which represents a query result.- Parameters:
tid- transaction handleexpr- XPath expressioncontext- A context nodechunkSize- Result chunksize to fetchoffset- The offset to start fetchselect- A list of XPath "select" expressionscls- Result type- Returns:
- A QueryResult where resulting nodes and values could be fetched.
- Throws:
IOException- if the underlying socket or input stream is closed for some reasonConfException- if the XPath parser encounters error for some reason
-
setDelayedWhen
This function enables/disables the "delayed when" mode of a transaction. When successful, it returns true/false as indication of whether "delayed when" was enabled or disabled before the call. The YANG when statement makes its parent data definition statement conditional. This can be problematic in cases where we don't have control over the order of writing different data nodes. E.g. when loading configuration from a file, the data that will satisfy the when condition may occur after the data that the when applies to, making it impossible to actually write the latter data into the transaction - since the when isn't satisifed, the data nodes effectively do not exist in the schema. This is addressed by the "delayed when" mode for a transaction. When "delayed when" is enabled, it is possible to write to data nodes even though they are conditional on a when that isn't satisfied. It has no effect on reading though - trying to read data that is conditional on an unsatisfied when will always result in ConfNoExists value or equivalent. When disabling "delayed when", any "delayed" when statements will take effect immediately - i.e. if the when isn't satisfied at that point, the conditional nodes and any data values for them will be deleted. If we don't explicitly disable "delayed when" by calling this function, it will be automatically disabled when the transaction enters the VALIDATE state (e.g. due to call ofapplyTrans(int, boolean).- Parameters:
tid- transaction idon- true if "delayed when" mode should be activated, false if "delayed when" mode should be deactivated.- Returns:
- true if "delayed when" was active before this call, otherwise false
- Throws:
IOExceptionConfException
-
clearOpCache
Same asclearOpCache(ConfPath), with the only difference that if clears all cached data from "/" and down.- Throws:
IOExceptionConfException
-
clearOpCache
Request clearing of the operational data cache (see the Operational Data the User Guide). A ConfPath argument is given to the top of the subtree for which cached data should be cleared- Parameters:
path- ConfPath to the subtree for which cached data should be cleared- Throws:
IOExceptionConfException
-
getMountId
- Throws:
ConfException
-
getSource
- Throws:
UnknownHostException
-
toString
-
hideGroup
Hide all nodes belonging to a hide group in a transaction that started withMaapiFlag.HIDE_ALL_HIDEGROUPSflag.- Parameters:
tid- Transaction IdentifiergroupName- Group Name- Throws:
MaapiExceptionIOExceptionConfException
-
unhideGroup
Unhide all nodes belonging to a hide group in a transaction that started withMaapiFlag.HIDE_ALL_HIDEGROUPSflag.- Parameters:
tid- Transaction IdentifiergroupName- Group Name- Throws:
MaapiExceptionIOExceptionConfException
-
startUserSession(String, String, String[], SocketAddress, MaapiUserSessionFlag)instead.