Bug 4094: Fix DCNs on initial registration
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardDataTree.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import java.util.AbstractMap.SimpleEntry;
14 import java.util.HashMap;
15 import java.util.Map;
16 import java.util.Map.Entry;
17 import javax.annotation.concurrent.NotThreadSafe;
18 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
19 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
20 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
21 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
22 import org.opendaylight.controller.md.sal.dom.store.impl.ResolveDataChangeEventsTask;
23 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ListenerTree;
24 import org.opendaylight.yangtools.concepts.ListenerRegistration;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
32 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
39  * e.g. it does not expose public interfaces and assumes it is only ever called from a
40  * single thread.
41  *
42  * This class is not part of the API contract and is subject to change at any time.
43  */
44 @NotThreadSafe
45 public class ShardDataTree extends ShardDataTreeTransactionParent {
46     private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
47     private static final YangInstanceIdentifier ROOT_PATH = YangInstanceIdentifier.builder().build();
48     private static final ShardDataTreeNotificationManager MANAGER = new ShardDataTreeNotificationManager();
49     private final Map<String, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
50     private final ShardDataTreeChangePublisher treeChangePublisher = new ShardDataTreeChangePublisher();
51     private final ListenerTree listenerTree = ListenerTree.create();
52     private final TipProducingDataTree dataTree;
53     private SchemaContext schemaContext;
54
55     public ShardDataTree(final SchemaContext schemaContext) {
56         dataTree = InMemoryDataTreeFactory.getInstance().create();
57         updateSchemaContext(schemaContext);
58
59     }
60
61     public TipProducingDataTree getDataTree() {
62         return dataTree;
63     }
64
65     SchemaContext getSchemaContext() {
66         return schemaContext;
67     }
68
69     void updateSchemaContext(final SchemaContext schemaContext) {
70         Preconditions.checkNotNull(schemaContext);
71         this.schemaContext = schemaContext;
72         dataTree.setSchemaContext(schemaContext);
73     }
74
75     private ShardDataTreeTransactionChain ensureTransactionChain(final String chainId) {
76         ShardDataTreeTransactionChain chain = transactionChains.get(chainId);
77         if (chain == null) {
78             chain = new ShardDataTreeTransactionChain(chainId, this);
79             transactionChains.put(chainId, chain);
80         }
81
82         return chain;
83     }
84
85     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final String txId, final String chainId) {
86         if (Strings.isNullOrEmpty(chainId)) {
87             return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
88         }
89
90         return ensureTransactionChain(chainId).newReadOnlyTransaction(txId);
91     }
92
93     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final String txId, final String chainId) {
94         if (Strings.isNullOrEmpty(chainId)) {
95             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
96                     .newModification());
97         }
98
99         return ensureTransactionChain(chainId).newReadWriteTransaction(txId);
100     }
101
102     public void notifyListeners(final DataTreeCandidate candidate) {
103         LOG.debug("Notifying listeners on candidate {}", candidate);
104
105         // DataTreeChanges first, as they are more light-weight
106         treeChangePublisher.publishChanges(candidate);
107
108         // DataChanges second, as they are heavier
109         ResolveDataChangeEventsTask.create(candidate, listenerTree).resolve(MANAGER);
110     }
111
112     void notifyOfInitialData(DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
113             NormalizedNode<?, ?>>> listenerReg, Optional<DataTreeCandidate> currentState) {
114
115         if(currentState.isPresent()) {
116             ListenerTree localListenerTree = ListenerTree.create();
117             localListenerTree.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
118                     listenerReg.getScope());
119
120             ResolveDataChangeEventsTask.create(currentState.get(), localListenerTree).resolve(MANAGER);
121         }
122     }
123
124     void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
125             final Optional<DataTreeCandidate> currentState) {
126         if(currentState.isPresent()) {
127             ShardDataTreeChangePublisher localTreeChangePublisher = new ShardDataTreeChangePublisher();
128             localTreeChangePublisher.registerTreeChangeListener(path, listener);
129             localTreeChangePublisher.publishChanges(currentState.get());
130         }
131     }
132
133     void closeAllTransactionChains() {
134         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
135             chain.close();
136         }
137
138         transactionChains.clear();
139     }
140
141     void closeTransactionChain(final String transactionChainId) {
142         final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
143         if (chain != null) {
144             chain.close();
145         } else {
146             LOG.debug("Closing non-existent transaction chain {}", transactionChainId);
147         }
148     }
149
150     Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
151             Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
152                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
153                     final DataChangeScope scope) {
154         final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
155                 listenerTree.registerDataChangeListener(path, listener, scope);
156
157         return new SimpleEntry<>(reg, readCurrentData());
158     }
159
160     private Optional<DataTreeCandidate> readCurrentData() {
161         final Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(ROOT_PATH);
162         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
163                 ROOT_PATH, currentState.get())) : Optional.<DataTreeCandidate>absent();
164     }
165
166     public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>> registerTreeChangeListener(
167             final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
168         final ListenerRegistration<DOMDataTreeChangeListener> reg = treeChangePublisher.registerTreeChangeListener(
169                 path, listener);
170
171         return new SimpleEntry<>(reg, readCurrentData());
172     }
173
174     void applyForeignCandidate(final String identifier, final DataTreeCandidate foreign) throws DataValidationFailedException {
175         LOG.debug("Applying foreign transaction {}", identifier);
176
177         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
178         DataTreeCandidates.applyToModification(mod, foreign);
179         mod.ready();
180
181         LOG.trace("Applying foreign modification {}", mod);
182         dataTree.validate(mod);
183         final DataTreeCandidate candidate = dataTree.prepare(mod);
184         dataTree.commit(candidate);
185         notifyListeners(candidate);
186     }
187
188     @Override
189     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
190         // Intentional no-op
191     }
192
193     @Override
194     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
195         final DataTreeModification snapshot = transaction.getSnapshot();
196         snapshot.ready();
197         return new SimpleShardDataTreeCohort(this, snapshot, transaction.getId());
198     }
199 }