Eliminate BootstrapConnectListener
[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((ChannelFutureListener) this::channelConnectComplete);
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     // Triggered when a connection attempt is resolved.
83     private synchronized void channelConnectComplete(final ChannelFuture cf) {
84         LOG.debug("Promise {} connection resolved", this);
85         checkState(pending.equals(cf));
86
87         /*
88          * The promise we gave out could have been cancelled,
89          * which cascades to the connect getting cancelled,
90          * but there is a slight race window, where the connect
91          * is already resolved, but the listener has not yet
92          * been notified -- cancellation at that point won't
93          * stop the notification arriving, so we have to close
94          * the race here.
95          */
96         if (isCancelled()) {
97             if (cf.isSuccess()) {
98                 LOG.debug("Closing channel for cancelled promise {}", this);
99                 cf.channel().close();
100             }
101             return;
102         }
103
104         if (cf.isSuccess()) {
105             LOG.debug("Promise {} connection successful", this);
106             return;
107         }
108
109         LOG.debug("Attempt to connect to {} failed", address, cf.cause());
110
111         final Future<Void> rf = strategy.scheduleReconnect(cf.cause());
112         rf.addListener(new ReconnectingStrategyListener());
113         pending = rf;
114     }
115
116     private class ReconnectingStrategyListener implements FutureListener<Void> {
117         @Override
118         public void operationComplete(final Future<Void> sf) {
119             synchronized (NetconfSessionPromise.this) {
120                 // Triggered when a connection attempt is to be made.
121                 checkState(pending.equals(sf));
122
123                 /*
124                  * The promise we gave out could have been cancelled,
125                  * which cascades to the reconnect attempt getting
126                  * cancelled, but there is a slight race window, where
127                  * the reconnect attempt is already enqueued, but the
128                  * listener has not yet been notified -- if cancellation
129                  * happens at that point, we need to catch it here.
130                  */
131                 if (!isCancelled()) {
132                     if (sf.isSuccess()) {
133                         connect();
134                     } else {
135                         setFailure(sf.cause());
136                     }
137                 }
138             }
139         }
140     }
141 }