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