7c0ccd1c1b6a4d345447985165c4956cff8ece20
[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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.Futures;
14 import java.util.function.Consumer;
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.mdsal.common.api.ReadFailedException;
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) {
62         super(parent);
63         this.identifier = Preconditions.checkNotNull(identifier);
64     }
65
66     @Override
67     public final TransactionIdentifier getIdentifier() {
68         return identifier;
69     }
70
71     abstract DataTreeSnapshot readOnlyView();
72
73     abstract void applyModifyTransactionRequest(ModifyTransactionRequest request,
74             @Nullable Consumer<Response<?, ?>> callback);
75
76     abstract void replayModifyTransactionRequest(ModifyTransactionRequest request,
77             @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
78
79     @Override
80     final CheckedFuture<Boolean, ReadFailedException> doExists(final YangInstanceIdentifier path) {
81         return Futures.immediateCheckedFuture(readOnlyView().readNode(path).isPresent());
82     }
83
84     @Override
85     final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> doRead(final YangInstanceIdentifier path) {
86         return Futures.immediateCheckedFuture(readOnlyView().readNode(path));
87     }
88
89     @Override
90     final void doAbort() {
91         sendAbort(new AbortLocalTransactionRequest(identifier, localActor()), response -> {
92             LOG.debug("Transaction {} abort completed with {}", identifier, response);
93         });
94     }
95
96     @Override
97     void handleReplayedLocalRequest(final AbstractLocalTransactionRequest<?> request,
98             final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
99         if (request instanceof AbortLocalTransactionRequest) {
100             enqueueAbort(request, callback, enqueuedTicks);
101         } else {
102             throw new IllegalArgumentException("Unhandled request" + request);
103         }
104     }
105
106     private boolean handleReadRequest(final TransactionRequest<?> request,
107             final @Nullable Consumer<Response<?, ?>> callback) {
108         if (request instanceof ReadTransactionRequest) {
109             final YangInstanceIdentifier path = ((ReadTransactionRequest) request).getPath();
110             final Optional<NormalizedNode<?, ?>> result = readOnlyView().readNode(path);
111             callback.accept(new ReadTransactionSuccess(request.getTarget(), request.getSequence(), result));
112             return true;
113         } else if (request instanceof ExistsTransactionRequest) {
114             final YangInstanceIdentifier path = ((ExistsTransactionRequest) request).getPath();
115             final boolean result = readOnlyView().readNode(path).isPresent();
116             callback.accept(new ExistsTransactionSuccess(request.getTarget(), request.getSequence(), result));
117             return true;
118         } else {
119             return false;
120         }
121     }
122
123     @Override
124     void handleReplayedRemoteRequest(final TransactionRequest<?> request,
125             final @Nullable Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
126         if (request instanceof ModifyTransactionRequest) {
127             replayModifyTransactionRequest((ModifyTransactionRequest) request, callback, enqueuedTicks);
128         } else if (handleReadRequest(request, callback)) {
129             // No-op
130         } else if (request instanceof TransactionPurgeRequest) {
131             enqueuePurge(enqueuedTicks);
132         } else if (request instanceof IncrementTransactionSequenceRequest) {
133             // Local transactions do not have non-replayable requests which would be visible to the backend,
134             // hence we can skip sequence increments.
135             LOG.debug("Not replaying {}", request);
136         } else {
137             throw new IllegalArgumentException("Unhandled request " + request);
138         }
139     }
140
141     /**
142      * Remote-to-local equivalent of {@link #handleReplayedRemoteRequest(TransactionRequest, Consumer, long)},
143      * except it is invoked in the forwarding path from
144      * {@link RemoteProxyTransaction#forwardToLocal(LocalProxyTransaction, TransactionRequest, Consumer)}.
145      *
146      * @param request Forwarded request
147      * @param callback Callback to be invoked once the request completes
148      */
149     void handleForwardedRemoteRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
150         if (request instanceof ModifyTransactionRequest) {
151             applyModifyTransactionRequest((ModifyTransactionRequest) request, callback);
152         } else if (handleReadRequest(request, callback)) {
153             // No-op
154         } else if (request instanceof TransactionPurgeRequest) {
155             sendPurge();
156         } else {
157             throw new IllegalArgumentException("Unhandled request " + request);
158         }
159     }
160
161     @Override
162     final void forwardToRemote(final RemoteProxyTransaction successor, final TransactionRequest<?> request,
163                          final Consumer<Response<?, ?>> callback) {
164         if (request instanceof CommitLocalTransactionRequest) {
165             final CommitLocalTransactionRequest req = (CommitLocalTransactionRequest) request;
166             final DataTreeModification mod = req.getModification();
167
168             LOG.debug("Applying modification {} to successor {}", mod, successor);
169             mod.applyToCursor(new AbstractDataTreeModificationCursor() {
170                 @Override
171                 public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
172                     successor.write(current().node(child), data);
173                 }
174
175                 @Override
176                 public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
177                     successor.merge(current().node(child), data);
178                 }
179
180                 @Override
181                 public void delete(final PathArgument child) {
182                     successor.delete(current().node(child));
183                 }
184             });
185
186             successor.ensureSealed();
187
188             final ModifyTransactionRequest successorReq = successor.commitRequest(req.isCoordinated());
189             successor.sendRequest(successorReq, callback);
190         } else if (request instanceof AbortLocalTransactionRequest) {
191             LOG.debug("Forwarding abort {} to successor {}", request, successor);
192             successor.abort();
193         } else if (request instanceof TransactionPurgeRequest) {
194             LOG.debug("Forwarding purge {} to successor {}", request, successor);
195             successor.sendPurge();
196         } else {
197             throw new IllegalArgumentException("Unhandled request" + request);
198         }
199     }
200
201     @Override
202     void forwardToLocal(final LocalProxyTransaction successor, final TransactionRequest<?> request,
203             final Consumer<Response<?, ?>> callback) {
204         if (request instanceof AbortLocalTransactionRequest) {
205             successor.sendAbort(request, callback);
206         } else if (request instanceof TransactionPurgeRequest) {
207             successor.sendPurge();
208         } else {
209             throw new IllegalArgumentException("Unhandled request" + request);
210         }
211
212         LOG.debug("Forwarded request {} to successor {}", request, successor);
213     }
214
215     void sendAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
216         sendRequest(request, callback);
217     }
218
219     void enqueueAbort(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
220             final long enqueuedTicks) {
221         enqueueRequest(request, callback, enqueuedTicks);
222     }
223 }