cc09265b5da3cb986c1e00d19831de07b8d61c2b
[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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.util.concurrent.FluentFuture;
13 import java.util.Optional;
14 import java.util.function.Consumer;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.eclipse.jdt.annotation.Nullable;
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.tree.api.DataTreeModification;
36 import org.opendaylight.yangtools.yang.data.tree.api.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. This class is NOT thread-safe.
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 abstract class LocalProxyTransaction extends AbstractProxyTransaction {
56     private static final Logger LOG = LoggerFactory.getLogger(LocalProxyTransaction.class);
57
58     private final TransactionIdentifier identifier;
59
60     LocalProxyTransaction(final ProxyHistory parent, final TransactionIdentifier identifier, final boolean isDone) {
61         super(parent, isDone);
62         this.identifier = requireNonNull(identifier);
63     }
64
65     @Override
66     public final TransactionIdentifier getIdentifier() {
67         return identifier;
68     }
69
70     abstract @NonNull DataTreeSnapshot readOnlyView();
71
72     abstract void applyForwardedModifyTransactionRequest(ModifyTransactionRequest request,
73             @Nullable Consumer<Response<?, ?>> callback);
74
75     abstract void replayModifyTransactionRequest(ModifyTransactionRequest request,
76             @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
77
78     @Override
79     final FluentFuture<Boolean> doExists(final YangInstanceIdentifier path) {
80         return FluentFutures.immediateBooleanFluentFuture(readOnlyView().readNode(path).isPresent());
81     }
82
83     @Override
84     final FluentFuture<Optional<NormalizedNode>> doRead(final YangInstanceIdentifier path) {
85         return FluentFutures.immediateFluentFuture(readOnlyView().readNode(path));
86     }
87
88     @Override
89     final AbortLocalTransactionRequest abortRequest() {
90         return new AbortLocalTransactionRequest(identifier, localActor());
91     }
92
93     @Override
94     void handleReplayedLocalRequest(final AbstractLocalTransactionRequest<?> request,
95             final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
96         if (request instanceof AbortLocalTransactionRequest) {
97             enqueueAbort(request, callback, enqueuedTicks);
98         } else {
99             throw new IllegalArgumentException("Unhandled request" + request);
100         }
101     }
102
103     private boolean handleReadRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
104         // Note we delay completion of read requests to limit the scope at which the client can run, as they have
105         // listeners, which we do not want to execute while we are reconnecting.
106         if (request instanceof ReadTransactionRequest) {
107             if (callback != null) {
108                 final YangInstanceIdentifier path = ((ReadTransactionRequest) request).getPath();
109                 final Optional<NormalizedNode> result = readOnlyView().readNode(path);
110                 executeInActor(() -> callback.accept(new ReadTransactionSuccess(request.getTarget(),
111                     request.getSequence(), result)));
112             }
113             return true;
114         } else if (request instanceof ExistsTransactionRequest) {
115             if (callback != null) {
116                 final YangInstanceIdentifier path = ((ExistsTransactionRequest) request).getPath();
117                 final boolean result = readOnlyView().readNode(path).isPresent();
118                 executeInActor(() -> callback.accept(new ExistsTransactionSuccess(request.getTarget(),
119                     request.getSequence(), result)));
120             }
121             return true;
122         } else {
123             return false;
124         }
125     }
126
127     @Override
128     void handleReplayedRemoteRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
129             final long enqueuedTicks) {
130         if (request instanceof ModifyTransactionRequest) {
131             replayModifyTransactionRequest((ModifyTransactionRequest) request, callback, enqueuedTicks);
132         } else if (handleReadRequest(request, callback)) {
133             // No-op
134         } else if (request instanceof TransactionPurgeRequest) {
135             enqueuePurge(callback, enqueuedTicks);
136         } else if (request instanceof IncrementTransactionSequenceRequest) {
137             // Local transactions do not have non-replayable requests which would be visible to the backend,
138             // hence we can skip sequence increments.
139             LOG.debug("Not replaying {}", request);
140         } else {
141             throw new IllegalArgumentException("Unhandled request " + request);
142         }
143     }
144
145     /**
146      * Remote-to-local equivalent of {@link #handleReplayedRemoteRequest(TransactionRequest, Consumer, long)},
147      * except it is invoked in the forwarding path from
148      * {@link RemoteProxyTransaction#forwardToLocal(LocalProxyTransaction, TransactionRequest, Consumer)}.
149      *
150      * @param request Forwarded request
151      * @param callback Callback to be invoked once the request completes
152      */
153     void handleForwardedRemoteRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
154         if (request instanceof ModifyTransactionRequest) {
155             applyForwardedModifyTransactionRequest((ModifyTransactionRequest) request, callback);
156         } else if (handleReadRequest(request, callback)) {
157             // No-op
158         } else if (request instanceof TransactionPurgeRequest) {
159             enqueuePurge(callback);
160         } else {
161             throw new IllegalArgumentException("Unhandled request " + request);
162         }
163     }
164
165     @Override
166     final void forwardToRemote(final RemoteProxyTransaction successor, final TransactionRequest<?> request,
167                          final Consumer<Response<?, ?>> callback) {
168         if (request instanceof CommitLocalTransactionRequest) {
169             final CommitLocalTransactionRequest req = (CommitLocalTransactionRequest) request;
170             final DataTreeModification mod = req.getModification();
171
172             LOG.debug("Applying modification {} to successor {}", mod, successor);
173             mod.applyToCursor(new AbstractDataTreeModificationCursor() {
174                 @Override
175                 public void write(final PathArgument child, final NormalizedNode data) {
176                     successor.write(current().node(child), data);
177                 }
178
179                 @Override
180                 public void merge(final PathArgument child, final NormalizedNode data) {
181                     successor.merge(current().node(child), data);
182                 }
183
184                 @Override
185                 public void delete(final PathArgument child) {
186                     successor.delete(current().node(child));
187                 }
188             });
189
190             successor.sealOnly();
191             final ModifyTransactionRequest successorReq = successor.commitRequest(req.isCoordinated());
192             successor.sendRequest(successorReq, callback);
193         } else if (request instanceof AbortLocalTransactionRequest) {
194             LOG.debug("Forwarding abort {} to successor {}", request, successor);
195             successor.abort();
196         } else if (request instanceof TransactionPurgeRequest) {
197             LOG.debug("Forwarding purge {} to successor {}", request, successor);
198             successor.enqueuePurge(callback);
199         } else if (request instanceof ModifyTransactionRequest) {
200             successor.handleForwardedRequest(request, callback);
201         } else {
202             throwUnhandledRequest(request);
203         }
204     }
205
206     @Override
207     void forwardToLocal(final LocalProxyTransaction successor, final TransactionRequest<?> request,
208             final Consumer<Response<?, ?>> callback) {
209         if (request instanceof AbortLocalTransactionRequest) {
210             successor.sendAbort(request, callback);
211         } else if (request instanceof TransactionPurgeRequest) {
212             successor.enqueuePurge(callback);
213         } else {
214             throwUnhandledRequest(request);
215         }
216
217         LOG.debug("Forwarded request {} to successor {}", request, successor);
218     }
219
220     private static void throwUnhandledRequest(final TransactionRequest<?> request) {
221         throw new IllegalArgumentException("Unhandled request " + request);
222     }
223
224     void sendAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
225         sendRequest(request, callback);
226     }
227
228     void enqueueAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
229             final long enqueuedTicks) {
230         enqueueRequest(request, callback, enqueuedTicks);
231     }
232 }