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.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;
65 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession, BGPSessionStatistics, AutoCloseable {
67 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
69 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
71 private static final int KA_TO_DEADTIMER_RATIO = 3;
73 private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
75 static final String END_OF_INPUT = "End of input detected. Close the session.";
78 * Internal session state.
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.
88 * The session has been completely established.
92 * The session has been closed. It will not be resurrected.
98 * System.nanoTime value about when was sent the last message.
101 private long lastMessageSentAt;
104 * System.nanoTime value about when was received the last message
106 private long lastMessageReceivedAt;
108 private final BGPSessionListener listener;
110 private final BGPSynchronization sync;
112 private int kaCounter = 0;
114 private final Channel channel;
117 private State state = State.OPEN_CONFIRM;
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;
128 private BGPSessionStats sessionStats;
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);
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);
149 this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER, BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
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) {
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);
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());
176 this.sync = new BGPSynchronization(this.listener, tts);
177 this.tableTypes = tats;
178 this.addPathTypes = addPathCapabilitiesList;
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));
187 if (this.holdTimerValue != 0) {
188 channel.eventLoop().schedule(new Runnable() {
193 }, this.holdTimerValue, TimeUnit.SECONDS);
195 channel.eventLoop().schedule(new Runnable() {
198 handleKeepaliveTimer();
200 }, this.keepAlive, TimeUnit.SECONDS);
202 this.bgpId = remoteOpen.getBgpIdentifier();
203 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
204 this.tableTypes, this.addPathTypes);
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());
213 this.closeWithoutMessage();
217 * Handles incoming message based on their type.
219 * @param msg incoming message
221 public synchronized void handleMessage(final Notification msg) {
222 // Update last reception time
223 this.lastMessageReceivedAt = System.nanoTime();
224 this.sessionStats.updateReceivedMsgTotal();
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.");
241 this.sessionStats.updateReceivedMsgKA();
242 if (this.kaCounter >= 2) {
243 this.sync.kaReceived();
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();
253 LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
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));
265 private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
267 new ChannelFutureListener() {
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);
273 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
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);
288 this.channel.flush();
291 synchronized void write(final Notification msg) {
293 writeEpilogue(this.channel.write(msg), msg);
294 } catch (final Exception e) {
295 LOG.warn("Message {} was not sent.", msg, e);
299 synchronized ChannelFuture writeAndFlush(final Notification msg) {
300 return writeEpilogue(this.channel.writeAndFlush(msg), msg);
303 private synchronized void closeWithoutMessage() {
304 LOG.info("Closing session: {}", this);
306 this.channel.close();
307 this.state = State.IDLE;
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).
316 private void terminate(final BGPError error) {
317 this.writeAndFlush(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
318 this.closeWithoutMessage();
320 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
323 private void removePeerSession() {
324 if (this.peerRegistry != null) {
325 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
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.
335 private synchronized void handleHoldTimer() {
336 if (this.state == State.IDLE) {
340 final long ct = System.nanoTime();
341 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
343 if (ct >= nextHold) {
344 LOG.debug("HoldTimer expired. {}", new Date());
345 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
347 this.channel.eventLoop().schedule(new Runnable() {
352 }, nextHold - ct, TimeUnit.NANOSECONDS);
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.
362 private synchronized void handleKeepaliveTimer() {
363 if (this.state == State.IDLE) {
367 final long ct = System.nanoTime();
368 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
370 if (ct >= nextKeepalive) {
371 this.writeAndFlush(KEEP_ALIVE);
372 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
373 this.sessionStats.updateSentMsgKA();
375 this.channel.eventLoop().schedule(new Runnable() {
378 handleKeepaliveTimer();
380 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
384 public final String toString() {
385 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
388 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
389 toStringHelper.add("channel", this.channel);
390 toStringHelper.add("state", this.getState());
391 return toStringHelper;
395 public Set<BgpTableType> getAdvertisedTableTypes() {
396 return this.tableTypes;
400 public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
401 return this.addPathTypes;
404 protected synchronized void sessionUp() {
405 this.sessionStats.startSessionStopwatch();
406 this.state = State.UP;
407 this.listener.onSessionUp(this);
410 public synchronized State getState() {
415 public final Ipv4Address getBgpId() {
420 public final AsNumber getAsNumber() {
421 return this.asNumber;
424 synchronized boolean isWritable() {
425 return this.channel != null && this.channel.isWritable();
428 void schedule(final Runnable task) {
429 Preconditions.checkState(this.channel != null);
430 this.channel.eventLoop().submit(task);
434 protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
435 this.lastMessageSentAt = lastMessageSentAt;
439 public synchronized BgpSessionState getBgpSesionState() {
440 return this.sessionStats.getBgpSessionState(this.state);
444 public synchronized void resetSessionStats() {
445 this.sessionStats.resetStats();
448 ChannelOutputLimiter getLimiter() {
453 public final void channelInactive(final ChannelHandlerContext ctx) {
454 LOG.debug("Channel {} inactive.", ctx.channel());
458 super.channelInactive(ctx);
459 } catch (final Exception e) {
460 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
465 protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
466 LOG.debug("Message was received: {}", msg);
467 this.handleMessage(msg);
471 public final void handlerAdded(final ChannelHandlerContext ctx) {