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