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