Bug-6781: Inbound and outbound connection attempts from controller are not synchronized
[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.GlobalEventExecutor;
18 import io.netty.util.concurrent.Promise;
19 import java.net.InetSocketAddress;
20 import java.util.concurrent.TimeUnit;
21 import javax.annotation.Nonnull;
22 import javax.annotation.concurrent.GuardedBy;
23 import org.opendaylight.protocol.bgp.rib.impl.StrictBGPPeerRegistry;
24 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistrySessionListener;
26 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 public class BGPProtocolSessionPromise<S extends BGPSession> extends DefaultPromise<S> {
32     private static final Logger LOG = LoggerFactory.getLogger(BGPProtocolSessionPromise.class);
33     private static final int CONNECT_TIMEOUT = 5000;
34
35     private InetSocketAddress address;
36     private final int retryTimer;
37     private final Bootstrap bootstrap;
38     private final BGPPeerRegistry peerRegistry;
39     private final AutoCloseable listenerRegistration;
40     @GuardedBy("this")
41     private ChannelFuture pending;
42     @GuardedBy("this")
43     private boolean peerSessionPresent;
44     @GuardedBy("this")
45     private boolean connectSkipped;
46
47
48     public BGPProtocolSessionPromise(InetSocketAddress remoteAddress, int retryTimer, Bootstrap bootstrap, BGPPeerRegistry peerRegistry) {
49         super(GlobalEventExecutor.INSTANCE);
50         this.address = Preconditions.checkNotNull(remoteAddress);
51         this.retryTimer = retryTimer;
52         this.bootstrap = Preconditions.checkNotNull(bootstrap);
53         this.peerRegistry = Preconditions.checkNotNull(peerRegistry);
54         this.listenerRegistration = this.peerRegistry
55                 .registerPeerSessionListener(new BGPProtocolSessionPromise.PeerRegistrySessionListenerImpl(this,
56                         StrictBGPPeerRegistry.getIpAddress(this.address)));
57     }
58
59     public synchronized void connect() {
60         if (this.peerSessionPresent) {
61             LOG.debug("Connection to {} already exists", this.address);
62             this.connectSkipped = true;
63             return;
64         } else {
65             this.connectSkipped = false;
66         }
67
68         final BGPProtocolSessionPromise lock = this;
69         try {
70             LOG.debug("Promise {} attempting connect for {}ms", lock, Integer.valueOf(CONNECT_TIMEOUT));
71             if (this.address.isUnresolved()) {
72                 this.address = new InetSocketAddress(this.address.getHostName(), this.address.getPort());
73             }
74
75             this.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);
76             this.bootstrap.remoteAddress(this.address);
77             final ChannelFuture connectFuture = this.bootstrap.connect();
78             connectFuture.addListener(new BGPProtocolSessionPromise.BootstrapConnectListener(lock));
79             this.pending = connectFuture;
80         } catch (Exception e) {
81             LOG.info("Failed to connect to {}", this.address, e);
82             this.setFailure(e);
83         }
84     }
85
86     public synchronized void reconnect() {
87         if (this.retryTimer == 0) {
88             LOG.debug("Retry timer value is 0. Reconnection will not be attempted");
89             this.setFailure(this.pending.cause());
90             return;
91         }
92
93         final BGPProtocolSessionPromise lock = this;
94         final EventLoop loop = this.pending.channel().eventLoop();
95         loop.schedule(new Runnable() {
96             @Override
97             public void run() {
98                 if (BGPProtocolSessionPromise.this.peerSessionPresent) {
99                     LOG.debug("Connection to {} already exists", BGPProtocolSessionPromise.this.address);
100                     BGPProtocolSessionPromise.this.connectSkipped = true;
101                     return;
102                 } else {
103                     BGPProtocolSessionPromise.this.connectSkipped = false;
104                 }
105                 LOG.debug("Attempting to connect to {}", BGPProtocolSessionPromise.this.address);
106                 final ChannelFuture reconnectFuture = BGPProtocolSessionPromise.this.bootstrap.connect();
107                 reconnectFuture.addListener(new BootstrapConnectListener(lock));
108                 BGPProtocolSessionPromise.this.pending = reconnectFuture;
109             }
110         }, this.retryTimer, TimeUnit.SECONDS);
111         LOG.debug("Next reconnection attempt in {}s", this.retryTimer);
112     }
113
114     @Override
115     public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
116         closePeerSessionListener();
117         if (super.cancel(mayInterruptIfRunning)) {
118             Preconditions.checkNotNull(this.pending);
119             this.pending.cancel(mayInterruptIfRunning);
120             return true;
121         } else {
122             return false;
123         }
124     }
125
126     private void closePeerSessionListener() {
127         try {
128             this.listenerRegistration.close();
129         } catch (final Exception e) {
130             LOG.debug("Exception encountered while closing peer registry session listener registration", e);
131         }
132     }
133
134     @Override
135     public synchronized Promise<S> setSuccess(final S result) {
136         LOG.debug("Promise {} completed", this);
137         return super.setSuccess(result);
138     }
139
140     private class BootstrapConnectListener implements ChannelFutureListener {
141         private final Object lock;
142
143         public BootstrapConnectListener(final Object lock) {
144             this.lock = lock;
145         }
146
147         @Override
148         public void operationComplete(final ChannelFuture channelFuture) throws Exception {
149             synchronized (this.lock) {
150                 BGPProtocolSessionPromise.LOG.debug("Promise {} connection resolved", this.lock);
151                 Preconditions.checkState(BGPProtocolSessionPromise.this.pending.equals(channelFuture));
152                 if (BGPProtocolSessionPromise.this.isCancelled()) {
153                     if (channelFuture.isSuccess()) {
154                         BGPProtocolSessionPromise.LOG.debug("Closing channel for cancelled promise {}", this.lock);
155                         channelFuture.channel().close();
156                     }
157                 } else if (channelFuture.isSuccess()) {
158                     BGPProtocolSessionPromise.LOG.debug("Promise {} connection successful", this.lock);
159                 } else {
160                     BGPProtocolSessionPromise.LOG.debug("Attempt to connect to {} failed", BGPProtocolSessionPromise.this.address, channelFuture.cause());
161                     BGPProtocolSessionPromise.this.reconnect();
162                 }
163             }
164         }
165     }
166
167     private class PeerRegistrySessionListenerImpl implements PeerRegistrySessionListener {
168         private final Object lock;
169         private final IpAddress peerAddress;
170
171         PeerRegistrySessionListenerImpl(final Object lock, final IpAddress peerAddress) {
172             this.lock = lock;
173             this.peerAddress = peerAddress;
174         }
175
176         @Override
177         public void onSessionCreated(@Nonnull final IpAddress ip) {
178             if (!ip.equals(this.peerAddress)) {
179                 return;
180             }
181             BGPProtocolSessionPromise.LOG.debug("Callback for session creation with peer {} received", ip);
182             synchronized (this.lock) {
183                 BGPProtocolSessionPromise.this.peerSessionPresent = true;
184             }
185         }
186
187         @Override
188         public void onSessionRemoved(@Nonnull final IpAddress ip) {
189             if (!ip.equals(this.peerAddress)) {
190                 return;
191             }
192             BGPProtocolSessionPromise.LOG.debug("Callback for session removal with peer {} received", ip);
193             synchronized (this.lock) {
194                 BGPProtocolSessionPromise.this.peerSessionPresent = false;
195                 if (BGPProtocolSessionPromise.this.connectSkipped) {
196                     BGPProtocolSessionPromise.this.connect();
197                 }
198             }
199         }
200     }
201
202 }