Fix CS warnings in cds-access-client and enable enforcement
[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(@Nonnull final ClientActorContext context) {
38         super(context);
39     }
40
41     @Override
42     @Nonnull
43     public final ClientIdentifier getIdentifier() {
44         return context().getIdentifier();
45     }
46
47     @Override
48     final ClientActorBehavior onReceiveCommand(final Object command) {
49         if (command instanceof InternalCommand) {
50             return ((InternalCommand) command).execute(this);
51         }
52         if (command instanceof SuccessEnvelope) {
53             return onRequestSuccess((SuccessEnvelope) command);
54         }
55         if (command instanceof FailureEnvelope) {
56             return onRequestFailure((FailureEnvelope) command);
57         }
58
59         return onCommand(command);
60     }
61
62     private ClientActorBehavior onRequestSuccess(final SuccessEnvelope command) {
63         return context().completeRequest(this, command);
64     }
65
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);
71             haltClient(cause);
72             context().poison(cause);
73             return null;
74         }
75
76         if (failure.isHardFailure()) {
77             return context().completeRequest(this, command);
78         }
79
80         // TODO: add instanceof checks on cause to detect more problems
81
82         LOG.warn("{}: Unhandled retriable failure {}, promoting to hard failure", persistenceId(), command);
83         return context().completeRequest(this, command);
84     }
85
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());
90
91         // Note this is a tri-state return and can be null
92         final Optional<FiniteDuration> result = queue.enqueueRequest(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             LOG.debug("{}: No progress made - removing queue", persistenceId(), e);
150             context().removeQueue(queue);
151             return this;
152         }
153
154         if (needBackend) {
155             startResolve(queue, queue.getCookie());
156         }
157
158         return this;
159     }
160
161     /**
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.
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 the command to process
174      * @return Next behavior to use, null if this actor should shut down.
175      */
176     @Nullable
177     protected abstract ClientActorBehavior onCommand(@Nonnull Object command);
178
179     /**
180      * Override this method to provide a backend resolver instance.
181      *
182      * @return a backend resolver instance
183      */
184     @Nonnull
185     protected abstract BackendInfoResolver<?> resolver();
186
187     /**
188      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
189      * from any thread.
190      *
191      * @param request Request to send
192      * @param callback Callback to invoke
193      */
194     public final void sendRequest(final TransactionRequest<?> request, final RequestCallback callback) {
195         context().executeInActor(cb -> cb.doSendRequest(request, callback));
196     }
197 }