1 .. _controller-dev-guide:
9 OpenDaylight Controller is Java-based, model-driven controller using
10 YANG as its modeling language for various aspects of the system and
11 applications and with its components serves as a base platform for other
12 OpenDaylight applications.
14 The OpenDaylight Controller relies on the following technologies:
16 - **OSGI** - This framework is the back-end of OpenDaylight as it
17 allows dynamically loading of bundles and packages JAR files, and
18 binding bundles together for exchanging information.
20 - **Karaf** - Application container built on top of OSGI, which
21 simplifies operational aspects of packaging and installing
24 - **YANG** - a data modeling language used to model configuration and
25 state data manipulated by the applications, remote procedure calls,
28 The OpenDaylight Controller provides following model-driven subsystems
29 as a foundation for Java applications:
31 - **`Config Subsystem <#_config_subsystem>`__** - an activation,
32 dependency-injection and configuration framework, which allows
33 two-phase commits of configuration and dependency-injection, and
34 allows for run-time rewiring.
36 - **`MD-SAL <#_md_sal_overview>`__** - messaging and data storage
37 functionality for data, notifications and RPCs modeled by application
38 developers. MD-SAL uses YANG as the modeling for both interface and
39 data definitions, and provides a messaging and data-centric runtime
40 for such services based on YANG modeling.
42 - **MD-SAL Clustering** - enables cluster support for core MD-SAL
43 functionality and provides location-transparent accesss to
46 The OpenDaylight Controller supports external access to applications and
47 data using following model-driven protocols:
49 - **NETCONF** - XML-based RPC protocol, which provides abilities for
50 client to invoke YANG-modeled RPCs, receive notifications and to
51 read, modify and manipulate YANG modeled data.
53 - **RESTCONF** - HTTP-based protocol, which provides REST-like APIs to
54 manipulate YANG modeled data and invoke YANG modeled RPCs, using XML
55 or JSON as payload format.
62 The Model-Driven Service Adaptation Layer (MD-SAL) is message-bus
63 inspired extensible middleware component that provides messaging and
64 data storage functionality based on data and interface models defined by
65 application developers (i.e. user-defined models).
69 - Defines a **common-layer, concepts, data model building blocks and
70 messaging patterns** and provides infrastructure / framework for
71 applications and inter-application communication.
73 - Provide common support for user-defined transport and payload
74 formats, including payload serialization and adaptation (e.g. binary,
77 The MD-SAL uses **YANG** as the modeling language for both interface and
78 data definitions, and provides a messaging and data-centric runtime for
79 such services based on YANG modeling.
81 | The MD-SAL provides two different API types (flavours):
83 - **MD-SAL Binding:** MD-SAL APIs which extensively uses APIs and
84 classes generated from YANG models, which provides compile-time
87 - **MD-SAL DOM:** (Document Object Model) APIs which uses DOM-like
88 representation of data, which makes them more powerful, but provides
89 less compile-time safety.
93 Model-driven nature of the MD-SAL and **DOM**-based APIs allows for
94 behind-the-scene API and payload type mediation and transformation
95 to facilitate seamless communication between applications - this
96 enables for other components and applications to provide connectors
97 / expose different set of APIs and derive most of its functionality
98 purely from models, which all existing code can benefit from without
99 modification. For example **RESTCONF Connector** is an application
100 built on top of MD-SAL and exposes YANG-modeled application APIs
101 transparently via HTTP and adds support for XML and JSON payload
107 Basic concepts are building blocks which are used by applications, and
108 from which MD-SAL uses to define messaging patterns and to provide
109 services and behavior based on developer-supplied YANG models.
112 All state-related data are modeled and represented as data tree,
113 with possibility to address any element / subtree
115 - **Operational Data Tree** - Reported state of the system,
116 published by the providers using MD-SAL. Represents a feedback
117 loop for applications to observe state of the network / system.
119 - **Configuration Data Tree** - Intended state of the system or
120 network, populated by consumers, which expresses their intention.
123 Unique identifier of node / subtree in data tree, which provides
124 unambiguous information, how to reference and retrieve node /
125 subtree from conceptual data trees.
128 Asynchronous transient event which may be consumed by subscribers
129 and they may act upon it
132 asynchronous request-reply message pair, when request is triggered
133 by consumer, send to the provider, which in future replies with
138 In MD-SAL terminology, the term *RPC* is used to define the
139 input and output for a procedure (function) that is to be
140 provided by a provider, and mediated by the MD-SAL, that means
141 it may not result in remote call.
146 MD-SAL provides several messaging patterns using broker derived from
147 basic concepts, which are intended to transfer YANG modeled data between
148 applications to provide data-centric integration between applications
149 instead of API-centric integration.
151 - **Unicast communication**
153 - **Remote Procedure Calls** - unicast between consumer and
154 provider, where consumer sends **request** message to provider,
155 which asynchronously responds with **reply** message
157 - **Publish / Subscribe**
159 - **Notifications** - multicast transient message which is published
160 by provider and is delivered to subscribers
162 - **Data Change Events** - multicast asynchronous event, which is
163 sent by data broker if there is change in conceptual data tree,
164 and is delivered to subscribers
166 - **Transactional access to Data Tree**
168 - Transactional **reads** from conceptual **data tree** - read-only
169 transactions with isolation from other running transactions.
171 - Transactional **modification** to conceptual **data tree** - write
172 transactions with isolation from other running transactions.
174 - **Transaction chaining**
176 MD-SAL Data Transactions
177 ------------------------
179 MD-SAL **Data Broker** provides transactional access to conceptual
180 **data trees** representing configuration and operational state.
184 **Data tree** usually represents state of the modeled data, usually
185 this is state of controller, applications and also external systems
188 **Transactions** provide **`stable and isolated
189 view <#_transaction_isolation>`__** from other currently running
190 transactions. The state of running transaction and underlying data tree
191 is not affected by other concurrently running transactions.
194 Transaction provides only modification capabilities, but does not
195 provide read capabilities. Write-only transaction is allocated using
196 ``newWriteOnlyTransaction()``.
200 This allows less state tracking for write-only transactions and
201 allows MD-SAL Clustering to optimize internal representation of
202 transaction in cluster.
205 Transaction provides both read and write capabilities. It is
206 allocated using ``newReadWriteTransaction()``.
209 Transaction provides stable read-only view based on current data
210 tree. Read-only view is not affected by any subsequent write
211 transactions. Read-only transaction is allocated using
212 ``newReadOnlyTransaction()``.
216 If an application needs to observe changes itself in data tree,
217 it should use **data tree listeners** instead of read-only
218 transactions and polling data tree.
220 Transactions may be allocated using the **data broker** itself or using
221 **transaction chain**. In the case of **transaction chain**, the new
222 allocated transaction is not based on current state of data tree, but
223 rather on state introduced by previous transaction from the same chain,
224 even if the commit for previous transaction has not yet occurred (but
225 transaction was submitted).
227 Write-Only & Read-Write Transaction
228 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
230 Write-Only and Read-Write transactions provide modification capabilities
231 for the conceptual data trees.
233 1. application allocates new transactions using
234 ``newWriteOnlyTransaction()`` or ``newReadWriteTransaction()``.
236 2. application `modifies data tree <#_modification_of_data_tree>`__
237 using ``put``, ``merge`` and/or ``delete``.
239 3. application finishes transaction using
240 ```submit()`` <#_submitting_transaction>`__, which seals transaction
241 and submits it to be processed.
243 4. application observes the result of the transaction commit using
244 either blocking or asynchronous calls.
246 The **initial state** of the write transaction is a **stable snapshot**
247 of the current data tree state captured when transaction was created and
248 it’s state and underlying data tree are not affected by other
249 concurrently running transactions.
251 Write transactions are **isolated** from other concurrent write
252 transactions. All **`writes are local <#_transaction_local_state>`__**
253 to the transaction and represents only a **proposal of state change**
254 for data tree and **are not visible** to any other concurrently running
255 transactions (including read-only transactions).
257 The transaction **`commit may fail <#_commit_failure_scenarios>`__** due
258 to failing verification of data or concurrent transaction modifying and
259 affected data in an incompatible way.
261 Modification of Data Tree
262 ^^^^^^^^^^^^^^^^^^^^^^^^^
264 Write-only and read-write transaction provides following methods to
270 <T> void put(LogicalDatastoreType store, InstanceIdentifier<T> path, T data);
272 Stores a piece of data at a specified path. This acts as an **add /
273 replace** operation, which is to say that whole subtree will be
274 replaced by the specified data.
279 <T> void merge(LogicalDatastoreType store, InstanceIdentifier<T> path, T data);
281 Merges a piece of data with the existing data at a specified path.
282 Any **pre-existing data** which are not explicitly overwritten
283 **will be preserved**. This means that if you store a container, its
284 child subtrees will be merged.
289 void delete(LogicalDatastoreType store, InstanceIdentifier<?> path);
291 Removes a whole subtree from a specified path.
293 Submitting transaction
294 ^^^^^^^^^^^^^^^^^^^^^^
296 Transaction is submitted to be processed and committed using following
301 CheckedFuture<Void,TransactionCommitFailedException> submit();
303 Applications publish the changes proposed in the transaction by calling
304 ``submit()`` on the transaction. This **seals the transaction**
305 (preventing any further writes using this transaction) and submits it to
306 be processed and applied to global conceptual data tree. The
307 ``submit()`` method does not block, but rather returns
308 ``ListenableFuture``, which will complete successfully once processing
309 of transaction is finished and changes are applied to data tree. If
310 **commit** of data failed, the future will fail with
311 ``TransactionFailedException``.
313 Application may listen on commit state asynchronously using
314 ``ListenableFuture``.
318 Futures.addCallback( writeTx.submit(), new FutureCallback<Void>() {
319 public void onSuccess( Void result ) {
320 LOG.debug("Transaction committed successfully.");
323 public void onFailure( Throwable t ) {
324 LOG.error("Commit failed.",e);
328 - Submits ``writeTx`` and registers application provided
329 ``FutureCallback`` on returned future.
331 - Invoked when future completed successfully - transaction ``writeTx``
332 was successfully committed to data tree.
334 - Invoked when future failed - commit of transaction ``writeTx``
335 failed. Supplied exception provides additional details and cause of
338 If application need to block till commit is finished it may use
339 ``checkedGet()`` to wait till commit is finished.
344 writeTx.submit().checkedGet();
345 } catch (TransactionCommitFailedException e) {
346 LOG.error("Commit failed.",e);
349 - Submits ``writeTx`` and blocks till commit of ``writeTx`` is
350 finished. If commit fails ``TransactionCommitFailedException`` will
353 - Catches ``TransactionCommitFailedException`` and logs it.
355 Transaction local state
356 ^^^^^^^^^^^^^^^^^^^^^^^
358 Read-Write transactions maintain transaction-local state, which renders
359 all modifications as if they happened, but this is only local to
362 Reads from the transaction returns data as if the previous modifications
363 in transaction already happened.
365 Let assume initial state of data tree for ``PATH`` is ``A``.
369 ReadWriteTransaction rwTx = broker.newReadWriteTransaction();
371 rwRx.read(OPERATIONAL,PATH).get();
372 rwRx.put(OPERATIONAL,PATH,B);
373 rwRx.read(OPERATIONAL,PATH).get();
374 rwRx.put(OPERATIONAL,PATH,C);
375 rwRx.read(OPERATIONAL,PATH).get();
377 - Allocates new ``ReadWriteTransaction``.
379 - Read from ``rwTx`` will return value ``A`` for ``PATH``.
381 - Writes value ``B`` to ``PATH`` using ``rwTx``.
383 - Read will return value ``B`` for ``PATH``, since previous write
384 occurred in same transaction.
386 - Writes value ``C`` to ``PATH`` using ``rwTx``.
388 - Read will return value ``C`` for ``PATH``, since previous write
389 occurred in same transaction.
391 Transaction isolation
392 ~~~~~~~~~~~~~~~~~~~~~
394 Running (not submitted) transactions are isolated from each other and
395 changes done in one transaction are not observable in other currently
398 Lets assume initial state of data tree for ``PATH`` is ``A``.
402 ReadOnlyTransaction txRead = broker.newReadOnlyTransaction();
403 ReadWriteTransaction txWrite = broker.newReadWriteTransaction();
405 txRead.read(OPERATIONAL,PATH).get();
406 txWrite.put(OPERATIONAL,PATH,B);
407 txWrite.read(OPERATIONAL,PATH).get();
408 txWrite.submit().get();
409 txRead.read(OPERATIONAL,PATH).get();
410 txAfterCommit = broker.newReadOnlyTransaction();
411 txAfterCommit.read(OPERATIONAL,PATH).get();
413 - Allocates read only transaction, which is based on data tree which
414 contains value ``A`` for ``PATH``.
416 - Allocates read write transaction, which is based on data tree which
417 contains value ``A`` for ``PATH``.
419 - Read from read-only transaction returns value ``A`` for ``PATH``.
421 - Data tree is updated using read-write transaction, ``PATH`` contains
422 ``B``. Change is not public and only local to transaction.
424 - Read from read-write transaction returns value ``B`` for ``PATH``.
426 - Submits changes in read-write transaction to be committed to data
427 tree. Once commit will finish, changes will be published and ``PATH``
428 will be updated for value ``B``. Previously allocated transactions
429 are not affected by this change.
431 - Read from previously allocated read-only transaction still returns
432 value ``A`` for ``PATH``, since it provides stable and isolated view.
434 - Allocates new read-only transaction, which is based on data tree,
435 which contains value ``B`` for ``PATH``.
437 - Read from new read-only transaction return value ``B`` for ``PATH``
438 since read-write transaction was committed.
442 Examples contain blocking calls on future only to illustrate that
443 action happened after other asynchronous action. The use of the
444 blocking call ``ListenableFuture#get()`` is discouraged for most
445 use-cases and you should use
446 ``Futures#addCallback(ListenableFuture, FutureCallback)`` to listen
447 asynchronously for result.
449 Commit failure scenarios
450 ~~~~~~~~~~~~~~~~~~~~~~~~
452 A transaction commit may fail because of following reasons:
454 Optimistic Lock Failure
455 Another transaction finished earlier and **modified the same node in
456 a non-compatible way**. The commit (and the returned future) will
457 fail with an ``OptimisticLockFailedException``.
459 It is the responsibility of the caller to create a new transaction
460 and submit the same modification again in order to update data tree.
464 ``OptimisticLockFailedException`` usually exposes **multiple
465 writers** to the same data subtree, which may conflict on same
468 In most cases, retrying may result in a probability of success.
470 There are scenarios, albeit unusual, where any number of retries
471 will not succeed. Therefore it is strongly recommended to limit
472 the number of retries (2 or 3) to avoid an endless loop.
475 The data change introduced by this transaction **did not pass
476 validation** by commit handlers or data was incorrectly structured.
477 The returned future will fail with a
478 ``DataValidationFailedException``. User **should not retry** to
479 create new transaction with same data, since it probably will fail
482 Example conflict of two transactions
483 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
485 This example illustrates two concurrent transactions, which derived from
486 same initial state of data tree and proposes conflicting modifications.
490 WriteTransaction txA = broker.newWriteTransaction();
491 WriteTransaction txB = broker.newWriteTransaction();
493 txA.put(CONFIGURATION, PATH, A);
494 txB.put(CONFIGURATION, PATH, B);
496 CheckedFuture<?,?> futureA = txA.submit();
497 CheckedFuture<?,?> futureB = txB.submit();
499 - Updates ``PATH`` to value ``A`` using ``txA``
501 - Updates ``PATH`` to value ``B`` using ``txB``
503 - Seals & submits ``txA``. The commit will be processed asynchronously
504 and data tree will be updated to contain value ``A`` for ``PATH``.
505 The returned ‘ListenableFuture’ will complete successfully once state
506 is applied to data tree.
508 - Seals & submits ``txB``. Commit of ``txB`` will fail, because
509 previous transaction also modified path in a concurrent way. The
510 state introduced by ``txB`` will not be applied. The returned
511 ``ListenableFuture`` will fail with ``OptimisticLockFailedException``
512 exception, which indicates that concurrent transaction prevented the
513 submitted transaction from being applied.
515 Example asynchronous retry-loop
516 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
520 private void doWrite( final int tries ) {
521 WriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
523 MyDataObject data = ...;
524 InstanceIdentifier<MyDataObject> path = ...;
525 writeTx.put( LogicalDatastoreType.OPERATIONAL, path, data );
527 Futures.addCallback( writeTx.submit(), new FutureCallback<Void>() {
528 public void onSuccess( Void result ) {
532 public void onFailure( Throwable t ) {
533 if( t instanceof OptimisticLockFailedException && (( tries - 1 ) > 0)) {
534 doWrite( tries - 1 );
542 Concurrent change compatibility
543 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
545 There are several sets of changes which could be considered incompatible
546 between two transactions which are derived from same initial state.
547 Rules for conflict detection applies recursively for each subtree level.
549 Following table shows state changes and failures between two concurrent
550 transactions, which are based on same initial state, ``tx1`` is
551 submitted before ``tx2``.
553 INFO: Following tables stores numeric values and shows data using
554 ``toString()`` to simplify examples.
556 +--------------------+--------------------+--------------------+--------------------+
557 | Initial state | tx1 | tx2 | Observable Result |
558 +====================+====================+====================+====================+
559 | Empty | ``put(A,1)`` | ``put(A,2)`` | ``tx2`` will fail, |
560 | | | | value of ``A`` is |
562 +--------------------+--------------------+--------------------+--------------------+
563 | Empty | ``put(A,1)`` | ``merge(A,2)`` | value of ``A`` is |
565 +--------------------+--------------------+--------------------+--------------------+
566 | Empty | ``merge(A,1)`` | ``put(A,2)`` | ``tx2`` will fail, |
567 | | | | value of ``A`` is |
569 +--------------------+--------------------+--------------------+--------------------+
570 | Empty | ``merge(A,1)`` | ``merge(A,2)`` | ``A`` is ``2`` |
571 +--------------------+--------------------+--------------------+--------------------+
572 | A=0 | ``put(A,1)`` | ``put(A,2)`` | ``tx2`` will fail, |
573 | | | | ``A`` is ``1`` |
574 +--------------------+--------------------+--------------------+--------------------+
575 | A=0 | ``put(A,1)`` | ``merge(A,2)`` | ``A`` is ``2`` |
576 +--------------------+--------------------+--------------------+--------------------+
577 | A=0 | ``merge(A,1)`` | ``put(A,2)`` | ``tx2`` will fail, |
578 | | | | value of ``A`` is |
580 +--------------------+--------------------+--------------------+--------------------+
581 | A=0 | ``merge(A,1)`` | ``merge(A,2)`` | ``A`` is ``2`` |
582 +--------------------+--------------------+--------------------+--------------------+
583 | A=0 | ``delete(A)`` | ``put(A,2)`` | ``tx2`` will fail, |
584 | | | | ``A`` does not |
586 +--------------------+--------------------+--------------------+--------------------+
587 | A=0 | ``delete(A)`` | ``merge(A,2)`` | ``A`` is ``2`` |
588 +--------------------+--------------------+--------------------+--------------------+
590 Table: Concurrent change resolution for leaves and leaf-list items
592 +--------------------+--------------------+--------------------+--------------------+
593 | Initial state | ``tx1`` | ``tx2`` | Result |
594 +====================+====================+====================+====================+
595 | Empty | put(TOP,[]) | put(TOP,[]) | ``tx2`` will fail, |
596 | | | | state is TOP=[] |
597 +--------------------+--------------------+--------------------+--------------------+
598 | Empty | put(TOP,[]) | merge(TOP,[]) | TOP=[] |
599 +--------------------+--------------------+--------------------+--------------------+
600 | Empty | put(TOP,[FOO=1]) | put(TOP,[BAR=1]) | ``tx2`` will fail, |
602 | | | | TOP=[FOO=1] |
603 +--------------------+--------------------+--------------------+--------------------+
604 | Empty | put(TOP,[FOO=1]) | merge(TOP,[BAR=1]) | TOP=[FOO=1,BAR=1] |
605 +--------------------+--------------------+--------------------+--------------------+
606 | Empty | merge(TOP,[FOO=1]) | put(TOP,[BAR=1]) | ``tx2`` will fail, |
608 | | | | TOP=[FOO=1] |
609 +--------------------+--------------------+--------------------+--------------------+
610 | Empty | merge(TOP,[FOO=1]) | merge(TOP,[BAR=1]) | TOP=[FOO=1,BAR=1] |
611 +--------------------+--------------------+--------------------+--------------------+
612 | TOP=[] | put(TOP,[FOO=1]) | put(TOP,[BAR=1]) | ``tx2`` will fail, |
614 | | | | TOP=[FOO=1] |
615 +--------------------+--------------------+--------------------+--------------------+
616 | TOP=[] | put(TOP,[FOO=1]) | merge(TOP,[BAR=1]) | state is |
617 | | | | TOP=[FOO=1,BAR=1] |
618 +--------------------+--------------------+--------------------+--------------------+
619 | TOP=[] | merge(TOP,[FOO=1]) | put(TOP,[BAR=1]) | ``tx2`` will fail, |
621 | | | | TOP=[FOO=1] |
622 +--------------------+--------------------+--------------------+--------------------+
623 | TOP=[] | merge(TOP,[FOO=1]) | merge(TOP,[BAR=1]) | state is |
624 | | | | TOP=[FOO=1,BAR=1] |
625 +--------------------+--------------------+--------------------+--------------------+
626 | TOP=[] | delete(TOP) | put(TOP,[BAR=1]) | ``tx2`` will fail, |
627 | | | | state is empty |
629 +--------------------+--------------------+--------------------+--------------------+
630 | TOP=[] | delete(TOP) | merge(TOP,[BAR=1]) | state is |
631 | | | | TOP=[BAR=1] |
632 +--------------------+--------------------+--------------------+--------------------+
633 | TOP=[] | put(TOP/FOO,1) | put(TOP/BAR,1]) | state is |
634 | | | | TOP=[FOO=1,BAR=1] |
635 +--------------------+--------------------+--------------------+--------------------+
636 | TOP=[] | put(TOP/FOO,1) | merge(TOP/BAR,1) | state is |
637 | | | | TOP=[FOO=1,BAR=1] |
638 +--------------------+--------------------+--------------------+--------------------+
639 | TOP=[] | merge(TOP/FOO,1) | put(TOP/BAR,1) | state is |
640 | | | | TOP=[FOO=1,BAR=1] |
641 +--------------------+--------------------+--------------------+--------------------+
642 | TOP=[] | merge(TOP/FOO,1) | merge(TOP/BAR,1) | state is |
643 | | | | TOP=[FOO=1,BAR=1] |
644 +--------------------+--------------------+--------------------+--------------------+
645 | TOP=[] | delete(TOP) | put(TOP/BAR,1) | ``tx2`` will fail, |
646 | | | | state is empty |
648 +--------------------+--------------------+--------------------+--------------------+
649 | TOP=[] | delete(TOP) | merge(TOP/BAR,1] | ``tx2`` will fail, |
650 | | | | state is empty |
652 +--------------------+--------------------+--------------------+--------------------+
653 | TOP=[FOO=1] | put(TOP/FOO,2) | put(TOP/BAR,1) | state is |
654 | | | | TOP=[FOO=2,BAR=1] |
655 +--------------------+--------------------+--------------------+--------------------+
656 | TOP=[FOO=1] | put(TOP/FOO,2) | merge(TOP/BAR,1) | state is |
657 | | | | TOP=[FOO=2,BAR=1] |
658 +--------------------+--------------------+--------------------+--------------------+
659 | TOP=[FOO=1] | merge(TOP/FOO,2) | put(TOP/BAR,1) | state is |
660 | | | | TOP=[FOO=2,BAR=1] |
661 +--------------------+--------------------+--------------------+--------------------+
662 | TOP=[FOO=1] | merge(TOP/FOO,2) | merge(TOP/BAR,1) | state is |
663 | | | | TOP=[FOO=2,BAR=1] |
664 +--------------------+--------------------+--------------------+--------------------+
665 | TOP=[FOO=1] | delete(TOP/FOO) | put(TOP/BAR,1) | state is |
666 | | | | TOP=[BAR=1] |
667 +--------------------+--------------------+--------------------+--------------------+
668 | TOP=[FOO=1] | delete(TOP/FOO) | merge(TOP/BAR,1] | state is |
669 | | | | TOP=[BAR=1] |
670 +--------------------+--------------------+--------------------+--------------------+
672 Table: Concurrent change resolution for containers, lists, list items
677 The MD-SAL provides a way to deliver Remote Procedure Calls (RPCs) to a
678 particular implementation based on content in the input as it is modeled
679 in YANG. This part of the the RPC input is referred to as a **context
682 The MD-SAL does not dictate the name of the leaf which is used for this
683 RPC routing, but provides necessary functionality for YANG model author
684 to define their **context reference** in their model of RPCs.
686 MD-SAL routing behavior is modeled using following terminology and its
687 application to YANG models:
690 Logical type of RPC routing. Context type is modeled as YANG
691 ``identity`` and is referenced in model to provide scoping
695 Conceptual location in data tree, which represents context in which
696 RPC could be executed. Context instance usually represent logical
697 point to which RPC execution is attached.
700 Field of RPC input payload which contains Instance Identifier
701 referencing **context instance** in which the RPC should be
704 Modeling a routed RPC
705 ~~~~~~~~~~~~~~~~~~~~~
707 In order to define routed RPCs, the YANG model author needs to declare
708 (or reuse) a **context type**, set of possible **context instances** and
709 finally RPCs which will contain **context reference** on which they will
712 Declaring a routing context type
713 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
717 identity node-context {
718 description "Identity used to mark node context";
721 This declares an identity named ``node-context``, which is used as
722 marker for node-based routing and is used in other places to reference
725 Declaring possible context instances
726 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
728 In order to define possible values of **context instances** for routed
729 RPCs, we need to model that set accordingly using ``context-instance``
730 extension from the ``yang-ext`` model.
734 import yang-ext { prefix ext; }
736 /** Base structure **/
740 ext:context-instance "node-context";
741 // other node-related fields would go here
745 The statement ``ext:context-instance "node-context";`` marks any element
746 of the ``list node`` as a possible valid **context instance** in
747 ``node-context`` based routing.
751 The existence of a **context instance** node in operational or
752 config data tree is not strongly tied to existence of RPC
755 For most routed RPC models, there is relationship between the data
756 present in operational data tree and RPC implementation
757 availability, but this is not enforced by MD-SAL. This provides some
758 flexibility for YANG model writers to better specify their routing
759 model and requirements for implementations. Details when RPC
760 implementations are available should be documented in YANG model.
762 If user invokes RPC with a **context instance** that has no
763 registered implementation, the RPC invocation will fail with the
764 exception ``DOMRpcImplementationNotAvailableException``.
766 Declaring a routed RPC
767 ^^^^^^^^^^^^^^^^^^^^^^
769 To declare RPC to be routed based on ``node-context`` we need to add
770 leaf of ``instance-identifier`` type (or type derived from
771 ``instance-identifier``) to the RPC and mark it as **context
774 This is achieved using YANG extension ``context-reference`` from
775 ``yang-ext`` model on leaf, which will be used for RPC routing.
779 rpc example-routed-rpc {
782 ext:context-reference "node-context";
783 type "instance-identifier";
785 // other input to the RPC would go here
789 The statement ``ext:context-reference "node-context"`` marks
790 ``leaf node`` as **context reference** of type ``node-context``. The
791 value of this leaf, will be used by the MD-SAL to select the particular
792 RPC implementation that registered itself as the implementation of the
793 RPC for particular **context instance**.
798 From a user perspective (e.g. invoking RPCs) there is no difference
799 between routed and non-routed RPCs. Routing information is just an
800 additional leaf in RPC which must be populated.
802 Implementing a routed RPC
803 ~~~~~~~~~~~~~~~~~~~~~~~~~
807 Registering implementations
808 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
810 Implementations of a routed RPC (e.g., southbound plugins) will specify
811 an instance-identifier for the **context reference** (in this case a
812 node) for which they want to provide an implementation during
813 registration. Consumers, e.g., those calling the RPC are required to
814 specify that instance-identifier (in this case the identifier of a node)
817 Simple code which showcases that for add-flow via Binding-Aware APIs
818 (`RoutedServiceTest.java <https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=blob;f=opendaylight/md-sal/sal-binding-it/src/test/java/org/opendaylight/controller/test/sal/binding/it/RoutedServiceTest.java;h=d49d6f0e25e271e43c8550feb5eef63d96301184;hb=HEAD>`__
824 62 public void onSessionInitiated(ProviderContext session) {
825 63 assertNotNull(session);
826 64 firstReg = session.addRoutedRpcImplementation(SalFlowService.class, salFlowService1);
829 Line 64: We are registering salFlowService1 as implementation of
834 107 NodeRef nodeOne = createNodeRef("foo:node:1");
836 110 * Provider 1 registers path of node 1
838 112 firstReg.registerPath(NodeContext.class, nodeOne);
840 Line 107: We are creating NodeRef (encapsulation of InstanceIdentifier)
843 Line 112: We register salFlowService1 as implementation for nodeOne.
845 The salFlowService1 will be executed only for RPCs which contains
846 Instance Identifier for foo:node:1.
848 OpenDaylight Controller MD-SAL: RESTCONF
849 ----------------------------------------
851 RESCONF operations overview
852 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
854 | RESTCONF allows access to datastores in the controller.
855 | There are two datastores:
857 - Config: Contains data inserted via controller
859 - Operational: Contains other data
863 | Each request must start with the URI /restconf.
864 | RESTCONF listens on port 8080 for HTTP requests.
866 RESTCONF supports **OPTIONS**, **GET**, **PUT**, **POST**, and
867 **DELETE** operations. Request and response data can either be in the
868 XML or JSON format. XML structures according to yang are defined at:
869 `XML-YANG <http://tools.ietf.org/html/rfc6020>`__. JSON structures are
871 `JSON-YANG <http://tools.ietf.org/html/draft-lhotka-netmod-yang-json-02>`__.
872 Data in the request must have a correctly set **Content-Type** field in
873 the http header with the allowed value of the media type. The media type
874 of the requested data has to be set in the **Accept** field. Get the
875 media types for each resource by calling the OPTIONS operation. Most of
876 the paths of the pathsRestconf endpoints use `Instance
877 Identifier <https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL:Concepts#Instance_Identifier>`__.
878 ``<identifier>`` is used in the explanation of the operations.
882 - It must start with <moduleName>:<nodeName> where <moduleName> is a
883 name of the module and <nodeName> is the name of a node in the
884 module. It is sufficient to just use <nodeName> after
885 <moduleName>:<nodeName>. Each <nodeName> has to be separated by /.
887 - <nodeName> can represent a data node which is a list or container
888 yang built-in type. If the data node is a list, there must be defined
889 keys of the list behind the data node name for example,
890 <nodeName>/<valueOfKey1>/<valueOfKey2>.
892 - | The format <moduleName>:<nodeName> has to be used in this case as
894 | Module A has node A1. Module B augments node A1 by adding node X.
895 Module C augments node A1 by adding node X. For clarity, it has to
896 be known which node is X (for example: C:X). For more details about
897 encoding, see: `RESTCONF 02 - Encoding YANG Instance Identifiers in
899 URI. <http://tools.ietf.org/html/draft-bierman-netconf-restconf-02#section-5.3.1>`__
904 | A Node can be behind a mount point. In this case, the URI has to be in
905 format <identifier>/**yang-ext:mount**/<identifier>. The first
906 <identifier> is the path to a mount point and the second <identifier>
907 is the path to a node behind the mount point. A URI can end in a mount
908 point itself by using <identifier>/**yang-ext:mount**.
909 | More information on how to actually use mountpoints is available at:
911 Controller:Config:Examples:Netconf <https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf>`__.
919 - Returns the XML description of the resources with the required
920 request and response media types in Web Application Description
923 GET /restconf/config/<identifier>
924 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
926 - Returns a data node from the Config datastore.
928 - <identifier> points to a data node which must be retrieved.
930 GET /restconf/operational/<identifier>
931 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
933 - Returns the value of the data node from the Operational datastore.
935 - <identifier> points to a data node which must be retrieved.
937 PUT /restconf/config/<identifier>
938 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
940 - Updates or creates data in the Config datastore and returns the state
943 - <identifier> points to a data node which must be stored.
949 PUT http://<controllerIP>:8080/restconf/config/module1:foo/bar
950 Content-Type: applicaton/xml
955 | **Example with mount point:**
959 PUT http://<controllerIP>:8080/restconf/config/module1:foo1/foo2/yang-ext:mount/module2:foo/bar
960 Content-Type: applicaton/xml
965 POST /restconf/config
966 ^^^^^^^^^^^^^^^^^^^^^
968 - Creates the data if it does not exist
974 POST URL: http://localhost:8080/restconf/config/
975 content-type: application/yang.data+json
981 "toaster:toasterManufacturer" : "General Electric",
982 "toaster:toasterModelNumber" : "123",
983 "toaster:toasterStatus" : "up"
987 POST /restconf/config/<identifier>
988 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
990 - Creates the data if it does not exist in the Config datastore, and
991 returns the state about success.
993 - <identifier> points to a data node where data must be stored.
995 - The root element of data must have the namespace (data are in XML) or
996 module name (data are in JSON.)
1002 POST http://<controllerIP>:8080/restconf/config/module1:foo
1003 Content-Type: applicaton/xml/
1004 <bar xmlns=“module1namespace”>
1008 **Example with mount point:**
1012 http://<controllerIP>:8080/restconf/config/module1:foo1/foo2/yang-ext:mount/module2:foo
1013 Content-Type: applicaton/xml
1014 <bar xmlns=“module2namespace”>
1018 POST /restconf/operations/<moduleName>:<rpcName>
1019 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1023 - <moduleName>:<rpcName> - <moduleName> is the name of the module and
1024 <rpcName> is the name of the RPC in this module.
1026 - The Root element of the data sent to RPC must have the name “input”.
1028 - The result can be the status code or the retrieved data having the
1029 root element “output”.
1035 POST http://<controllerIP>:8080/restconf/operations/module1:fooRpc
1036 Content-Type: applicaton/xml
1037 Accept: applicaton/xml
1042 The answer from the server could be:
1047 | **An example using a JSON payload:**
1051 POST http://localhost:8080/restconf/operations/toaster:make-toast
1052 Content-Type: application/yang.data+json
1056 "toaster:toasterDoneness" : "10",
1057 "toaster:toasterToastType":"wheat-bread"
1063 Even though this is a default for the toasterToastType value in the
1064 yang, you still need to define it.
1066 DELETE /restconf/config/<identifier>
1067 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1069 - Removes the data node in the Config datastore and returns the state
1072 - <identifier> points to a data node which must be removed.
1074 More information is available in the `RESTCONF
1075 RFC <http://tools.ietf.org/html/draft-bierman-netconf-restconf-02>`__.
1080 | RESTCONF uses these base classes:
1083 Represents the path in the data tree
1086 Used for invoking RPCs
1089 Offers manipulation with transactions and reading data from the
1093 Holds information about yang modules
1096 Returns MountInstance based on the InstanceIdentifier pointing to a
1100 Contains the SchemaContext behind the mount point
1103 Provides information about the schema node
1106 Possesses the same name as the schema node, and contains the value
1107 representing the data node value
1110 Can contain CompositeNode-s and SimpleNode-s
1115 Figure 1 shows the GET operation with URI restconf/config/M:N where M is
1116 the module name, and N is the node name.
1118 .. figure:: ./images/Get.png
1123 1. The requested URI is translated into the InstanceIdentifier which
1124 points to the data node. During this translation, the DataSchemaNode
1125 that conforms to the data node is obtained. If the data node is
1126 behind the mount point, the MountInstance is obtained as well.
1128 2. RESTCONF asks for the value of the data node from DataBrokerService
1129 based on InstanceIdentifier.
1131 3. DataBrokerService returns CompositeNode as data.
1133 4. StructuredDataToXmlProvider or StructuredDataToJsonProvider is called
1134 based on the **Accept** field from the http request. These two
1135 providers can transform CompositeNode regarding DataSchemaNode to an
1136 XML or JSON document.
1138 5. XML or JSON is returned as the answer on the request from the client.
1143 Figure 2 shows the PUT operation with the URI restconf/config/M:N where
1144 M is the module name, and N is the node name. Data is sent in the
1145 request either in the XML or JSON format.
1147 .. figure:: ./images/Put.png
1152 1. Input data is sent to JsonToCompositeNodeProvider or
1153 XmlToCompositeNodeProvider. The correct provider is selected based on
1154 the Content-Type field from the http request. These two providers can
1155 transform input data to CompositeNode. However, this CompositeNode
1156 does not contain enough information for transactions.
1158 2. The requested URI is translated into InstanceIdentifier which points
1159 to the data node. DataSchemaNode conforming to the data node is
1160 obtained during this translation. If the data node is behind the
1161 mount point, the MountInstance is obtained as well.
1163 3. CompositeNode can be normalized by adding additional information from
1166 4. RESTCONF begins the transaction, and puts CompositeNode with
1167 InstanceIdentifier into it. The response on the request from the
1168 client is the status code which depends on the result from the
1174 1. Create a new flow on the switch openflow:1 in table 2.
1181 URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2
1182 Content-Type: application/xml
1186 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1188 xmlns="urn:opendaylight:flow:inventory">
1189 <strict>false</strict>
1201 <table_id>2</table_id>
1203 <cookie_mask>10</cookie_mask>
1204 <out_port>10</out_port>
1205 <installHw>false</installHw>
1206 <out_group>2</out_group>
1213 <ipv4-destination>10.0.0.1/24</ipv4-destination>
1215 <hard-timeout>0</hard-timeout>
1217 <idle-timeout>0</idle-timeout>
1218 <flow-name>FooXf22</flow-name>
1219 <priority>2</priority>
1220 <barrier>false</barrier>
1227 Status: 204 No Content
1229 1. Change *strict* to *true* in the previous flow.
1236 URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
1237 Content-Type: application/xml
1241 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1243 xmlns="urn:opendaylight:flow:inventory">
1244 <strict>true</strict>
1256 <table_id>2</table_id>
1258 <cookie_mask>10</cookie_mask>
1259 <out_port>10</out_port>
1260 <installHw>false</installHw>
1261 <out_group>2</out_group>
1268 <ipv4-destination>10.0.0.1/24</ipv4-destination>
1270 <hard-timeout>0</hard-timeout>
1272 <idle-timeout>0</idle-timeout>
1273 <flow-name>FooXf22</flow-name>
1274 <priority>2</priority>
1275 <barrier>false</barrier>
1284 1. Show flow: check that *strict* is *true*.
1291 URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
1292 Accept: application/xml
1302 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1304 xmlns="urn:opendaylight:flow:inventory">
1305 <strict>true</strict>
1317 <table_id>2</table_id>
1319 <cookie_mask>10</cookie_mask>
1320 <out_port>10</out_port>
1321 <installHw>false</installHw>
1322 <out_group>2</out_group>
1329 <ipv4-destination>10.0.0.1/24</ipv4-destination>
1331 <hard-timeout>0</hard-timeout>
1333 <idle-timeout>0</idle-timeout>
1334 <flow-name>FooXf22</flow-name>
1335 <priority>2</priority>
1336 <barrier>false</barrier>
1339 1. Delete the flow created.
1346 URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
1354 Websocket change event notification subscription tutorial
1355 ---------------------------------------------------------
1357 Subscribing to data change notifications makes it possible to obtain
1358 notifications about data manipulation (insert, change, delete) which are
1359 done on any specified **path** of any specified **datastore** with
1360 specific **scope**. In following examples *{odlAddress}* is address of
1361 server where ODL is running and *{odlPort}* is port on which
1362 OpenDaylight is running.
1364 Websocket notifications subscription process
1365 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1367 In this section we will learn what steps need to be taken in order to
1368 successfully subscribe to data change event notifications.
1373 In order to use event notifications you first need to call RPC that
1374 creates notification stream that you can later listen to. You need to
1375 provide three parameters to this RPC:
1377 - **path**: data store path that you plan to listen to. You can
1378 register listener on containers, lists and leaves.
1380 - **datastore**: data store type. *OPERATIONAL* or *CONFIGURATION*.
1382 - **scope**: Represents scope of data change. Possible options are:
1384 - BASE: only changes directly to the data tree node specified in the
1385 path will be reported
1387 - ONE: changes to the node and to direct child nodes will be
1390 - SUBTREE: changes anywhere in the subtree starting at the node will
1393 The RPC to create the stream can be invoked via RESCONF like this:
1396 http://{odlAddress}:{odlPort}/restconf/operations/sal-remote:create-data-change-event-subscription
1398 - HEADER: Content-Type=application/json
1408 "path": "/toaster:toaster/toaster:toasterStatus",
1409 "sal-remote-augment:datastore": "OPERATIONAL",
1410 "sal-remote-augment:scope": "ONE"
1414 The response should look something like this:
1420 "stream-name": "data-change-event-subscription/toaster:toaster/toaster:toasterStatus/datastore=CONFIGURATION/scope=SUBTREE"
1424 **stream-name** is important because you will need to use it when you
1425 subscribe to the stream in the next step.
1429 Internally, this will create a new listener for *stream-name* if it
1430 did not already exist.
1435 In order to subscribe to stream and obtain WebSocket location you need
1436 to call *GET* on your stream path. The URI should generally be
1437 http://{odlAddress}:{odlPort}/restconf/streams/stream/{streamName},
1438 where *{streamName}* is the *stream-name* parameter contained in
1439 response from *create-data-change-event-subscription* RPC from the
1443 http://{odlAddress}:{odlPort}/restconf/streams/stream/data-change-event-subscription/toaster:toaster/datastore=CONFIGURATION/scope=SUBTREE
1447 The subscription call may be modified with the following query parameters defined in the RESTCONF RFC:
1449 - `filter <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.6>`__
1451 - `start-time <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.7>`__
1453 - `end-time <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.8>`__
1455 In addition, the following ODL extension query parameter is supported:
1457 :odl-leaf-nodes-only:
1458 If this parameter is set to "true", create and update notifications will only
1459 contain the leaf nodes modified instead of the entire subscription subtree.
1460 This can help in reducing the size of the notifications.
1462 The expected response status is 200 OK and response body should be
1463 empty. You will get your WebSocket location from **Location** header of
1464 response. For example in our particular toaster example location header
1465 would have this value:
1466 *ws://{odlAddress}:8185/toaster:toaster/datastore=CONFIGURATION/scope=SUBTREE*
1470 During this phase there is an internal check for to see if a
1471 listener for the *stream-name* from the URI exists. If not, new a
1472 new listener is registered with the DOM data broker.
1474 Receive notifications
1475 ^^^^^^^^^^^^^^^^^^^^^
1477 You should now have a data change notification stream created and have
1478 location of a WebSocket. You can use this WebSocket to listen to data
1479 change notifications. To listen to notifications you can use a
1480 JavaScript client or if you are using chrome browser you can use the
1482 Client <https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo>`__.
1484 Also, for testing purposes, there is simple Java application named
1485 WebSocketClient. The application is placed in the
1486 *-sal-rest-connector-classes.class* project. It accepts a WebSocket URI
1487 as and input parameter. After starting the utility (WebSocketClient
1488 class directly in Eclipse/InteliJ Idea) received notifications should be
1489 displayed in console.
1491 Notifications are always in XML format and look like this:
1495 <notification xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0">
1496 <eventTime>2014-09-11T09:58:23+02:00</eventTime>
1497 <data-changed-notification xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote">
1499 <path xmlns:meae="http://netconfcentral.org/ns/toaster">/meae:toaster</path>
1500 <operation>updated</operation>
1502 <!-- updated data -->
1504 </data-change-event>
1505 </data-changed-notification>
1511 The typical use case is listening to data change events to update web
1512 page data in real-time. In this tutorial we will be using toaster as the
1515 When you call *make-toast* RPC, it sets *toasterStatus* to "down" to
1516 reflect that the toaster is busy making toast. When it finishes,
1517 *toasterStatus* is set to "up" again. We will listen to this toaster
1518 status changes in data store and will reflect it on our web page in
1519 real-time thanks to WebSocket data change notification.
1521 Simple javascript client implementation
1522 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1524 We will create simple JavaScript web application that will listen
1525 updates on *toasterStatus* leaf and update some element of our web page
1526 according to new toaster status state.
1531 First you need to create stream that you are planing to subscribe to.
1532 This can be achieved by invoking "create-data-change-event-subscription"
1533 RPC on RESTCONF via AJAX request. You need to provide data store
1534 **path** that you plan to listen on, **data store type** and **scope**.
1535 If the request is successful you can extract the **stream-name** from
1536 the response and use that to subscribe to the newly created stream. The
1537 *{username}* and *{password}* fields represent your credentials that you
1538 use to connect to OpenDaylight via RESTCONF:
1542 The default user name and password are "admin".
1544 .. code:: javascript
1546 function createStream() {
1549 url: 'http://{odlAddress}:{odlPort}/restconf/operations/sal-remote:create-data-change-event-subscription',
1552 'Authorization': 'Basic ' + btoa('{username}:{password}'),
1553 'Content-Type': 'application/json'
1555 data: JSON.stringify(
1558 'path': '/toaster:toaster/toaster:toasterStatus',
1559 'sal-remote-augment:datastore': 'OPERATIONAL',
1560 'sal-remote-augment:scope': 'ONE'
1564 }).done(function (data) {
1565 // this function will be called when ajax call is executed successfully
1566 subscribeToStream(data.output['stream-name']);
1567 }).fail(function (data) {
1568 // this function will be called when ajax call fails
1569 console.log("Create stream call unsuccessful");
1576 The Next step is to subscribe to the stream. To subscribe to the stream
1577 you need to call *GET* on
1578 *http://{odlAddress}:{odlPort}/restconf/streams/stream/{stream-name}*.
1579 If the call is successful, you get WebSocket address for this stream in
1580 **Location** parameter inside response header. You can get response
1581 header by calling *getResponseHeader(\ *Location*)* on HttpRequest
1582 object inside *done()* function call:
1584 .. code:: javascript
1586 function subscribeToStream(streamName) {
1589 url: 'http://{odlAddress}:{odlPort}/restconf/streams/stream/' + streamName;
1592 'Authorization': 'Basic ' + btoa('{username}:{password}'),
1595 ).done(function (data, textStatus, httpReq) {
1596 // we need function that has http request object parameter in order to access response headers.
1597 listenToNotifications(httpReq.getResponseHeader('Location'));
1598 }).fail(function (data) {
1599 console.log("Subscribe to stream call unsuccessful");
1603 Receive notifications
1604 ^^^^^^^^^^^^^^^^^^^^^
1606 Once you got WebSocket server location you can now connect to it and
1607 start receiving data change events. You need to define functions that
1608 will handle events on WebSocket. In order to process incoming events
1609 from OpenDaylight you need to provide a function that will handle
1610 *onmessage* events. The function must have one parameter that represents
1611 the received event object. The event data will be stored in
1612 *event.data*. The data will be in an XML format that you can then easily
1615 .. code:: javascript
1617 function listenToNotifications(socketLocation) {
1619 var notificatinSocket = new WebSocket(socketLocation);
1621 notificatinSocket.onmessage = function (event) {
1622 // we process our received event here
1623 console.log('Received toaster data change event.');
1624 $($.parseXML(event.data)).find('data-change-event').each(
1626 var operation = $(this).find('operation').text();
1627 if (operation == 'updated') {
1628 // toaster status was updated so we call function that gets the value of toasterStatus leaf
1629 updateToasterStatus();
1635 notificatinSocket.onerror = function (error) {
1636 console.log("Socket error: " + error);
1638 notificatinSocket.onopen = function (event) {
1639 console.log("Socket connection opened.");
1641 notificatinSocket.onclose = function (event) {
1642 console.log("Socket connection closed.");
1644 // if there is a problem on socket creation we get exception (i.e. when socket address is incorrect)
1646 alert("Error when creating WebSocket" + e );
1650 The *updateToasterStatus()* function represents function that calls
1651 *GET* on the path that was modified and sets toaster status in some web
1652 page element according to received data. After the WebSocket connection
1653 has been established you can test events by calling make-toast RPC via
1658 for more information about WebSockets in JavaScript visit `Writing
1660 applications <https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_client_applications>`__
1668 The Controller configuration operation has three stages:
1670 - First, a Proposed configuration is created. Its target is to replace
1671 the old configuration.
1673 - Second, the Proposed configuration is validated, and then committed.
1674 If it passes validation successfully, the Proposed configuration
1675 state will be changed to Validated.
1677 - Finally, a Validated configuration can be Committed, and the affected
1678 modules can be reconfigured.
1680 In fact, each configuration operation is wrapped in a transaction. Once
1681 a transaction is created, it can be configured, that is to say, a user
1682 can abort the transaction during this stage. After the transaction
1683 configuration is done, it is committed to the validation stage. In this
1684 stage, the validation procedures are invoked. If one or more validations
1685 fail, the transaction can be reconfigured. Upon success, the second
1686 phase commit is invoked. If this commit is successful, the transaction
1687 enters the last stage, committed. After that, the desired modules are
1688 reconfigured. If the second phase commit fails, it means that the
1689 transaction is unhealthy - basically, a new configuration instance
1690 creation failed, and the application can be in an inconsistent state.
1692 .. figure:: ./images/configuration.jpg
1693 :alt: Configuration states
1695 Configuration states
1697 .. figure:: ./images/Transaction.jpg
1698 :alt: Transaction states
1705 To secure the consistency and safety of the new configuration and to
1706 avoid conflicts, the configuration validation process is necessary.
1707 Usually, validation checks the input parameters of a new configuration,
1708 and mostly verifies module-specific relationships. The validation
1709 procedure results in a decision on whether the proposed configuration is
1715 Since there can be dependencies between modules, a change in a module
1716 configuration can affect the state of other modules. Therefore, we need
1717 to verify whether dependencies on other modules can be resolved. The
1718 Dependency Resolver acts in a manner similar to dependency injectors.
1719 Basically, a dependency tree is built.
1724 This section describes configuration system APIs and SPIs.
1729 **Module** org.opendaylight.controller.config.spi. Module is the common
1730 interface for all modules: every module must implement it. The module is
1731 designated to hold configuration attributes, validate them, and create
1732 instances of service based on the attributes. This instance must
1733 implement the AutoCloseable interface, owing to resources clean up. If
1734 the module was created from an already running instance, it contains an
1735 old instance of the module. A module can implement multiple services. If
1736 the module depends on other modules, setters need to be annotated with
1741 1. The module needs to be configured, set with all required attributes.
1743 2. The module is then moved to the commit stage for validation. If the
1744 validation fails, the module attributes can be reconfigured.
1745 Otherwise, a new instance is either created, or an old instance is
1746 reconfigured. A module instance is identified by ModuleIdentifier,
1747 consisting of the factory name and instance name.
1749 | **ModuleFactory** org.opendaylight.controller.config.spi. The
1750 ModuleFactory interface must be implemented by each module factory.
1751 | A module factory can create a new module instance in two ways:
1753 - From an existing module instance
1755 - | An entirely new instance
1756 | ModuleFactory can also return default modules, useful for
1757 populating registry with already existing configurations. A module
1758 factory implementation must have a globally unique name.
1763 +--------------------------------------+--------------------------------------+
1764 | ConfigRegistry | Represents functionality provided by |
1765 | | a configuration transaction (create, |
1766 | | destroy module, validate, or abort |
1768 +--------------------------------------+--------------------------------------+
1769 | ConfigTransactionController | Represents functionality for |
1770 | | manipulating with configuration |
1771 | | transactions (begin, commit config). |
1772 +--------------------------------------+--------------------------------------+
1773 | RuntimeBeanRegistratorAwareConfiBean | The module implementing this |
1774 | | interface will receive |
1775 | | RuntimeBeanRegistrator before |
1776 | | getInstance is invoked. |
1777 +--------------------------------------+--------------------------------------+
1782 +--------------------------------------+--------------------------------------+
1783 | RuntimeBean | Common interface for all runtime |
1785 +--------------------------------------+--------------------------------------+
1786 | RootRuntimeBeanRegistrator | Represents functionality for root |
1787 | | runtime bean registration, which |
1788 | | subsequently allows hierarchical |
1790 +--------------------------------------+--------------------------------------+
1791 | HierarchicalRuntimeBeanRegistration | Represents functionality for runtime |
1792 | | bean registration and |
1793 | | unreregistration from hierarchy |
1794 +--------------------------------------+--------------------------------------+
1799 | JMX API is purposed as a transition between the Client API and the JMX
1802 +--------------------------------------+--------------------------------------+
1803 | ConfigTransactionControllerMXBean | Extends ConfigTransactionController, |
1804 | | executed by Jolokia clients on |
1805 | | configuration transaction. |
1806 +--------------------------------------+--------------------------------------+
1807 | ConfigRegistryMXBean | Represents entry point of |
1808 | | configuration management for |
1810 +--------------------------------------+--------------------------------------+
1811 | Object names | Object Name is the pattern used in |
1812 | | JMX to locate JMX beans. It consists |
1813 | | of domain and key properties (at |
1814 | | least one key-value pair). Domain is |
1816 | | "org.opendaylight.controller". The |
1817 | | only mandatory property is "type". |
1818 +--------------------------------------+--------------------------------------+
1823 | A few samples of successful and unsuccessful transaction scenarios
1826 **Successful commit scenario**
1828 1. The user creates a transaction calling creteTransaction() method on
1831 2. ConfigRegisty creates a transaction controller, and registers the
1832 transaction as a new bean.
1834 3. Runtime configurations are copied to the transaction. The user can
1835 create modules and set their attributes.
1837 4. The configuration transaction is to be committed.
1839 5. The validation process is performed.
1841 6. After successful validation, the second phase commit begins.
1843 7. Modules proposed to be destroyed are destroyed, and their service
1844 instances are closed.
1846 8. Runtime beans are set to registrator.
1848 9. The transaction controller invokes the method getInstance on each
1851 10. The transaction is committed, and resources are either closed or
1854 | **Validation failure scenario**
1855 | The transaction is the same as the previous case until the validation
1858 1. If validation fails, (that is to day, illegal input attributes values
1859 or dependency resolver failure), the validationException is thrown
1860 and exposed to the user.
1862 2. The user can decide to reconfigure the transaction and commit again,
1863 or abort the current transaction.
1865 3. On aborted transactions, TransactionController and JMXRegistrator are
1868 4. Unregistration event is sent to ConfigRegistry.
1870 Default module instances
1871 ^^^^^^^^^^^^^^^^^^^^^^^^
1873 The configuration subsystem provides a way for modules to create default
1874 instances. A default instance is an instance of a module, that is
1875 created at the module bundle start-up (module becomes visible for
1876 configuration subsystem, for example, its bundle is activated in the
1877 OSGi environment). By default, no default instances are produced.
1879 The default instance does not differ from instances created later in the
1880 module life-cycle. The only difference is that the configuration for the
1881 default instance cannot be provided by the configuration subsystem. The
1882 module has to acquire the configuration for these instances on its own.
1883 It can be acquired from, for example, environment variables. After the
1884 creation of a default instance, it acts as a regular instance and fully
1885 participates in the configuration subsystem (It can be reconfigured or
1886 deleted in following transactions.).