BUG-5280: split out cds akka client substrate
[controller.git] / opendaylight / md-sal / cds-access-client / src / main / java / org / opendaylight / controller / cluster / access / client / ClientActorBehavior.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.access.client;
9
10 import com.google.common.annotations.Beta;
11 import java.util.Optional;
12 import java.util.concurrent.CompletionStage;
13 import javax.annotation.Nonnull;
14 import javax.annotation.Nullable;
15 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
16 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
17 import org.opendaylight.controller.cluster.access.concepts.FailureEnvelope;
18 import org.opendaylight.controller.cluster.access.concepts.RequestException;
19 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
20 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
21 import org.opendaylight.controller.cluster.access.concepts.SuccessEnvelope;
22 import org.opendaylight.yangtools.concepts.Identifiable;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import scala.concurrent.duration.FiniteDuration;
26
27 /**
28  * A behavior, which handles messages sent to a {@link AbstractClientActor}.
29  *
30  * @author Robert Varga
31  */
32 @Beta
33 public abstract class ClientActorBehavior extends RecoveredClientActorBehavior<ClientActorContext>
34         implements Identifiable<ClientIdentifier> {
35     private static final Logger LOG = LoggerFactory.getLogger(ClientActorBehavior.class);
36
37     protected ClientActorBehavior(final @Nonnull ClientActorContext context) {
38         super(context);
39     }
40
41     @Override
42     public final @Nonnull ClientIdentifier getIdentifier() {
43         return context().getIdentifier();
44     }
45
46     @Override
47     final ClientActorBehavior onReceiveCommand(final Object command) {
48         if (command instanceof InternalCommand) {
49             return ((InternalCommand) command).execute(this);
50         }
51         if (command instanceof SuccessEnvelope) {
52             return onRequestSuccess((SuccessEnvelope) command);
53         }
54         if (command instanceof FailureEnvelope) {
55             return onRequestFailure((FailureEnvelope) command);
56         }
57
58         return onCommand(command);
59     }
60
61     private ClientActorBehavior onRequestSuccess(final SuccessEnvelope command) {
62         return context().completeRequest(this, command);
63     }
64
65     private ClientActorBehavior onRequestFailure(final FailureEnvelope command) {
66         final RequestFailure<?, ?> failure = command.getMessage();
67         final RequestException cause = failure.getCause();
68         if (cause instanceof RetiredGenerationException) {
69             LOG.error("{}: current generation {} has been superseded", persistenceId(), getIdentifier(), cause);
70             haltClient(cause);
71             context().poison(cause);
72             return null;
73         }
74
75         if (failure.isHardFailure()) {
76             return context().completeRequest(this, command);
77         }
78
79         // TODO: add instanceof checks on cause to detect more problems
80
81         LOG.warn("{}: Unhandled retriable failure {}, promoting to hard failure", persistenceId(), command);
82         return context().completeRequest(this, command);
83     }
84
85     // This method is executing in the actor context, hence we can safely interact with the queue
86     private ClientActorBehavior doSendRequest(final long sequence, final TransactionRequest<?> request,
87             final RequestCallback callback) {
88         // Get or allocate queue for the request
89         final SequencedQueue queue = context().queueFor(request.getTarget().getHistoryId().getCookie());
90
91         // Note this is a tri-state return and can be null
92         final Optional<FiniteDuration> result = queue.enqueueRequest(sequence, request, callback);
93         if (result == null) {
94             // Happy path: we are done here
95             return this;
96         }
97
98         if (result.isPresent()) {
99             // Less happy path: we need to schedule a timer
100             scheduleQueueTimeout(queue, result.get());
101             return this;
102         }
103
104         startResolve(queue, request.getTarget().getHistoryId().getCookie());
105         return this;
106     }
107
108     // This method is executing in the actor context, hence we can safely interact with the queue
109     private void startResolve(final SequencedQueue queue, final long cookie) {
110         // Queue does not have backend information. Initiate resolution, which may actually be piggy-backing on to a
111         // previous request to resolve.
112         final CompletionStage<? extends BackendInfo> f = resolver().getBackendInfo(cookie);
113
114         // This is the tricky part: depending on timing, the queue may have a stale request for resolution, which has
115         // been invalidated or it may already have a reference to this resolution request. Let us give it a chance to
116         // update and it will indicate if this resolution request is an update. If it is, we'll piggy-back on it and
117         // run backend information update in the actor thread. If it is not, we do not need to do anything, as we will
118         // bulk-process all requests.
119         if (queue.expectProof(f)) {
120             f.thenAccept(backend -> context().executeInActor(cb -> cb.finishResolve(queue, f, backend)));
121         }
122     }
123
124     // This method is executing in the actor context, hence we can safely interact with the queue
125     private ClientActorBehavior finishResolve(final SequencedQueue queue,
126             final CompletionStage<? extends BackendInfo> futureBackend, final BackendInfo backend) {
127
128         final Optional<FiniteDuration> maybeTimeout = queue.setBackendInfo(futureBackend, backend);
129         if (maybeTimeout.isPresent()) {
130             scheduleQueueTimeout(queue, maybeTimeout.get());
131         }
132         return this;
133     }
134
135     // This method is executing in the actor context, hence we can safely interact with the queue
136     private void scheduleQueueTimeout(final SequencedQueue queue, final FiniteDuration timeout) {
137         LOG.debug("{}: scheduling timeout in {}", persistenceId(), timeout);
138         context().executeInActor(cb -> cb.queueTimeout(queue), timeout);
139     }
140
141     // This method is executing in the actor context, hence we can safely interact with the queue
142     private ClientActorBehavior queueTimeout(final SequencedQueue queue) {
143         final boolean needBackend;
144
145         try {
146             needBackend = queue.runTimeout();
147         } catch (NoProgressException e) {
148             // Uh-oh, no progress. The queue has already killed itself, now we need to remove it
149             context().removeQueue(queue);
150             return this;
151         }
152
153         if (needBackend) {
154             startResolve(queue, queue.getCookie());
155         }
156
157         return this;
158     }
159
160     /**
161      * Halt And Catch Fire.
162      *
163      * Halt processing on this client. Implementations need to ensure they initiate state flush procedures. No attempt
164      * to use this instance should be made after this method returns. Any such use may result in undefined behavior.
165      *
166      * @param cause Failure cause
167      */
168     protected abstract void haltClient(@Nonnull Throwable cause);
169
170     /**
171      * Override this method to handle any command which is not handled by the base behavior.
172      *
173      * @param command
174      * @return Next behavior to use, null if this actor should shut down.
175      */
176     protected abstract @Nullable ClientActorBehavior onCommand(@Nonnull Object command);
177
178     /**
179      * Override this method to provide a backend resolver instance.
180      *
181      * @return
182      */
183     protected abstract @Nonnull BackendInfoResolver<?> resolver();
184
185     /**
186      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
187      * from any thread.
188      *
189      * @param request Request to send
190      * @param callback Callback to invoke
191      */
192     public final void sendRequest(final long sequence, final TransactionRequest<?> request, final RequestCallback callback) {
193         context().executeInActor(cb -> cb.doSendRequest(sequence, request, callback));
194     }
195 }