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