Merge "Move basic names to Nitrogen from Carbon"
[docs.git] / docs / developer-guide / controller.rst
1 .. _controller-dev-guide:
2
3 Controller
4 ==========
5
6 Overview
7 --------
8
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.
13
14 The OpenDaylight Controller relies on the following technologies:
15
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.
19
20 -  **Karaf** - Application container built on top of OSGI, which
21    simplifies operational aspects of packaging and installing
22    applications.
23
24 -  **YANG** - a data modeling language used to model configuration and
25    state data manipulated by the applications, remote procedure calls,
26    and notifications.
27
28 The OpenDaylight Controller provides following model-driven subsystems
29 as a foundation for Java applications:
30
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.
35
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.
41
42 -  **MD-SAL Clustering** - enables cluster support for core MD-SAL
43    functionality and provides location-transparent accesss to
44    YANG-modeled data.
45
46 The OpenDaylight Controller supports external access to applications and
47 data using following model-driven protocols:
48
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.
52
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.
56
57 .. _mdsal_dev_guide:
58
59 MD-SAL Overview
60 ---------------
61
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).
66
67 The MD-SAL:
68
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.
72
73 -  Provide common support for user-defined transport and payload
74    formats, including payload serialization and adaptation (e.g. binary,
75    XML or JSON).
76
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.
80
81 | The MD-SAL provides two different API types (flavours):
82
83 -  **MD-SAL Binding:** MD-SAL APIs which extensively uses APIs and
84    classes generated from YANG models, which provides compile-time
85    safety.
86
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.
90
91 .. note::
92
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
102     type.
103
104 Basic concepts
105 ~~~~~~~~~~~~~~
106
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.
110
111 Data Tree
112     All state-related data are modeled and represented as data tree,
113     with possibility to address any element / subtree
114
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.
118
119     -  **Configuration Data Tree** - Intended state of the system or
120        network, populated by consumers, which expresses their intention.
121
122 Instance Identifier
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.
126
127 Notification
128     Asynchronous transient event which may be consumed by subscribers
129     and they may act upon it
130
131 RPC
132     asynchronous request-reply message pair, when request is triggered
133     by consumer, send to the provider, which in future replies with
134     reply message.
135
136     .. note::
137
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.
142
143 Messaging Patterns
144 ~~~~~~~~~~~~~~~~~~
145
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.
150
151 -  **Unicast communication**
152
153    -  **Remote Procedure Calls** - unicast between consumer and
154       provider, where consumer sends **request** message to provider,
155       which asynchronously responds with **reply** message
156
157 -  **Publish / Subscribe**
158
159    -  **Notifications** - multicast transient message which is published
160       by provider and is delivered to subscribers
161
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
165
166 -  **Transactional access to Data Tree**
167
168    -  Transactional **reads** from conceptual **data tree** - read-only
169       transactions with isolation from other running transactions.
170
171    -  Transactional **modification** to conceptual **data tree** - write
172       transactions with isolation from other running transactions.
173
174    -  **Transaction chaining**
175
176 MD-SAL Data Transactions
177 ------------------------
178
179 MD-SAL **Data Broker** provides transactional access to conceptual
180 **data trees** representing configuration and operational state.
181
182 .. note::
183
184     **Data tree** usually represents state of the modeled data, usually
185     this is state of controller, applications and also external systems
186     (network devices).
187
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.
192
193 Write-Only
194     Transaction provides only modification capabilities, but does not
195     provide read capabilities. Write-only transaction is allocated using
196     ``newWriteOnlyTransaction()``.
197
198     .. note::
199
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.
203
204 Read-Write
205     Transaction provides both read and write capabilities. It is
206     allocated using ``newReadWriteTransaction()``.
207
208 Read-Only
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()``.
213
214     .. note::
215
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.
219
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).
226
227 Write-Only & Read-Write Transaction
228 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
229
230 Write-Only and Read-Write transactions provide modification capabilities
231 for the conceptual data trees.
232
233 1. application allocates new transactions using
234    ``newWriteOnlyTransaction()`` or ``newReadWriteTransaction()``.
235
236 2. application `modifies data tree <#_modification_of_data_tree>`__
237    using ``put``, ``merge`` and/or ``delete``.
238
239 3. application finishes transaction using
240    ```submit()`` <#_submitting_transaction>`__, which seals transaction
241    and submits it to be processed.
242
243 4. application observes the result of the transaction commit using
244    either blocking or asynchronous calls.
245
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.
250
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).
256
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.
260
261 Modification of Data Tree
262 ^^^^^^^^^^^^^^^^^^^^^^^^^
263
264 Write-only and read-write transaction provides following methods to
265 modify data tree:
266
267 put
268     .. code:: java
269
270         <T> void put(LogicalDatastoreType store, InstanceIdentifier<T> path, T data);
271
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.
275
276 merge
277     .. code:: java
278
279         <T> void merge(LogicalDatastoreType store, InstanceIdentifier<T> path, T data);
280
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.
285
286 delete
287     .. code:: java
288
289         void delete(LogicalDatastoreType store, InstanceIdentifier<?> path);
290
291     Removes a whole subtree from a specified path.
292
293 Submitting transaction
294 ^^^^^^^^^^^^^^^^^^^^^^
295
296 Transaction is submitted to be processed and committed using following
297 method:
298
299 .. code:: java
300
301     CheckedFuture<Void,TransactionCommitFailedException> submit();
302
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``.
312
313 Application may listen on commit state asynchronously using
314 ``ListenableFuture``.
315
316 .. code:: java
317
318     Futures.addCallback( writeTx.submit(), new FutureCallback<Void>() {
319             public void onSuccess( Void result ) {
320                 LOG.debug("Transaction committed successfully.");
321             }
322
323             public void onFailure( Throwable t ) {
324                 LOG.error("Commit failed.",e);
325             }
326         });
327
328 -  Submits ``writeTx`` and registers application provided
329    ``FutureCallback`` on returned future.
330
331 -  Invoked when future completed successfully - transaction ``writeTx``
332    was successfully committed to data tree.
333
334 -  Invoked when future failed - commit of transaction ``writeTx``
335    failed. Supplied exception provides additional details and cause of
336    failure.
337
338 If application need to block till commit is finished it may use
339 ``checkedGet()`` to wait till commit is finished.
340
341 .. code:: java
342
343     try {
344         writeTx.submit().checkedGet();
345     } catch (TransactionCommitFailedException e) {
346         LOG.error("Commit failed.",e);
347     }
348
349 -  Submits ``writeTx`` and blocks till commit of ``writeTx`` is
350    finished. If commit fails ``TransactionCommitFailedException`` will
351    be thrown.
352
353 -  Catches ``TransactionCommitFailedException`` and logs it.
354
355 Transaction local state
356 ^^^^^^^^^^^^^^^^^^^^^^^
357
358 Read-Write transactions maintain transaction-local state, which renders
359 all modifications as if they happened, but this is only local to
360 transaction.
361
362 Reads from the transaction returns data as if the previous modifications
363 in transaction already happened.
364
365 Let assume initial state of data tree for ``PATH`` is ``A``.
366
367 .. code:: java
368
369     ReadWriteTransaction rwTx = broker.newReadWriteTransaction();
370
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();
376
377 -  Allocates new ``ReadWriteTransaction``.
378
379 -  Read from ``rwTx`` will return value ``A`` for ``PATH``.
380
381 -  Writes value ``B`` to ``PATH`` using ``rwTx``.
382
383 -  Read will return value ``B`` for ``PATH``, since previous write
384    occurred in same transaction.
385
386 -  Writes value ``C`` to ``PATH`` using ``rwTx``.
387
388 -  Read will return value ``C`` for ``PATH``, since previous write
389    occurred in same transaction.
390
391 Transaction isolation
392 ~~~~~~~~~~~~~~~~~~~~~
393
394 Running (not submitted) transactions are isolated from each other and
395 changes done in one transaction are not observable in other currently
396 running transaction.
397
398 Lets assume initial state of data tree for ``PATH`` is ``A``.
399
400 .. code:: java
401
402     ReadOnlyTransaction txRead = broker.newReadOnlyTransaction();
403     ReadWriteTransaction txWrite = broker.newReadWriteTransaction();
404
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();
412
413 -  Allocates read only transaction, which is based on data tree which
414    contains value ``A`` for ``PATH``.
415
416 -  Allocates read write transaction, which is based on data tree which
417    contains value ``A`` for ``PATH``.
418
419 -  Read from read-only transaction returns value ``A`` for ``PATH``.
420
421 -  Data tree is updated using read-write transaction, ``PATH`` contains
422    ``B``. Change is not public and only local to transaction.
423
424 -  Read from read-write transaction returns value ``B`` for ``PATH``.
425
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.
430
431 -  Read from previously allocated read-only transaction still returns
432    value ``A`` for ``PATH``, since it provides stable and isolated view.
433
434 -  Allocates new read-only transaction, which is based on data tree,
435    which contains value ``B`` for ``PATH``.
436
437 -  Read from new read-only transaction return value ``B`` for ``PATH``
438    since read-write transaction was committed.
439
440 .. note::
441
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.
448
449 Commit failure scenarios
450 ~~~~~~~~~~~~~~~~~~~~~~~~
451
452 A transaction commit may fail because of following reasons:
453
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``.
458
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.
461
462     .. warning::
463
464         ``OptimisticLockFailedException`` usually exposes **multiple
465         writers** to the same data subtree, which may conflict on same
466         resources.
467
468         In most cases, retrying may result in a probability of success.
469
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.
473
474 Data Validation
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
480     again.
481
482 Example conflict of two transactions
483 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
484
485 This example illustrates two concurrent transactions, which derived from
486 same initial state of data tree and proposes conflicting modifications.
487
488 .. code:: java
489
490     WriteTransaction txA = broker.newWriteTransaction();
491     WriteTransaction txB = broker.newWriteTransaction();
492
493     txA.put(CONFIGURATION, PATH, A);
494     txB.put(CONFIGURATION, PATH, B);
495
496     CheckedFuture<?,?> futureA = txA.submit();
497     CheckedFuture<?,?> futureB = txB.submit();
498
499 -  Updates ``PATH`` to value ``A`` using ``txA``
500
501 -  Updates ``PATH`` to value ``B`` using ``txB``
502
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.
507
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.
514
515 Example asynchronous retry-loop
516 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
517
518 .. code:: java
519
520     private void doWrite( final int tries ) {
521         WriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
522
523         MyDataObject data = ...;
524         InstanceIdentifier<MyDataObject> path = ...;
525         writeTx.put( LogicalDatastoreType.OPERATIONAL, path, data );
526
527         Futures.addCallback( writeTx.submit(), new FutureCallback<Void>() {
528             public void onSuccess( Void result ) {
529                 // succeeded
530             }
531
532             public void onFailure( Throwable t ) {
533                 if( t instanceof OptimisticLockFailedException && (( tries - 1 ) > 0)) {
534                     doWrite( tries - 1 );
535                 }
536             }
537           });
538     }
539     ...
540     doWrite( 2 );
541
542 Concurrent change compatibility
543 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
544
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.
548
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``.
552
553 INFO: Following tables stores numeric values and shows data using
554 ``toString()`` to simplify examples.
555
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  |
561 |                    |                    |                    | ``1``              |
562 +--------------------+--------------------+--------------------+--------------------+
563 | Empty              | ``put(A,1)``       | ``merge(A,2)``     | value of ``A`` is  |
564 |                    |                    |                    | ``2``              |
565 +--------------------+--------------------+--------------------+--------------------+
566 | Empty              | ``merge(A,1)``     | ``put(A,2)``       | ``tx2`` will fail, |
567 |                    |                    |                    | value of ``A`` is  |
568 |                    |                    |                    | ``1``              |
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  |
579 |                    |                    |                    | ``1``              |
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     |
585 |                    |                    |                    | exists             |
586 +--------------------+--------------------+--------------------+--------------------+
587 | A=0                | ``delete(A)``      | ``merge(A,2)``     | ``A`` is ``2``     |
588 +--------------------+--------------------+--------------------+--------------------+
589
590 Table: Concurrent change resolution for leaves and leaf-list items
591
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, |
601 |                    |                    |                    | state is           |
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, |
607 |                    |                    |                    | state is           |
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, |
613 |                    |                    |                    | state is           |
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, |
620 |                    |                    |                    | state is           |
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     |
628 |                    |                    |                    | store              |
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     |
647 |                    |                    |                    | store              |
648 +--------------------+--------------------+--------------------+--------------------+
649 | TOP=[]             | delete(TOP)        | merge(TOP/BAR,1]   | ``tx2`` will fail, |
650 |                    |                    |                    | state is empty     |
651 |                    |                    |                    | store              |
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 +--------------------+--------------------+--------------------+--------------------+
671
672 Table: Concurrent change resolution for containers, lists, list items
673
674 MD-SAL RPC routing
675 ------------------
676
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
680 reference**.
681
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.
685
686 MD-SAL routing behavior is modeled using following terminology and its
687 application to YANG models:
688
689 Context Type
690     Logical type of RPC routing. Context type is modeled as YANG
691     ``identity`` and is referenced in model to provide scoping
692     information.
693
694 Context Instance
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.
698
699 Context Reference
700     Field of RPC input payload which contains Instance Identifier
701     referencing **context instance** in which the RPC should be
702     executed.
703
704 Modeling a routed RPC
705 ~~~~~~~~~~~~~~~~~~~~~
706
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
710 be routed.
711
712 Declaring a routing context type
713 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
714
715 .. code:: yang
716
717     identity node-context {
718         description "Identity used to mark node context";
719     }
720
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
723 that routing type.
724
725 Declaring possible context instances
726 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
727
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.
731
732 .. code:: yang
733
734     import yang-ext { prefix ext; }
735
736     /** Base structure **/
737     container nodes {
738         list node {
739             key "id";
740             ext:context-instance "node-context";
741             // other node-related fields would go here
742         }
743     }
744
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.
748
749 .. note::
750
751     The existence of a **context instance** node in operational or
752     config data tree is not strongly tied to existence of RPC
753     implementation.
754
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.
761
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``.
765
766 Declaring a routed RPC
767 ^^^^^^^^^^^^^^^^^^^^^^
768
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
772 reference**.
773
774 This is achieved using YANG extension ``context-reference`` from
775 ``yang-ext`` model on leaf, which will be used for RPC routing.
776
777 .. code:: yang
778
779     rpc example-routed-rpc  {
780         input {
781             leaf node {
782                 ext:context-reference "node-context";
783                 type "instance-identifier";
784             }
785             // other input to the RPC would go here
786         }
787     }
788
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**.
794
795 Using routed RPCs
796 ~~~~~~~~~~~~~~~~~
797
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.
801
802 Implementing a routed RPC
803 ~~~~~~~~~~~~~~~~~~~~~~~~~
804
805 Implementation
806
807 Registering implementations
808 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
809
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)
815 when invoking RPC.
816
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>`__
819 ):
820
821 .. code:: java
822
823      61  @Override
824      62  public void onSessionInitiated(ProviderContext session) {
825      63      assertNotNull(session);
826      64      firstReg = session.addRoutedRpcImplementation(SalFlowService.class, salFlowService1);
827      65  }
828
829 Line 64: We are registering salFlowService1 as implementation of
830 SalFlowService RPC
831
832 .. code:: java
833
834     107  NodeRef nodeOne = createNodeRef("foo:node:1");
835     109  /**
836     110   * Provider 1 registers path of node 1
837     111   */
838     112  firstReg.registerPath(NodeContext.class, nodeOne);
839
840 Line 107: We are creating NodeRef (encapsulation of InstanceIdentifier)
841 for "foo:node:1".
842
843 Line 112: We register salFlowService1 as implementation for nodeOne.
844
845 The salFlowService1 will be executed only for RPCs which contains
846 Instance Identifier for foo:node:1.
847
848 OpenDaylight Controller MD-SAL: RESTCONF
849 ----------------------------------------
850
851 RESCONF operations overview
852 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
853
854 | RESTCONF allows access to datastores in the controller.
855 | There are two datastores:
856
857 -  Config: Contains data inserted via controller
858
859 -  Operational: Contains other data
860
861 .. note::
862
863     | Each request must start with the URI /restconf.
864     | RESTCONF listens on port 8080 for HTTP requests.
865
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
870 defined at:
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.
879
880 | **<identifier>**
881
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 /.
886
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>.
891
892 -  | The format <moduleName>:<nodeName> has to be used in this case as
893      well:
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
898      the Request
899      URI. <http://tools.ietf.org/html/draft-bierman-netconf-restconf-02#section-5.3.1>`__
900
901 Mount point
902 ~~~~~~~~~~~
903
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:
910   `OpenDaylight
911   Controller:Config:Examples:Netconf <https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf>`__.
912
913 HTTP methods
914 ~~~~~~~~~~~~
915
916 OPTIONS /restconf
917 ^^^^^^^^^^^^^^^^^
918
919 -  Returns the XML description of the resources with the required
920    request and response media types in Web Application Description
921    Language (WADL)
922
923 GET /restconf/config/<identifier>
924 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
925
926 -  Returns a data node from the Config datastore.
927
928 -  <identifier> points to a data node which must be retrieved.
929
930 GET /restconf/operational/<identifier>
931 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
932
933 -  Returns the value of the data node from the Operational datastore.
934
935 -  <identifier> points to a data node which must be retrieved.
936
937 PUT /restconf/config/<identifier>
938 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
939
940 -  Updates or creates data in the Config datastore and returns the state
941    about success.
942
943 -  <identifier> points to a data node which must be stored.
944
945 | **Example:**
946
947 ::
948
949     PUT http://<controllerIP>:8080/restconf/config/module1:foo/bar
950     Content-Type: applicaton/xml
951     <bar>
952       …
953     </bar>
954
955 | **Example with mount point:**
956
957 ::
958
959     PUT http://<controllerIP>:8080/restconf/config/module1:foo1/foo2/yang-ext:mount/module2:foo/bar
960     Content-Type: applicaton/xml
961     <bar>
962       …
963     </bar>
964
965 POST /restconf/config
966 ^^^^^^^^^^^^^^^^^^^^^
967
968 -  Creates the data if it does not exist
969
970 | For example:
971
972 ::
973
974     POST URL: http://localhost:8080/restconf/config/
975     content-type: application/yang.data+json
976     JSON payload:
977
978        {
979          "toaster:toaster" :
980          {
981            "toaster:toasterManufacturer" : "General Electric",
982            "toaster:toasterModelNumber" : "123",
983            "toaster:toasterStatus" : "up"
984          }
985       }
986
987 POST /restconf/config/<identifier>
988 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
989
990 -  Creates the data if it does not exist in the Config datastore, and
991    returns the state about success.
992
993 -  <identifier> points to a data node where data must be stored.
994
995 -  The root element of data must have the namespace (data are in XML) or
996    module name (data are in JSON.)
997
998 | **Example:**
999
1000 ::
1001
1002     POST http://<controllerIP>:8080/restconf/config/module1:foo
1003     Content-Type: applicaton/xml/
1004     <bar xmlns=“module1namespace”>
1005       …
1006     </bar>
1007
1008 **Example with mount point:**
1009
1010 ::
1011
1012     http://<controllerIP>:8080/restconf/config/module1:foo1/foo2/yang-ext:mount/module2:foo
1013     Content-Type: applicaton/xml
1014     <bar xmlns=“module2namespace”>
1015       …
1016     </bar>
1017
1018 POST /restconf/operations/<moduleName>:<rpcName>
1019 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1020
1021 -  Invokes RPC.
1022
1023 -  <moduleName>:<rpcName> - <moduleName> is the name of the module and
1024    <rpcName> is the name of the RPC in this module.
1025
1026 -  The Root element of the data sent to RPC must have the name “input”.
1027
1028 -  The result can be the status code or the retrieved data having the
1029    root element “output”.
1030
1031 | **Example:**
1032
1033 ::
1034
1035     POST http://<controllerIP>:8080/restconf/operations/module1:fooRpc
1036     Content-Type: applicaton/xml
1037     Accept: applicaton/xml
1038     <input>
1039       …
1040     </input>
1041
1042     The answer from the server could be:
1043     <output>
1044       …
1045     </output>
1046
1047 | **An example using a JSON payload:**
1048
1049 ::
1050
1051     POST http://localhost:8080/restconf/operations/toaster:make-toast
1052     Content-Type: application/yang.data+json
1053     {
1054       "input" :
1055       {
1056          "toaster:toasterDoneness" : "10",
1057          "toaster:toasterToastType":"wheat-bread"
1058       }
1059     }
1060
1061 .. note::
1062
1063     Even though this is a default for the toasterToastType value in the
1064     yang, you still need to define it.
1065
1066 DELETE /restconf/config/<identifier>
1067 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1068
1069 -  Removes the data node in the Config datastore and returns the state
1070    about success.
1071
1072 -  <identifier> points to a data node which must be removed.
1073
1074 More information is available in the `RESTCONF
1075 RFC <http://tools.ietf.org/html/draft-bierman-netconf-restconf-02>`__.
1076
1077 How RESTCONF works
1078 ~~~~~~~~~~~~~~~~~~
1079
1080 | RESTCONF uses these base classes:
1081
1082 InstanceIdentifier
1083     Represents the path in the data tree
1084
1085 ConsumerSession
1086     Used for invoking RPCs
1087
1088 DataBrokerService
1089     Offers manipulation with transactions and reading data from the
1090     datastores
1091
1092 SchemaContext
1093     Holds information about yang modules
1094
1095 MountService
1096     Returns MountInstance based on the InstanceIdentifier pointing to a
1097     mount point
1098
1099 MountInstace
1100     Contains the SchemaContext behind the mount point
1101
1102 DataSchemaNode
1103     Provides information about the schema node
1104
1105 SimpleNode
1106     Possesses the same name as the schema node, and contains the value
1107     representing the data node value
1108
1109 CompositeNode
1110     Can contain CompositeNode-s and SimpleNode-s
1111
1112 GET in action
1113 ~~~~~~~~~~~~~
1114
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.
1117
1118 .. figure:: ./images/Get.png
1119    :alt: Get
1120
1121    Get
1122
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.
1127
1128 2. RESTCONF asks for the value of the data node from DataBrokerService
1129    based on InstanceIdentifier.
1130
1131 3. DataBrokerService returns CompositeNode as data.
1132
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.
1137
1138 5. XML or JSON is returned as the answer on the request from the client.
1139
1140 PUT in action
1141 ~~~~~~~~~~~~~
1142
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.
1146
1147 .. figure:: ./images/Put.png
1148    :alt: Put
1149
1150    Put
1151
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.
1157
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.
1162
1163 3. CompositeNode can be normalized by adding additional information from
1164    DataSchemaNode.
1165
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
1169    transaction.
1170
1171 Something practical
1172 ~~~~~~~~~~~~~~~~~~~
1173
1174 1. Create a new flow on the switch openflow:1 in table 2.
1175
1176 | **HTTP request**
1177
1178 ::
1179
1180     Operation: POST
1181     URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2
1182     Content-Type: application/xml
1183
1184 ::
1185
1186     <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1187     <flow
1188         xmlns="urn:opendaylight:flow:inventory">
1189         <strict>false</strict>
1190         <instructions>
1191             <instruction>
1192                 <order>1</order>
1193                 <apply-actions>
1194                     <action>
1195                       <order>1</order>
1196                         <flood-all-action/>
1197                     </action>
1198                 </apply-actions>
1199             </instruction>
1200         </instructions>
1201         <table_id>2</table_id>
1202         <id>111</id>
1203         <cookie_mask>10</cookie_mask>
1204         <out_port>10</out_port>
1205         <installHw>false</installHw>
1206         <out_group>2</out_group>
1207         <match>
1208             <ethernet-match>
1209                 <ethernet-type>
1210                     <type>2048</type>
1211                 </ethernet-type>
1212             </ethernet-match>
1213             <ipv4-destination>10.0.0.1/24</ipv4-destination>
1214         </match>
1215         <hard-timeout>0</hard-timeout>
1216         <cookie>10</cookie>
1217         <idle-timeout>0</idle-timeout>
1218         <flow-name>FooXf22</flow-name>
1219         <priority>2</priority>
1220         <barrier>false</barrier>
1221     </flow>
1222
1223 | **HTTP response**
1224
1225 ::
1226
1227     Status: 204 No Content
1228
1229 1. Change *strict* to *true* in the previous flow.
1230
1231 | **HTTP request**
1232
1233 ::
1234
1235     Operation: PUT
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
1238
1239 ::
1240
1241     <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1242     <flow
1243         xmlns="urn:opendaylight:flow:inventory">
1244         <strict>true</strict>
1245         <instructions>
1246             <instruction>
1247                 <order>1</order>
1248                 <apply-actions>
1249                     <action>
1250                       <order>1</order>
1251                         <flood-all-action/>
1252                     </action>
1253                 </apply-actions>
1254             </instruction>
1255         </instructions>
1256         <table_id>2</table_id>
1257         <id>111</id>
1258         <cookie_mask>10</cookie_mask>
1259         <out_port>10</out_port>
1260         <installHw>false</installHw>
1261         <out_group>2</out_group>
1262         <match>
1263             <ethernet-match>
1264                 <ethernet-type>
1265                     <type>2048</type>
1266                 </ethernet-type>
1267             </ethernet-match>
1268             <ipv4-destination>10.0.0.1/24</ipv4-destination>
1269         </match>
1270         <hard-timeout>0</hard-timeout>
1271         <cookie>10</cookie>
1272         <idle-timeout>0</idle-timeout>
1273         <flow-name>FooXf22</flow-name>
1274         <priority>2</priority>
1275         <barrier>false</barrier>
1276     </flow>
1277
1278 | **HTTP response**
1279
1280 ::
1281
1282     Status: 200 OK
1283
1284 1. Show flow: check that *strict* is *true*.
1285
1286 | **HTTP request**
1287
1288 ::
1289
1290     Operation: GET
1291     URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
1292     Accept: application/xml
1293
1294 | **HTTP response**
1295
1296 ::
1297
1298     Status: 200 OK
1299
1300 ::
1301
1302     <?xml version="1.0" encoding="UTF-8" standalone="no"?>
1303     <flow
1304         xmlns="urn:opendaylight:flow:inventory">
1305         <strict>true</strict>
1306         <instructions>
1307             <instruction>
1308                 <order>1</order>
1309                 <apply-actions>
1310                     <action>
1311                       <order>1</order>
1312                         <flood-all-action/>
1313                     </action>
1314                 </apply-actions>
1315             </instruction>
1316         </instructions>
1317         <table_id>2</table_id>
1318         <id>111</id>
1319         <cookie_mask>10</cookie_mask>
1320         <out_port>10</out_port>
1321         <installHw>false</installHw>
1322         <out_group>2</out_group>
1323         <match>
1324             <ethernet-match>
1325                 <ethernet-type>
1326                     <type>2048</type>
1327                 </ethernet-type>
1328             </ethernet-match>
1329             <ipv4-destination>10.0.0.1/24</ipv4-destination>
1330         </match>
1331         <hard-timeout>0</hard-timeout>
1332         <cookie>10</cookie>
1333         <idle-timeout>0</idle-timeout>
1334         <flow-name>FooXf22</flow-name>
1335         <priority>2</priority>
1336         <barrier>false</barrier>
1337     </flow>
1338
1339 1. Delete the flow created.
1340
1341 | **HTTP request**
1342
1343 ::
1344
1345     Operation: DELETE
1346     URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
1347
1348 | **HTTP response**
1349
1350 ::
1351
1352     Status: 200 OK
1353
1354 Websocket change event notification subscription tutorial
1355 ---------------------------------------------------------
1356
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.
1363
1364 Websocket notifications subscription process
1365 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1366
1367 In this section we will learn what steps need to be taken in order to
1368 successfully subscribe to data change event notifications.
1369
1370 Create stream
1371 ^^^^^^^^^^^^^
1372
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:
1376
1377 -  **path**: data store path that you plan to listen to. You can
1378    register listener on containers, lists and leaves.
1379
1380 -  **datastore**: data store type. *OPERATIONAL* or *CONFIGURATION*.
1381
1382 -  **scope**: Represents scope of data change. Possible options are:
1383
1384    -  BASE: only changes directly to the data tree node specified in the
1385       path will be reported
1386
1387    -  ONE: changes to the node and to direct child nodes will be
1388       reported
1389
1390    -  SUBTREE: changes anywhere in the subtree starting at the node will
1391       be reported
1392
1393 The RPC to create the stream can be invoked via RESCONF like this:
1394
1395 -  URI:
1396    http://{odlAddress}:{odlPort}/restconf/operations/sal-remote:create-data-change-event-subscription
1397
1398 -  HEADER: Content-Type=application/json
1399
1400 -  OPERATION: POST
1401
1402 -  DATA:
1403
1404    .. code:: json
1405
1406        {
1407            "input": {
1408                "path": "/toaster:toaster/toaster:toasterStatus",
1409                "sal-remote-augment:datastore": "OPERATIONAL",
1410                "sal-remote-augment:scope": "ONE"
1411            }
1412        }
1413
1414 The response should look something like this:
1415
1416 .. code:: json
1417
1418     {
1419         "output": {
1420             "stream-name": "data-change-event-subscription/toaster:toaster/toaster:toasterStatus/datastore=CONFIGURATION/scope=SUBTREE"
1421         }
1422     }
1423
1424 **stream-name** is important because you will need to use it when you
1425 subscribe to the stream in the next step.
1426
1427 .. note::
1428
1429     Internally, this will create a new listener for *stream-name* if it
1430     did not already exist.
1431
1432 Subscribe to stream
1433 ^^^^^^^^^^^^^^^^^^^
1434
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
1440 previous step.
1441
1442 -  URI:
1443    http://{odlAddress}:{odlPort}/restconf/streams/stream/data-change-event-subscription/toaster:toaster/datastore=CONFIGURATION/scope=SUBTREE
1444
1445 -  OPERATION: GET
1446
1447 The subscription call may be modified with the following query parameters defined in the RESTCONF RFC:
1448
1449 -  `filter <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.6>`__
1450
1451 -  `start-time <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.7>`__
1452
1453 -  `end-time <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.8>`__
1454
1455 In addition, the following ODL extension query parameter is supported:
1456
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.
1461
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*
1467
1468 .. note::
1469
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.
1473
1474 Receive notifications
1475 ^^^^^^^^^^^^^^^^^^^^^
1476
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
1481 `Simple WebSocket
1482 Client <https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo>`__.
1483
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.
1490
1491 Notifications are always in XML format and look like this:
1492
1493 .. code:: xml
1494
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">
1498             <data-change-event>
1499                 <path xmlns:meae="http://netconfcentral.org/ns/toaster">/meae:toaster</path>
1500                 <operation>updated</operation>
1501                 <data>
1502                    <!-- updated data -->
1503                 </data>
1504             </data-change-event>
1505         </data-changed-notification>
1506     </notification>
1507
1508 Example use case
1509 ~~~~~~~~~~~~~~~~
1510
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
1513 base.
1514
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.
1520
1521 Simple javascript client implementation
1522 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1523
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.
1527
1528 Create stream
1529 ^^^^^^^^^^^^^
1530
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:
1539
1540 .. note::
1541
1542     The default user name and password are "admin".
1543
1544 .. code:: javascript
1545
1546     function createStream() {
1547         $.ajax(
1548             {
1549                 url: 'http://{odlAddress}:{odlPort}/restconf/operations/sal-remote:create-data-change-event-subscription',
1550                 type: 'POST',
1551                 headers: {
1552                   'Authorization': 'Basic ' + btoa('{username}:{password}'),
1553                   'Content-Type': 'application/json'
1554                 },
1555                 data: JSON.stringify(
1556                     {
1557                         'input': {
1558                             'path': '/toaster:toaster/toaster:toasterStatus',
1559                             'sal-remote-augment:datastore': 'OPERATIONAL',
1560                             'sal-remote-augment:scope': 'ONE'
1561                         }
1562                     }
1563                 )
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");
1570             })
1571     }
1572
1573 Subscribe to stream
1574 ^^^^^^^^^^^^^^^^^^^
1575
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:
1583
1584 .. code:: javascript
1585
1586     function subscribeToStream(streamName) {
1587         $.ajax(
1588             {
1589                 url: 'http://{odlAddress}:{odlPort}/restconf/streams/stream/' + streamName;
1590                 type: 'GET',
1591                 headers: {
1592                   'Authorization': 'Basic ' + btoa('{username}:{password}'),
1593                 }
1594             }
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");
1600         });
1601     }
1602
1603 Receive notifications
1604 ^^^^^^^^^^^^^^^^^^^^^
1605
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
1613 parse using jQuery.
1614
1615 .. code:: javascript
1616
1617     function listenToNotifications(socketLocation) {
1618         try {
1619             var notificatinSocket = new WebSocket(socketLocation);
1620
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(
1625                     function (index) {
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();
1630                             return false;
1631                         }
1632                     }
1633                 );
1634             }
1635             notificatinSocket.onerror = function (error) {
1636                 console.log("Socket error: " + error);
1637             }
1638             notificatinSocket.onopen = function (event) {
1639                 console.log("Socket connection opened.");
1640             }
1641             notificatinSocket.onclose = function (event) {
1642                 console.log("Socket connection closed.");
1643             }
1644             // if there is a problem on socket creation we get exception (i.e. when socket address is incorrect)
1645         } catch(e) {
1646             alert("Error when creating WebSocket" + e );
1647         }
1648     }
1649
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
1654 RESTCONF.
1655
1656 .. note::
1657
1658     for more information about WebSockets in JavaScript visit `Writing
1659     WebSocket client
1660     applications <https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_client_applications>`__
1661
1662 Config Subsystem
1663 ----------------
1664
1665 Overview
1666 ~~~~~~~~
1667
1668 The Controller configuration operation has three stages:
1669
1670 -  First, a Proposed configuration is created. Its target is to replace
1671    the old configuration.
1672
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.
1676
1677 -  Finally, a Validated configuration can be Committed, and the affected
1678    modules can be reconfigured.
1679
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.
1691
1692 .. figure:: ./images/configuration.jpg
1693    :alt: Configuration states
1694
1695    Configuration states
1696
1697 .. figure:: ./images/Transaction.jpg
1698    :alt: Transaction states
1699
1700    Transaction states
1701
1702 Validation
1703 ~~~~~~~~~~
1704
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
1710 healthy.
1711
1712 Dependency resolver
1713 ~~~~~~~~~~~~~~~~~~~
1714
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.
1720
1721 APIs and SPIs
1722 ~~~~~~~~~~~~~
1723
1724 This section describes configuration system APIs and SPIs.
1725
1726 SPIs
1727 ^^^^
1728
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
1737 @RequireInterface.
1738
1739 **Module creation**
1740
1741 1. The module needs to be configured, set with all required attributes.
1742
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.
1748
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:
1752
1753 -  From an existing module instance
1754
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.
1759
1760 APIs
1761 ^^^^
1762
1763 +--------------------------------------+--------------------------------------+
1764 | ConfigRegistry                       | Represents functionality provided by |
1765 |                                      | a configuration transaction (create, |
1766 |                                      | destroy module, validate, or abort   |
1767 |                                      | transaction).                        |
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 +--------------------------------------+--------------------------------------+
1778
1779 Runtime APIs
1780 ^^^^^^^^^^^^
1781
1782 +--------------------------------------+--------------------------------------+
1783 | RuntimeBean                          | Common interface for all runtime     |
1784 |                                      | beans                                |
1785 +--------------------------------------+--------------------------------------+
1786 | RootRuntimeBeanRegistrator           | Represents functionality for root    |
1787 |                                      | runtime bean registration, which     |
1788 |                                      | subsequently allows hierarchical     |
1789 |                                      | registrations                        |
1790 +--------------------------------------+--------------------------------------+
1791 | HierarchicalRuntimeBeanRegistration  | Represents functionality for runtime |
1792 |                                      | bean registration and                |
1793 |                                      | unreregistration from hierarchy      |
1794 +--------------------------------------+--------------------------------------+
1795
1796 JMX APIs
1797 ^^^^^^^^
1798
1799 | JMX API is purposed as a transition between the Client API and the JMX
1800   platform.
1801
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         |
1809 |                                      | MXBeans.                             |
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 |
1815 |                                      | defined as                           |
1816 |                                      | "org.opendaylight.controller". The   |
1817 |                                      | only mandatory property is "type".   |
1818 +--------------------------------------+--------------------------------------+
1819
1820 Use case scenarios
1821 ^^^^^^^^^^^^^^^^^^
1822
1823 | A few samples of successful and unsuccessful transaction scenarios
1824   follow:
1825
1826 **Successful commit scenario**
1827
1828 1.  The user creates a transaction calling creteTransaction() method on
1829     ConfigRegistry.
1830
1831 2.  ConfigRegisty creates a transaction controller, and registers the
1832     transaction as a new bean.
1833
1834 3.  Runtime configurations are copied to the transaction. The user can
1835     create modules and set their attributes.
1836
1837 4.  The configuration transaction is to be committed.
1838
1839 5.  The validation process is performed.
1840
1841 6.  After successful validation, the second phase commit begins.
1842
1843 7.  Modules proposed to be destroyed are destroyed, and their service
1844     instances are closed.
1845
1846 8.  Runtime beans are set to registrator.
1847
1848 9.  The transaction controller invokes the method getInstance on each
1849     module.
1850
1851 10. The transaction is committed, and resources are either closed or
1852     released.
1853
1854 | **Validation failure scenario**
1855 | The transaction is the same as the previous case until the validation
1856   process.
1857
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.
1861
1862 2. The user can decide to reconfigure the transaction and commit again,
1863    or abort the current transaction.
1864
1865 3. On aborted transactions, TransactionController and JMXRegistrator are
1866    properly closed.
1867
1868 4. Unregistration event is sent to ConfigRegistry.
1869
1870 Default module instances
1871 ^^^^^^^^^^^^^^^^^^^^^^^^
1872
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.
1878
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.).
1887