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;
65 * Internal session state.
69 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
70 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
71 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
75 * The session has been completely established.
79 * The session has been closed. It will not be resurrected.
85 * System.nanoTime value about when was sent the last message.
88 private long lastMessageSentAt;
91 * System.nanoTime value about when was received the last message
93 private long lastMessageReceivedAt;
95 private final BGPSessionListener listener;
97 private final BGPSynchronization sync;
99 private int kaCounter = 0;
101 private final Channel channel;
104 private State state = State.OPEN_CONFIRM;
106 private final Set<BgpTableType> tableTypes;
107 private final int holdTimerValue;
108 private final int keepAlive;
109 private final AsNumber asNumber;
110 private final Ipv4Address bgpId;
111 private final BGPPeerRegistry peerRegistry;
112 private final ChannelOutputLimiter limiter;
114 private BGPSessionStats sessionStats;
116 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences,
117 final BGPPeerRegistry peerRegistry) {
118 this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
119 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes);
122 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer,
123 final BGPPeerRegistry peerRegistry) {
124 this.listener = Preconditions.checkNotNull(listener);
125 this.channel = Preconditions.checkNotNull(channel);
126 this.limiter = new ChannelOutputLimiter(this);
127 this.channel.pipeline().addLast(this.limiter);
128 this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
129 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
130 this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
131 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
132 this.peerRegistry = peerRegistry;
134 final Set<TablesKey> tts = Sets.newHashSet();
135 final Set<BgpTableType> tats = Sets.newHashSet();
136 if (remoteOpen.getBgpParameters() != null) {
137 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
138 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
139 final CParameters cParam = optCapa.getCParameters();
140 if ( cParam.getAugmentation(CParameters1.class) == null ||
141 cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() == null ) {
144 final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability();
145 final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
146 LOG.trace("Added table type to sync {}", tt);
148 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
153 this.sync = new BGPSynchronization(this.listener, tts);
154 this.tableTypes = tats;
156 if (this.holdTimerValue != 0) {
157 channel.eventLoop().schedule(new Runnable() {
162 }, this.holdTimerValue, TimeUnit.SECONDS);
164 channel.eventLoop().schedule(new Runnable() {
167 handleKeepaliveTimer();
169 }, this.keepAlive, TimeUnit.SECONDS);
171 this.bgpId = remoteOpen.getBgpIdentifier();
172 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
177 public synchronized void close() {
178 LOG.info("Closing session: {}", this);
180 if (this.state != State.IDLE) {
181 this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(
182 BGPError.CEASE.getSubcode()).build());
184 this.channel.close();
185 this.state = State.IDLE;
190 * Handles incoming message based on their type.
192 * @param msg incoming message
194 public synchronized void handleMessage(final Notification msg) {
195 // Update last reception time
196 this.lastMessageReceivedAt = System.nanoTime();
197 this.sessionStats.updateReceivedMsgTotal();
199 if (msg instanceof Open) {
200 // Open messages should not be present here
201 this.terminate(BGPError.FSM_ERROR);
202 } else if (msg instanceof Notify) {
203 // Notifications are handled internally
204 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
205 ((Notify) msg).getErrorSubcode());
206 this.closeWithoutMessage();
207 this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
208 ((Notify) msg).getErrorSubcode())));
209 this.sessionStats.updateReceivedMsgErr((Notify) msg);
210 } else if (msg instanceof Keepalive) {
211 // Keepalives are handled internally
212 LOG.trace("Received KeepAlive messsage.");
214 this.sessionStats.updateReceivedMsgKA();
215 if (this.kaCounter >= 2) {
216 this.sync.kaReceived();
219 // All others are passed up
220 this.listener.onMessage(this, msg);
221 this.sync.updReceived((Update) msg);
222 this.sessionStats.updateReceivedMsgUpd();
226 public synchronized void endOfInput() {
227 if (this.state == State.UP) {
228 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
233 private void writeEpilogue(final ChannelFuture future, final Notification msg) {
235 new ChannelFutureListener() {
237 public void operationComplete(final ChannelFuture f) {
238 if (!f.isSuccess()) {
239 LOG.warn("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
241 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
245 this.lastMessageSentAt = System.nanoTime();
246 this.sessionStats.updateSentMsgTotal();
247 if (msg instanceof Update) {
248 this.sessionStats.updateSentMsgUpd();
249 } else if (msg instanceof Notify) {
250 this.sessionStats.updateSentMsgErr((Notify) msg);
255 this.channel.flush();
258 synchronized void write(final Notification msg) {
260 writeEpilogue(this.channel.write(msg), msg);
261 } catch (final Exception e) {
262 LOG.warn("Message {} was not sent.", msg, e);
266 synchronized void writeAndFlush(final Notification msg) {
267 writeEpilogue(this.channel.writeAndFlush(msg), msg);
270 private synchronized void closeWithoutMessage() {
271 LOG.debug("Closing session: {}", this);
273 this.channel.close();
274 this.state = State.IDLE;
278 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
279 * modified, because he initiated the closing. (To prevent concurrent modification exception).
283 private void terminate(final BGPError error) {
284 this.writeAndFlush(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
285 this.closeWithoutMessage();
287 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
290 private void removePeerSession() {
291 if (this.peerRegistry != null) {
292 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
297 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
298 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
299 * which the message was received. If the session was closed by the time this method starts to execute (the session
300 * state will become IDLE), then rescheduling won't occur.
302 private synchronized void handleHoldTimer() {
303 if (this.state == State.IDLE) {
307 final long ct = System.nanoTime();
308 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
310 if (ct >= nextHold) {
311 LOG.debug("HoldTimer expired. {}", new Date());
312 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
314 this.channel.eventLoop().schedule(new Runnable() {
319 }, nextHold - ct, TimeUnit.NANOSECONDS);
324 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
325 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
326 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
327 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
329 private synchronized void handleKeepaliveTimer() {
330 if (this.state == State.IDLE) {
334 final long ct = System.nanoTime();
335 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
337 if (ct >= nextKeepalive) {
338 this.writeAndFlush(KEEP_ALIVE);
339 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
340 this.sessionStats.updateSentMsgKA();
342 this.channel.eventLoop().schedule(new Runnable() {
345 handleKeepaliveTimer();
347 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
351 public final String toString() {
352 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
355 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
356 toStringHelper.add("channel", this.channel);
357 toStringHelper.add("state", this.getState());
358 return toStringHelper;
362 public Set<BgpTableType> getAdvertisedTableTypes() {
363 return this.tableTypes;
366 protected synchronized void sessionUp() {
367 this.sessionStats.startSessionStopwatch();
368 this.state = State.UP;
369 this.listener.onSessionUp(this);
372 public synchronized State getState() {
377 public final Ipv4Address getBgpId() {
382 public final AsNumber getAsNumber() {
383 return this.asNumber;
386 synchronized boolean isWritable() {
387 return this.channel != null && this.channel.isWritable();
390 void schedule(final Runnable task) {
391 Preconditions.checkState(this.channel != null);
392 this.channel.eventLoop().submit(task);
396 protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
397 this.lastMessageSentAt = lastMessageSentAt;
401 public synchronized BgpSessionState getBgpSesionState() {
402 return this.sessionStats.getBgpSessionState(this.state);
406 public synchronized void resetSessionStats() {
407 this.sessionStats.resetStats();
410 ChannelOutputLimiter getLimiter() {
415 public final void channelInactive(final ChannelHandlerContext ctx) {
416 LOG.debug("Channel {} inactive.", ctx.channel());
420 super.channelInactive(ctx);
421 } catch (final Exception e) {
422 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
427 protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
428 LOG.debug("Message was received: {}", msg);
429 this.handleMessage(msg);
433 public final void handlerAdded(final ChannelHandlerContext ctx) {