Merge "BUG-2510: Remove all registrations when a routed rpc is closed"
[controller.git] / opendaylight / md-sal / sal-inmemory-datastore / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / InMemoryDOMDataStore.java
1 /*
2  * Copyright (c) 2014 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.md.sal.dom.store.impl;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.TimeUnit;
17 import java.util.concurrent.atomic.AtomicLong;
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.common.api.data.OptimisticLockFailedException;
21 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
22 import org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction.TransactionReadyPrototype;
23 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ListenerTree;
24 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
25 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
26 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
27 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
30 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
31 import org.opendaylight.yangtools.concepts.Identifiable;
32 import org.opendaylight.yangtools.concepts.ListenerRegistration;
33 import org.opendaylight.yangtools.util.ExecutorServiceUtil;
34 import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager;
35 import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager.Invoker;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
39 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
40 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
41 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
42 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
43 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
44 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * In-memory DOM Data Store
52  *
53  * Implementation of {@link DOMStore} which uses {@link DataTree} and other
54  * classes such as {@link SnapshotBackedWriteTransaction}.
55  * {@link SnapshotBackedReadTransaction} and {@link ResolveDataChangeEventsTask}
56  * to implement {@link DOMStore} contract.
57  *
58  */
59 public class InMemoryDOMDataStore extends TransactionReadyPrototype implements DOMStore, Identifiable<String>, SchemaContextListener, AutoCloseable {
60     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataStore.class);
61     private static final ListenableFuture<Void> SUCCESSFUL_FUTURE = Futures.immediateFuture(null);
62     private static final ListenableFuture<Boolean> CAN_COMMIT_FUTURE = Futures.immediateFuture(Boolean.TRUE);
63
64     private static final Invoker<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> DCL_NOTIFICATION_MGR_INVOKER =
65             new Invoker<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent>() {
66                 @Override
67                 public void invokeListener(final DataChangeListenerRegistration<?> listener,
68                                            final DOMImmutableDataChangeEvent notification ) {
69                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> inst = listener.getInstance();
70                     if (inst != null) {
71                         inst.onDataChanged(notification);
72                     }
73                 }
74             };
75
76     private final DataTree dataTree = InMemoryDataTreeFactory.getInstance().create();
77     private final ListenerTree listenerTree = ListenerTree.create();
78     private final AtomicLong txCounter = new AtomicLong(0);
79
80     private final QueuedNotificationManager<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> dataChangeListenerNotificationManager;
81     private final ExecutorService dataChangeListenerExecutor;
82     private final boolean debugTransactions;
83     private final String name;
84
85     private volatile AutoCloseable closeable;
86
87     public InMemoryDOMDataStore(final String name, final ExecutorService dataChangeListenerExecutor) {
88         this(name, dataChangeListenerExecutor, InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_LISTENER_QUEUE_SIZE, false);
89     }
90
91     public InMemoryDOMDataStore(final String name, final ExecutorService dataChangeListenerExecutor,
92             final int maxDataChangeListenerQueueSize, final boolean debugTransactions) {
93         this.name = Preconditions.checkNotNull(name);
94         this.dataChangeListenerExecutor = Preconditions.checkNotNull(dataChangeListenerExecutor);
95         this.debugTransactions = debugTransactions;
96
97         dataChangeListenerNotificationManager =
98                 new QueuedNotificationManager<>(this.dataChangeListenerExecutor,
99                         DCL_NOTIFICATION_MGR_INVOKER, maxDataChangeListenerQueueSize,
100                         "DataChangeListenerQueueMgr");
101     }
102
103     public void setCloseable(final AutoCloseable closeable) {
104         this.closeable = closeable;
105     }
106
107     public QueuedNotificationManager<?, ?> getDataChangeListenerNotificationManager() {
108         return dataChangeListenerNotificationManager;
109     }
110
111     @Override
112     public final String getIdentifier() {
113         return name;
114     }
115
116     @Override
117     public DOMStoreReadTransaction newReadOnlyTransaction() {
118         return new SnapshotBackedReadTransaction(nextIdentifier(), debugTransactions, dataTree.takeSnapshot());
119     }
120
121     @Override
122     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
123         return new SnapshotBackedReadWriteTransaction(nextIdentifier(), debugTransactions, dataTree.takeSnapshot(), this);
124     }
125
126     @Override
127     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
128         return new SnapshotBackedWriteTransaction(nextIdentifier(), debugTransactions, dataTree.takeSnapshot(), this);
129     }
130
131     @Override
132     public DOMStoreTransactionChain createTransactionChain() {
133         return new DOMStoreTransactionChainImpl(this);
134     }
135
136     @Override
137     public synchronized void onGlobalContextUpdated(final SchemaContext ctx) {
138         dataTree.setSchemaContext(ctx);
139     }
140
141     @Override
142     public void close() {
143         ExecutorServiceUtil.tryGracefulShutdown(dataChangeListenerExecutor, 30, TimeUnit.SECONDS);
144
145         if(closeable != null) {
146             try {
147                 closeable.close();
148             } catch(Exception e) {
149                 LOG.debug("Error closing instance", e);
150             }
151         }
152     }
153
154     public final boolean getDebugTransactions() {
155         return debugTransactions;
156     }
157
158     final DataTreeSnapshot takeSnapshot() {
159         return dataTree.takeSnapshot();
160     }
161
162     @Override
163     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(
164             final YangInstanceIdentifier path, final L listener, final DataChangeScope scope) {
165
166         /*
167          * Make sure commit is not occurring right now. Listener has to be
168          * registered and its state capture enqueued at a consistent point.
169          *
170          * FIXME: improve this to read-write lock, such that multiple listener
171          * registrations can occur simultaneously
172          */
173         final DataChangeListenerRegistration<L> reg;
174         synchronized (this) {
175             LOG.debug("{}: Registering data change listener {} for {}", name, listener, path);
176
177             reg = listenerTree.registerDataChangeListener(path, listener, scope);
178
179             Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
180             if (currentState.isPresent()) {
181                 final NormalizedNode<?, ?> data = currentState.get();
182
183                 final DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE) //
184                         .setAfter(data) //
185                         .addCreated(path, data) //
186                         .build();
187
188                 dataChangeListenerNotificationManager.submitNotification(reg, event);
189             }
190         }
191
192         return new AbstractListenerRegistration<L>(listener) {
193             @Override
194             protected void removeRegistration() {
195                 synchronized (InMemoryDOMDataStore.this) {
196                     reg.close();
197                 }
198             }
199         };
200     }
201
202     @Override
203     protected void transactionAborted(final SnapshotBackedWriteTransaction tx) {
204         LOG.debug("Tx: {} is closed.", tx.getIdentifier());
205     }
206
207     @Override
208     protected DOMStoreThreePhaseCommitCohort transactionReady(final SnapshotBackedWriteTransaction tx, final DataTreeModification tree) {
209         LOG.debug("Tx: {} is submitted. Modifications: {}", tx.getIdentifier(), tree);
210         return new ThreePhaseCommitImpl(tx, tree);
211     }
212
213     Object nextIdentifier() {
214         return name + "-" + txCounter.getAndIncrement();
215     }
216
217     private final class ThreePhaseCommitImpl implements DOMStoreThreePhaseCommitCohort {
218         private final SnapshotBackedWriteTransaction transaction;
219         private final DataTreeModification modification;
220
221         private ResolveDataChangeEventsTask listenerResolver;
222         private DataTreeCandidate candidate;
223
224         public ThreePhaseCommitImpl(final SnapshotBackedWriteTransaction writeTransaction, final DataTreeModification modification) {
225             this.transaction = writeTransaction;
226             this.modification = modification;
227         }
228
229         @Override
230         public ListenableFuture<Boolean> canCommit() {
231             try {
232                 dataTree.validate(modification);
233                 LOG.debug("Store Transaction: {} can be committed", transaction.getIdentifier());
234                 return CAN_COMMIT_FUTURE;
235             } catch (ConflictingModificationAppliedException e) {
236                 LOG.warn("Store Tx: {} Conflicting modification for {}.", transaction.getIdentifier(),
237                         e.getPath());
238                 transaction.warnDebugContext(LOG);
239                 return Futures.immediateFailedFuture(new OptimisticLockFailedException("Optimistic lock failed.", e));
240             } catch (DataValidationFailedException e) {
241                 LOG.warn("Store Tx: {} Data Precondition failed for {}.", transaction.getIdentifier(),
242                         e.getPath(), e);
243                 transaction.warnDebugContext(LOG);
244
245                 // For debugging purposes, allow dumping of the modification. Coupled with the above
246                 // precondition log, it should allow us to understand what went on.
247                 LOG.trace("Store Tx: {} modifications: {} tree: {}", modification, dataTree);
248
249                 return Futures.immediateFailedFuture(new TransactionCommitFailedException("Data did not pass validation.", e));
250             } catch (Exception e) {
251                 LOG.warn("Unexpected failure in validation phase", e);
252                 return Futures.immediateFailedFuture(e);
253             }
254         }
255
256         @Override
257         public ListenableFuture<Void> preCommit() {
258             try {
259                 candidate = dataTree.prepare(modification);
260                 listenerResolver = ResolveDataChangeEventsTask.create(candidate, listenerTree);
261                 return SUCCESSFUL_FUTURE;
262             } catch (Exception e) {
263                 LOG.warn("Unexpected failure in pre-commit phase", e);
264                 return Futures.immediateFailedFuture(e);
265             }
266         }
267
268         @Override
269         public ListenableFuture<Void> abort() {
270             candidate = null;
271             return SUCCESSFUL_FUTURE;
272         }
273
274         @Override
275         public ListenableFuture<Void> commit() {
276             checkState(candidate != null, "Proposed subtree must be computed");
277
278             /*
279              * The commit has to occur atomically with regard to listener
280              * registrations.
281              */
282             synchronized (InMemoryDOMDataStore.this) {
283                 dataTree.commit(candidate);
284                 listenerResolver.resolve(dataChangeListenerNotificationManager);
285             }
286
287             return SUCCESSFUL_FUTURE;
288         }
289     }
290 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.