2 * Copyright (c) 2013 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.netconf.nettyutil;
10 import com.google.common.base.Preconditions;
11 import io.netty.util.concurrent.EventExecutor;
12 import io.netty.util.concurrent.Future;
13 import java.util.concurrent.TimeUnit;
14 import java.util.concurrent.TimeoutException;
15 import org.checkerframework.checker.lock.qual.GuardedBy;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
20 * Swiss army knife equivalent for reconnect strategies. This class is thread-safe.
23 * This strategy continues to schedule reconnect attempts, each having to complete in a fixed time (connectTime).
26 * Initial sleep time is specified as minSleep. Each subsequent unsuccessful attempt multiplies this time by a constant
27 * factor (sleepFactor) -- this allows for either constant reconnect times (sleepFactor = 1), or various degrees of
28 * exponential back-off (sleepFactor > 1). Maximum sleep time between attempts can be capped to a specific value
32 * The strategy can optionally give up based on two criteria:
35 * A preset number of connection retries (maxAttempts) has been reached, or
38 * A preset absolute deadline is reached (deadline nanoseconds, as reported by System.nanoTime(). In this specific case,
39 * both connectTime and maxSleep will be controlled such that the connection attempt is resolved as closely to the
40 * deadline as possible.
43 * Both these caps can be combined, with the strategy giving up as soon as the first one is reached.
46 public final class TimedReconnectStrategy implements ReconnectStrategy {
47 private static final Logger LOG = LoggerFactory.getLogger(TimedReconnectStrategy.class);
48 private final EventExecutor executor;
49 private final Long deadline;
50 private final Long maxAttempts;
51 private final Long maxSleep;
52 private final double sleepFactor;
53 private final int connectTime;
54 private final long minSleep;
57 private long attempts;
60 private long lastSleep;
63 private boolean scheduled;
65 public TimedReconnectStrategy(final EventExecutor executor, final int connectTime, final long minSleep,
66 final double sleepFactor, final Long maxSleep, final Long maxAttempts, final Long deadline) {
67 Preconditions.checkArgument(maxSleep == null || minSleep <= maxSleep);
68 Preconditions.checkArgument(sleepFactor >= 1);
69 Preconditions.checkArgument(connectTime >= 0);
70 this.executor = Preconditions.checkNotNull(executor);
71 this.deadline = deadline;
72 this.maxAttempts = maxAttempts;
73 this.minSleep = minSleep;
74 this.maxSleep = maxSleep;
75 this.sleepFactor = sleepFactor;
76 this.connectTime = connectTime;
80 public synchronized Future<Void> scheduleReconnect(final Throwable cause) {
81 LOG.debug("Connection attempt failed", cause);
83 // Check if a reconnect attempt is scheduled
84 Preconditions.checkState(!this.scheduled);
86 // Get a stable 'now' time for deadline calculations
87 final long now = System.nanoTime();
89 // Obvious stop conditions
90 if (this.maxAttempts != null && this.attempts >= this.maxAttempts) {
91 return this.executor.newFailedFuture(new Throwable("Maximum reconnection attempts reached"));
93 if (this.deadline != null && this.deadline <= now) {
94 return this.executor.newFailedFuture(new TimeoutException("Reconnect deadline reached"));
98 * First connection attempt gets initialized to minimum sleep,
99 * each subsequent is exponentially backed off by sleepFactor.
101 if (this.attempts != 0) {
102 this.lastSleep *= this.sleepFactor;
104 this.lastSleep = this.minSleep;
107 // Cap the sleep time to maxSleep
108 if (this.maxSleep != null && this.lastSleep > this.maxSleep) {
109 LOG.debug("Capped sleep time from {} to {}", this.lastSleep, this.maxSleep);
110 this.lastSleep = this.maxSleep;
115 // Check if the reconnect attempt is within the deadline
116 if (this.deadline != null && this.deadline <= now + TimeUnit.MILLISECONDS.toNanos(this.lastSleep)) {
117 return this.executor.newFailedFuture(new TimeoutException("Next reconnect would happen after deadline"));
120 LOG.debug("Connection attempt {} sleeping for {} milliseconds", this.attempts, this.lastSleep);
122 // If we are not sleeping at all, return an already-succeeded future
123 if (this.lastSleep == 0) {
124 return this.executor.newSucceededFuture(null);
127 // Set the scheduled flag.
128 this.scheduled = true;
130 // Schedule a task for the right time. It will also clear the flag.
131 return this.executor.schedule(() -> {
132 synchronized (TimedReconnectStrategy.this) {
133 Preconditions.checkState(TimedReconnectStrategy.this.scheduled);
134 TimedReconnectStrategy.this.scheduled = false;
138 }, this.lastSleep, TimeUnit.MILLISECONDS);
142 public synchronized void reconnectSuccessful() {
143 Preconditions.checkState(!this.scheduled);
148 public int getConnectTimeout() throws TimeoutException {
149 int timeout = this.connectTime;
151 if (this.deadline != null) {
153 // If there is a deadline, we may need to cap the connect
154 // timeout to meet the deadline.
155 final long now = System.nanoTime();
156 if (now >= this.deadline) {
157 throw new TimeoutException("Reconnect deadline already passed");
160 final long left = TimeUnit.NANOSECONDS.toMillis(this.deadline - now);
162 throw new TimeoutException("Connect timeout too close to deadline");
167 * - if time left is less than the timeout, set it directly
168 * - if there is no timeout, and time left is:
169 * - less than maximum integer, set timeout to time left
170 * - more than maximum integer, set timeout Integer.MAX_VALUE
172 if (timeout > left) {
173 timeout = (int) left;
174 } else if (timeout == 0) {
175 timeout = left <= Integer.MAX_VALUE ? (int) left : Integer.MAX_VALUE;