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