BUG-8403: propagate DONE state to successor
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / LocalReadWriteProxyTransaction.java
1 /*
2  * Copyright (c) 2016 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.databroker.actors.dds;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import java.util.Optional;
13 import java.util.function.BiConsumer;
14 import java.util.function.Consumer;
15 import java.util.function.Supplier;
16 import javax.annotation.Nonnull;
17 import javax.annotation.Nullable;
18 import javax.annotation.concurrent.NotThreadSafe;
19 import org.opendaylight.controller.cluster.access.commands.AbortLocalTransactionRequest;
20 import org.opendaylight.controller.cluster.access.commands.AbstractLocalTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
22 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
23 import org.opendaylight.controller.cluster.access.commands.PersistenceProtocol;
24 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
25 import org.opendaylight.controller.cluster.access.commands.TransactionDelete;
26 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
27 import org.opendaylight.controller.cluster.access.commands.TransactionMerge;
28 import org.opendaylight.controller.cluster.access.commands.TransactionModification;
29 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
30 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
31 import org.opendaylight.controller.cluster.access.commands.TransactionWrite;
32 import org.opendaylight.controller.cluster.access.concepts.Response;
33 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
34 import org.opendaylight.controller.cluster.datastore.util.AbstractDataTreeModificationCursor;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.tree.CursorAwareDataTreeModification;
39 import org.opendaylight.yangtools.yang.data.api.schema.tree.CursorAwareDataTreeSnapshot;
40 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
41 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
42 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * An {@link AbstractProxyTransaction} for dispatching a transaction towards a shard leader which is co-located with
48  * the client instance.
49  *
50  * <p>
51  * It requires a {@link DataTreeSnapshot}, which is used to instantiated a new {@link DataTreeModification}. Operations
52  * are then performed on this modification and once the transaction is submitted, the modification is sent to the shard
53  * leader.
54  *
55  * <p>
56  * This class is not thread-safe as usual with transactions. Since it does not interact with the backend until the
57  * transaction is submitted, at which point this class gets out of the picture, this is not a cause for concern.
58  *
59  * @author Robert Varga
60  */
61 @NotThreadSafe
62 final class LocalReadWriteProxyTransaction extends LocalProxyTransaction {
63     private static final Logger LOG = LoggerFactory.getLogger(LocalReadWriteProxyTransaction.class);
64
65     /**
66      * This field needs to be accessed via {@link #getModification()}, which performs state checking to ensure
67      * the modification can actually be accessed.
68      */
69     private final CursorAwareDataTreeModification modification;
70
71     private Supplier<? extends RuntimeException> closedException;
72
73     private CursorAwareDataTreeModification sealedModification;
74
75     /**
76      * Recorded failure from previous operations. Normally we would want to propagate the error directly to the
77      * offending call site, but that exposes inconsistency in behavior during initial connection, when we go through
78      * {@link RemoteProxyTransaction}, which detects this sort of issues at canCommit/directCommit time on the backend.
79      *
80      * <p>
81      * We therefore do not report incurred exceptions directly, but report them once the user attempts to commit
82      * this transaction.
83      */
84     private Exception recordedFailure;
85
86     LocalReadWriteProxyTransaction(final ProxyHistory parent, final TransactionIdentifier identifier,
87         final DataTreeSnapshot snapshot) {
88         super(parent, identifier, false);
89         this.modification = (CursorAwareDataTreeModification) snapshot.newModification();
90     }
91
92     LocalReadWriteProxyTransaction(final ProxyHistory parent, final TransactionIdentifier identifier) {
93         super(parent, identifier, true);
94         // This is DONE transaction, this should never be touched
95         this.modification = null;
96     }
97
98     @Override
99     boolean isSnapshotOnly() {
100         return false;
101     }
102
103     @Override
104     CursorAwareDataTreeSnapshot readOnlyView() {
105         return getModification();
106     }
107
108     @Override
109     @SuppressWarnings("checkstyle:IllegalCatch")
110     void doDelete(final YangInstanceIdentifier path) {
111         final CursorAwareDataTreeModification mod = getModification();
112         if (recordedFailure != null) {
113             LOG.debug("Transaction {} recorded failure, ignoring delete of {}", getIdentifier(), path);
114             return;
115         }
116
117         try {
118             mod.delete(path);
119         } catch (Exception e) {
120             LOG.debug("Transaction {} delete on {} incurred failure, delaying it until commit", getIdentifier(), path,
121                 e);
122             recordedFailure = e;
123         }
124     }
125
126     @Override
127     @SuppressWarnings("checkstyle:IllegalCatch")
128     void doMerge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
129         final CursorAwareDataTreeModification mod = getModification();
130         if (recordedFailure != null) {
131             LOG.debug("Transaction {} recorded failure, ignoring merge to {}", getIdentifier(), path);
132             return;
133         }
134
135         try {
136             mod.merge(path, data);
137         } catch (Exception e) {
138             LOG.debug("Transaction {} merge to {} incurred failure, delaying it until commit", getIdentifier(), path,
139                 e);
140             recordedFailure = e;
141         }
142     }
143
144     @Override
145     @SuppressWarnings("checkstyle:IllegalCatch")
146     void doWrite(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
147         final CursorAwareDataTreeModification mod = getModification();
148         if (recordedFailure != null) {
149             LOG.debug("Transaction {} recorded failure, ignoring write to {}", getIdentifier(), path);
150             return;
151         }
152
153         try {
154             mod.write(path, data);
155         } catch (Exception e) {
156             LOG.debug("Transaction {} write to {} incurred failure, delaying it until commit", getIdentifier(), path,
157                 e);
158             recordedFailure = e;
159         }
160     }
161
162     private RuntimeException abortedException() {
163         return new IllegalStateException("Tracker " + getIdentifier() + " has been aborted");
164     }
165
166     private RuntimeException submittedException() {
167         return new IllegalStateException("Tracker " + getIdentifier() + " has been submitted");
168     }
169
170     @Override
171     CommitLocalTransactionRequest commitRequest(final boolean coordinated) {
172         final CursorAwareDataTreeModification mod = getModification();
173         final CommitLocalTransactionRequest ret = new CommitLocalTransactionRequest(getIdentifier(), nextSequence(),
174             localActor(), mod, recordedFailure, coordinated);
175         closedException = this::submittedException;
176         return ret;
177     }
178
179     @Override
180     void doSeal() {
181         Preconditions.checkState(sealedModification == null, "Transaction %s is already sealed", getIdentifier());
182         final CursorAwareDataTreeModification mod = getModification();
183         mod.ready();
184         sealedModification = mod;
185     }
186
187     @Override
188     void flushState(final AbstractProxyTransaction successor) {
189         sealedModification.applyToCursor(new AbstractDataTreeModificationCursor() {
190             @Override
191             public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
192                 successor.write(current().node(child), data);
193             }
194
195             @Override
196             public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
197                 successor.merge(current().node(child), data);
198             }
199
200             @Override
201             public void delete(final PathArgument child) {
202                 successor.delete(current().node(child));
203             }
204         });
205     }
206
207     DataTreeSnapshot getSnapshot() {
208         Preconditions.checkState(sealedModification != null, "Proxy %s is not sealed yet", getIdentifier());
209         return sealedModification;
210     }
211
212     @Override
213     void applyForwardedModifyTransactionRequest(final ModifyTransactionRequest request,
214             final @Nullable Consumer<Response<?, ?>> callback) {
215         commonModifyTransactionRequest(request, callback, this::sendRequest);
216     }
217
218     @Override
219     void replayModifyTransactionRequest(final ModifyTransactionRequest request,
220             final @Nullable Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
221         commonModifyTransactionRequest(request, callback, (req, cb) -> enqueueRequest(req, cb, enqueuedTicks));
222     }
223
224     private void commonModifyTransactionRequest(final ModifyTransactionRequest request,
225             final @Nullable Consumer<Response<?, ?>> callback,
226             final BiConsumer<TransactionRequest<?>, Consumer<Response<?, ?>>> sendMethod) {
227         for (final TransactionModification mod : request.getModifications()) {
228             if (mod instanceof TransactionWrite) {
229                 write(mod.getPath(), ((TransactionWrite)mod).getData());
230             } else if (mod instanceof TransactionMerge) {
231                 merge(mod.getPath(), ((TransactionMerge)mod).getData());
232             } else if (mod instanceof TransactionDelete) {
233                 delete(mod.getPath());
234             } else {
235                 throw new IllegalArgumentException("Unsupported modification " + mod);
236             }
237         }
238
239         final Optional<PersistenceProtocol> maybeProtocol = request.getPersistenceProtocol();
240         if (maybeProtocol.isPresent()) {
241             Verify.verify(callback != null, "Request {} has null callback", request);
242             ensureSealed();
243
244             switch (maybeProtocol.get()) {
245                 case ABORT:
246                     sendMethod.accept(new AbortLocalTransactionRequest(getIdentifier(), localActor()), callback);
247                     break;
248                 case READY:
249                     // No-op, as we have already issued a seal()
250                     break;
251                 case SIMPLE:
252                     sendMethod.accept(commitRequest(false), callback);
253                     break;
254                 case THREE_PHASE:
255                     sendMethod.accept(commitRequest(true), callback);
256                     break;
257                 default:
258                     throw new IllegalArgumentException("Unhandled protocol " + maybeProtocol.get());
259             }
260         }
261     }
262
263     @Override
264     void handleReplayedLocalRequest(final AbstractLocalTransactionRequest<?> request,
265             final Consumer<Response<?, ?>> callback, final long now) {
266         if (request instanceof CommitLocalTransactionRequest) {
267             sendCommit((CommitLocalTransactionRequest) request, callback);
268         } else {
269             super.handleReplayedLocalRequest(request, callback, now);
270         }
271     }
272
273     @Override
274     void handleReplayedRemoteRequest(final TransactionRequest<?> request,
275             final @Nullable Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
276         LOG.debug("Applying replayed request {}", request);
277
278         if (request instanceof TransactionPreCommitRequest) {
279             enqueueRequest(new TransactionPreCommitRequest(getIdentifier(), nextSequence(), localActor()), callback,
280                 enqueuedTicks);
281         } else if (request instanceof TransactionDoCommitRequest) {
282             enqueueRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), callback,
283                 enqueuedTicks);
284         } else if (request instanceof TransactionAbortRequest) {
285             enqueueDoAbort(callback, enqueuedTicks);
286         } else {
287             super.handleReplayedRemoteRequest(request, callback, enqueuedTicks);
288         }
289     }
290
291     @Override
292     void handleForwardedRemoteRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
293         LOG.debug("Applying forwarded request {}", request);
294
295         if (request instanceof TransactionPreCommitRequest) {
296             sendRequest(new TransactionPreCommitRequest(getIdentifier(), nextSequence(), localActor()), callback);
297         } else if (request instanceof TransactionDoCommitRequest) {
298             sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), callback);
299         } else if (request instanceof TransactionAbortRequest) {
300             sendDoAbort(callback);
301         } else {
302             super.handleForwardedRemoteRequest(request, callback);
303         }
304     }
305
306     @Override
307     void forwardToLocal(final LocalProxyTransaction successor, final TransactionRequest<?> request,
308             final Consumer<Response<?, ?>> callback) {
309         if (request instanceof CommitLocalTransactionRequest) {
310             Verify.verify(successor instanceof LocalReadWriteProxyTransaction);
311             ((LocalReadWriteProxyTransaction) successor).sendCommit((CommitLocalTransactionRequest)request, callback);
312             LOG.debug("Forwarded request {} to successor {}", request, successor);
313         } else {
314             super.forwardToLocal(successor, request, callback);
315         }
316     }
317
318     @Override
319     void sendAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
320         super.sendAbort(request, callback);
321         closedException = this::abortedException;
322     }
323
324     @Override
325     void enqueueAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
326             final long enqueuedTicks) {
327         super.enqueueAbort(request, callback, enqueuedTicks);
328         closedException = this::abortedException;
329     }
330
331     private @Nonnull CursorAwareDataTreeModification getModification() {
332         if (closedException != null) {
333             throw closedException.get();
334         }
335
336         return Preconditions.checkNotNull(modification, "Transaction %s is DONE", getIdentifier());
337     }
338
339     private void sendCommit(final CommitLocalTransactionRequest request, final Consumer<Response<?, ?>> callback) {
340         // Rebase old modification on new data tree.
341         final CursorAwareDataTreeModification mod = getModification();
342
343         try (DataTreeModificationCursor cursor = mod.createCursor(YangInstanceIdentifier.EMPTY)) {
344             request.getModification().applyToCursor(cursor);
345         }
346
347         ensureSealed();
348         sendRequest(commitRequest(request.isCoordinated()), callback);
349     }
350 }