Bump odlparent to 5.0.0
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / TimedReconnectStrategy.java
1 /*
2  * Copyright (c) 2013 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.netconf.nettyutil;
9
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;
18
19 /**
20  * Swiss army knife equivalent for reconnect strategies. This class is thread-safe.
21  *
22  * <p>
23  * This strategy continues to schedule reconnect attempts, each having to complete in a fixed time (connectTime).
24  *
25  * <p>
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 &gt; 1). Maximum sleep time between attempts can be capped to a specific value
29  * (maxSleep).
30  *
31  * <p>
32  * The strategy can optionally give up based on two criteria:
33  *
34  * <p>
35  * A preset number of connection retries (maxAttempts) has been reached, or
36  *
37  * <p>
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.
41  *
42  * <p>
43  * Both these caps can be combined, with the strategy giving up as soon as the first one is reached.
44  */
45 @Deprecated
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;
55
56     @GuardedBy("this")
57     private long attempts;
58
59     @GuardedBy("this")
60     private long lastSleep;
61
62     @GuardedBy("this")
63     private boolean scheduled;
64
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;
77     }
78
79     @Override
80     public synchronized Future<Void> scheduleReconnect(final Throwable cause) {
81         LOG.debug("Connection attempt failed", cause);
82
83         // Check if a reconnect attempt is scheduled
84         Preconditions.checkState(!this.scheduled);
85
86         // Get a stable 'now' time for deadline calculations
87         final long now = System.nanoTime();
88
89         // Obvious stop conditions
90         if (this.maxAttempts != null && this.attempts >= this.maxAttempts) {
91             return this.executor.newFailedFuture(new Throwable("Maximum reconnection attempts reached"));
92         }
93         if (this.deadline != null && this.deadline <= now) {
94             return this.executor.newFailedFuture(new TimeoutException("Reconnect deadline reached"));
95         }
96
97         /*
98          * First connection attempt gets initialized to minimum sleep,
99          * each subsequent is exponentially backed off by sleepFactor.
100          */
101         if (this.attempts != 0) {
102             this.lastSleep *= this.sleepFactor;
103         } else {
104             this.lastSleep = this.minSleep;
105         }
106
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;
111         }
112
113         this.attempts++;
114
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"));
118         }
119
120         LOG.debug("Connection attempt {} sleeping for {} milliseconds", this.attempts, this.lastSleep);
121
122         // If we are not sleeping at all, return an already-succeeded future
123         if (this.lastSleep == 0) {
124             return this.executor.newSucceededFuture(null);
125         }
126
127         // Set the scheduled flag.
128         this.scheduled = true;
129
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;
135             }
136
137             return null;
138         }, this.lastSleep, TimeUnit.MILLISECONDS);
139     }
140
141     @Override
142     public synchronized void reconnectSuccessful() {
143         Preconditions.checkState(!this.scheduled);
144         this.attempts = 0;
145     }
146
147     @Override
148     public int getConnectTimeout() throws TimeoutException {
149         int timeout = this.connectTime;
150
151         if (this.deadline != null) {
152
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");
158             }
159
160             final long left = TimeUnit.NANOSECONDS.toMillis(this.deadline - now);
161             if (left < 1) {
162                 throw new TimeoutException("Connect timeout too close to deadline");
163             }
164
165             /*
166              * A bit of magic:
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
171              */
172             if (timeout > left) {
173                 timeout = (int) left;
174             } else if (timeout == 0) {
175                 timeout = left <= Integer.MAX_VALUE ? (int) left : Integer.MAX_VALUE;
176             }
177         }
178         return timeout;
179     }
180 }