BUG-8733: switch to using DOMDataTreeListener-based APIs
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / ShardedDOMDataTreeProducer.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.mdsal.dom.broker;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.Collection;
14 import java.util.Map;
15 import java.util.Set;
16 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
17 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
18 import javax.annotation.concurrent.GuardedBy;
19 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
20 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
21 import org.opendaylight.mdsal.dom.api.DOMDataTreeListener;
22 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerBusyException;
24 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
25 import org.opendaylight.mdsal.dom.api.DOMDataTreeShard;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 class ShardedDOMDataTreeProducer implements DOMDataTreeProducer {
30     private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeProducer.class);
31
32     private final Set<DOMDataTreeIdentifier> subtrees;
33     private final ShardedDOMDataTree dataTree;
34
35     private static final AtomicReferenceFieldUpdater<ShardedDOMDataTreeProducer, ShardedDOMDataTreeWriteTransaction>
36         CURRENT_UPDATER = AtomicReferenceFieldUpdater.newUpdater(ShardedDOMDataTreeProducer.class,
37             ShardedDOMDataTreeWriteTransaction.class, "currentTx");
38     private volatile ShardedDOMDataTreeWriteTransaction currentTx;
39
40     private static final AtomicReferenceFieldUpdater<ShardedDOMDataTreeProducer, ShardedDOMDataTreeWriteTransaction>
41         OPEN_UPDATER = AtomicReferenceFieldUpdater.newUpdater(ShardedDOMDataTreeProducer.class,
42             ShardedDOMDataTreeWriteTransaction.class, "openTx");
43     private volatile ShardedDOMDataTreeWriteTransaction openTx;
44
45     private static final AtomicReferenceFieldUpdater<ShardedDOMDataTreeProducer, ShardedDOMDataTreeWriteTransaction>
46         LAST_UPDATER = AtomicReferenceFieldUpdater.newUpdater(ShardedDOMDataTreeProducer.class,
47             ShardedDOMDataTreeWriteTransaction.class, "lastTx");
48     private volatile ShardedDOMDataTreeWriteTransaction lastTx;
49
50     private static final AtomicIntegerFieldUpdater<ShardedDOMDataTreeProducer> CLOSED_UPDATER =
51             AtomicIntegerFieldUpdater.newUpdater(ShardedDOMDataTreeProducer.class, "closed");
52     private volatile int closed;
53
54     private volatile DOMDataTreeListener attachedListener;
55     private volatile ProducerLayout layout;
56
57     private ShardedDOMDataTreeProducer(final ShardedDOMDataTree dataTree,
58                                final Collection<DOMDataTreeIdentifier> subtrees,
59                                final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap) {
60         this.dataTree = Preconditions.checkNotNull(dataTree);
61         this.subtrees = ImmutableSet.copyOf(subtrees);
62         this.layout = ProducerLayout.create(shardMap);
63     }
64
65     static DOMDataTreeProducer create(final ShardedDOMDataTree dataTree,
66                                       final Collection<DOMDataTreeIdentifier> subtrees,
67                                       final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap) {
68         return new ShardedDOMDataTreeProducer(dataTree, subtrees, shardMap);
69     }
70
71     private void checkNotClosed() {
72         Preconditions.checkState(closed == 0, "Producer is already closed");
73     }
74
75     private void checkIdle() {
76         Preconditions.checkState(openTx == null, "Transaction %s is still open", openTx);
77     }
78
79     void subshardAdded(final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap) {
80         checkIdle();
81
82         layout = layout.reshard(shardMap);
83     }
84
85     @Override
86     public DOMDataTreeCursorAwareTransaction createTransaction(final boolean isolated) {
87         checkNotClosed();
88         checkIdle();
89
90         LOG.debug("Creating transaction from producer {}", this);
91
92         final ShardedDOMDataTreeWriteTransaction current = CURRENT_UPDATER.getAndSet(this, null);
93         final ShardedDOMDataTreeWriteTransaction ret;
94         if (isolated) {
95             ret = createIsolatedTransaction(layout, current);
96         } else {
97             ret = createReusedTransaction(layout, current);
98         }
99
100         final boolean success = OPEN_UPDATER.compareAndSet(this, null, ret);
101         Preconditions.checkState(success, "Illegal concurrent access to producer %s detected", this);
102         return ret;
103     }
104
105     // This may look weird, but this has side-effects on local's producers, hence it needs to be properly synchronized
106     // so that it happens-after submitTransaction() which may have been stolen by a callback.
107     @GuardedBy("this")
108     private ShardedDOMDataTreeWriteTransaction createTransaction(final ProducerLayout local) {
109         return new ShardedDOMDataTreeWriteTransaction(this, local.createTransactions(), local);
110
111     }
112
113     // Isolated case. If we have a previous transaction, submit it before returning this one.
114     private synchronized ShardedDOMDataTreeWriteTransaction createIsolatedTransaction(
115             final ProducerLayout local, final ShardedDOMDataTreeWriteTransaction current) {
116         if (current != null) {
117             submitTransaction(current);
118         }
119
120         return createTransaction(local);
121     }
122
123     private ShardedDOMDataTreeWriteTransaction createReusedTransaction(final ProducerLayout local,
124             final ShardedDOMDataTreeWriteTransaction current) {
125         if (current != null) {
126             // Lock-free fast path
127             if (local.equals(current.getLayout())) {
128                 LOG.debug("Reusing previous transaction {} since there is still a transaction inflight",
129                     current.getIdentifier());
130                 return current;
131             }
132
133             synchronized (this) {
134                 submitTransaction(current);
135                 return createTransaction(local);
136             }
137         }
138
139         // Null indicates we have not seen a previous transaction -- which does not mean it is ready, as it may have
140         // been stolen and in is process of being submitted.
141         synchronized (this) {
142             return createTransaction(local);
143         }
144     }
145
146     @GuardedBy("this")
147     private void submitTransaction(final ShardedDOMDataTreeWriteTransaction tx) {
148         lastTx = tx;
149         tx.doSubmit(this::transactionSuccessful, this::transactionFailed);
150     }
151
152     @Override
153     public DOMDataTreeProducer createProducer(final Collection<DOMDataTreeIdentifier> subtrees) {
154         checkNotClosed();
155         checkIdle();
156
157         final ProducerLayout local = layout;
158
159         for (final DOMDataTreeIdentifier s : subtrees) {
160             // Check if the subtree was visible at any time
161             Preconditions.checkArgument(local.haveSubtree(s), "Subtree %s was never available in producer %s", s, this);
162             // Check if the subtree has not been delegated to a child
163             final DOMDataTreeProducer child = local.lookupChild(s);
164             Preconditions.checkArgument(child == null, "Subtree %s is delegated to child producer %s", s, child);
165
166             // Check if part of the requested subtree is not delegated to a child.
167             for (final DOMDataTreeIdentifier c : local.getChildTrees()) {
168                 Preconditions.checkArgument(!s.contains(c),
169                     "Subtree %s cannot be delegated as it is a superset of already-delegated %s", s, c);
170             }
171         }
172
173
174         final DOMDataTreeProducer ret;
175         synchronized (this) {
176             ret = dataTree.createProducer(this, subtrees);
177         }
178
179         layout = local.addChild(ret, subtrees);
180         return ret;
181     }
182
183     boolean isDelegatedToChild(final DOMDataTreeIdentifier path) {
184         return layout.lookupChild(path) != null;
185     }
186
187     @Override
188     public void close() throws DOMDataTreeProducerException {
189         if (openTx != null) {
190             throw new DOMDataTreeProducerBusyException(String.format("Transaction %s is still open", openTx));
191         }
192
193         if (CLOSED_UPDATER.compareAndSet(this, 0, 1)) {
194             synchronized (this) {
195                 dataTree.destroyProducer(this);
196             }
197         }
198     }
199
200     protected Set<DOMDataTreeIdentifier> getSubtrees() {
201         return subtrees;
202     }
203
204     void cancelTransaction(final ShardedDOMDataTreeWriteTransaction transaction) {
205         final boolean success = OPEN_UPDATER.compareAndSet(this, transaction, null);
206         if (success) {
207             LOG.debug("Transaction {} cancelled", transaction);
208         } else {
209             LOG.warn("Transaction {} is not open in producer {}", transaction, this);
210         }
211     }
212
213     // Called when the user submits a transaction
214     void transactionSubmitted(final ShardedDOMDataTreeWriteTransaction transaction) {
215         final boolean wasOpen = OPEN_UPDATER.compareAndSet(this, transaction, null);
216         Preconditions.checkState(wasOpen, "Attempted to submit non-open transaction %s", transaction);
217
218         if (lastTx == null) {
219             // No transaction outstanding, we need to submit it now
220             synchronized (this) {
221                 submitTransaction(transaction);
222             }
223
224             return;
225         }
226
227         // There is a potentially-racing submitted transaction. Publish the new one, which may end up being
228         // picked up by processNextTransaction.
229         final boolean success = CURRENT_UPDATER.compareAndSet(this, null, transaction);
230         Verify.verify(success);
231
232         // Now a quick check: if the racing transaction completed in between, it may have missed the current
233         // transaction, hence we need to re-check
234         if (lastTx == null) {
235             submitCurrentTransaction();
236         }
237     }
238
239     private void submitCurrentTransaction() {
240         final ShardedDOMDataTreeWriteTransaction current = currentTx;
241         if (current != null) {
242             synchronized (this) {
243                 if (CURRENT_UPDATER.compareAndSet(this, current, null)) {
244                     submitTransaction(current);
245                 }
246             }
247         }
248     }
249
250     private void transactionSuccessful(final ShardedDOMDataTreeWriteTransaction tx) {
251         LOG.debug("Transaction {} completed successfully", tx.getIdentifier());
252
253         tx.onTransactionSuccess(null);
254         transactionCompleted(tx);
255     }
256
257     private void transactionFailed(final ShardedDOMDataTreeWriteTransaction tx, final Throwable throwable) {
258         LOG.debug("Transaction {} failed", tx.getIdentifier(), throwable);
259
260         tx.onTransactionFailure(throwable);
261         // FIXME: transaction failure should result in a hard error
262         transactionCompleted(tx);
263     }
264
265     private void transactionCompleted(final ShardedDOMDataTreeWriteTransaction tx) {
266         final boolean wasLast = LAST_UPDATER.compareAndSet(this, tx, null);
267         if (wasLast) {
268             submitCurrentTransaction();
269         }
270     }
271
272     void bindToListener(final DOMDataTreeListener listener) {
273         final DOMDataTreeListener local = attachedListener;
274         Preconditions.checkState(local == null, "Producer %s is already attached to listener %s", this, local);
275         this.attachedListener = Preconditions.checkNotNull(listener);
276     }
277 }