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;
13 import java.util.concurrent.ConcurrentHashMap;
14 import javax.annotation.Nonnull;
15 import javax.annotation.Nullable;
16 import javax.annotation.concurrent.GuardedBy;
17 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
18 import org.opendaylight.controller.cluster.access.concepts.FailureEnvelope;
19 import org.opendaylight.controller.cluster.access.concepts.RequestException;
20 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
21 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
22 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
23 import org.opendaylight.controller.cluster.access.concepts.SuccessEnvelope;
24 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
25 import org.opendaylight.yangtools.concepts.Identifiable;
26 import org.opendaylight.yangtools.concepts.WritableIdentifier;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
31 * A behavior, which handles messages sent to a {@link AbstractClientActor}.
33 * @author Robert Varga
36 public abstract class ClientActorBehavior<T extends BackendInfo> extends
37 RecoveredClientActorBehavior<ClientActorContext> implements Identifiable<ClientIdentifier> {
38 private static final Logger LOG = LoggerFactory.getLogger(ClientActorBehavior.class);
41 * Map of connections to the backend. This map is concurrent to allow lookups, but given complex operations
42 * involved in connection transitions it is protected by a {@link InversibleLock}. Write-side of the lock is taken
43 * during connection transitions. Optimistic read-side of the lock is taken when new connections are introduced
47 * The lock detects potential AB/BA deadlock scenarios and will force the reader side out by throwing
48 * a {@link InversibleLockException} -- which must be propagated up, releasing locks as it propagates. The initial
49 * entry point causing the the conflicting lookup must then call {@link InversibleLockException#awaitResolution()}
50 * before retrying the operation.
52 // TODO: it should be possible to move these two into ClientActorContext
53 private final Map<Long, AbstractClientConnection<T>> connections = new ConcurrentHashMap<>();
54 private final InversibleLock connectionsLock = new InversibleLock();
55 private final BackendInfoResolver<T> resolver;
57 protected ClientActorBehavior(@Nonnull final ClientActorContext context,
58 @Nonnull final BackendInfoResolver<T> resolver) {
60 this.resolver = Preconditions.checkNotNull(resolver);
65 public final ClientIdentifier getIdentifier() {
66 return context().getIdentifier();
70 * Get a connection to a shard.
72 * @param shard Shard cookie
73 * @return Connection to a shard
74 * @throws InversibleLockException if the shard is being reconnected
76 public final AbstractClientConnection<T> getConnection(final Long shard) {
78 final long stamp = connectionsLock.optimisticRead();
79 final AbstractClientConnection<T> conn = connections.computeIfAbsent(shard, this::createConnection);
80 if (connectionsLock.validate(stamp)) {
81 // No write-lock in-between, return success
87 @SuppressWarnings("unchecked")
89 final ClientActorBehavior<T> onReceiveCommand(final Object command) {
90 if (command instanceof InternalCommand) {
91 return ((InternalCommand<T>) command).execute(this);
93 if (command instanceof SuccessEnvelope) {
94 return onRequestSuccess((SuccessEnvelope) command);
96 if (command instanceof FailureEnvelope) {
97 return internalOnRequestFailure((FailureEnvelope) command);
100 return onCommand(command);
103 private void onResponse(final ResponseEnvelope<?> response) {
104 final WritableIdentifier id = response.getMessage().getTarget();
106 // FIXME: this will need to be updated for other Request/Response types to extract cookie
107 Preconditions.checkArgument(id instanceof TransactionIdentifier);
108 final TransactionIdentifier txId = (TransactionIdentifier) id;
110 final AbstractClientConnection<T> connection = connections.get(txId.getHistoryId().getCookie());
111 if (connection != null) {
112 connection.receiveResponse(response);
114 LOG.info("{}: Ignoring unknown response {}", persistenceId(), response);
118 private ClientActorBehavior<T> onRequestSuccess(final SuccessEnvelope success) {
123 private ClientActorBehavior<T> onRequestFailure(final FailureEnvelope failure) {
128 private ClientActorBehavior<T> internalOnRequestFailure(final FailureEnvelope command) {
129 final RequestFailure<?, ?> failure = command.getMessage();
130 final RequestException cause = failure.getCause();
131 if (cause instanceof RetiredGenerationException) {
132 LOG.error("{}: current generation {} has been superseded", persistenceId(), getIdentifier(), cause);
138 return onRequestFailure(command);
141 private void poison(final RequestException cause) {
142 final long stamp = connectionsLock.writeLock();
144 for (AbstractClientConnection<T> q : connections.values()) {
150 connectionsLock.unlockWrite(stamp);
155 * Halt And Catch Fire. Halt processing on this client. Implementations need to ensure they initiate state flush
156 * procedures. No attempt to use this instance should be made after this method returns. Any such use may result
157 * in undefined behavior.
159 * @param cause Failure cause
161 protected abstract void haltClient(@Nonnull Throwable cause);
164 * Override this method to handle any command which is not handled by the base behavior.
166 * @param command the command to process
167 * @return Next behavior to use, null if this actor should shut down.
170 protected abstract ClientActorBehavior<T> onCommand(@Nonnull Object command);
173 * Override this method to provide a backend resolver instance.
175 * @return a backend resolver instance
177 protected final @Nonnull BackendInfoResolver<T> resolver() {
182 * Callback invoked when a new connection has been established.
184 * @param conn Old connection
185 * @param backend New backend
186 * @return Newly-connected connection.
188 @GuardedBy("connectionsLock")
189 protected abstract @Nonnull ConnectedClientConnection<T> connectionUp(
190 final @Nonnull AbstractClientConnection<T> conn, final @Nonnull T backend);
192 private void backendConnectFinished(final Long shard, final AbstractClientConnection<T> conn,
193 final T backend, final Throwable failure) {
194 if (failure != null) {
195 LOG.error("{}: failed to resolve shard {}", persistenceId(), shard, failure);
199 final long stamp = connectionsLock.writeLock();
201 // Bring the connection up
202 final ConnectedClientConnection<T> newConn = connectionUp(conn, backend);
204 // Make sure new lookups pick up the new connection
205 connections.replace(shard, conn, newConn);
206 LOG.debug("{}: replaced connection {} with {}", persistenceId(), conn, newConn);
208 connectionsLock.unlockWrite(stamp);
212 void removeConnection(final AbstractClientConnection<?> conn) {
213 connections.remove(conn.cookie(), conn);
214 LOG.debug("{}: removed connection {}", persistenceId(), conn);
217 @SuppressWarnings("unchecked")
218 void reconnectConnection(final ConnectedClientConnection<?> oldConn,
219 final ReconnectingClientConnection<?> newConn) {
220 final ReconnectingClientConnection<T> conn = (ReconnectingClientConnection<T>)newConn;
221 connections.replace(oldConn.cookie(), (AbstractClientConnection<T>)oldConn, conn);
222 LOG.debug("{}: connection {} reconnecting as {}", persistenceId(), oldConn, newConn);
224 final Long shard = oldConn.cookie();
225 resolver().refreshBackendInfo(shard, conn.getBackendInfo().get()).whenComplete(
226 (backend, failure) -> context().executeInActor(behavior -> {
227 backendConnectFinished(shard, conn, backend, failure);
232 private ConnectingClientConnection<T> createConnection(final Long shard) {
233 final ConnectingClientConnection<T> conn = new ConnectingClientConnection<>(context(), shard);
235 resolver().getBackendInfo(shard).whenComplete((backend, failure) -> context().executeInActor(behavior -> {
236 backendConnectFinished(shard, conn, backend, failure);