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