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.SimpleChannelInboundHandler;
22 import java.io.IOException;
23 import java.util.Date;
24 import java.util.List;
26 import java.util.concurrent.TimeUnit;
27 import javax.annotation.concurrent.GuardedBy;
28 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
29 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
30 import org.opendaylight.protocol.bgp.parser.BGPError;
31 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
32 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
34 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
35 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
36 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
37 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
38 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParameters;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.AddPathCapability;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapability;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
57 import org.opendaylight.yangtools.yang.binding.Notification;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession, BGPSessionStatistics, AutoCloseable {
64 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
66 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
68 private static final int KA_TO_DEADTIMER_RATIO = 3;
70 private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
72 static final String END_OF_INPUT = "End of input detected. Close the session.";
75 * Internal session state.
79 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
80 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
81 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
85 * The session has been completely established.
89 * The session has been closed. It will not be resurrected.
95 * System.nanoTime value about when was sent the last message.
98 private long lastMessageSentAt;
101 * System.nanoTime value about when was received the last message
103 private long lastMessageReceivedAt;
105 private final BGPSessionListener listener;
107 private final BGPSynchronization sync;
109 private int kaCounter = 0;
111 private final Channel channel;
114 private State state = State.OPEN_CONFIRM;
116 private final Set<BgpTableType> tableTypes;
117 private final List<AddressFamilies> addPathTypes;
118 private final int holdTimerValue;
119 private final int keepAlive;
120 private final AsNumber asNumber;
121 private final Ipv4Address bgpId;
122 private final BGPPeerRegistry peerRegistry;
123 private final ChannelOutputLimiter limiter;
125 private BGPSessionStats sessionStats;
127 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences,
128 final BGPPeerRegistry peerRegistry) {
129 this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
130 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes, this.addPathTypes);
133 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer,
134 final BGPPeerRegistry peerRegistry) {
135 this.listener = Preconditions.checkNotNull(listener);
136 this.channel = Preconditions.checkNotNull(channel);
137 this.limiter = new ChannelOutputLimiter(this);
138 this.channel.pipeline().addLast(this.limiter);
139 this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
140 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
141 this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
142 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
143 this.peerRegistry = peerRegistry;
144 final boolean enableExMess = BgpExtendedMessageUtil.advertizedBgpExtendedMessageCapability(remoteOpen);
146 this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER, BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
149 final Set<TablesKey> tts = Sets.newHashSet();
150 final Set<BgpTableType> tats = Sets.newHashSet();
151 final List<AddressFamilies> addPathCapabilitiesList = Lists.newArrayList();
152 if (remoteOpen.getBgpParameters() != null) {
153 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
154 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
155 final CParameters cParam = optCapa.getCParameters();
156 if ( cParam.getAugmentation(CParameters1.class) == null) {
159 if(cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() != null) {
160 final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability();
161 final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
162 LOG.trace("Added table type to sync {}", tt);
164 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
165 } else if (cParam.getAugmentation(CParameters1.class).getAddPathCapability() != null) {
166 final AddPathCapability addPathCap = cParam.getAugmentation(CParameters1.class).getAddPathCapability();
167 addPathCapabilitiesList.addAll(addPathCap.getAddressFamilies());
173 this.sync = new BGPSynchronization(this.listener, tts);
174 this.tableTypes = tats;
175 this.addPathTypes = addPathCapabilitiesList;
177 if (this.holdTimerValue != 0) {
178 channel.eventLoop().schedule(new Runnable() {
183 }, this.holdTimerValue, TimeUnit.SECONDS);
185 channel.eventLoop().schedule(new Runnable() {
188 handleKeepaliveTimer();
190 }, this.keepAlive, TimeUnit.SECONDS);
192 this.bgpId = remoteOpen.getBgpIdentifier();
193 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
194 this.tableTypes, this.addPathTypes);
198 public synchronized void close() {
199 if (this.state != State.IDLE && this.channel.isActive()) {
200 this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(
201 BGPError.CEASE.getSubcode()).build());
203 this.closeWithoutMessage();
207 * Handles incoming message based on their type.
209 * @param msg incoming message
211 public synchronized void handleMessage(final Notification msg) {
212 // Update last reception time
213 this.lastMessageReceivedAt = System.nanoTime();
214 this.sessionStats.updateReceivedMsgTotal();
216 if (msg instanceof Open) {
217 // Open messages should not be present here
218 this.terminate(BGPError.FSM_ERROR);
219 } else if (msg instanceof Notify) {
220 // Notifications are handled internally
221 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
222 ((Notify) msg).getErrorSubcode());
223 this.closeWithoutMessage();
224 this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
225 ((Notify) msg).getErrorSubcode())));
226 this.sessionStats.updateReceivedMsgErr((Notify) msg);
227 } else if (msg instanceof Keepalive) {
228 // Keepalives are handled internally
229 LOG.trace("Received KeepAlive messsage.");
231 this.sessionStats.updateReceivedMsgKA();
232 if (this.kaCounter >= 2) {
233 this.sync.kaReceived();
235 } else if (msg instanceof RouteRefresh) {
236 this.listener.onMessage(this, msg);
237 this.sessionStats.updateReceivedMsgRR();
238 } else if (msg instanceof Update) {
239 this.listener.onMessage(this, msg);
240 this.sync.updReceived((Update) msg);
241 this.sessionStats.updateReceivedMsgUpd();
243 LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
247 public synchronized void endOfInput() {
248 if (this.state == State.UP) {
249 LOG.info(END_OF_INPUT);
250 this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
255 private void writeEpilogue(final ChannelFuture future, final Notification msg) {
257 new ChannelFutureListener() {
259 public void operationComplete(final ChannelFuture f) {
260 if (!f.isSuccess()) {
261 LOG.warn("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
263 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
267 this.lastMessageSentAt = System.nanoTime();
268 this.sessionStats.updateSentMsgTotal();
269 if (msg instanceof Update) {
270 this.sessionStats.updateSentMsgUpd();
271 } else if (msg instanceof Notify) {
272 this.sessionStats.updateSentMsgErr((Notify) msg);
277 this.channel.flush();
280 synchronized void write(final Notification msg) {
282 writeEpilogue(this.channel.write(msg), msg);
283 } catch (final Exception e) {
284 LOG.warn("Message {} was not sent.", msg, e);
288 synchronized void writeAndFlush(final Notification msg) {
289 writeEpilogue(this.channel.writeAndFlush(msg), msg);
292 private synchronized void closeWithoutMessage() {
293 LOG.info("Closing session: {}", this);
295 this.channel.close();
296 this.state = State.IDLE;
300 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
301 * modified, because he initiated the closing. (To prevent concurrent modification exception).
305 private void terminate(final BGPError error) {
306 this.writeAndFlush(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
307 this.closeWithoutMessage();
309 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
312 private void removePeerSession() {
313 if (this.peerRegistry != null) {
314 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
319 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
320 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
321 * which the message was received. If the session was closed by the time this method starts to execute (the session
322 * state will become IDLE), then rescheduling won't occur.
324 private synchronized void handleHoldTimer() {
325 if (this.state == State.IDLE) {
329 final long ct = System.nanoTime();
330 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
332 if (ct >= nextHold) {
333 LOG.debug("HoldTimer expired. {}", new Date());
334 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
336 this.channel.eventLoop().schedule(new Runnable() {
341 }, nextHold - ct, TimeUnit.NANOSECONDS);
346 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
347 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
348 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
349 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
351 private synchronized void handleKeepaliveTimer() {
352 if (this.state == State.IDLE) {
356 final long ct = System.nanoTime();
357 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
359 if (ct >= nextKeepalive) {
360 this.writeAndFlush(KEEP_ALIVE);
361 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
362 this.sessionStats.updateSentMsgKA();
364 this.channel.eventLoop().schedule(new Runnable() {
367 handleKeepaliveTimer();
369 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
373 public final String toString() {
374 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
377 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
378 toStringHelper.add("channel", this.channel);
379 toStringHelper.add("state", this.getState());
380 return toStringHelper;
384 public Set<BgpTableType> getAdvertisedTableTypes() {
385 return this.tableTypes;
389 public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
390 return this.addPathTypes;
393 protected synchronized void sessionUp() {
394 this.sessionStats.startSessionStopwatch();
395 this.state = State.UP;
396 this.listener.onSessionUp(this);
399 public synchronized State getState() {
404 public final Ipv4Address getBgpId() {
409 public final AsNumber getAsNumber() {
410 return this.asNumber;
413 synchronized boolean isWritable() {
414 return this.channel != null && this.channel.isWritable();
417 void schedule(final Runnable task) {
418 Preconditions.checkState(this.channel != null);
419 this.channel.eventLoop().submit(task);
423 protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
424 this.lastMessageSentAt = lastMessageSentAt;
428 public synchronized BgpSessionState getBgpSesionState() {
429 return this.sessionStats.getBgpSessionState(this.state);
433 public synchronized void resetSessionStats() {
434 this.sessionStats.resetStats();
437 ChannelOutputLimiter getLimiter() {
442 public final void channelInactive(final ChannelHandlerContext ctx) {
443 LOG.debug("Channel {} inactive.", ctx.channel());
447 super.channelInactive(ctx);
448 } catch (final Exception e) {
449 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
454 protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
455 LOG.debug("Message was received: {}", msg);
456 this.handleMessage(msg);
460 public final void handlerAdded(final ChannelHandlerContext ctx) {