Fix more rib-impl checkstyle
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AbstractBGPSessionNegotiator.java
1 /*
2  * Copyright (c) 2014 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
9 package org.opendaylight.protocol.bgp.rib.impl;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelFutureListener;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import io.netty.util.concurrent.Promise;
19 import io.netty.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21 import javax.annotation.concurrent.GuardedBy;
22 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
23 import org.opendaylight.protocol.bgp.parser.BGPError;
24 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
26 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
27 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
28 import org.opendaylight.protocol.util.Ipv6Util;
29 import org.opendaylight.protocol.util.Values;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Keepalive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.KeepaliveBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Notify;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.NotifyBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.OpenBuilder;
38 import org.opendaylight.yangtools.yang.binding.Notification;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Bgp Session negotiator. Common for local-to-remote and remote-to-local connections.
44  * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
45  */
46 abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandlerAdapter implements SessionNegotiator {
47     // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
48     private static final int INITIAL_HOLDTIMER = 4;
49
50     // <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
51     private static final int AS_TRANS = 23456;
52     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
53     private final BGPPeerRegistry registry;
54     private final Promise<BGPSessionImpl> promise;
55     private final Channel channel;
56     @GuardedBy("this")
57     private State state = State.IDLE;
58     @GuardedBy("this")
59     private BGPSessionImpl session;
60     @GuardedBy("this")
61     private ScheduledFuture<?> pending;
62
63     @VisibleForTesting
64     public enum State {
65         /**
66          * Negotiation has not started yet.
67          */
68         IDLE,
69         /**
70          * We have sent our Open message, and are waiting for the peer's Open message.
71          */
72         OPEN_SENT,
73         /**
74          * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
75          * Open message.
76          */
77         OPEN_CONFIRM,
78         /**
79          * The negotiation finished.
80          */
81         FINISHED,
82     }
83
84     AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
85             final BGPPeerRegistry registry) {
86         this.promise = requireNonNull(promise);
87         this.channel = requireNonNull(channel);
88         this.registry = registry;
89     }
90
91     private synchronized void startNegotiation() {
92         if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
93             return;
94         }
95         // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
96         final IpAddress remoteIp = getRemoteIp();
97         try {
98             // Check if peer is configured in registry before retrieving preferences
99             if (!this.registry.isPeerConfigured(remoteIp)) {
100                 final BGPDocumentedException cause = new BGPDocumentedException(
101                         String.format("BGP peer with ip: %s not configured, check configured peers in : %s",
102                                 remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
103                 negotiationFailed(cause);
104                 return;
105             }
106
107             final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
108
109             int as = preferences.getMyAs().getValue().intValue();
110             // Set as AS_TRANS if the value is bigger than 2B
111             if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
112                 as = AS_TRANS;
113             }
114             sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
115                     preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
116             if (this.state != State.FINISHED) {
117                 this.state = State.OPEN_SENT;
118                 this.pending = this.channel.eventLoop().schedule(() -> {
119                     synchronized (AbstractBGPSessionNegotiator.this) {
120                         AbstractBGPSessionNegotiator.this.pending = null;
121                         if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
122                             AbstractBGPSessionNegotiator.this
123                                     .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
124                             negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
125                             AbstractBGPSessionNegotiator.this.state = State.FINISHED;
126                         }
127                     }
128                 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
129             }
130         } catch (final Exception e) {
131             LOG.warn("Unexpected negotiation failure", e);
132             negotiationFailedCloseChannel(e);
133         }
134     }
135
136     private IpAddress getRemoteIp() {
137         final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
138         if (remoteIp.getIpv6Address() != null) {
139             return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
140         }
141         return remoteIp;
142     }
143
144     synchronized void handleMessage(final Notification msg) {
145         LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
146         switch (this.state) {
147             case FINISHED:
148                 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
149                 return;
150             case IDLE:
151                 // to avoid race condition when Open message was sent by the peer before startNegotiation could be
152                 // executed
153                 if (msg instanceof Open) {
154                     startNegotiation();
155                     handleOpen((Open) msg);
156                     return;
157                 }
158                 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
159                 break;
160             case OPEN_CONFIRM:
161                 if (msg instanceof Keepalive) {
162                     negotiationSuccessful(this.session);
163                     LOG.info("BGP Session with peer {} established successfully.", this.channel);
164                 } else if (msg instanceof Notify) {
165                     final Notify ntf = (Notify) msg;
166                     negotiationFailed(new BGPDocumentedException("Peer refusal",
167                             BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
168                 }
169                 this.state = State.FINISHED;
170                 return;
171             case OPEN_SENT:
172                 if (msg instanceof Open) {
173                     handleOpen((Open) msg);
174                     return;
175                 }
176                 break;
177             default:
178                 break;
179         }
180
181         // Catch-all for unexpected message
182         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
183         sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
184         negotiationFailed(new BGPDocumentedException("Unexpected message channel: "
185                 + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
186         this.state = State.FINISHED;
187     }
188
189     private static Notify buildErrorNotify(final BGPError err) {
190         return buildErrorNotify(err, null);
191     }
192
193     private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
194         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
195         if (data != null && data.length != 0) {
196             builder.setData(data);
197         }
198         return builder.build();
199     }
200
201     private synchronized void handleOpen(final Open openObj) {
202         final IpAddress remoteIp = getRemoteIp();
203         final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
204         try {
205             final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences),
206                     getDestinationId(openObj, preferences), openObj);
207             sendMessage(new KeepaliveBuilder().build());
208             this.state = State.OPEN_CONFIRM;
209             this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
210             this.session.setChannelExtMsgCoder(openObj);
211             LOG.debug("Channel {} moved to OPEN_CONFIRM state with remote proposal {}", this.channel, openObj);
212         } catch (final BGPDocumentedException e) {
213             LOG.warn("Channel {} negotiation failed", this.channel, e);
214             negotiationFailed(e);
215         }
216     }
217
218     private synchronized void negotiationFailed(final Throwable e) {
219         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
220         if (e instanceof BGPDocumentedException) {
221             // although sendMessage() can also result in calling this method, it won't create a cycle.
222             // In case sendMessage() fails to deliver the message, this method gets called with different
223             // exception (definitely not with BGPDocumentedException).
224             sendMessage(buildErrorNotify(((BGPDocumentedException) e).getError(),
225                     ((BGPDocumentedException) e).getData()));
226         }
227         if (this.state == State.OPEN_CONFIRM) {
228             this.registry.removePeerSession(getRemoteIp());
229         }
230         negotiationFailedCloseChannel(e);
231         this.state = State.FINISHED;
232     }
233
234     /**
235      * Get destination identifier.
236      *
237      * @param openMsg Open message received from remote BGP speaker
238      * @param preferences Local BGP speaker preferences
239      * @return BGP Id of device that accepted the connection
240      */
241     protected abstract Ipv4Address getDestinationId(Open openMsg, BGPSessionPreferences preferences);
242
243     /**
244      * Get source identifier.
245      *
246      * @param openMsg Open message received from remote BGP speaker
247      * @param preferences Local BGP speaker preferences
248      * @return BGP Id of device that accepted the connection
249      */
250     protected abstract Ipv4Address getSourceId(Open openMsg, BGPSessionPreferences preferences);
251
252     public synchronized State getState() {
253         return this.state;
254     }
255
256     private void negotiationSuccessful(final BGPSessionImpl session) {
257         LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
258         this.channel.pipeline().replace(this, "session", session);
259         this.promise.setSuccess(session);
260     }
261
262     private void negotiationFailedCloseChannel(final Throwable cause) {
263         LOG.debug("Negotiation on channel {} failed", this.channel, cause);
264         this.channel.close();
265         synchronized (AbstractBGPSessionNegotiator.this) {
266             if (this.pending != null && this.pending.isCancellable()) {
267                 this.pending.cancel(true);
268                 this.pending = null;
269             }
270         }
271     }
272
273     private void sendMessage(final Notification msg) {
274         this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
275             if (!f.isSuccess()) {
276                 LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel,
277                         f.cause());
278                 negotiationFailedCloseChannel(f.cause());
279             } else {
280                 LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
281             }
282         });
283     }
284
285     @Override
286     public final void channelActive(final ChannelHandlerContext ctx) {
287         LOG.debug("Starting session negotiation on channel {}", this.channel);
288         startNegotiation();
289     }
290
291     @Override
292     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
293         LOG.debug("Negotiation read invoked on channel {}", this.channel);
294         try {
295             handleMessage((Notification) msg);
296         } catch (final Exception e) {
297             LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
298             negotiationFailedCloseChannel(e);
299         }
300
301     }
302
303     @Override
304     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
305         LOG.info("Unexpected error during negotiation", cause);
306         negotiationFailedCloseChannel(cause);
307     }
308 }