a41bef9c9e992518c672c418da82769ea6cfdfc9
[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         try {
107             mod.delete(path);
108         } catch (Exception e) {
109             LOG.debug("Transaction {} delete on {} incurred failure, delaying it until commit", getIdentifier(), path,
110                 e);
111             recordedFailure = e;
112         }
113     }
114
115     @Override
116     @SuppressWarnings("checkstyle:IllegalCatch")
117     void doMerge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
118         final CursorAwareDataTreeModification mod = getModification();
119         if (recordedFailure != null) {
120             LOG.debug("Transaction {} recorded failure, ignoring merge to {}", getIdentifier(), path);
121             return;
122         }
123
124         try {
125             mod.merge(path, data);
126         } catch (Exception e) {
127             LOG.debug("Transaction {} merge to {} incurred failure, delaying it until commit", getIdentifier(), path,
128                 e);
129             recordedFailure = e;
130         }
131     }
132
133     @Override
134     @SuppressWarnings("checkstyle:IllegalCatch")
135     void doWrite(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
136         final CursorAwareDataTreeModification mod = getModification();
137         if (recordedFailure != null) {
138             LOG.debug("Transaction {} recorded failure, ignoring write to {}", getIdentifier(), path);
139             return;
140         }
141
142         try {
143             mod.write(path, data);
144         } catch (Exception e) {
145             LOG.debug("Transaction {} write to {} incurred failure, delaying it until commit", getIdentifier(), path,
146                 e);
147             recordedFailure = e;
148         }
149     }
150
151     private RuntimeException abortedException() {
152         return new IllegalStateException("Tracker " + getIdentifier() + " has been aborted");
153     }
154
155     private RuntimeException submittedException() {
156         return new IllegalStateException("Tracker " + getIdentifier() + " has been submitted");
157     }
158
159     @Override
160     CommitLocalTransactionRequest commitRequest(final boolean coordinated) {
161         final CursorAwareDataTreeModification mod = getModification();
162         final CommitLocalTransactionRequest ret = new CommitLocalTransactionRequest(getIdentifier(), nextSequence(),
163             localActor(), mod, recordedFailure, coordinated);
164         closedException = this::submittedException;
165         return ret;
166     }
167
168     @Override
169     void doSeal() {
170         Preconditions.checkState(sealedModification == null, "Transaction %s is already sealed", getIdentifier());
171         final CursorAwareDataTreeModification mod = getModification();
172         mod.ready();
173         sealedModification = mod;
174     }
175
176     @Override
177     void flushState(final AbstractProxyTransaction successor) {
178         sealedModification.applyToCursor(new AbstractDataTreeModificationCursor() {
179             @Override
180             public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
181                 successor.write(current().node(child), data);
182             }
183
184             @Override
185             public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
186                 successor.merge(current().node(child), data);
187             }
188
189             @Override
190             public void delete(final PathArgument child) {
191                 successor.delete(current().node(child));
192             }
193         });
194     }
195
196     DataTreeSnapshot getSnapshot() {
197         Preconditions.checkState(sealedModification != null, "Proxy %s is not sealed yet", getIdentifier());
198         return sealedModification;
199     }
200
201     @Override
202     void applyModifyTransactionRequest(final ModifyTransactionRequest request,
203             final @Nullable Consumer<Response<?, ?>> callback) {
204         for (final TransactionModification mod : request.getModifications()) {
205             if (mod instanceof TransactionWrite) {
206                 write(mod.getPath(), ((TransactionWrite)mod).getData());
207             } else if (mod instanceof TransactionMerge) {
208                 merge(mod.getPath(), ((TransactionMerge)mod).getData());
209             } else if (mod instanceof TransactionDelete) {
210                 delete(mod.getPath());
211             } else {
212                 throw new IllegalArgumentException("Unsupported modification " + mod);
213             }
214         }
215
216         final java.util.Optional<PersistenceProtocol> maybeProtocol = request.getPersistenceProtocol();
217         if (maybeProtocol.isPresent()) {
218             Verify.verify(callback != null, "Request {} has null callback", request);
219             ensureSealed();
220
221             switch (maybeProtocol.get()) {
222                 case ABORT:
223                     sendAbort(callback);
224                     break;
225                 case READY:
226                     // No-op, as we have already issued a seal()
227                     break;
228                 case SIMPLE:
229                     sendRequest(commitRequest(false), callback);
230                     break;
231                 case THREE_PHASE:
232                     sendRequest(commitRequest(true), callback);
233                     break;
234                 default:
235                     throw new IllegalArgumentException("Unhandled protocol " + maybeProtocol.get());
236             }
237         }
238     }
239
240     @Override
241     void handleForwardedRemoteRequest(final TransactionRequest<?> request,
242             final @Nullable Consumer<Response<?, ?>> callback) {
243         LOG.debug("Applying forwarded request {}", request);
244
245         if (request instanceof TransactionPreCommitRequest) {
246             sendRequest(new TransactionPreCommitRequest(getIdentifier(), nextSequence(), localActor()), callback);
247         } else if (request instanceof TransactionDoCommitRequest) {
248             sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), callback);
249         } else if (request instanceof TransactionAbortRequest) {
250             sendAbort(callback);
251         } else {
252             super.handleForwardedRemoteRequest(request, callback);
253         }
254     }
255
256     @Override
257     void forwardToLocal(final LocalProxyTransaction successor, final TransactionRequest<?> request,
258             final Consumer<Response<?, ?>> callback) {
259         if (request instanceof CommitLocalTransactionRequest) {
260             Verify.verify(successor instanceof LocalReadWriteProxyTransaction);
261             ((LocalReadWriteProxyTransaction) successor).sendCommit((CommitLocalTransactionRequest)request, callback);
262             LOG.debug("Forwarded request {} to successor {}", request, successor);
263         } else {
264             super.forwardToLocal(successor, request, callback);
265         }
266     }
267
268     @Override
269     void sendAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
270         super.sendAbort(request, callback);
271         closedException = this::abortedException;
272     }
273
274     private CursorAwareDataTreeModification getModification() {
275         if (closedException != null) {
276             throw closedException.get();
277         }
278
279         return modification;
280     }
281
282     private void sendCommit(final CommitLocalTransactionRequest request, final Consumer<Response<?, ?>> callback) {
283         // Rebase old modification on new data tree.
284         final CursorAwareDataTreeModification mod = getModification();
285
286         try (DataTreeModificationCursor cursor = mod.createCursor(YangInstanceIdentifier.EMPTY)) {
287             request.getModification().applyToCursor(cursor);
288         }
289
290         ensureSealed();
291         sendRequest(commitRequest(request.isCoordinated()), callback);
292     }
293 }

©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.