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(final @Nonnull ClientActorContext context) {
42 public final @Nonnull ClientIdentifier getIdentifier() {
43 return context().getIdentifier();
47 final ClientActorBehavior onReceiveCommand(final Object command) {
48 if (command instanceof InternalCommand) {
49 return ((InternalCommand) command).execute(this);
51 if (command instanceof SuccessEnvelope) {
52 return onRequestSuccess((SuccessEnvelope) command);
54 if (command instanceof FailureEnvelope) {
55 return onRequestFailure((FailureEnvelope) command);
58 return onCommand(command);
61 private ClientActorBehavior onRequestSuccess(final SuccessEnvelope command) {
62 return context().completeRequest(this, command);
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);
71 context().poison(cause);
75 if (failure.isHardFailure()) {
76 return context().completeRequest(this, command);
79 // TODO: add instanceof checks on cause to detect more problems
81 LOG.warn("{}: Unhandled retriable failure {}, promoting to hard failure", persistenceId(), command);
82 return context().completeRequest(this, command);
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());
91 // Note this is a tri-state return and can be null
92 final Optional<FiniteDuration> result = queue.enqueueRequest(sequence, 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 context().removeQueue(queue);
154 startResolve(queue, queue.getCookie());
161 * Halt And Catch Fire.
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.
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.
174 * @return Next behavior to use, null if this actor should shut down.
176 protected abstract @Nullable ClientActorBehavior onCommand(@Nonnull Object command);
179 * Override this method to provide a backend resolver instance.
183 protected abstract @Nonnull BackendInfoResolver<?> resolver();
186 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
189 * @param request Request to send
190 * @param callback Callback to invoke
192 public final void sendRequest(final long sequence, final TransactionRequest<?> request, final RequestCallback callback) {
193 context().executeInActor(cb -> cb.doSendRequest(sequence, request, callback));