3b5f80ffe8bc02ee267620f7bfafdbcd1cf01a2a
[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 javax.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.AbstractReadTransactionRequest;
20 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionRequest;
22 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionSuccess;
23 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceRequest;
24 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
25 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequestBuilder;
26 import org.opendaylight.controller.cluster.access.commands.PersistenceProtocol;
27 import org.opendaylight.controller.cluster.access.commands.ReadTransactionRequest;
28 import org.opendaylight.controller.cluster.access.commands.ReadTransactionSuccess;
29 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
30 import org.opendaylight.controller.cluster.access.commands.TransactionDelete;
31 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
32 import org.opendaylight.controller.cluster.access.commands.TransactionMerge;
33 import org.opendaylight.controller.cluster.access.commands.TransactionModification;
34 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
35 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
36 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
37 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
38 import org.opendaylight.controller.cluster.access.commands.TransactionWrite;
39 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
40 import org.opendaylight.controller.cluster.access.concepts.Response;
41 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
42 import org.opendaylight.controller.cluster.datastore.util.AbstractDataTreeModificationCursor;
43 import org.opendaylight.mdsal.common.api.ReadFailedException;
44 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * An {@link AbstractProxyTransaction} for dispatching a transaction towards a shard leader whose location is currently
54  * not known or is known to be not co-located with the client.
55  *
56  * <p>
57  * It packages operations and sends them via the client actor queue to the shard leader. That queue is responsible for
58  * maintaining any submitted operations until the leader is discovered.
59  *
60  * <p>
61  * This class is not safe to access from multiple application threads, as is usual for transactions. Its internal state
62  * transitions based on backend responses are thread-safe.
63  *
64  * @author Robert Varga
65  */
66 final class RemoteProxyTransaction extends AbstractProxyTransaction {
67     private static final Logger LOG = LoggerFactory.getLogger(RemoteProxyTransaction.class);
68
69     // FIXME: make this tuneable
70     private static final int REQUEST_MAX_MODIFICATIONS = 1000;
71
72     private final ModifyTransactionRequestBuilder builder;
73     private final boolean sendReadyOnSeal;
74     private final boolean snapshotOnly;
75
76     private boolean builderBusy;
77
78     private volatile Exception operationFailure;
79
80     RemoteProxyTransaction(final ProxyHistory parent, final TransactionIdentifier identifier,
81             final boolean snapshotOnly, final boolean sendReadyOnSeal, final boolean isDone) {
82         super(parent, isDone);
83         this.snapshotOnly = snapshotOnly;
84         this.sendReadyOnSeal = sendReadyOnSeal;
85         builder = new ModifyTransactionRequestBuilder(identifier, localActor());
86     }
87
88     @Override
89     boolean isSnapshotOnly() {
90         return snapshotOnly;
91     }
92
93     @Override
94     public TransactionIdentifier getIdentifier() {
95         return builder.getIdentifier();
96     }
97
98     @Override
99     void doDelete(final YangInstanceIdentifier path) {
100         appendModification(new TransactionDelete(path), Optional.absent());
101     }
102
103     @Override
104     void doMerge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
105         appendModification(new TransactionMerge(path, data), Optional.absent());
106     }
107
108     @Override
109     void doWrite(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
110         appendModification(new TransactionWrite(path, data), Optional.absent());
111     }
112
113     private <T> CheckedFuture<T, ReadFailedException> sendReadRequest(final AbstractReadTransactionRequest<?> request,
114             final Consumer<Response<?, ?>> completer, final ListenableFuture<T> future) {
115         // Check if a previous operation failed. If it has, do not bother sending anything and report a failure
116         final Exception local = operationFailure;
117         if (local != null) {
118             return Futures.immediateFailedCheckedFuture(new ReadFailedException("Previous operation failed", local));
119         }
120
121         // Make sure we send any modifications before issuing a read
122         ensureFlushedBuider();
123         sendRequest(request, completer);
124         return MappingCheckedFuture.create(future, ReadFailedException.MAPPER);
125     }
126
127     @Override
128     CheckedFuture<Boolean, ReadFailedException> doExists(final YangInstanceIdentifier path) {
129         final SettableFuture<Boolean> future = SettableFuture.create();
130         return sendReadRequest(new ExistsTransactionRequest(getIdentifier(), nextSequence(), localActor(), path,
131             isSnapshotOnly()), t -> completeExists(future, t), future);
132     }
133
134     @Override
135     CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> doRead(final YangInstanceIdentifier path) {
136         final SettableFuture<Optional<NormalizedNode<?, ?>>> future = SettableFuture.create();
137         return sendReadRequest(new ReadTransactionRequest(getIdentifier(), nextSequence(), localActor(), path,
138             isSnapshotOnly()), t -> completeRead(future, t), future);
139     }
140
141     private void ensureInitializedBuilder() {
142         if (!builderBusy) {
143             builder.setSequence(nextSequence());
144             builderBusy = true;
145         }
146     }
147
148     private void ensureFlushedBuider() {
149         if (builderBusy) {
150             flushBuilder();
151         }
152     }
153
154     private void ensureFlushedBuider(final Optional<Long> enqueuedTicks) {
155         if (builderBusy) {
156             flushBuilder(enqueuedTicks);
157         }
158     }
159
160     private void flushBuilder() {
161         flushBuilder(Optional.absent());
162     }
163
164     private void flushBuilder(final Optional<Long> enqueuedTicks) {
165         final ModifyTransactionRequest request = builder.build();
166         builderBusy = false;
167
168         sendModification(request, enqueuedTicks);
169     }
170
171     private void sendModification(final TransactionRequest<?> request, final Optional<Long> enqueuedTicks) {
172         if (enqueuedTicks.isPresent()) {
173             enqueueRequest(request, response -> completeModify(request, response), enqueuedTicks.get().longValue());
174         } else {
175             sendRequest(request, response -> completeModify(request, response));
176         }
177     }
178
179     private void appendModification(final TransactionModification modification) {
180         appendModification(modification, Optional.absent());
181     }
182
183     private void appendModification(final TransactionModification modification, final Optional<Long> enqueuedTicks) {
184         if (operationFailure == null) {
185             ensureInitializedBuilder();
186
187             builder.addModification(modification);
188             if (builder.size() >= REQUEST_MAX_MODIFICATIONS) {
189                 flushBuilder(enqueuedTicks);
190             }
191         } else {
192             LOG.debug("Transaction {} failed, not attempting further transactions", getIdentifier());
193         }
194     }
195
196     private void completeModify(final TransactionRequest<?> request, final Response<?, ?> response) {
197         LOG.debug("Modification request {} completed with {}", request, response);
198
199         if (response instanceof TransactionSuccess) {
200             // Happy path
201             recordSuccessfulRequest(request);
202         } else {
203             recordFailedResponse(response);
204         }
205     }
206
207     private Exception recordFailedResponse(final Response<?, ?> response) {
208         final Exception failure;
209         if (response instanceof RequestFailure) {
210             failure = ((RequestFailure<?, ?>) response).getCause();
211         } else {
212             LOG.warn("Unhandled response {}", response);
213             failure = new IllegalArgumentException("Unhandled response " + response.getClass());
214         }
215
216         if (operationFailure == null) {
217             LOG.debug("Transaction {} failed", getIdentifier(), failure);
218             operationFailure = failure;
219         }
220         return failure;
221     }
222
223     private void failFuture(final SettableFuture<?> future, final Response<?, ?> response) {
224         future.setException(recordFailedResponse(response));
225     }
226
227     private void completeExists(final SettableFuture<Boolean> future, final Response<?, ?> response) {
228         LOG.debug("Exists request completed with {}", response);
229
230         if (response instanceof ExistsTransactionSuccess) {
231             future.set(((ExistsTransactionSuccess) response).getExists());
232         } else {
233             failFuture(future, response);
234         }
235
236         recordFinishedRequest(response);
237     }
238
239     private void completeRead(final SettableFuture<Optional<NormalizedNode<?, ?>>> future,
240             final Response<?, ?> response) {
241         LOG.debug("Read request completed with {}", response);
242
243         if (response instanceof ReadTransactionSuccess) {
244             future.set(((ReadTransactionSuccess) response).getData());
245         } else {
246             failFuture(future, response);
247         }
248
249         recordFinishedRequest(response);
250     }
251
252     @Override
253     ModifyTransactionRequest abortRequest() {
254         ensureInitializedBuilder();
255         builder.setAbort();
256         final ModifyTransactionRequest ret = builder.build();
257         builderBusy = false;
258         return ret;
259     }
260
261     @Override
262     ModifyTransactionRequest commitRequest(final boolean coordinated) {
263         ensureInitializedBuilder();
264         builder.setCommit(coordinated);
265
266         final ModifyTransactionRequest ret = builder.build();
267         builderBusy = false;
268         return ret;
269     }
270
271     @Override
272     void doSeal() {
273         if (sendReadyOnSeal) {
274             ensureInitializedBuilder();
275             builder.setReady();
276             flushBuilder();
277         }
278     }
279
280     @Override
281     void flushState(final AbstractProxyTransaction successor) {
282         if (builderBusy) {
283             final ModifyTransactionRequest request = builder.build();
284             builderBusy = false;
285             forwardToSuccessor(successor, request, null);
286         }
287     }
288
289     @Override
290     void forwardToRemote(final RemoteProxyTransaction successor, final TransactionRequest<?> request,
291             final Consumer<Response<?, ?>> callback) {
292         successor.handleForwardedRequest(request, callback);
293     }
294
295     private void handleForwardedRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
296         if (request instanceof ModifyTransactionRequest) {
297             final ModifyTransactionRequest req = (ModifyTransactionRequest) request;
298
299             req.getModifications().forEach(this::appendModification);
300
301             final java.util.Optional<PersistenceProtocol> maybeProto = req.getPersistenceProtocol();
302             if (maybeProto.isPresent()) {
303                 ensureSealed();
304
305                 final TransactionRequest<?> tmp;
306                 switch (maybeProto.get()) {
307                     case ABORT:
308                         tmp = abortRequest();
309                         sendRequest(tmp, resp -> {
310                             completeModify(tmp, resp);
311                             callback.accept(resp);
312                         });
313                         break;
314                     case SIMPLE:
315                         tmp = commitRequest(false);
316                         sendRequest(tmp, resp -> {
317                             completeModify(tmp, resp);
318                             callback.accept(resp);
319                         });
320                         break;
321                     case THREE_PHASE:
322                         tmp = commitRequest(true);
323                         sendRequest(tmp, resp -> {
324                             recordSuccessfulRequest(tmp);
325                             callback.accept(resp);
326                         });
327                         break;
328                     case READY:
329                         //no op
330                         break;
331                     default:
332                         throw new IllegalArgumentException("Unhandled protocol " + maybeProto.get());
333                 }
334             }
335         } else if (request instanceof ReadTransactionRequest) {
336             ensureFlushedBuider();
337             sendRequest(new ReadTransactionRequest(getIdentifier(), nextSequence(), localActor(),
338                 ((ReadTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
339                     recordFinishedRequest(resp);
340                     callback.accept(resp);
341                 });
342         } else if (request instanceof ExistsTransactionRequest) {
343             ensureFlushedBuider();
344             sendRequest(new ExistsTransactionRequest(getIdentifier(), nextSequence(), localActor(),
345                 ((ExistsTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
346                     recordFinishedRequest(resp);
347                     callback.accept(resp);
348                 });
349         } else if (request instanceof TransactionPreCommitRequest) {
350             ensureFlushedBuider();
351             final TransactionRequest<?> tmp = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
352                 localActor());
353             sendRequest(tmp, resp -> {
354                 recordSuccessfulRequest(tmp);
355                 callback.accept(resp);
356             });
357         } else if (request instanceof TransactionDoCommitRequest) {
358             ensureFlushedBuider();
359             sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), callback);
360         } else if (request instanceof TransactionAbortRequest) {
361             ensureFlushedBuider();
362             sendDoAbort(callback);
363         } else if (request instanceof TransactionPurgeRequest) {
364             enqueuePurge(callback);
365         } else {
366             throw new IllegalArgumentException("Unhandled request {}" + request);
367         }
368     }
369
370     @Override
371     void forwardToLocal(final LocalProxyTransaction successor, final TransactionRequest<?> request,
372             final Consumer<Response<?, ?>> callback) {
373         successor.handleForwardedRemoteRequest(request, callback);
374     }
375
376     @Override
377     void handleReplayedLocalRequest(final AbstractLocalTransactionRequest<?> request,
378             final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
379         if (request instanceof CommitLocalTransactionRequest) {
380             replayLocalCommitRequest((CommitLocalTransactionRequest) request, callback, enqueuedTicks);
381         } else if (request instanceof AbortLocalTransactionRequest) {
382             enqueueRequest(abortRequest(), callback, enqueuedTicks);
383         } else {
384             throw new IllegalStateException("Unhandled request " + request);
385         }
386     }
387
388     private void replayLocalCommitRequest(final CommitLocalTransactionRequest request,
389             final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
390         final DataTreeModification mod = request.getModification();
391         final Optional<Long> optTicks = Optional.of(Long.valueOf(enqueuedTicks));
392
393         mod.applyToCursor(new AbstractDataTreeModificationCursor() {
394             @Override
395             public void write(final PathArgument child, final NormalizedNode<?, ?> data) {
396                 appendModification(new TransactionWrite(current().node(child), data), optTicks);
397             }
398
399             @Override
400             public void merge(final PathArgument child, final NormalizedNode<?, ?> data) {
401                 appendModification(new TransactionMerge(current().node(child), data), optTicks);
402             }
403
404             @Override
405             public void delete(final PathArgument child) {
406                 appendModification(new TransactionDelete(current().node(child)), optTicks);
407             }
408         });
409
410         enqueueRequest(commitRequest(request.isCoordinated()), callback, enqueuedTicks);
411     }
412
413     @Override
414     void handleReplayedRemoteRequest(final TransactionRequest<?> request,
415             final @Nullable Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
416         final Consumer<Response<?, ?>> cb = callback != null ? callback : resp -> { };
417         final Optional<Long> optTicks = Optional.of(Long.valueOf(enqueuedTicks));
418
419         if (request instanceof ModifyTransactionRequest) {
420             final ModifyTransactionRequest req = (ModifyTransactionRequest) request;
421             for (TransactionModification mod : req.getModifications()) {
422                 appendModification(mod, optTicks);
423             }
424
425             final java.util.Optional<PersistenceProtocol> maybeProto = req.getPersistenceProtocol();
426             if (maybeProto.isPresent()) {
427                 ensureSealed();
428
429                 final TransactionRequest<?> tmp;
430                 switch (maybeProto.get()) {
431                     case ABORT:
432                         tmp = abortRequest();
433                         enqueueRequest(tmp, resp -> {
434                             completeModify(tmp, resp);
435                             cb.accept(resp);
436                         }, enqueuedTicks);
437                         break;
438                     case SIMPLE:
439                         tmp = commitRequest(false);
440                         enqueueRequest(tmp, resp -> {
441                             completeModify(tmp, resp);
442                             cb.accept(resp);
443                         }, enqueuedTicks);
444                         break;
445                     case THREE_PHASE:
446                         tmp = commitRequest(true);
447                         enqueueRequest(tmp, resp -> {
448                             recordSuccessfulRequest(tmp);
449                             cb.accept(resp);
450                         }, enqueuedTicks);
451                         break;
452                     case READY:
453                         //no op
454                         break;
455                     default:
456                         throw new IllegalArgumentException("Unhandled protocol " + maybeProto.get());
457                 }
458             }
459         } else if (request instanceof ReadTransactionRequest) {
460             ensureFlushedBuider(optTicks);
461             enqueueRequest(new ReadTransactionRequest(getIdentifier(), nextSequence(), localActor(),
462                 ((ReadTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
463                     recordFinishedRequest(resp);
464                     cb.accept(resp);
465                 }, enqueuedTicks);
466         } else if (request instanceof ExistsTransactionRequest) {
467             ensureFlushedBuider(optTicks);
468             enqueueRequest(new ExistsTransactionRequest(getIdentifier(), nextSequence(), localActor(),
469                 ((ExistsTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
470                     recordFinishedRequest(resp);
471                     cb.accept(resp);
472                 }, enqueuedTicks);
473         } else if (request instanceof TransactionPreCommitRequest) {
474             ensureFlushedBuider(optTicks);
475             final TransactionRequest<?> tmp = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
476                 localActor());
477             enqueueRequest(tmp, resp -> {
478                 recordSuccessfulRequest(tmp);
479                 cb.accept(resp);
480             }, enqueuedTicks);
481         } else if (request instanceof TransactionDoCommitRequest) {
482             ensureFlushedBuider(optTicks);
483             enqueueRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), callback,
484                 enqueuedTicks);
485         } else if (request instanceof TransactionAbortRequest) {
486             ensureFlushedBuider(optTicks);
487             enqueueDoAbort(callback, enqueuedTicks);
488         } else if (request instanceof TransactionPurgeRequest) {
489             enqueuePurge(callback, enqueuedTicks);
490         } else if (request instanceof IncrementTransactionSequenceRequest) {
491             final IncrementTransactionSequenceRequest req = (IncrementTransactionSequenceRequest) request;
492             ensureFlushedBuider(optTicks);
493             enqueueRequest(new IncrementTransactionSequenceRequest(getIdentifier(), nextSequence(), localActor(),
494                 snapshotOnly, req.getIncrement()), callback, enqueuedTicks);
495             incrementSequence(req.getIncrement());
496         } else {
497             throw new IllegalArgumentException("Unhandled request {}" + request);
498         }
499     }
500 }

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