Reduce ReconnectingStrategyListener nesting
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / NetconfSessionPromise.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 static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import io.netty.bootstrap.Bootstrap;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.ChannelFutureListener;
16 import io.netty.util.concurrent.DefaultPromise;
17 import io.netty.util.concurrent.EventExecutor;
18 import io.netty.util.concurrent.Future;
19 import io.netty.util.concurrent.FutureListener;
20 import io.netty.util.concurrent.Promise;
21 import java.net.InetSocketAddress;
22 import org.checkerframework.checker.lock.qual.GuardedBy;
23 import org.opendaylight.netconf.api.NetconfSession;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 @Deprecated
28 final class NetconfSessionPromise<S extends NetconfSession> extends DefaultPromise<S> {
29     private static final Logger LOG = LoggerFactory.getLogger(NetconfSessionPromise.class);
30     private final ReconnectStrategy strategy;
31     private InetSocketAddress address;
32     private final Bootstrap bootstrap;
33
34     @GuardedBy("this")
35     private Future<?> pending;
36
37     NetconfSessionPromise(final EventExecutor executor, final InetSocketAddress address,
38             final ReconnectStrategy strategy, final Bootstrap bootstrap) {
39         super(executor);
40         this.strategy = requireNonNull(strategy);
41         this.address = requireNonNull(address);
42         this.bootstrap = requireNonNull(bootstrap);
43     }
44
45     @SuppressWarnings("checkstyle:illegalCatch")
46     synchronized void connect() {
47         try {
48             final int timeout = strategy.getConnectTimeout();
49
50             LOG.debug("Promise {} attempting connect for {}ms", this, timeout);
51
52             if (address.isUnresolved()) {
53                 address = new InetSocketAddress(address.getHostName(), address.getPort());
54             }
55             final ChannelFuture connectFuture = bootstrap.connect(address);
56             // Add listener that attempts reconnect by invoking this method again.
57             connectFuture.addListener(new BootstrapConnectListener());
58             pending = connectFuture;
59         } catch (final Exception e) {
60             LOG.info("Failed to connect to {}", address, e);
61             setFailure(e);
62         }
63     }
64
65     @Override
66     public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
67         if (super.cancel(mayInterruptIfRunning)) {
68             pending.cancel(mayInterruptIfRunning);
69             return true;
70         }
71
72         return false;
73     }
74
75     @Override
76     public synchronized Promise<S> setSuccess(final S result) {
77         LOG.debug("Promise {} completed", this);
78         strategy.reconnectSuccessful();
79         return super.setSuccess(result);
80     }
81
82     private class BootstrapConnectListener implements ChannelFutureListener {
83         @Override
84         public void operationComplete(final ChannelFuture cf) {
85             synchronized (NetconfSessionPromise.this) {
86                 LOG.debug("Promise {} connection resolved", NetconfSessionPromise.this);
87
88                 // Triggered when a connection attempt is resolved.
89                 checkState(pending.equals(cf));
90
91                 /*
92                  * The promise we gave out could have been cancelled,
93                  * which cascades to the connect getting cancelled,
94                  * but there is a slight race window, where the connect
95                  * is already resolved, but the listener has not yet
96                  * been notified -- cancellation at that point won't
97                  * stop the notification arriving, so we have to close
98                  * the race here.
99                  */
100                 if (isCancelled()) {
101                     if (cf.isSuccess()) {
102                         LOG.debug("Closing channel for cancelled promise {}", NetconfSessionPromise.this);
103                         cf.channel().close();
104                     }
105                     return;
106                 }
107
108                 if (cf.isSuccess()) {
109                     LOG.debug("Promise {} connection successful", NetconfSessionPromise.this);
110                     return;
111                 }
112
113                 LOG.debug("Attempt to connect to {} failed", address, cf.cause());
114
115                 final Future<Void> rf = strategy.scheduleReconnect(cf.cause());
116                 rf.addListener(new ReconnectingStrategyListener());
117                 pending = rf;
118             }
119         }
120     }
121
122     private class ReconnectingStrategyListener implements FutureListener<Void> {
123         @Override
124         public void operationComplete(final Future<Void> sf) {
125             synchronized (NetconfSessionPromise.this) {
126                 // Triggered when a connection attempt is to be made.
127                 checkState(pending.equals(sf));
128
129                 /*
130                  * The promise we gave out could have been cancelled,
131                  * which cascades to the reconnect attempt getting
132                  * cancelled, but there is a slight race window, where
133                  * the reconnect attempt is already enqueued, but the
134                  * listener has not yet been notified -- if cancellation
135                  * happens at that point, we need to catch it here.
136                  */
137                 if (!isCancelled()) {
138                     if (sf.isSuccess()) {
139                         connect();
140                     } else {
141                         setFailure(sf.cause());
142                     }
143                 }
144             }
145         }
146     }
147 }