Mass-convert all compontents to use -no-zone addresses
[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 com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
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 org.checkerframework.checker.lock.qual.GuardedBy;
24 import org.eclipse.jdt.annotation.NonNull;
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.IpAddressNoZone;
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(final @NonNull InetSocketAddress remoteAddress, final int retryTimer,
51             final @NonNull Bootstrap bootstrap, final @NonNull 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     @SuppressWarnings("checkstyle:illegalCatch")
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         }
67
68         this.connectSkipped = false;
69
70         final BGPProtocolSessionPromise<?> lock = this;
71         try {
72             LOG.debug("Promise {} attempting connect for {}ms", lock, 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 BootstrapConnectListener());
81             this.pending = connectFuture;
82         } catch (final Exception e) {
83             LOG.warn("Failed to connect to {}", this.address, e);
84             this.setFailure(e);
85         }
86     }
87
88     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 EventLoop loop = this.pending.channel().eventLoop();
96         loop.schedule(() -> {
97             synchronized (BGPProtocolSessionPromise.this) {
98                 if (BGPProtocolSessionPromise.this.peerSessionPresent) {
99                     LOG.debug("Connection to {} already exists", BGPProtocolSessionPromise.this.address);
100                     BGPProtocolSessionPromise.this.connectSkipped = true;
101                     return;
102                 }
103
104                 BGPProtocolSessionPromise.this.connectSkipped = false;
105                 LOG.debug("Attempting to connect to {}", BGPProtocolSessionPromise.this.address);
106                 final ChannelFuture reconnectFuture = BGPProtocolSessionPromise.this.bootstrap.connect();
107                 reconnectFuture.addListener(new BootstrapConnectListener());
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             requireNonNull(this.pending);
119             this.pending.cancel(mayInterruptIfRunning);
120             return true;
121         }
122
123         return false;
124     }
125
126     @SuppressWarnings("checkstyle:illegalCatch")
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         @Override
143         public void operationComplete(final ChannelFuture channelFuture) throws Exception {
144             synchronized (BGPProtocolSessionPromise.this) {
145                 LOG.debug("Promise {} connection resolved", BGPProtocolSessionPromise.this);
146                 checkState(BGPProtocolSessionPromise.this.pending.equals(channelFuture), "Unexpected promise %s",
147                     channelFuture);
148                 if (BGPProtocolSessionPromise.this.isCancelled()) {
149                     if (channelFuture.isSuccess()) {
150                         LOG.debug("Closing channel for cancelled promise {}", BGPProtocolSessionPromise.this);
151                         channelFuture.channel().close();
152                     }
153                 } else if (channelFuture.isSuccess()) {
154                     LOG.debug("Promise {} connection successful", BGPProtocolSessionPromise.this);
155                 } else {
156                     LOG.warn("Attempt to connect to {} failed", BGPProtocolSessionPromise.this.address,
157                         channelFuture.cause());
158                     BGPProtocolSessionPromise.this.reconnect();
159                 }
160             }
161         }
162     }
163
164     private class PeerRegistrySessionListenerImpl implements PeerRegistrySessionListener {
165         private final IpAddressNoZone peerAddress;
166
167         PeerRegistrySessionListenerImpl(final IpAddressNoZone peerAddress) {
168             this.peerAddress = peerAddress;
169         }
170
171         @Override
172         public void onSessionCreated(final IpAddressNoZone ip) {
173             if (ip.equals(this.peerAddress)) {
174                 LOG.debug("Callback for session creation with peer {} received", ip);
175                 synchronized (BGPProtocolSessionPromise.this) {
176                     BGPProtocolSessionPromise.this.peerSessionPresent = true;
177                 }
178             }
179         }
180
181         @Override
182         public void onSessionRemoved(final IpAddressNoZone ip) {
183             if (ip.equals(this.peerAddress)) {
184                 LOG.debug("Callback for session removal with peer {} received", ip);
185                 synchronized (BGPProtocolSessionPromise.this) {
186                     BGPProtocolSessionPromise.this.peerSessionPresent = false;
187                     if (BGPProtocolSessionPromise.this.connectSkipped) {
188                         BGPProtocolSessionPromise.this.connect();
189                     }
190                 }
191             }
192         }
193     }
194 }