Reduce JSR305 proliferation
[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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.base.Verify;
15 import java.util.Collection;
16 import java.util.Map;
17 import java.util.Optional;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.TimeoutException;
21 import javax.annotation.concurrent.GuardedBy;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
25 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
26 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
27 import org.opendaylight.controller.cluster.access.concepts.FailureEnvelope;
28 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
29 import org.opendaylight.controller.cluster.access.concepts.RequestException;
30 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
31 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
32 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
33 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
34 import org.opendaylight.controller.cluster.access.concepts.SuccessEnvelope;
35 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
36 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
37 import org.opendaylight.controller.cluster.io.FileBackedOutputStreamFactory;
38 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
39 import org.opendaylight.yangtools.concepts.Identifiable;
40 import org.opendaylight.yangtools.concepts.Identifier;
41 import org.opendaylight.yangtools.concepts.Registration;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import scala.concurrent.duration.FiniteDuration;
45
46 /**
47  * A behavior, which handles messages sent to a {@link AbstractClientActor}.
48  *
49  * @author Robert Varga
50  */
51 @Beta
52 public abstract class ClientActorBehavior<T extends BackendInfo> extends
53         RecoveredClientActorBehavior<ClientActorContext> implements Identifiable<ClientIdentifier> {
54     /**
55      * Connection reconnect cohort, driven by this class.
56      */
57     @FunctionalInterface
58     protected interface ConnectionConnectCohort {
59         /**
60          * Finish the connection by replaying previous messages onto the new connection.
61          *
62          * @param enqueuedEntries Previously-enqueued entries
63          * @return A {@link ReconnectForwarder} to handle any straggler messages which arrive after this method returns.
64          */
65         @NonNull ReconnectForwarder finishReconnect(@NonNull Collection<ConnectionEntry> enqueuedEntries);
66     }
67
68     private static final Logger LOG = LoggerFactory.getLogger(ClientActorBehavior.class);
69     private static final FiniteDuration RESOLVE_RETRY_DURATION = FiniteDuration.apply(1, TimeUnit.SECONDS);
70
71     /**
72      * Map of connections to the backend. This map is concurrent to allow lookups, but given complex operations
73      * involved in connection transitions it is protected by a {@link InversibleLock}. Write-side of the lock is taken
74      * during connection transitions. Optimistic read-side of the lock is taken when new connections are introduced
75      * into the map.
76      *
77      * <p>
78      * The lock detects potential AB/BA deadlock scenarios and will force the reader side out by throwing
79      * a {@link InversibleLockException} -- which must be propagated up, releasing locks as it propagates. The initial
80      * entry point causing the the conflicting lookup must then call {@link InversibleLockException#awaitResolution()}
81      * before retrying the operation.
82      */
83     // TODO: it should be possible to move these two into ClientActorContext
84     private final Map<Long, AbstractClientConnection<T>> connections = new ConcurrentHashMap<>();
85     private final InversibleLock connectionsLock = new InversibleLock();
86     private final BackendInfoResolver<T> resolver;
87     private final MessageAssembler responseMessageAssembler;
88     private final Registration staleBackendInfoReg;
89
90     protected ClientActorBehavior(final @NonNull ClientActorContext context,
91             final @NonNull BackendInfoResolver<T> resolver) {
92         super(context);
93         this.resolver = requireNonNull(resolver);
94
95         final ClientActorConfig config = context.config();
96         responseMessageAssembler = MessageAssembler.builder().logContext(persistenceId())
97                 .fileBackedStreamFactory(new FileBackedOutputStreamFactory(config.getFileBackedStreamingThreshold(),
98                         config.getTempFileDirectory()))
99                 .assembledMessageCallback((message, sender) -> context.self().tell(message, sender)).build();
100
101         staleBackendInfoReg = resolver.notifyWhenBackendInfoIsStale(shard -> {
102             context().executeInActor(behavior -> {
103                 LOG.debug("BackendInfo for shard {} is now stale", shard);
104                 final AbstractClientConnection<T> conn = connections.get(shard);
105                 if (conn instanceof ConnectedClientConnection) {
106                     conn.reconnect(this, new BackendStaleException(shard));
107                 }
108                 return behavior;
109             });
110         });
111     }
112
113     @Override
114     public final ClientIdentifier getIdentifier() {
115         return context().getIdentifier();
116     }
117
118     @Override
119     public void close() {
120         super.close();
121         responseMessageAssembler.close();
122         staleBackendInfoReg.close();
123     }
124
125     /**
126      * Get a connection to a shard.
127      *
128      * @param shard Shard cookie
129      * @return Connection to a shard
130      * @throws InversibleLockException if the shard is being reconnected
131      */
132     public final AbstractClientConnection<T> getConnection(final Long shard) {
133         while (true) {
134             final long stamp = connectionsLock.optimisticRead();
135             final AbstractClientConnection<T> conn = connections.computeIfAbsent(shard, this::createConnection);
136             if (connectionsLock.validate(stamp)) {
137                 // No write-lock in-between, return success
138                 return conn;
139             }
140         }
141     }
142
143     private AbstractClientConnection<T> getConnection(final ResponseEnvelope<?> response) {
144         // Always called from actor context: no locking required
145         return connections.get(extractCookie(response.getMessage().getTarget()));
146     }
147
148     @SuppressWarnings("unchecked")
149     @Override
150     final ClientActorBehavior<T> onReceiveCommand(final Object command) {
151         if (command instanceof InternalCommand) {
152             return ((InternalCommand<T>) command).execute(this);
153         }
154
155         if (command instanceof SuccessEnvelope) {
156             return onRequestSuccess((SuccessEnvelope) command);
157         }
158
159         if (command instanceof FailureEnvelope) {
160             return internalOnRequestFailure((FailureEnvelope) command);
161         }
162
163         if (MessageAssembler.isHandledMessage(command)) {
164             context().dispatchers().getDispatcher(DispatcherType.Serialization).execute(
165                 () -> responseMessageAssembler.handleMessage(command, context().self()));
166             return this;
167         }
168
169         if (context().messageSlicer().handleMessage(command)) {
170             return this;
171         }
172
173         return onCommand(command);
174     }
175
176     private static long extractCookie(final Identifier id) {
177         if (id instanceof TransactionIdentifier) {
178             return ((TransactionIdentifier) id).getHistoryId().getCookie();
179         } else if (id instanceof LocalHistoryIdentifier) {
180             return ((LocalHistoryIdentifier) id).getCookie();
181         } else {
182             throw new IllegalArgumentException("Unhandled identifier " + id);
183         }
184     }
185
186     private void onResponse(final ResponseEnvelope<?> response) {
187         final AbstractClientConnection<T> connection = getConnection(response);
188         if (connection != null) {
189             connection.receiveResponse(response);
190         } else {
191             LOG.info("{}: Ignoring unknown response {}", persistenceId(), response);
192         }
193     }
194
195     private ClientActorBehavior<T> onRequestSuccess(final SuccessEnvelope success) {
196         onResponse(success);
197         return this;
198     }
199
200     private ClientActorBehavior<T> onRequestFailure(final FailureEnvelope failure) {
201         onResponse(failure);
202         return this;
203     }
204
205     private ClientActorBehavior<T> internalOnRequestFailure(final FailureEnvelope command) {
206         final AbstractClientConnection<T> conn = getConnection(command);
207         if (conn != null) {
208             /*
209              * We are talking to multiple actors, which may be lagging behind our state significantly. This has
210              * the effect that we may be receiving responses from a previous connection after we have created a new
211              * one to a different actor.
212              *
213              * Since we are already replaying requests to the new actor, we want to ignore errors reported on the old
214              * connection -- for example NotLeaderException, which must not cause a new reconnect. Check the envelope's
215              * sessionId and if it does not match our current connection just ignore it.
216              */
217             final Optional<T> optBackend = conn.getBackendInfo();
218             if (optBackend.isPresent() && optBackend.get().getSessionId() != command.getSessionId()) {
219                 LOG.debug("{}: Mismatched current connection {} and envelope {}, ignoring response", persistenceId(),
220                     conn, command);
221                 return this;
222             }
223         }
224
225         final RequestFailure<?, ?> failure = command.getMessage();
226         final RequestException cause = failure.getCause();
227         if (cause instanceof RetiredGenerationException) {
228             LOG.error("{}: current generation {} has been superseded", persistenceId(), getIdentifier(), cause);
229             haltClient(cause);
230             poison(cause);
231             return null;
232         }
233         if (cause instanceof NotLeaderException) {
234             if (conn instanceof ReconnectingClientConnection) {
235                 // Already reconnecting, do not churn the logs
236                 return this;
237             } else if (conn != null) {
238                 LOG.info("{}: connection {} indicated no leadership, reconnecting it", persistenceId(), conn, cause);
239                 return conn.reconnect(this, cause);
240             }
241         }
242         if (cause instanceof OutOfSequenceEnvelopeException) {
243             if (conn instanceof ReconnectingClientConnection) {
244                 // Already reconnecting, do not churn the logs
245                 return this;
246             } else if (conn != null) {
247                 LOG.info("{}: connection {} indicated sequencing mismatch on {} sequence {} ({}), reconnecting it",
248                     persistenceId(), conn, failure.getTarget(), failure.getSequence(), command.getTxSequence(), cause);
249                 return conn.reconnect(this, cause);
250             }
251         }
252
253         return onRequestFailure(command);
254     }
255
256     private void poison(final RequestException cause) {
257         final long stamp = connectionsLock.writeLock();
258         try {
259             for (AbstractClientConnection<T> q : connections.values()) {
260                 q.poison(cause);
261             }
262
263             connections.clear();
264         } finally {
265             connectionsLock.unlockWrite(stamp);
266         }
267
268         context().messageSlicer().close();
269     }
270
271     /**
272      * Halt And Catch Fire. Halt processing on this client. Implementations need to ensure they initiate state flush
273      * procedures. No attempt to use this instance should be made after this method returns. Any such use may result
274      * in undefined behavior.
275      *
276      * @param cause Failure cause
277      */
278     protected abstract void haltClient(@NonNull Throwable cause);
279
280     /**
281      * Override this method to handle any command which is not handled by the base behavior.
282      *
283      * @param command the command to process
284      * @return Next behavior to use, null if this actor should shut down.
285      */
286     protected abstract @Nullable ClientActorBehavior<T> onCommand(@NonNull Object command);
287
288     /**
289      * Override this method to provide a backend resolver instance.
290      *
291      * @return a backend resolver instance
292      */
293     protected final @NonNull BackendInfoResolver<T> resolver() {
294         return resolver;
295     }
296
297     /**
298      * Callback invoked when a new connection has been established. Implementations are expected perform preparatory
299      * tasks before the previous connection is frozen.
300      *
301      * @param newConn New connection
302      * @return ConnectionConnectCohort which will be used to complete the process of bringing the connection up.
303      */
304     @GuardedBy("connectionsLock")
305     protected abstract @NonNull ConnectionConnectCohort connectionUp(@NonNull ConnectedClientConnection<T> newConn);
306
307     private void backendConnectFinished(final Long shard, final AbstractClientConnection<T> oldConn,
308             final T backend, final Throwable failure) {
309         if (failure != null) {
310             if (failure instanceof TimeoutException) {
311                 if (!oldConn.equals(connections.get(shard))) {
312                     // AbstractClientConnection will remove itself when it decides there is no point in continuing,
313                     // at which point we want to stop retrying
314                     LOG.info("{}: stopping resolution of shard {} on stale connection {}", persistenceId(), shard,
315                         oldConn, failure);
316                     return;
317                 }
318
319                 LOG.debug("{}: timed out resolving shard {}, scheduling retry in {}", persistenceId(), shard,
320                     RESOLVE_RETRY_DURATION, failure);
321                 context().executeInActor(b -> {
322                     resolveConnection(shard, oldConn);
323                     return b;
324                 }, RESOLVE_RETRY_DURATION);
325                 return;
326             }
327
328             LOG.error("{}: failed to resolve shard {}", persistenceId(), shard, failure);
329             final RequestException cause;
330             if (failure instanceof RequestException) {
331                 cause = (RequestException) failure;
332             } else {
333                 cause = new RuntimeRequestException("Failed to resolve shard " + shard, failure);
334             }
335
336             oldConn.poison(cause);
337             return;
338         }
339
340         LOG.info("{}: resolved shard {} to {}", persistenceId(), shard, backend);
341         final long stamp = connectionsLock.writeLock();
342         try {
343             final Stopwatch sw = Stopwatch.createStarted();
344
345             // Create a new connected connection
346             final ConnectedClientConnection<T> newConn = new ConnectedClientConnection<>(oldConn, backend);
347             LOG.info("{}: resolving connection {} to {}", persistenceId(), oldConn, newConn);
348
349             // Start reconnecting without the old connection lock held
350             final ConnectionConnectCohort cohort = Verify.verifyNotNull(connectionUp(newConn));
351
352             // Lock the old connection and get a reference to its entries
353             final Collection<ConnectionEntry> replayIterable = oldConn.startReplay();
354
355             // Finish the connection attempt
356             final ReconnectForwarder forwarder = Verify.verifyNotNull(cohort.finishReconnect(replayIterable));
357
358             // Cancel sleep debt after entries were replayed, before new connection starts receiving.
359             newConn.cancelDebt();
360
361             // Install the forwarder, unlocking the old connection
362             oldConn.finishReplay(forwarder);
363
364             // Make sure new lookups pick up the new connection
365             if (!connections.replace(shard, oldConn, newConn)) {
366                 final AbstractClientConnection<T> existing = connections.get(oldConn.cookie());
367                 LOG.warn("{}: old connection {} does not match existing {}, new connection {} in limbo",
368                     persistenceId(), oldConn, existing, newConn);
369             } else {
370                 LOG.info("{}: replaced connection {} with {} in {}", persistenceId(), oldConn, newConn, sw);
371             }
372         } finally {
373             connectionsLock.unlockWrite(stamp);
374         }
375     }
376
377     void removeConnection(final AbstractClientConnection<?> conn) {
378         final long stamp = connectionsLock.writeLock();
379         try {
380             if (!connections.remove(conn.cookie(), conn)) {
381                 final AbstractClientConnection<T> existing = connections.get(conn.cookie());
382                 if (existing != null) {
383                     LOG.warn("{}: failed to remove connection {}, as it was superseded by {}", persistenceId(), conn,
384                         existing);
385                 } else {
386                     LOG.warn("{}: failed to remove connection {}, as it was not tracked", persistenceId(), conn);
387                 }
388             } else {
389                 LOG.info("{}: removed connection {}", persistenceId(), conn);
390                 cancelSlicing(conn.cookie());
391             }
392         } finally {
393             connectionsLock.unlockWrite(stamp);
394         }
395     }
396
397     @SuppressWarnings("unchecked")
398     void reconnectConnection(final ConnectedClientConnection<?> oldConn,
399             final ReconnectingClientConnection<?> newConn) {
400         final ReconnectingClientConnection<T> conn = (ReconnectingClientConnection<T>)newConn;
401         LOG.info("{}: connection {} reconnecting as {}", persistenceId(), oldConn, newConn);
402
403         final long stamp = connectionsLock.writeLock();
404         try {
405             final boolean replaced = connections.replace(oldConn.cookie(), (AbstractClientConnection<T>)oldConn, conn);
406             if (!replaced) {
407                 final AbstractClientConnection<T> existing = connections.get(oldConn.cookie());
408                 if (existing != null) {
409                     LOG.warn("{}: failed to replace connection {}, as it was superseded by {}", persistenceId(), conn,
410                         existing);
411                 } else {
412                     LOG.warn("{}: failed to replace connection {}, as it was not tracked", persistenceId(), conn);
413                 }
414             } else {
415                 cancelSlicing(oldConn.cookie());
416             }
417         } finally {
418             connectionsLock.unlockWrite(stamp);
419         }
420
421         final Long shard = oldConn.cookie();
422         LOG.info("{}: refreshing backend for shard {}", persistenceId(), shard);
423         resolver().refreshBackendInfo(shard, conn.getBackendInfo().get()).whenComplete(
424             (backend, failure) -> context().executeInActor(behavior -> {
425                 backendConnectFinished(shard, conn, backend, failure);
426                 return behavior;
427             }));
428     }
429
430     private void cancelSlicing(final Long cookie) {
431         context().messageSlicer().cancelSlicing(id -> {
432             try {
433                 return cookie.equals(extractCookie(id));
434             } catch (IllegalArgumentException e) {
435                 LOG.debug("extractCookie failed while cancelling slicing for cookie {}", cookie, e);
436                 return false;
437             }
438         });
439     }
440
441     private ConnectingClientConnection<T> createConnection(final Long shard) {
442         final ConnectingClientConnection<T> conn = new ConnectingClientConnection<>(context(), shard,
443                 resolver().resolveCookieName(shard));
444         resolveConnection(shard, conn);
445         return conn;
446     }
447
448     private void resolveConnection(final Long shard, final AbstractClientConnection<T> conn) {
449         LOG.debug("{}: resolving shard {} connection {}", persistenceId(), shard, conn);
450         resolver().getBackendInfo(shard).whenComplete((backend, failure) -> context().executeInActor(behavior -> {
451             backendConnectFinished(shard, conn, backend, failure);
452             return behavior;
453         }));
454     }
455
456     private static class BackendStaleException extends RequestException {
457         private static final long serialVersionUID = 1L;
458
459         BackendStaleException(final Long shard) {
460             super("Backend for shard " + shard + " is stale");
461         }
462
463         @Override
464         public boolean isRetriable() {
465             return false;
466         }
467     }
468 }