Use Object.requireNonNull
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / ReconnectPromise.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 java.util.Objects.requireNonNull;
11
12 import io.netty.bootstrap.Bootstrap;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelInboundHandlerAdapter;
15 import io.netty.util.concurrent.DefaultPromise;
16 import io.netty.util.concurrent.EventExecutor;
17 import io.netty.util.concurrent.Future;
18 import java.net.InetSocketAddress;
19 import org.opendaylight.netconf.api.NetconfSession;
20 import org.opendaylight.netconf.api.NetconfSessionListener;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 @Deprecated
25 final class ReconnectPromise<S extends NetconfSession, L extends NetconfSessionListener<? super S>>
26         extends DefaultPromise<Void> {
27     private static final Logger LOG = LoggerFactory.getLogger(ReconnectPromise.class);
28
29     private final AbstractNetconfDispatcher<S, L> dispatcher;
30     private final InetSocketAddress address;
31     private final ReconnectStrategyFactory strategyFactory;
32     private final Bootstrap bootstrap;
33     private final AbstractNetconfDispatcher.PipelineInitializer<S> initializer;
34     private Future<?> pending;
35
36     ReconnectPromise(final EventExecutor executor, final AbstractNetconfDispatcher<S, L> dispatcher,
37             final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
38             final Bootstrap bootstrap, final AbstractNetconfDispatcher.PipelineInitializer<S> initializer) {
39         super(executor);
40         this.bootstrap = bootstrap;
41         this.initializer = requireNonNull(initializer);
42         this.dispatcher = requireNonNull(dispatcher);
43         this.address = requireNonNull(address);
44         this.strategyFactory = requireNonNull(connectStrategyFactory);
45     }
46
47     synchronized void connect() {
48         final ReconnectStrategy cs = this.strategyFactory.createReconnectStrategy();
49
50         // Set up a client with pre-configured bootstrap, but add a closed channel handler into the pipeline to support
51         // reconnect attempts
52         pending = this.dispatcher.createClient(this.address, cs, bootstrap, (channel, promise) -> {
53             initializer.initializeChannel(channel, promise);
54             // add closed channel handler
55             // This handler has to be added as last channel handler and the channel inactive event has to be caught by
56             // it
57             // Handlers in front of it can react to channelInactive event, but have to forward the event or the
58             // reconnect will not work
59             // This handler is last so all handlers in front of it can handle channel inactive (to e.g. resource
60             // cleanup) before a new connection is started
61             channel.pipeline().addLast(new ClosedChannelHandler(ReconnectPromise.this));
62         });
63
64         pending.addListener(future -> {
65             if (!future.isSuccess() && !ReconnectPromise.this.isDone()) {
66                 ReconnectPromise.this.setFailure(future.cause());
67             }
68         });
69     }
70
71     /**
72      * Indicate if the initial connection succeeded.
73      *
74      * @return true if initial connection was established successfully, false if initial connection failed due to e.g.
75      *         Connection refused, Negotiation failed
76      */
77     private synchronized boolean isInitialConnectFinished() {
78         requireNonNull(pending);
79         return pending.isDone() && pending.isSuccess();
80     }
81
82     @Override
83     public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
84         if (super.cancel(mayInterruptIfRunning)) {
85             requireNonNull(pending);
86             this.pending.cancel(mayInterruptIfRunning);
87             return true;
88         }
89
90         return false;
91     }
92
93     /**
94      * Channel handler that responds to channelInactive event and reconnects the session.
95      * Only if the promise was not canceled.
96      */
97     private static final class ClosedChannelHandler extends ChannelInboundHandlerAdapter {
98         private final ReconnectPromise<?, ?> promise;
99
100         ClosedChannelHandler(final ReconnectPromise<?, ?> promise) {
101             this.promise = promise;
102         }
103
104         @Override
105         public void channelInactive(final ChannelHandlerContext ctx) {
106             // This is the ultimate channel inactive handler, not forwarding
107             if (promise.isCancelled()) {
108                 return;
109             }
110
111             if (promise.isInitialConnectFinished() == false) {
112                 LOG.debug("Connection to {} was dropped during negotiation, reattempting", promise.address);
113             }
114
115             LOG.debug("Reconnecting after connection to {} was dropped", promise.address);
116             promise.connect();
117         }
118     }
119 }