Replace Preconditions.CheckNotNull per RequireNonNull
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / protocol / BGPReconnectPromise.java
1 /*
2  * Copyright (c) 2015 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.bgp.rib.impl.protocol;
9
10 import static java.util.Objects.requireNonNull;
11
12 import io.netty.bootstrap.Bootstrap;
13 import io.netty.channel.ChannelHandler;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.channel.ChannelInboundHandlerAdapter;
16 import io.netty.channel.ChannelInitializer;
17 import io.netty.channel.socket.SocketChannel;
18 import io.netty.util.concurrent.DefaultPromise;
19 import io.netty.util.concurrent.EventExecutor;
20 import java.net.InetSocketAddress;
21 import javax.annotation.Nonnull;
22 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
23 import org.opendaylight.protocol.bgp.rib.impl.spi.ChannelPipelineInitializer;
24 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 public class BGPReconnectPromise<S extends BGPSession> extends DefaultPromise<Void> {
29     private static final Logger LOG = LoggerFactory.getLogger(BGPReconnectPromise.class);
30
31     private final InetSocketAddress address;
32     private final int retryTimer;
33     private final Bootstrap bootstrap;
34     private final BGPPeerRegistry peerRegistry;
35     private final ChannelPipelineInitializer<S> initializer;
36     private BGPProtocolSessionPromise<S> pending;
37
38     public BGPReconnectPromise(@Nonnull final EventExecutor executor, @Nonnull final InetSocketAddress address,
39         final int retryTimer, @Nonnull final Bootstrap bootstrap, @Nonnull final BGPPeerRegistry peerRegistry,
40         @Nonnull final ChannelPipelineInitializer<S> initializer) {
41         super(executor);
42         this.bootstrap = bootstrap;
43         this.initializer = requireNonNull(initializer);
44         this.address = requireNonNull(address);
45         this.retryTimer = retryTimer;
46         this.peerRegistry = requireNonNull(peerRegistry);
47     }
48
49     public synchronized void connect() {
50         if (this.pending != null) {
51             this.pending.cancel(true);
52         }
53
54         // Set up a client with pre-configured bootstrap, but add a closed channel handler into the pipeline to support reconnect attempts
55         this.pending = connectSessionPromise(this.address, this.retryTimer, this.bootstrap, this.peerRegistry, (channel, promise) -> {
56             this.initializer.initializeChannel(channel, promise);
57             // add closed channel handler
58             // This handler has to be added as last channel handler and the channel inactive event has to be caught by it
59             // Handlers in front of it can react to channelInactive event, but have to forward the event or the reconnect will not work
60             // 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
61             channel.pipeline().addLast(new ClosedChannelHandler(this));
62         });
63
64         this.pending.addListener(future -> {
65             if (!future.isSuccess() && !this.isDone()) {
66                 this.setFailure(future.cause());
67             }
68         });
69     }
70
71     private BGPProtocolSessionPromise<S> connectSessionPromise(final InetSocketAddress address, final int retryTimer,
72             final Bootstrap bootstrap, final BGPPeerRegistry peerRegistry,
73             final ChannelPipelineInitializer<S> initializer) {
74         final BGPProtocolSessionPromise<S> sessionPromise = new BGPProtocolSessionPromise<>(address, retryTimer,
75                 bootstrap, peerRegistry);
76         final ChannelHandler chInit = new ChannelInitializer<SocketChannel>() {
77             @Override
78             protected void initChannel(final SocketChannel channel) {
79                 initializer.initializeChannel(channel, sessionPromise);
80             }
81         };
82
83         bootstrap.handler(chInit);
84         sessionPromise.connect();
85         LOG.debug("Client created.");
86         return sessionPromise;
87     }
88
89     /**
90      * @return true if initial connection was established successfully, false if initial connection failed due
91      *         to e.g. Connection refused, Negotiation failed
92      */
93     private  synchronized boolean isInitialConnectFinished() {
94         requireNonNull(this.pending);
95         return this.pending.isDone() && this.pending.isSuccess();
96     }
97
98     private synchronized void reconnect() {
99         requireNonNull(this.pending);
100         this.pending.reconnect();
101     }
102
103     @Override
104     public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
105         if (super.cancel(mayInterruptIfRunning)) {
106             requireNonNull(this.pending);
107             this.pending.cancel(mayInterruptIfRunning);
108             return true;
109         }
110         return false;
111     }
112
113     /**
114      * Channel handler that responds to channelInactive event and reconnects the session.
115      * Only if the promise was not canceled.
116      */
117     private static final class ClosedChannelHandler extends ChannelInboundHandlerAdapter {
118         private final BGPReconnectPromise<?> promise;
119
120         ClosedChannelHandler(final BGPReconnectPromise<?> promise) {
121             this.promise = promise;
122         }
123
124         @Override
125         public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
126             // This is the ultimate channel inactive handler, not forwarding
127             if (this.promise.isCancelled()) {
128                 return;
129             }
130
131             if (!this.promise.isInitialConnectFinished()) {
132                 LOG.debug("Connection to {} was dropped during negotiation, reattempting", this.promise.address);
133                 this.promise.reconnect();
134                 return;
135             }
136
137             LOG.debug("Reconnecting after connection to {} was dropped", this.promise.address);
138             this.promise.connect();
139         }
140     }
141 }