2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.bgp.rib.impl;
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;
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;
66 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession, BGPSessionStatistics, AutoCloseable {
68 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
70 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
72 private static final int KA_TO_DEADTIMER_RATIO = 3;
74 private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
76 static final String END_OF_INPUT = "End of input detected. Close the session.";
79 * Internal session state.
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.
89 * The session has been completely established.
93 * The session has been closed. It will not be resurrected.
99 * System.nanoTime value about when was sent the last message.
102 private long lastMessageSentAt;
105 * System.nanoTime value about when was received the last message
107 private long lastMessageReceivedAt;
109 private final BGPSessionListener listener;
111 private final BGPSynchronization sync;
113 private int kaCounter = 0;
115 private final Channel channel;
118 private State state = State.OPEN_CONFIRM;
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;
129 private BGPSessionStats sessionStats;
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);
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);
150 this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER, BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
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) {
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);
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());
177 this.sync = new BGPSynchronization(this.listener, tts);
178 this.tableTypes = tats;
179 this.addPathTypes = addPathCapabilitiesList;
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));
188 if (this.holdTimerValue != 0) {
189 channel.eventLoop().schedule(new Runnable() {
194 }, this.holdTimerValue, TimeUnit.SECONDS);
196 channel.eventLoop().schedule(new Runnable() {
199 handleKeepaliveTimer();
201 }, this.keepAlive, TimeUnit.SECONDS);
203 this.bgpId = remoteOpen.getBgpIdentifier();
204 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
205 this.tableTypes, this.addPathTypes);
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());
214 this.closeWithoutMessage();
218 * Handles incoming message based on their type.
220 * @param msg incoming message
222 public synchronized void handleMessage(final Notification msg) throws BGPDocumentedException {
223 // Update last reception time
224 this.lastMessageReceivedAt = System.nanoTime();
225 this.sessionStats.updateReceivedMsgTotal();
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.");
242 this.sessionStats.updateReceivedMsgKA();
243 if (this.kaCounter >= 2) {
244 this.sync.kaReceived();
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();
254 LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
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));
266 private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
268 new ChannelFutureListener() {
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);
274 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
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);
289 this.channel.flush();
292 synchronized void write(final Notification msg) {
294 writeEpilogue(this.channel.write(msg), msg);
295 } catch (final Exception e) {
296 LOG.warn("Message {} was not sent.", msg, e);
300 synchronized ChannelFuture writeAndFlush(final Notification msg) {
301 return writeEpilogue(this.channel.writeAndFlush(msg), msg);
304 private synchronized void closeWithoutMessage() {
305 LOG.info("Closing session: {}", this);
307 this.channel.close();
308 this.state = State.IDLE;
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).
315 * @param e BGPDocumentedException
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);
324 this.writeAndFlush(builder.build());
325 this.closeWithoutMessage();
327 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
330 private void removePeerSession() {
331 if (this.peerRegistry != null) {
332 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
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.
342 private synchronized void handleHoldTimer() {
343 if (this.state == State.IDLE) {
347 final long ct = System.nanoTime();
348 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
350 if (ct >= nextHold) {
351 LOG.debug("HoldTimer expired. {}", new Date());
352 this.terminate(new BGPDocumentedException(BGPError.HOLD_TIMER_EXPIRED));
354 this.channel.eventLoop().schedule(new Runnable() {
359 }, nextHold - ct, TimeUnit.NANOSECONDS);
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.
369 private synchronized void handleKeepaliveTimer() {
370 if (this.state == State.IDLE) {
374 final long ct = System.nanoTime();
375 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
377 if (ct >= nextKeepalive) {
378 this.writeAndFlush(KEEP_ALIVE);
379 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
380 this.sessionStats.updateSentMsgKA();
382 this.channel.eventLoop().schedule(new Runnable() {
385 handleKeepaliveTimer();
387 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
391 public final String toString() {
392 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
395 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
396 toStringHelper.add("channel", this.channel);
397 toStringHelper.add("state", this.getState());
398 return toStringHelper;
402 public Set<BgpTableType> getAdvertisedTableTypes() {
403 return this.tableTypes;
407 public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
408 return this.addPathTypes;
411 protected synchronized void sessionUp() {
412 this.sessionStats.startSessionStopwatch();
413 this.state = State.UP;
414 this.listener.onSessionUp(this);
417 public synchronized State getState() {
422 public final Ipv4Address getBgpId() {
427 public final AsNumber getAsNumber() {
428 return this.asNumber;
431 synchronized boolean isWritable() {
432 return this.channel != null && this.channel.isWritable();
435 void schedule(final Runnable task) {
436 Preconditions.checkState(this.channel != null);
437 this.channel.eventLoop().submit(task);
441 protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
442 this.lastMessageSentAt = lastMessageSentAt;
446 public synchronized BgpSessionState getBgpSesionState() {
447 return this.sessionStats.getBgpSessionState(this.state);
451 public synchronized void resetSessionStats() {
452 this.sessionStats.resetStats();
455 ChannelOutputLimiter getLimiter() {
460 public final void channelInactive(final ChannelHandlerContext ctx) {
461 LOG.debug("Channel {} inactive.", ctx.channel());
465 super.channelInactive(ctx);
466 } catch (final Exception e) {
467 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
472 protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
473 LOG.debug("Message was received: {}", msg);
475 this.handleMessage(msg);
476 } catch (final BGPDocumentedException e) {
482 public final void handlerAdded(final ChannelHandlerContext ctx) {
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());