Bug-6662: On connection reset by peer, sometimes re-connection attempt stops after...
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / protocol / BGPProtocolSessionPromise.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 com.google.common.base.Preconditions;
11 import io.netty.bootstrap.Bootstrap;
12 import io.netty.channel.ChannelFuture;
13 import io.netty.channel.ChannelFutureListener;
14 import io.netty.channel.ChannelOption;
15 import io.netty.channel.EventLoop;
16 import io.netty.util.concurrent.DefaultPromise;
17 import io.netty.util.concurrent.Future;
18 import io.netty.util.concurrent.GlobalEventExecutor;
19 import io.netty.util.concurrent.Promise;
20 import java.net.InetSocketAddress;
21 import java.util.concurrent.TimeUnit;
22 import javax.annotation.concurrent.GuardedBy;
23 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 public class BGPProtocolSessionPromise<S extends BGPSession> extends DefaultPromise<S> {
28     private static final Logger LOG = LoggerFactory.getLogger(BGPProtocolSessionPromise.class);
29     private static final int CONNECT_TIMEOUT = 5000;
30
31     private InetSocketAddress address;
32     private final int retryTimer;
33     private final Bootstrap bootstrap;
34     @GuardedBy("this")
35     private ChannelFuture pending;
36
37     public BGPProtocolSessionPromise(InetSocketAddress remoteAddress, int retryTimer, Bootstrap bootstrap) {
38         super(GlobalEventExecutor.INSTANCE);
39         this.address = Preconditions.checkNotNull(remoteAddress);
40         this.retryTimer = retryTimer;
41         this.bootstrap = Preconditions.checkNotNull(bootstrap);
42     }
43
44     public synchronized void connect() {
45         final BGPProtocolSessionPromise lock = this;
46
47         try {
48             LOG.debug("Promise {} attempting connect for {}ms", lock, Integer.valueOf(CONNECT_TIMEOUT));
49             if (this.address.isUnresolved()) {
50                 this.address = new InetSocketAddress(this.address.getHostName(), this.address.getPort());
51             }
52
53             this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
54             this.bootstrap.remoteAddress(this.address);
55             final ChannelFuture connectFuture = this.bootstrap.connect();
56             connectFuture.addListener(new BGPProtocolSessionPromise.BootstrapConnectListener(lock));
57             this.pending = connectFuture;
58         } catch (Exception e) {
59             LOG.info("Failed to connect to {}", this.address, e);
60             this.setFailure(e);
61         }
62     }
63
64     public synchronized void reconnect() {
65         if (this.retryTimer == 0) {
66             LOG.debug("Retry timer value is 0. Reconnection will not be attempted");
67             this.setFailure(this.pending.cause());
68             return;
69         }
70
71         final BGPProtocolSessionPromise lock = this;
72         final EventLoop loop = this.pending.channel().eventLoop();
73         loop.schedule(new Runnable() {
74             @Override
75             public void run() {
76                 LOG.debug("Attempting to connect to {}", BGPProtocolSessionPromise.this.address);
77                 final ChannelFuture reconnectFuture = BGPProtocolSessionPromise.this.bootstrap.connect();
78                 reconnectFuture.addListener(new BootstrapConnectListener(lock));
79                 BGPProtocolSessionPromise.this.pending = reconnectFuture;
80             }
81         }, this.retryTimer, TimeUnit.SECONDS);
82         LOG.debug("Next reconnection attempt in {}s", this.retryTimer);
83     }
84
85     @Override
86     public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
87         if (super.cancel(mayInterruptIfRunning)) {
88             this.pending.cancel(mayInterruptIfRunning);
89             return true;
90         } else {
91             return false;
92         }
93     }
94
95     @Override
96     public synchronized Promise<S> setSuccess(final S result) {
97         LOG.debug("Promise {} completed", this);
98         return super.setSuccess(result);
99     }
100
101     private class BootstrapConnectListener implements ChannelFutureListener {
102         private final Object lock;
103
104         public BootstrapConnectListener(final Object lock) {
105             this.lock = lock;
106         }
107
108         @Override
109         public void operationComplete(final ChannelFuture channelFuture) throws Exception {
110             synchronized (this.lock) {
111                 BGPProtocolSessionPromise.LOG.debug("Promise {} connection resolved", this.lock);
112                 Preconditions.checkState(BGPProtocolSessionPromise.this.pending.equals(channelFuture));
113                 if (BGPProtocolSessionPromise.this.isCancelled()) {
114                     if (channelFuture.isSuccess()) {
115                         BGPProtocolSessionPromise.LOG.debug("Closing channel for cancelled promise {}", this.lock);
116                         channelFuture.channel().close();
117                     }
118                 } else if (channelFuture.isSuccess()) {
119                     BGPProtocolSessionPromise.LOG.debug("Promise {} connection successful", this.lock);
120                 } else {
121                     BGPProtocolSessionPromise.LOG.debug("Attempt to connect to {} failed", BGPProtocolSessionPromise.this.address, channelFuture.cause());
122                     BGPProtocolSessionPromise.this.reconnect();
123                 }
124             }
125         }
126     }
127 }