2a81e1d0aa37714cf208beea5d9012cf893ff96c
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / LocalProxyTransaction.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.util.concurrent.FluentFuture;
12 import java.util.Optional;
13 import java.util.function.Consumer;
14 import javax.annotation.Nonnull;
15 import javax.annotation.Nullable;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.opendaylight.controller.cluster.access.commands.AbortLocalTransactionRequest;
18 import org.opendaylight.controller.cluster.access.commands.AbstractLocalTransactionRequest;
19 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
20 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionSuccess;
22 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceRequest;
23 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
24 import org.opendaylight.controller.cluster.access.commands.ReadTransactionRequest;
25 import org.opendaylight.controller.cluster.access.commands.ReadTransactionSuccess;
26 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
27 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
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.util.concurrent.FluentFutures;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
36 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * An {@link AbstractProxyTransaction} for dispatching a transaction towards a shard leader which is co-located with
42  * the client instance.
43  *
44  * <p>
45  * It requires a {@link DataTreeSnapshot}, which is used to instantiated a new {@link DataTreeModification}. Operations
46  * are then performed on this modification and once the transaction is submitted, the modification is sent to the shard
47  * leader.
48  *
49  * <p>
50  * This class is not thread-safe as usual with transactions. Since it does not interact with the backend until the
51  * transaction is submitted, at which point this class gets out of the picture, this is not a cause for concern.
52  *
53  * @author Robert Varga
54  */
55 @NotThreadSafe
56 abstract class LocalProxyTransaction extends AbstractProxyTransaction {
57     private static final Logger LOG = LoggerFactory.getLogger(LocalProxyTransaction.class);
58
59     private final TransactionIdentifier identifier;
60
61     LocalProxyTransaction(final ProxyHistory parent, final TransactionIdentifier identifier, final boolean isDone) {
62         super(parent, isDone);
63         this.identifier = Preconditions.checkNotNull(identifier);
64     }
65
66     @Override
67     public final TransactionIdentifier getIdentifier() {
68         return identifier;
69     }
70
71     @Nonnull
72     abstract DataTreeSnapshot readOnlyView();
73
74     abstract void applyForwardedModifyTransactionRequest(ModifyTransactionRequest request,
75             @Nullable Consumer<Response<?, ?>> callback);
76
77     abstract void replayModifyTransactionRequest(ModifyTransactionRequest request,
78             @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
79
80     @Override
81     final FluentFuture<Boolean> doExists(final YangInstanceIdentifier path) {
82         return FluentFutures.immediateFluentFuture(readOnlyView().readNode(path).isPresent());
83     }
84
85     @Override
86     final FluentFuture<Optional<NormalizedNode<?, ?>>> doRead(final YangInstanceIdentifier path) {
87         return FluentFutures.immediateFluentFuture(readOnlyView().readNode(path));
88     }
89
90     @Override
91     final AbortLocalTransactionRequest abortRequest() {
92         return new AbortLocalTransactionRequest(identifier, localActor());
93     }
94
95     @Override
96     void handleReplayedLocalRequest(final AbstractLocalTransactionRequest<?> request,
97             final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
98         if (request instanceof AbortLocalTransactionRequest) {
99             enqueueAbort(request, callback, enqueuedTicks);
100         } else {
101             throw new IllegalArgumentException("Unhandled request" + request);
102         }
103     }
104
105     private boolean handleReadRequest(final TransactionRequest<?> request,
106             @Nullable final Consumer<Response<?, ?>> callback) {
107         // Note we delay completion of read requests to limit the scope at which the client can run, as they have
108         // listeners, which we do not want to execute while we are reconnecting.
109         if (request instanceof ReadTransactionRequest) {
110             final YangInstanceIdentifier path = ((ReadTransactionRequest) request).getPath();
111             final Optional<NormalizedNode<?, ?>> result = readOnlyView().readNode(path);
112             if (callback != null) {
113                 // XXX: FB does not see that callback is final, on stack and has be check for non-null.
114                 final Consumer<Response<?, ?>> fbIsStupid = Preconditions.checkNotNull(callback);
115                 executeInActor(() -> fbIsStupid.accept(new ReadTransactionSuccess(request.getTarget(),
116                     request.getSequence(), result)));
117             }
118             return true;
119         } else if (request instanceof ExistsTransactionRequest) {
120             final YangInstanceIdentifier path = ((ExistsTransactionRequest) request).getPath();
121             final boolean result = readOnlyView().readNode(path).isPresent();
122             if (callback != null) {
123                 // XXX: FB does not see that callback is final, on stack and has be check for non-null.
124                 final Consumer<Response<?, ?>> fbIsStupid = Preconditions.checkNotNull(callback);
125                 executeInActor(() -> fbIsStupid.accept(new ExistsTransactionSuccess(request.getTarget(),
126                     request.getSequence(), result)));
127             }
128             return true;
129         } else {
130             return false;
131         }
132     }
133
134     @Override
135     void handleReplayedRemoteRequest(final TransactionRequest<?> request,
136             @Nullable final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
137         if (request instanceof ModifyTransactionRequest) {
138             replayModifyTransactionRequest((ModifyTransactionRequest) request, callback, enqueuedTicks);
139         } else if (handleReadRequest(request, callback)) {
140             // No-op
141         } else if (request instanceof TransactionPurgeRequest) {
142             enqueuePurge(callback, enqueuedTicks);
143         } else if (request instanceof IncrementTransactionSequenceRequest) {
144             // Local transactions do not have non-replayable requests which would be visible to the backend,
145             // hence we can skip sequence increments.
146             LOG.debug("Not replaying {}", request);
147         } else {
148             throw new IllegalArgumentException("Unhandled request " + request);
149         }
150     }
151
152     /**
153      * Remote-to-local equivalent of {@link #handleReplayedRemoteRequest(TransactionRequest, Consumer, long)},
154      * except it is invoked in the forwarding path from
155      * {@link RemoteProxyTransaction#forwardToLocal(LocalProxyTransaction, TransactionRequest, Consumer)}.
156      *
157      * @param request Forwarded request
158      * @param callback Callback to be invoked once the request completes
159      */
160     void handleForwardedRemoteRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
161         if (request instanceof ModifyTransactionRequest) {
162             applyForwardedModifyTransactionRequest((ModifyTransactionRequest) request, callback);
163         } else if (handleReadRequest(request, callback)) {
164             // No-op
165         } else if (request instanceof TransactionPurgeRequest) {
166             enqueuePurge(callback);
167         } else {
168             throw new IllegalArgumentException("Unhandled request " + request);
169         }
170     }
171
172     @Override
173     final void forwardToRemote(final RemoteProxyTransaction successor, final TransactionRequest<?> request,
174                          final Consumer<Response<?, ?>> callback) {
175         if (request instanceof CommitLocalTransactionRequest) {
176             final CommitLocalTransactionRequest req = (CommitLocalTransactionRequest) request;
177             final DataTreeModification mod = req.getModification();
178
179             LOG.debug("Applying modification {} to successor {}", mod, successor);
180             mod.applyToCursor(new AbstractDataTreeModificationCursor() {
181                 @Override
182                 public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
183                     successor.write(current().node(child), data);
184                 }
185
186                 @Override
187                 public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
188                     successor.merge(current().node(child), data);
189                 }
190
191                 @Override
192                 public void delete(final PathArgument child) {
193                     successor.delete(current().node(child));
194                 }
195             });
196
197             successor.sealOnly();
198             final ModifyTransactionRequest successorReq = successor.commitRequest(req.isCoordinated());
199             successor.sendRequest(successorReq, callback);
200         } else if (request instanceof AbortLocalTransactionRequest) {
201             LOG.debug("Forwarding abort {} to successor {}", request, successor);
202             successor.abort();
203         } else if (request instanceof TransactionPurgeRequest) {
204             LOG.debug("Forwarding purge {} to successor {}", request, successor);
205             successor.enqueuePurge(callback);
206         } else if (request instanceof ModifyTransactionRequest) {
207             successor.handleForwardedRequest(request, callback);
208         } else {
209             throwUnhandledRequest(request);
210         }
211     }
212
213     @Override
214     void forwardToLocal(final LocalProxyTransaction successor, final TransactionRequest<?> request,
215             final Consumer<Response<?, ?>> callback) {
216         if (request instanceof AbortLocalTransactionRequest) {
217             successor.sendAbort(request, callback);
218         } else if (request instanceof TransactionPurgeRequest) {
219             successor.enqueuePurge(callback);
220         } else {
221             throwUnhandledRequest(request);
222         }
223
224         LOG.debug("Forwarded request {} to successor {}", request, successor);
225     }
226
227     private static void throwUnhandledRequest(final TransactionRequest<?> request) {
228         throw new IllegalArgumentException("Unhandled request" + request);
229     }
230
231     void sendAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
232         sendRequest(request, callback);
233     }
234
235     void enqueueAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
236             final long enqueuedTicks) {
237         enqueueRequest(request, callback, enqueuedTicks);
238     }
239 }