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.Sets;
16 import io.netty.channel.Channel;
17 import io.netty.channel.ChannelFuture;
18 import io.netty.channel.ChannelFutureListener;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.channel.SimpleChannelInboundHandler;
21 import java.io.IOException;
22 import java.util.Date;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.concurrent.GuardedBy;
26 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
27 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
28 import org.opendaylight.protocol.bgp.parser.BGPError;
29 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
30 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
34 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
35 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
36 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParameters;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapability;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
52 import org.opendaylight.yangtools.yang.binding.Notification;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession, BGPSessionStatistics, AutoCloseable {
59 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
61 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
63 private static final int KA_TO_DEADTIMER_RATIO = 3;
65 private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
67 static final String END_OF_INPUT = "End of input detected. Close the session.";
70 * Internal session state.
74 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
75 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
76 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
80 * The session has been completely established.
84 * The session has been closed. It will not be resurrected.
90 * System.nanoTime value about when was sent the last message.
93 private long lastMessageSentAt;
96 * System.nanoTime value about when was received the last message
98 private long lastMessageReceivedAt;
100 private final BGPSessionListener listener;
102 private final BGPSynchronization sync;
104 private int kaCounter = 0;
106 private final Channel channel;
109 private State state = State.OPEN_CONFIRM;
111 private final Set<BgpTableType> tableTypes;
112 private final int holdTimerValue;
113 private final int keepAlive;
114 private final AsNumber asNumber;
115 private final Ipv4Address bgpId;
116 private final BGPPeerRegistry peerRegistry;
117 private final ChannelOutputLimiter limiter;
119 private BGPSessionStats sessionStats;
121 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences,
122 final BGPPeerRegistry peerRegistry) {
123 this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
124 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes);
127 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer,
128 final BGPPeerRegistry peerRegistry) {
129 this.listener = Preconditions.checkNotNull(listener);
130 this.channel = Preconditions.checkNotNull(channel);
131 this.limiter = new ChannelOutputLimiter(this);
132 this.channel.pipeline().addLast(this.limiter);
133 this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
134 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
135 this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
136 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
137 this.peerRegistry = peerRegistry;
138 final boolean enableExMess = BgpExtendedMessageUtil.advertizedBgpExtendedMessageCapability(remoteOpen);
140 this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER, BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
143 final Set<TablesKey> tts = Sets.newHashSet();
144 final Set<BgpTableType> tats = Sets.newHashSet();
145 if (remoteOpen.getBgpParameters() != null) {
146 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
147 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
148 final CParameters cParam = optCapa.getCParameters();
149 if ( cParam.getAugmentation(CParameters1.class) == null ||
150 cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() == null ) {
153 final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability();
154 final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
155 LOG.trace("Added table type to sync {}", tt);
157 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
162 this.sync = new BGPSynchronization(this.listener, tts);
163 this.tableTypes = tats;
165 if (this.holdTimerValue != 0) {
166 channel.eventLoop().schedule(new Runnable() {
171 }, this.holdTimerValue, TimeUnit.SECONDS);
173 channel.eventLoop().schedule(new Runnable() {
176 handleKeepaliveTimer();
178 }, this.keepAlive, TimeUnit.SECONDS);
180 this.bgpId = remoteOpen.getBgpIdentifier();
181 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
186 public synchronized void close() {
187 if (this.state != State.IDLE && this.channel.isActive()) {
188 this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(
189 BGPError.CEASE.getSubcode()).build());
191 this.closeWithoutMessage();
195 * Handles incoming message based on their type.
197 * @param msg incoming message
199 public synchronized void handleMessage(final Notification msg) {
200 // Update last reception time
201 this.lastMessageReceivedAt = System.nanoTime();
202 this.sessionStats.updateReceivedMsgTotal();
204 if (msg instanceof Open) {
205 // Open messages should not be present here
206 this.terminate(BGPError.FSM_ERROR);
207 } else if (msg instanceof Notify) {
208 // Notifications are handled internally
209 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
210 ((Notify) msg).getErrorSubcode());
211 this.closeWithoutMessage();
212 this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
213 ((Notify) msg).getErrorSubcode())));
214 this.sessionStats.updateReceivedMsgErr((Notify) msg);
215 } else if (msg instanceof Keepalive) {
216 // Keepalives are handled internally
217 LOG.trace("Received KeepAlive messsage.");
219 this.sessionStats.updateReceivedMsgKA();
220 if (this.kaCounter >= 2) {
221 this.sync.kaReceived();
224 // All others are passed up
225 this.listener.onMessage(this, msg);
226 this.sync.updReceived((Update) msg);
227 this.sessionStats.updateReceivedMsgUpd();
231 public synchronized void endOfInput() {
232 if (this.state == State.UP) {
233 LOG.info(END_OF_INPUT);
234 this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
239 private void writeEpilogue(final ChannelFuture future, final Notification msg) {
241 new ChannelFutureListener() {
243 public void operationComplete(final ChannelFuture f) {
244 if (!f.isSuccess()) {
245 LOG.warn("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
247 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
251 this.lastMessageSentAt = System.nanoTime();
252 this.sessionStats.updateSentMsgTotal();
253 if (msg instanceof Update) {
254 this.sessionStats.updateSentMsgUpd();
255 } else if (msg instanceof Notify) {
256 this.sessionStats.updateSentMsgErr((Notify) msg);
261 this.channel.flush();
264 synchronized void write(final Notification msg) {
266 writeEpilogue(this.channel.write(msg), msg);
267 } catch (final Exception e) {
268 LOG.warn("Message {} was not sent.", msg, e);
272 synchronized void writeAndFlush(final Notification msg) {
273 writeEpilogue(this.channel.writeAndFlush(msg), msg);
276 private synchronized void closeWithoutMessage() {
277 LOG.info("Closing session: {}", this);
279 this.channel.close();
280 this.state = State.IDLE;
284 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
285 * modified, because he initiated the closing. (To prevent concurrent modification exception).
289 private void terminate(final BGPError error) {
290 this.writeAndFlush(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
291 this.closeWithoutMessage();
293 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
296 private void removePeerSession() {
297 if (this.peerRegistry != null) {
298 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
303 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
304 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
305 * which the message was received. If the session was closed by the time this method starts to execute (the session
306 * state will become IDLE), then rescheduling won't occur.
308 private synchronized void handleHoldTimer() {
309 if (this.state == State.IDLE) {
313 final long ct = System.nanoTime();
314 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
316 if (ct >= nextHold) {
317 LOG.debug("HoldTimer expired. {}", new Date());
318 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
320 this.channel.eventLoop().schedule(new Runnable() {
325 }, nextHold - ct, TimeUnit.NANOSECONDS);
330 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
331 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
332 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
333 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
335 private synchronized void handleKeepaliveTimer() {
336 if (this.state == State.IDLE) {
340 final long ct = System.nanoTime();
341 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
343 if (ct >= nextKeepalive) {
344 this.writeAndFlush(KEEP_ALIVE);
345 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
346 this.sessionStats.updateSentMsgKA();
348 this.channel.eventLoop().schedule(new Runnable() {
351 handleKeepaliveTimer();
353 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
357 public final String toString() {
358 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
361 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
362 toStringHelper.add("channel", this.channel);
363 toStringHelper.add("state", this.getState());
364 return toStringHelper;
368 public Set<BgpTableType> getAdvertisedTableTypes() {
369 return this.tableTypes;
372 protected synchronized void sessionUp() {
373 this.sessionStats.startSessionStopwatch();
374 this.state = State.UP;
375 this.listener.onSessionUp(this);
378 public synchronized State getState() {
383 public final Ipv4Address getBgpId() {
388 public final AsNumber getAsNumber() {
389 return this.asNumber;
392 synchronized boolean isWritable() {
393 return this.channel != null && this.channel.isWritable();
396 void schedule(final Runnable task) {
397 Preconditions.checkState(this.channel != null);
398 this.channel.eventLoop().submit(task);
402 protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
403 this.lastMessageSentAt = lastMessageSentAt;
407 public synchronized BgpSessionState getBgpSesionState() {
408 return this.sessionStats.getBgpSessionState(this.state);
412 public synchronized void resetSessionStats() {
413 this.sessionStats.resetStats();
416 ChannelOutputLimiter getLimiter() {
421 public final void channelInactive(final ChannelHandlerContext ctx) {
422 LOG.debug("Channel {} inactive.", ctx.channel());
426 super.channelInactive(ctx);
427 } catch (final Exception e) {
428 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
433 protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
434 LOG.debug("Message was received: {}", msg);
435 this.handleMessage(msg);
439 public final void handlerAdded(final ChannelHandlerContext ctx) {