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