2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.access.client;
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;
28 * A behavior, which handles messages sent to a {@link AbstractClientActor}.
30 * @author Robert Varga
33 public abstract class ClientActorBehavior extends RecoveredClientActorBehavior<ClientActorContext>
34 implements Identifiable<ClientIdentifier> {
35 private static final Logger LOG = LoggerFactory.getLogger(ClientActorBehavior.class);
37 protected ClientActorBehavior(@Nonnull final ClientActorContext context) {
43 public final ClientIdentifier getIdentifier() {
44 return context().getIdentifier();
48 final ClientActorBehavior onReceiveCommand(final Object command) {
49 if (command instanceof InternalCommand) {
50 return ((InternalCommand) command).execute(this);
52 if (command instanceof SuccessEnvelope) {
53 return onRequestSuccess((SuccessEnvelope) command);
55 if (command instanceof FailureEnvelope) {
56 return onRequestFailure((FailureEnvelope) command);
59 return onCommand(command);
62 private ClientActorBehavior onRequestSuccess(final SuccessEnvelope command) {
63 return context().completeRequest(this, command);
66 private ClientActorBehavior onRequestFailure(final FailureEnvelope command) {
67 final RequestFailure<?, ?> failure = command.getMessage();
68 final RequestException cause = failure.getCause();
69 if (cause instanceof RetiredGenerationException) {
70 LOG.error("{}: current generation {} has been superseded", persistenceId(), getIdentifier(), cause);
72 context().poison(cause);
76 if (failure.isHardFailure()) {
77 return context().completeRequest(this, command);
80 // TODO: add instanceof checks on cause to detect more problems
82 LOG.warn("{}: Unhandled retriable failure {}, promoting to hard failure", persistenceId(), command);
83 return context().completeRequest(this, command);
86 // This method is executing in the actor context, hence we can safely interact with the queue
87 private ClientActorBehavior doSendRequest(final TransactionRequest<?> request, final RequestCallback callback) {
88 // Get or allocate queue for the request
89 final SequencedQueue queue = context().queueFor(request.getTarget().getHistoryId().getCookie());
91 // Note this is a tri-state return and can be null
92 final Optional<FiniteDuration> result = queue.enqueueRequest(request, callback);
94 // Happy path: we are done here
98 if (result.isPresent()) {
99 // Less happy path: we need to schedule a timer
100 scheduleQueueTimeout(queue, result.get());
104 startResolve(queue, request.getTarget().getHistoryId().getCookie());
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);
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)));
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) {
128 final Optional<FiniteDuration> maybeTimeout = queue.setBackendInfo(futureBackend, backend);
129 if (maybeTimeout.isPresent()) {
130 scheduleQueueTimeout(queue, maybeTimeout.get());
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);
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;
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 LOG.debug("{}: No progress made - removing queue", persistenceId(), e);
150 context().removeQueue(queue);
155 startResolve(queue, queue.getCookie());
162 * Halt And Catch Fire. Halt processing on this client. Implementations need to ensure they initiate state flush
163 * procedures. No attempt to use this instance should be made after this method returns. Any such use may result
164 * in undefined behavior.
166 * @param cause Failure cause
168 protected abstract void haltClient(@Nonnull Throwable cause);
171 * Override this method to handle any command which is not handled by the base behavior.
173 * @param command the command to process
174 * @return Next behavior to use, null if this actor should shut down.
177 protected abstract ClientActorBehavior onCommand(@Nonnull Object command);
180 * Override this method to provide a backend resolver instance.
182 * @return a backend resolver instance
185 protected abstract BackendInfoResolver<?> resolver();
188 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
191 * @param request Request to send
192 * @param callback Callback to invoke
194 public final void sendRequest(final TransactionRequest<?> request, final RequestCallback callback) {
195 context().executeInActor(cb -> cb.doSendRequest(request, callback));