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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.