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.BgpTableTypeImpl;
30 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
33 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
34 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
35 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParameters;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapability;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
51 import org.opendaylight.yangtools.yang.binding.Notification;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession, BGPSessionStatistics, AutoCloseable {
58 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
60 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
62 private static final int KA_TO_DEADTIMER_RATIO = 3;
64 static final String END_OF_INPUT = "End of input detected. Close the session.";
67 * Internal session state.
71 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
72 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
73 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
77 * The session has been completely established.
81 * The session has been closed. It will not be resurrected.
87 * System.nanoTime value about when was sent the last message.
90 private long lastMessageSentAt;
93 * System.nanoTime value about when was received the last message
95 private long lastMessageReceivedAt;
97 private final BGPSessionListener listener;
99 private final BGPSynchronization sync;
101 private int kaCounter = 0;
103 private final Channel channel;
106 private State state = State.OPEN_CONFIRM;
108 private final Set<BgpTableType> tableTypes;
109 private final int holdTimerValue;
110 private final int keepAlive;
111 private final AsNumber asNumber;
112 private final Ipv4Address bgpId;
113 private final BGPPeerRegistry peerRegistry;
114 private final ChannelOutputLimiter limiter;
116 private BGPSessionStats sessionStats;
118 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences,
119 final BGPPeerRegistry peerRegistry) {
120 this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
121 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes);
124 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer,
125 final BGPPeerRegistry peerRegistry) {
126 this.listener = Preconditions.checkNotNull(listener);
127 this.channel = Preconditions.checkNotNull(channel);
128 this.limiter = new ChannelOutputLimiter(this);
129 this.channel.pipeline().addLast(this.limiter);
130 this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
131 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
132 this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
133 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
134 this.peerRegistry = peerRegistry;
136 final Set<TablesKey> tts = Sets.newHashSet();
137 final Set<BgpTableType> tats = Sets.newHashSet();
138 if (remoteOpen.getBgpParameters() != null) {
139 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
140 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
141 final CParameters cParam = optCapa.getCParameters();
142 if ( cParam.getAugmentation(CParameters1.class) == null ||
143 cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() == null ) {
146 final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability();
147 final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
148 LOG.trace("Added table type to sync {}", tt);
150 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
155 this.sync = new BGPSynchronization(this.listener, tts);
156 this.tableTypes = tats;
158 if (this.holdTimerValue != 0) {
159 channel.eventLoop().schedule(new Runnable() {
164 }, this.holdTimerValue, TimeUnit.SECONDS);
166 channel.eventLoop().schedule(new Runnable() {
169 handleKeepaliveTimer();
171 }, this.keepAlive, TimeUnit.SECONDS);
173 this.bgpId = remoteOpen.getBgpIdentifier();
174 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
179 public synchronized void close() {
180 if (this.state != State.IDLE && this.channel.isActive()) {
181 this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(
182 BGPError.CEASE.getSubcode()).build());
184 this.closeWithoutMessage();
188 * Handles incoming message based on their type.
190 * @param msg incoming message
192 public synchronized void handleMessage(final Notification msg) {
193 // Update last reception time
194 this.lastMessageReceivedAt = System.nanoTime();
195 this.sessionStats.updateReceivedMsgTotal();
197 if (msg instanceof Open) {
198 // Open messages should not be present here
199 this.terminate(BGPError.FSM_ERROR);
200 } else if (msg instanceof Notify) {
201 // Notifications are handled internally
202 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
203 ((Notify) msg).getErrorSubcode());
204 this.closeWithoutMessage();
205 this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
206 ((Notify) msg).getErrorSubcode())));
207 this.sessionStats.updateReceivedMsgErr((Notify) msg);
208 } else if (msg instanceof Keepalive) {
209 // Keepalives are handled internally
210 LOG.trace("Received KeepAlive messsage.");
212 this.sessionStats.updateReceivedMsgKA();
213 if (this.kaCounter >= 2) {
214 this.sync.kaReceived();
217 // All others are passed up
218 this.listener.onMessage(this, msg);
219 this.sync.updReceived((Update) msg);
220 this.sessionStats.updateReceivedMsgUpd();
224 public synchronized void endOfInput() {
225 if (this.state == State.UP) {
226 LOG.info(END_OF_INPUT);
227 this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
232 private void writeEpilogue(final ChannelFuture future, final Notification msg) {
234 new ChannelFutureListener() {
236 public void operationComplete(final ChannelFuture f) {
237 if (!f.isSuccess()) {
238 LOG.warn("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
240 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
244 this.lastMessageSentAt = System.nanoTime();
245 this.sessionStats.updateSentMsgTotal();
246 if (msg instanceof Update) {
247 this.sessionStats.updateSentMsgUpd();
248 } else if (msg instanceof Notify) {
249 this.sessionStats.updateSentMsgErr((Notify) msg);
254 this.channel.flush();
257 synchronized void write(final Notification msg) {
259 writeEpilogue(this.channel.write(msg), msg);
260 } catch (final Exception e) {
261 LOG.warn("Message {} was not sent.", msg, e);
265 synchronized void writeAndFlush(final Notification msg) {
266 writeEpilogue(this.channel.writeAndFlush(msg), msg);
269 private synchronized void closeWithoutMessage() {
270 LOG.info("Closing session: {}", this);
272 this.channel.close();
273 this.state = State.IDLE;
277 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
278 * modified, because he initiated the closing. (To prevent concurrent modification exception).
282 private void terminate(final BGPError error) {
283 this.writeAndFlush(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
284 this.closeWithoutMessage();
286 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
289 private void removePeerSession() {
290 if (this.peerRegistry != null) {
291 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
296 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
297 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
298 * which the message was received. If the session was closed by the time this method starts to execute (the session
299 * state will become IDLE), then rescheduling won't occur.
301 private synchronized void handleHoldTimer() {
302 if (this.state == State.IDLE) {
306 final long ct = System.nanoTime();
307 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
309 if (ct >= nextHold) {
310 LOG.debug("HoldTimer expired. {}", new Date());
311 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
313 this.channel.eventLoop().schedule(new Runnable() {
318 }, nextHold - ct, TimeUnit.NANOSECONDS);
323 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
324 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
325 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
326 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
328 private synchronized void handleKeepaliveTimer() {
329 if (this.state == State.IDLE) {
333 final long ct = System.nanoTime();
334 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
336 if (ct >= nextKeepalive) {
337 this.writeAndFlush(KEEP_ALIVE);
338 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
339 this.sessionStats.updateSentMsgKA();
341 this.channel.eventLoop().schedule(new Runnable() {
344 handleKeepaliveTimer();
346 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
350 public final String toString() {
351 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
354 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
355 toStringHelper.add("channel", this.channel);
356 toStringHelper.add("state", this.getState());
357 return toStringHelper;
361 public Set<BgpTableType> getAdvertisedTableTypes() {
362 return this.tableTypes;
365 protected synchronized void sessionUp() {
366 this.sessionStats.startSessionStopwatch();
367 this.state = State.UP;
368 this.listener.onSessionUp(this);
371 public synchronized State getState() {
376 public final Ipv4Address getBgpId() {
381 public final AsNumber getAsNumber() {
382 return this.asNumber;
385 synchronized boolean isWritable() {
386 return this.channel != null && this.channel.isWritable();
389 void schedule(final Runnable task) {
390 Preconditions.checkState(this.channel != null);
391 this.channel.eventLoop().submit(task);
395 protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
396 this.lastMessageSentAt = lastMessageSentAt;
400 public synchronized BgpSessionState getBgpSesionState() {
401 return this.sessionStats.getBgpSessionState(this.state);
405 public synchronized void resetSessionStats() {
406 this.sessionStats.resetStats();
409 ChannelOutputLimiter getLimiter() {
414 public final void channelInactive(final ChannelHandlerContext ctx) {
415 LOG.debug("Channel {} inactive.", ctx.channel());
419 super.channelInactive(ctx);
420 } catch (final Exception e) {
421 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
426 protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
427 LOG.debug("Message was received: {}", msg);
428 this.handleMessage(msg);
432 public final void handlerAdded(final ChannelHandlerContext ctx) {