BUG-5511: Support Route Refresh operation from BGP
[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.mp.capabilities.AddPathCapability;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapability;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.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 if (msg instanceof Update) {
239             this.listener.onMessage(this, msg);
240             this.sync.updReceived((Update) msg);
241             this.sessionStats.updateReceivedMsgUpd();
242         } else {
243             LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
244         }
245     }
246
247     public synchronized void endOfInput() {
248         if (this.state == State.UP) {
249             LOG.info(END_OF_INPUT);
250             this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
251         }
252     }
253
254     @GuardedBy("this")
255     private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
256         future.addListener(
257                 new ChannelFutureListener() {
258                     @Override
259                     public void operationComplete(final ChannelFuture f) {
260                         if (!f.isSuccess()) {
261                             LOG.warn("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
262                         } else {
263                             LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
264                         }
265                     }
266                 });
267         this.lastMessageSentAt = System.nanoTime();
268         this.sessionStats.updateSentMsgTotal();
269         if (msg instanceof Update) {
270             this.sessionStats.updateSentMsgUpd();
271         } else if (msg instanceof Notify) {
272             this.sessionStats.updateSentMsgErr((Notify) msg);
273         }
274         return future;
275     }
276
277     void flush() {
278         this.channel.flush();
279     }
280
281     synchronized void write(final Notification msg) {
282         try {
283             writeEpilogue(this.channel.write(msg), msg);
284         } catch (final Exception e) {
285             LOG.warn("Message {} was not sent.", msg, e);
286         }
287     }
288
289     synchronized ChannelFuture writeAndFlush(final Notification msg) {
290         return writeEpilogue(this.channel.writeAndFlush(msg), msg);
291     }
292
293     private synchronized void closeWithoutMessage() {
294         LOG.info("Closing session: {}", this);
295         removePeerSession();
296         this.channel.close();
297         this.state = State.IDLE;
298     }
299
300     /**
301      * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
302      * modified, because he initiated the closing. (To prevent concurrent modification exception).
303      *
304      * @param error
305      */
306     private void terminate(final BGPError error) {
307         this.writeAndFlush(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
308         this.closeWithoutMessage();
309
310         this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
311     }
312
313     private void removePeerSession() {
314         if (this.peerRegistry != null) {
315             this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
316         }
317     }
318
319     /**
320      * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
321      * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
322      * which the message was received. If the session was closed by the time this method starts to execute (the session
323      * state will become IDLE), then rescheduling won't occur.
324      */
325     private synchronized void handleHoldTimer() {
326         if (this.state == State.IDLE) {
327             return;
328         }
329
330         final long ct = System.nanoTime();
331         final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
332
333         if (ct >= nextHold) {
334             LOG.debug("HoldTimer expired. {}", new Date());
335             this.terminate(BGPError.HOLD_TIMER_EXPIRED);
336         } else {
337             this.channel.eventLoop().schedule(new Runnable() {
338                 @Override
339                 public void run() {
340                     handleHoldTimer();
341                 }
342             }, nextHold - ct, TimeUnit.NANOSECONDS);
343         }
344     }
345
346     /**
347      * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
348      * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
349      * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
350      * starts to execute (the session state will become IDLE), that rescheduling won't occur.
351      */
352     private synchronized void handleKeepaliveTimer() {
353         if (this.state == State.IDLE) {
354             return;
355         }
356
357         final long ct = System.nanoTime();
358         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
359
360         if (ct >= nextKeepalive) {
361             this.writeAndFlush(KEEP_ALIVE);
362             nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
363             this.sessionStats.updateSentMsgKA();
364         }
365         this.channel.eventLoop().schedule(new Runnable() {
366             @Override
367             public void run() {
368                 handleKeepaliveTimer();
369             }
370         }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
371     }
372
373     @Override
374     public final String toString() {
375         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
376     }
377
378     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
379         toStringHelper.add("channel", this.channel);
380         toStringHelper.add("state", this.getState());
381         return toStringHelper;
382     }
383
384     @Override
385     public Set<BgpTableType> getAdvertisedTableTypes() {
386         return this.tableTypes;
387     }
388
389     @Override
390     public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
391         return this.addPathTypes;
392     }
393
394     protected synchronized void sessionUp() {
395         this.sessionStats.startSessionStopwatch();
396         this.state = State.UP;
397         this.listener.onSessionUp(this);
398     }
399
400     public synchronized State getState() {
401         return this.state;
402     }
403
404     @Override
405     public final Ipv4Address getBgpId() {
406         return this.bgpId;
407     }
408
409     @Override
410     public final AsNumber getAsNumber() {
411         return this.asNumber;
412     }
413
414     synchronized boolean isWritable() {
415         return this.channel != null && this.channel.isWritable();
416     }
417
418     void schedule(final Runnable task) {
419         Preconditions.checkState(this.channel != null);
420         this.channel.eventLoop().submit(task);
421     }
422
423     @VisibleForTesting
424     protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
425         this.lastMessageSentAt = lastMessageSentAt;
426     }
427
428     @Override
429     public synchronized BgpSessionState getBgpSesionState() {
430         return this.sessionStats.getBgpSessionState(this.state);
431     }
432
433     @Override
434     public synchronized void resetSessionStats() {
435         this.sessionStats.resetStats();
436     }
437
438     ChannelOutputLimiter getLimiter() {
439         return this.limiter;
440     }
441
442     @Override
443     public final void channelInactive(final ChannelHandlerContext ctx) {
444         LOG.debug("Channel {} inactive.", ctx.channel());
445         this.endOfInput();
446
447         try {
448             super.channelInactive(ctx);
449         } catch (final Exception e) {
450             throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
451         }
452     }
453
454     @Override
455     protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
456         LOG.debug("Message was received: {}", msg);
457         this.handleMessage(msg);
458     }
459
460     @Override
461     public final void handlerAdded(final ChannelHandlerContext ctx) {
462         this.sessionUp();
463     }
464 }