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 com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
14 import java.util.concurrent.ConcurrentHashMap;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.TimeoutException;
17 import javax.annotation.Nonnull;
18 import javax.annotation.Nullable;
19 import javax.annotation.concurrent.GuardedBy;
20 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
21 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
22 import org.opendaylight.controller.cluster.access.concepts.FailureEnvelope;
23 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
24 import org.opendaylight.controller.cluster.access.concepts.RequestException;
25 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
26 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
27 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
28 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
29 import org.opendaylight.controller.cluster.access.concepts.SuccessEnvelope;
30 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
31 import org.opendaylight.yangtools.concepts.Identifiable;
32 import org.opendaylight.yangtools.concepts.WritableIdentifier;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import scala.concurrent.duration.FiniteDuration;
38 * A behavior, which handles messages sent to a {@link AbstractClientActor}.
40 * @author Robert Varga
43 public abstract class ClientActorBehavior<T extends BackendInfo> extends
44 RecoveredClientActorBehavior<ClientActorContext> implements Identifiable<ClientIdentifier> {
46 * Connection reconnect cohort, driven by this class.
49 protected interface ConnectionConnectCohort {
51 * Finish the connection by replaying previous messages onto the new connection.
53 * @param enqueuedEntries Previously-enqueued entries
54 * @return A {@link ReconnectForwarder} to handle any straggler messages which arrive after this method returns.
56 @Nonnull ReconnectForwarder finishReconnect(@Nonnull Iterable<ConnectionEntry> enqueuedEntries);
59 private static final Logger LOG = LoggerFactory.getLogger(ClientActorBehavior.class);
60 private static final FiniteDuration RESOLVE_RETRY_DURATION = FiniteDuration.apply(5, TimeUnit.SECONDS);
63 * Map of connections to the backend. This map is concurrent to allow lookups, but given complex operations
64 * involved in connection transitions it is protected by a {@link InversibleLock}. Write-side of the lock is taken
65 * during connection transitions. Optimistic read-side of the lock is taken when new connections are introduced
69 * The lock detects potential AB/BA deadlock scenarios and will force the reader side out by throwing
70 * a {@link InversibleLockException} -- which must be propagated up, releasing locks as it propagates. The initial
71 * entry point causing the the conflicting lookup must then call {@link InversibleLockException#awaitResolution()}
72 * before retrying the operation.
74 // TODO: it should be possible to move these two into ClientActorContext
75 private final Map<Long, AbstractClientConnection<T>> connections = new ConcurrentHashMap<>();
76 private final InversibleLock connectionsLock = new InversibleLock();
77 private final BackendInfoResolver<T> resolver;
79 protected ClientActorBehavior(@Nonnull final ClientActorContext context,
80 @Nonnull final BackendInfoResolver<T> resolver) {
82 this.resolver = Preconditions.checkNotNull(resolver);
87 public final ClientIdentifier getIdentifier() {
88 return context().getIdentifier();
92 * Get a connection to a shard.
94 * @param shard Shard cookie
95 * @return Connection to a shard
96 * @throws InversibleLockException if the shard is being reconnected
98 public final AbstractClientConnection<T> getConnection(final Long shard) {
100 final long stamp = connectionsLock.optimisticRead();
101 final AbstractClientConnection<T> conn = connections.computeIfAbsent(shard, this::createConnection);
102 if (connectionsLock.validate(stamp)) {
103 // No write-lock in-between, return success
109 private AbstractClientConnection<T> getConnection(final ResponseEnvelope<?> response) {
110 // Always called from actor context: no locking required
111 return connections.get(extractCookie(response.getMessage().getTarget()));
114 @SuppressWarnings("unchecked")
116 final ClientActorBehavior<T> onReceiveCommand(final Object command) {
117 if (command instanceof InternalCommand) {
118 return ((InternalCommand<T>) command).execute(this);
120 if (command instanceof SuccessEnvelope) {
121 return onRequestSuccess((SuccessEnvelope) command);
123 if (command instanceof FailureEnvelope) {
124 return internalOnRequestFailure((FailureEnvelope) command);
127 return onCommand(command);
130 private static long extractCookie(final WritableIdentifier id) {
131 if (id instanceof TransactionIdentifier) {
132 return ((TransactionIdentifier) id).getHistoryId().getCookie();
133 } else if (id instanceof LocalHistoryIdentifier) {
134 return ((LocalHistoryIdentifier) id).getCookie();
136 throw new IllegalArgumentException("Unhandled identifier " + id);
140 private void onResponse(final ResponseEnvelope<?> response) {
141 final AbstractClientConnection<T> connection = getConnection(response);
142 if (connection != null) {
143 connection.receiveResponse(response);
145 LOG.info("{}: Ignoring unknown response {}", persistenceId(), response);
149 private ClientActorBehavior<T> onRequestSuccess(final SuccessEnvelope success) {
154 private ClientActorBehavior<T> onRequestFailure(final FailureEnvelope failure) {
159 private ClientActorBehavior<T> internalOnRequestFailure(final FailureEnvelope command) {
160 final RequestFailure<?, ?> failure = command.getMessage();
161 final RequestException cause = failure.getCause();
162 if (cause instanceof RetiredGenerationException) {
163 LOG.error("{}: current generation {} has been superseded", persistenceId(), getIdentifier(), cause);
168 if (cause instanceof NotLeaderException) {
169 final AbstractClientConnection<T> conn = getConnection(command);
170 if (conn instanceof ReconnectingClientConnection) {
171 // Already reconnecting, do not churn the logs
173 } else if (conn != null) {
174 LOG.info("{}: connection {} indicated no leadership, reconnecting it", persistenceId(), conn, cause);
175 return conn.reconnect(this);
179 return onRequestFailure(command);
182 private void poison(final RequestException cause) {
183 final long stamp = connectionsLock.writeLock();
185 for (AbstractClientConnection<T> q : connections.values()) {
191 connectionsLock.unlockWrite(stamp);
196 * Halt And Catch Fire. Halt processing on this client. Implementations need to ensure they initiate state flush
197 * procedures. No attempt to use this instance should be made after this method returns. Any such use may result
198 * in undefined behavior.
200 * @param cause Failure cause
202 protected abstract void haltClient(@Nonnull Throwable cause);
205 * Override this method to handle any command which is not handled by the base behavior.
207 * @param command the command to process
208 * @return Next behavior to use, null if this actor should shut down.
211 protected abstract ClientActorBehavior<T> onCommand(@Nonnull Object command);
214 * Override this method to provide a backend resolver instance.
216 * @return a backend resolver instance
218 protected final @Nonnull BackendInfoResolver<T> resolver() {
223 * Callback invoked when a new connection has been established. Implementations are expected perform preparatory
224 * tasks before the previous connection is frozen.
226 * @param newConn New connection
227 * @return ConnectionConnectCohort which will be used to complete the process of bringing the connection up.
229 @GuardedBy("connectionsLock")
230 @Nonnull protected abstract ConnectionConnectCohort connectionUp(@Nonnull ConnectedClientConnection<T> newConn);
232 private void backendConnectFinished(final Long shard, final AbstractClientConnection<T> conn,
233 final T backend, final Throwable failure) {
234 if (failure != null) {
235 if (failure instanceof TimeoutException) {
236 if (!conn.equals(connections.get(shard))) {
237 // AbstractClientConnection will remove itself when it decides there is no point in continuing,
238 // at which point we want to stop retrying
239 LOG.info("{}: stopping resolution of shard {} on stale connection {}", persistenceId(), shard, conn,
244 LOG.debug("{}: timed out resolving shard {}, scheduling retry in {}", persistenceId(), shard,
245 RESOLVE_RETRY_DURATION, failure);
246 context().executeInActor(b -> {
247 resolveConnection(shard, conn);
249 }, RESOLVE_RETRY_DURATION);
253 LOG.error("{}: failed to resolve shard {}", persistenceId(), shard, failure);
254 final RequestException cause;
255 if (failure instanceof RequestException) {
256 cause = (RequestException) failure;
258 cause = new RuntimeRequestException("Failed to resolve shard " + shard, failure);
265 LOG.debug("{}: resolved shard {} to {}", persistenceId(), shard, backend);
266 final long stamp = connectionsLock.writeLock();
268 // Create a new connected connection
269 final ConnectedClientConnection<T> newConn = new ConnectedClientConnection<>(conn.context(),
270 conn.cookie(), backend);
271 LOG.debug("{}: resolving connection {} to {}", persistenceId(), conn, newConn);
273 // Start reconnecting without the old connection lock held
274 final ConnectionConnectCohort cohort = Verify.verifyNotNull(connectionUp(newConn));
276 // Lock the old connection and get a reference to its entries
277 final Iterable<ConnectionEntry> replayIterable = conn.startReplay();
279 // Finish the connection attempt
280 final ReconnectForwarder forwarder = Verify.verifyNotNull(cohort.finishReconnect(replayIterable));
282 // Install the forwarder, unlocking the old connection
283 conn.finishReplay(forwarder);
285 // Make sure new lookups pick up the new connection
286 connections.replace(shard, conn, newConn);
287 LOG.debug("{}: replaced connection {} with {}", persistenceId(), conn, newConn);
289 connectionsLock.unlockWrite(stamp);
293 void removeConnection(final AbstractClientConnection<?> conn) {
294 connections.remove(conn.cookie(), conn);
295 LOG.debug("{}: removed connection {}", persistenceId(), conn);
298 @SuppressWarnings("unchecked")
299 void reconnectConnection(final ConnectedClientConnection<?> oldConn,
300 final ReconnectingClientConnection<?> newConn) {
301 final ReconnectingClientConnection<T> conn = (ReconnectingClientConnection<T>)newConn;
302 connections.replace(oldConn.cookie(), (AbstractClientConnection<T>)oldConn, conn);
303 LOG.debug("{}: connection {} reconnecting as {}", persistenceId(), oldConn, newConn);
305 final Long shard = oldConn.cookie();
306 resolver().refreshBackendInfo(shard, conn.getBackendInfo().get()).whenComplete(
307 (backend, failure) -> context().executeInActor(behavior -> {
308 backendConnectFinished(shard, conn, backend, failure);
313 private ConnectingClientConnection<T> createConnection(final Long shard) {
314 final ConnectingClientConnection<T> conn = new ConnectingClientConnection<>(context(), shard);
315 resolveConnection(shard, conn);
319 private void resolveConnection(final Long shard, final AbstractClientConnection<T> conn) {
320 LOG.debug("{}: resolving shard {} connection {}", persistenceId(), shard, conn);
321 resolver().getBackendInfo(shard).whenComplete((backend, failure) -> context().executeInActor(behavior -> {
322 backendConnectFinished(shard, conn, backend, failure);