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