13b7fb4f56555d032fea2be8b3f387dd40b24288
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / RemoteProxyTransaction.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.util.concurrent.CheckedFuture;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.util.function.Consumer;
16 import org.opendaylight.controller.cluster.access.commands.AbstractReadTransactionRequest;
17 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionRequest;
18 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionSuccess;
19 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
20 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequestBuilder;
21 import org.opendaylight.controller.cluster.access.commands.ReadTransactionRequest;
22 import org.opendaylight.controller.cluster.access.commands.ReadTransactionSuccess;
23 import org.opendaylight.controller.cluster.access.commands.TransactionDelete;
24 import org.opendaylight.controller.cluster.access.commands.TransactionMerge;
25 import org.opendaylight.controller.cluster.access.commands.TransactionModification;
26 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
27 import org.opendaylight.controller.cluster.access.commands.TransactionWrite;
28 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
29 import org.opendaylight.controller.cluster.access.concepts.Response;
30 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
31 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
32 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * An {@link AbstractProxyTransaction} for dispatching a transaction towards a shard leader whose location is currently
40  * not known or is known to be not co-located with the client.
41  *
42  * It packages operations and sends them via the client actor queue to the shard leader. That queue is responsible for
43  * maintaining any submitted operations until the leader is discovered.
44  *
45  * This class is not safe to access from multiple application threads, as is usual for transactions. Its internal state
46  * transitions based on backend responses are thread-safe.
47  *
48  * @author Robert Varga
49  */
50 final class RemoteProxyTransaction extends AbstractProxyTransaction {
51     private static final Logger LOG = LoggerFactory.getLogger(RemoteProxyTransaction.class);
52
53     // FIXME: make this tuneable
54     private static final int REQUEST_MAX_MODIFICATIONS = 1000;
55
56     private final ModifyTransactionRequestBuilder builder;
57
58     private boolean builderBusy;
59
60     private volatile Exception operationFailure;
61
62     RemoteProxyTransaction(final DistributedDataStoreClientBehavior client,
63         final TransactionIdentifier identifier) {
64         super(client);
65         builder = new ModifyTransactionRequestBuilder(identifier, client.self());
66     }
67
68     @Override
69     public TransactionIdentifier getIdentifier() {
70         return builder.getIdentifier();
71     }
72
73     @Override
74     void doDelete(final YangInstanceIdentifier path) {
75         appendModification(new TransactionDelete(path));
76     }
77
78     @Override
79     void doMerge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
80         appendModification(new TransactionMerge(path, data));
81     }
82
83     @Override
84     void doWrite(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
85         appendModification(new TransactionWrite(path, data));
86     }
87
88     private <T> CheckedFuture<T, ReadFailedException> sendReadRequest(final AbstractReadTransactionRequest<?> request,
89             final Consumer<Response<?, ?>> completer, final ListenableFuture<T> future) {
90         // Check if a previous operation failed. If it has, do not bother sending anything and report a failure
91         final Exception local = operationFailure;
92         if (local != null) {
93             return Futures.immediateFailedCheckedFuture(new ReadFailedException("Previous operation failed", local));
94         }
95
96         // Make sure we send any modifications before issuing a read
97         ensureFlushedBuider();
98         client().sendRequest(nextSequence(), request, completer);
99         return MappingCheckedFuture.create(future, ReadFailedException.MAPPER);
100     }
101
102     @Override
103     CheckedFuture<Boolean, ReadFailedException> doExists(final YangInstanceIdentifier path) {
104         final SettableFuture<Boolean> future = SettableFuture.create();
105         return sendReadRequest(new ExistsTransactionRequest(getIdentifier(), client().self(), path),
106             t -> completeExists(future, t), future);
107     }
108
109     @Override
110     CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> doRead(final YangInstanceIdentifier path) {
111         final SettableFuture<Optional<NormalizedNode<?, ?>>> future = SettableFuture.create();
112         return sendReadRequest(new ReadTransactionRequest(getIdentifier(), client().self(), path),
113             t -> completeRead(future, t), future);
114     }
115
116     @Override
117     void doAbort() {
118         ensureInitializedBuider();
119         builder.setAbort();
120         flushBuilder();
121     }
122
123     private void ensureInitializedBuider() {
124         if (!builderBusy) {
125             builderBusy = true;
126         }
127     }
128
129     private void ensureFlushedBuider() {
130         if (builderBusy) {
131             flushBuilder();
132         }
133     }
134
135     private void flushBuilder() {
136         client().sendRequest(nextSequence(), builder.build(), this::completeModify);
137         builderBusy = false;
138     }
139
140     private void appendModification(final TransactionModification modification) {
141         if (operationFailure == null) {
142             ensureInitializedBuider();
143
144             builder.addModification(modification);
145             if (builder.size() >= REQUEST_MAX_MODIFICATIONS) {
146                 flushBuilder();
147             }
148         } else {
149             LOG.debug("Transaction {} failed, not attempting further transactions", getIdentifier());
150         }
151     }
152
153     private void completeModify(final Response<?, ?> response) {
154         LOG.debug("Modification request completed with {}", response);
155
156         if (response instanceof TransactionSuccess) {
157             // Happy path no-op
158         } else {
159             recordFailedResponse(response);
160         }
161     }
162
163     private Exception recordFailedResponse(final Response<?, ?> response) {
164         final Exception failure;
165         if (response instanceof RequestFailure) {
166             failure = ((RequestFailure<?, ?>) response).getCause();
167         } else {
168             LOG.warn("Unhandled response {}", response);
169             failure = new IllegalArgumentException("Unhandled response " + response.getClass());
170         }
171
172         if (operationFailure == null) {
173             LOG.debug("Transaction {} failed", getIdentifier(), failure);
174             operationFailure = failure;
175         }
176         return failure;
177     }
178
179     private void failFuture(final SettableFuture<?> future, final Response<?, ?> response) {
180         future.setException(recordFailedResponse(response));
181     }
182
183     private void completeExists(final SettableFuture<Boolean> future, final Response<?, ?> response) {
184         LOG.debug("Exists request completed with {}", response);
185
186         if (response instanceof ExistsTransactionSuccess) {
187             future.set(((ExistsTransactionSuccess) response).getExists());
188         } else {
189             failFuture(future, response);
190         }
191     }
192
193     private void completeRead(final SettableFuture<Optional<NormalizedNode<?, ?>>> future, final Response<?, ?> response) {
194         LOG.debug("Read request completed with {}", response);
195
196         if (response instanceof ReadTransactionSuccess) {
197             future.set(((ReadTransactionSuccess) response).getData());
198         } else {
199             failFuture(future, response);
200         }
201     }
202
203     @Override
204     ModifyTransactionRequest doCommit(final boolean coordinated) {
205         ensureInitializedBuider();
206         builder.setCommit(coordinated);
207
208         final ModifyTransactionRequest ret = builder.build();
209         builderBusy = false;
210         return ret;
211     }
212
213     @Override
214     void doSeal() {
215         // No-op
216     }
217 }