Bug-5791: Make Next-Hop mandatory BGP path attribute
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPSessionImpl.java
1 /*
2  * Copyright (c) 2013 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;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Sets;
17 import io.netty.channel.Channel;
18 import io.netty.channel.ChannelFuture;
19 import io.netty.channel.ChannelFutureListener;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelPipeline;
22 import io.netty.channel.SimpleChannelInboundHandler;
23 import java.io.IOException;
24 import java.util.Date;
25 import java.util.List;
26 import java.util.Set;
27 import java.util.concurrent.TimeUnit;
28 import javax.annotation.concurrent.GuardedBy;
29 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
30 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
31 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
32 import org.opendaylight.protocol.bgp.parser.BGPError;
33 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
34 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
35 import org.opendaylight.protocol.bgp.parser.spi.MultiPathSupport;
36 import org.opendaylight.protocol.bgp.parser.spi.pojo.MultiPathSupportImpl;
37 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
38 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
39 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
40 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
41 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
42 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParameters;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.AddPathCapability;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapability;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
61 import org.opendaylight.yangtools.yang.binding.Notification;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 @VisibleForTesting
66 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession, BGPSessionStatistics, AutoCloseable {
67
68     private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
69
70     private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
71
72     private static final int KA_TO_DEADTIMER_RATIO = 3;
73
74     private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
75
76     static final String END_OF_INPUT = "End of input detected. Close the session.";
77
78     /**
79      * Internal session state.
80      */
81     public enum State {
82         /**
83          * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
84          * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
85          * announced to the listener. If the session is torn down in this state, we do not inform the listener.
86          */
87         OPEN_CONFIRM,
88         /**
89          * The session has been completely established.
90          */
91         UP,
92         /**
93          * The session has been closed. It will not be resurrected.
94          */
95         IDLE,
96     }
97
98     /**
99      * System.nanoTime value about when was sent the last message.
100      */
101     @VisibleForTesting
102     private long lastMessageSentAt;
103
104     /**
105      * System.nanoTime value about when was received the last message
106      */
107     private long lastMessageReceivedAt;
108
109     private final BGPSessionListener listener;
110
111     private final BGPSynchronization sync;
112
113     private int kaCounter = 0;
114
115     private final Channel channel;
116
117     @GuardedBy("this")
118     private State state = State.OPEN_CONFIRM;
119
120     private final Set<BgpTableType> tableTypes;
121     private final List<AddressFamilies> addPathTypes;
122     private final int holdTimerValue;
123     private final int keepAlive;
124     private final AsNumber asNumber;
125     private final Ipv4Address bgpId;
126     private final BGPPeerRegistry peerRegistry;
127     private final ChannelOutputLimiter limiter;
128
129     private BGPSessionStats sessionStats;
130
131     public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences,
132             final BGPPeerRegistry peerRegistry) {
133         this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
134         this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes, this.addPathTypes);
135     }
136
137     public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer,
138             final BGPPeerRegistry peerRegistry) {
139         this.listener = Preconditions.checkNotNull(listener);
140         this.channel = Preconditions.checkNotNull(channel);
141         this.limiter = new ChannelOutputLimiter(this);
142         this.channel.pipeline().addLast(this.limiter);
143         this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
144         LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
145         this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
146         this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
147         this.peerRegistry = peerRegistry;
148         final boolean enableExMess = BgpExtendedMessageUtil.advertizedBgpExtendedMessageCapability(remoteOpen);
149         if (enableExMess) {
150             this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER, BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
151         }
152
153         final Set<TablesKey> tts = Sets.newHashSet();
154         final Set<BgpTableType> tats = Sets.newHashSet();
155         final List<AddressFamilies> addPathCapabilitiesList = Lists.newArrayList();
156         if (remoteOpen.getBgpParameters() != null) {
157             for (final BgpParameters param : remoteOpen.getBgpParameters()) {
158                 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
159                     final CParameters cParam = optCapa.getCParameters();
160                     if ( cParam.getAugmentation(CParameters1.class) == null) {
161                         continue;
162                     }
163                     if(cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() != null) {
164                         final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability();
165                         final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
166                         LOG.trace("Added table type to sync {}", tt);
167                         tts.add(tt);
168                         tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
169                     } else if (cParam.getAugmentation(CParameters1.class).getAddPathCapability() != null) {
170                         final AddPathCapability addPathCap = cParam.getAugmentation(CParameters1.class).getAddPathCapability();
171                         addPathCapabilitiesList.addAll(addPathCap.getAddressFamilies());
172                     }
173                 }
174             }
175         }
176
177         this.sync = new BGPSynchronization(this.listener, tts);
178         this.tableTypes = tats;
179         this.addPathTypes = addPathCapabilitiesList;
180
181         if (! this.addPathTypes.isEmpty()) {
182             final ChannelPipeline pipeline = this.channel.pipeline();
183             final BGPByteToMessageDecoder decoder = pipeline.get(BGPByteToMessageDecoder.class);
184             decoder.addDecoderConstraint(MultiPathSupport.class,
185                     MultiPathSupportImpl.createParserMultiPathSupport(this.addPathTypes));
186         }
187
188         if (this.holdTimerValue != 0) {
189             channel.eventLoop().schedule(new Runnable() {
190                 @Override
191                 public void run() {
192                     handleHoldTimer();
193                 }
194             }, this.holdTimerValue, TimeUnit.SECONDS);
195
196             channel.eventLoop().schedule(new Runnable() {
197                 @Override
198                 public void run() {
199                     handleKeepaliveTimer();
200                 }
201             }, this.keepAlive, TimeUnit.SECONDS);
202         }
203         this.bgpId = remoteOpen.getBgpIdentifier();
204         this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
205                 this.tableTypes, this.addPathTypes);
206     }
207
208     @Override
209     public synchronized void close() {
210         if (this.state != State.IDLE && this.channel.isActive()) {
211             this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(
212                     BGPError.CEASE.getSubcode()).build());
213         }
214         this.closeWithoutMessage();
215     }
216
217     /**
218      * Handles incoming message based on their type.
219      *
220      * @param msg incoming message
221      */
222     public synchronized void handleMessage(final Notification msg) throws BGPDocumentedException {
223         // Update last reception time
224         this.lastMessageReceivedAt = System.nanoTime();
225         this.sessionStats.updateReceivedMsgTotal();
226
227         if (msg instanceof Open) {
228             // Open messages should not be present here
229             this.terminate(new BGPDocumentedException(null, BGPError.FSM_ERROR));
230         } else if (msg instanceof Notify) {
231             // Notifications are handled internally
232             LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
233                     ((Notify) msg).getErrorSubcode());
234             this.closeWithoutMessage();
235             this.listener.onSessionTerminated(this, new BGPTerminationReason(
236                     BGPError.forValue(((Notify) msg).getErrorCode(), ((Notify) msg).getErrorSubcode())));
237             this.sessionStats.updateReceivedMsgErr((Notify) msg);
238         } else if (msg instanceof Keepalive) {
239             // Keepalives are handled internally
240             LOG.trace("Received KeepAlive messsage.");
241             this.kaCounter++;
242             this.sessionStats.updateReceivedMsgKA();
243             if (this.kaCounter >= 2) {
244                 this.sync.kaReceived();
245             }
246         } else if (msg instanceof RouteRefresh) {
247             this.listener.onMessage(this, msg);
248             this.sessionStats.updateReceivedMsgRR();
249         } else if (msg instanceof Update) {
250             this.listener.onMessage(this, msg);
251             this.sync.updReceived((Update) msg);
252             this.sessionStats.updateReceivedMsgUpd();
253         } else {
254             LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
255         }
256     }
257
258     public synchronized void endOfInput() {
259         if (this.state == State.UP) {
260             LOG.info(END_OF_INPUT);
261             this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
262         }
263     }
264
265     @GuardedBy("this")
266     private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
267         future.addListener(
268                 new ChannelFutureListener() {
269                     @Override
270                     public void operationComplete(final ChannelFuture f) {
271                         if (!f.isSuccess()) {
272                             LOG.warn("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
273                         } else {
274                             LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
275                         }
276                     }
277                 });
278         this.lastMessageSentAt = System.nanoTime();
279         this.sessionStats.updateSentMsgTotal();
280         if (msg instanceof Update) {
281             this.sessionStats.updateSentMsgUpd();
282         } else if (msg instanceof Notify) {
283             this.sessionStats.updateSentMsgErr((Notify) msg);
284         }
285         return future;
286     }
287
288     void flush() {
289         this.channel.flush();
290     }
291
292     synchronized void write(final Notification msg) {
293         try {
294             writeEpilogue(this.channel.write(msg), msg);
295         } catch (final Exception e) {
296             LOG.warn("Message {} was not sent.", msg, e);
297         }
298     }
299
300     synchronized ChannelFuture writeAndFlush(final Notification msg) {
301         return writeEpilogue(this.channel.writeAndFlush(msg), msg);
302     }
303
304     private synchronized void closeWithoutMessage() {
305         LOG.info("Closing session: {}", this);
306         removePeerSession();
307         this.channel.close();
308         this.state = State.IDLE;
309     }
310
311     /**
312      * Closes BGP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
313      * modified, because he initiated the closing. (To prevent concurrent modification exception).
314      *
315      * @param e BGPDocumentedException
316      */
317     private synchronized void terminate(final BGPDocumentedException e) {
318         final BGPError error = e.getError();
319         final byte[] data = e.getData();
320         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode());
321         if (data != null && data.length != 0) {
322             builder.setData(data);
323         }
324         this.writeAndFlush(builder.build());
325         this.closeWithoutMessage();
326
327         this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
328     }
329
330     private void removePeerSession() {
331         if (this.peerRegistry != null) {
332             this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
333         }
334     }
335
336     /**
337      * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
338      * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
339      * which the message was received. If the session was closed by the time this method starts to execute (the session
340      * state will become IDLE), then rescheduling won't occur.
341      */
342     private synchronized void handleHoldTimer() {
343         if (this.state == State.IDLE) {
344             return;
345         }
346
347         final long ct = System.nanoTime();
348         final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
349
350         if (ct >= nextHold) {
351             LOG.debug("HoldTimer expired. {}", new Date());
352             this.terminate(new BGPDocumentedException(BGPError.HOLD_TIMER_EXPIRED));
353         } else {
354             this.channel.eventLoop().schedule(new Runnable() {
355                 @Override
356                 public void run() {
357                     handleHoldTimer();
358                 }
359             }, nextHold - ct, TimeUnit.NANOSECONDS);
360         }
361     }
362
363     /**
364      * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
365      * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
366      * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
367      * starts to execute (the session state will become IDLE), that rescheduling won't occur.
368      */
369     private synchronized void handleKeepaliveTimer() {
370         if (this.state == State.IDLE) {
371             return;
372         }
373
374         final long ct = System.nanoTime();
375         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
376
377         if (ct >= nextKeepalive) {
378             this.writeAndFlush(KEEP_ALIVE);
379             nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
380             this.sessionStats.updateSentMsgKA();
381         }
382         this.channel.eventLoop().schedule(new Runnable() {
383             @Override
384             public void run() {
385                 handleKeepaliveTimer();
386             }
387         }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
388     }
389
390     @Override
391     public final String toString() {
392         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
393     }
394
395     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
396         toStringHelper.add("channel", this.channel);
397         toStringHelper.add("state", this.getState());
398         return toStringHelper;
399     }
400
401     @Override
402     public Set<BgpTableType> getAdvertisedTableTypes() {
403         return this.tableTypes;
404     }
405
406     @Override
407     public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
408         return this.addPathTypes;
409     }
410
411     protected synchronized void sessionUp() {
412         this.sessionStats.startSessionStopwatch();
413         this.state = State.UP;
414         this.listener.onSessionUp(this);
415     }
416
417     public synchronized State getState() {
418         return this.state;
419     }
420
421     @Override
422     public final Ipv4Address getBgpId() {
423         return this.bgpId;
424     }
425
426     @Override
427     public final AsNumber getAsNumber() {
428         return this.asNumber;
429     }
430
431     synchronized boolean isWritable() {
432         return this.channel != null && this.channel.isWritable();
433     }
434
435     void schedule(final Runnable task) {
436         Preconditions.checkState(this.channel != null);
437         this.channel.eventLoop().submit(task);
438     }
439
440     @VisibleForTesting
441     protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
442         this.lastMessageSentAt = lastMessageSentAt;
443     }
444
445     @Override
446     public synchronized BgpSessionState getBgpSesionState() {
447         return this.sessionStats.getBgpSessionState(this.state);
448     }
449
450     @Override
451     public synchronized void resetSessionStats() {
452         this.sessionStats.resetStats();
453     }
454
455     ChannelOutputLimiter getLimiter() {
456         return this.limiter;
457     }
458
459     @Override
460     public final void channelInactive(final ChannelHandlerContext ctx) {
461         LOG.debug("Channel {} inactive.", ctx.channel());
462         this.endOfInput();
463
464         try {
465             super.channelInactive(ctx);
466         } catch (final Exception e) {
467             throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
468         }
469     }
470
471     @Override
472     protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
473         LOG.debug("Message was received: {}", msg);
474         try {
475             this.handleMessage(msg);
476         } catch (final BGPDocumentedException e) {
477             this.terminate(e);
478         }
479     }
480
481     @Override
482     public final void handlerAdded(final ChannelHandlerContext ctx) {
483         this.sessionUp();
484     }
485
486     @Override
487     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
488         LOG.warn("BGP session encountered error", cause);
489         if (cause.getCause() instanceof BGPDocumentedException) {
490             this.terminate((BGPDocumentedException) cause.getCause());
491         } else {
492             this.close();
493         }
494     }
495 }