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 static java.util.Objects.requireNonNull;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.ImmutableSet;
17 import io.netty.buffer.ByteBufUtil;
18 import io.netty.channel.Channel;
19 import io.netty.channel.ChannelFuture;
20 import io.netty.channel.ChannelFutureListener;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.SimpleChannelInboundHandler;
23 import java.io.IOException;
24 import java.nio.channels.NonWritableChannelException;
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Optional;
31 import java.util.concurrent.TimeUnit;
32 import java.util.function.Function;
33 import javax.annotation.concurrent.GuardedBy;
34 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
35 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
36 import org.opendaylight.protocol.bgp.parser.BGPError;
37 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
38 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
39 import org.opendaylight.protocol.bgp.parser.GracefulRestartUtil;
40 import org.opendaylight.protocol.bgp.parser.spi.MultiPathSupport;
41 import org.opendaylight.protocol.bgp.parser.spi.PeerConstraint;
42 import org.opendaylight.protocol.bgp.parser.spi.pojo.MultiPathSupportImpl;
43 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPMessagesListener;
44 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
45 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
46 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
47 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider;
48 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
49 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
50 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
51 import org.opendaylight.protocol.bgp.rib.spi.State;
52 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
53 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
54 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Keepalive;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.KeepaliveBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Notify;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.NotifyBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.BgpParameters;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.OptionalCapabilities;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.optional.capabilities.CParameters;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.CParameters1;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.MpCapabilities;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.RouteRefresh;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.AddPathCapability;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.GracefulRestartCapability;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.LlGracefulRestartCapability;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.MultiprotocolCapability;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.add.path.capability.AddressFamilies;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
76 import org.opendaylight.yangtools.yang.binding.ChildOf;
77 import org.opendaylight.yangtools.yang.binding.Notification;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
82 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession,
83 BGPSessionStateProvider, AutoCloseable {
85 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
87 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
89 private static final int KA_TO_DEADTIMER_RATIO = 3;
91 private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
93 static final String END_OF_INPUT = "End of input detected. Close the session.";
96 * System.nanoTime value about when was sent the last message.
99 private long lastMessageSentAt;
102 * System.nanoTime value about when was received the last message.
104 private long lastMessageReceivedAt;
106 private final BGPSessionListener listener;
108 private final BGPSynchronization sync;
110 private int kaCounter = 0;
112 private final Channel channel;
115 private State state = State.OPEN_CONFIRM;
117 private final Set<BgpTableType> tableTypes;
118 private final List<AddressFamilies> addPathTypes;
119 private final int holdTimerValue;
120 private final int keepAlive;
121 private final AsNumber asNumber;
122 private final Ipv4Address bgpId;
123 private final BGPPeerRegistry peerRegistry;
124 private final ChannelOutputLimiter limiter;
125 private final BGPSessionStateImpl sessionState;
126 private final GracefulRestartCapability gracefulCapability;
127 private final LlGracefulRestartCapability llGracefulCapability;
128 private boolean terminationReasonNotified;
130 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
131 final BGPSessionPreferences localPreferences, final BGPPeerRegistry peerRegistry) {
132 this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
135 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
136 final int localHoldTimer, final BGPPeerRegistry peerRegistry) {
137 this.listener = requireNonNull(listener);
138 this.channel = requireNonNull(channel);
139 this.limiter = new ChannelOutputLimiter(this);
140 this.channel.pipeline().addLast(this.limiter);
141 this.holdTimerValue = remoteOpen.getHoldTimer() < localHoldTimer ? remoteOpen.getHoldTimer() : localHoldTimer;
142 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
143 this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
144 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
145 this.peerRegistry = peerRegistry;
146 this.sessionState = new BGPSessionStateImpl();
148 final Set<TablesKey> tts = new HashSet<>();
149 final Set<BgpTableType> tats = new HashSet<>();
150 final List<AddressFamilies> addPathCapabilitiesList = new ArrayList<>();
151 final List<BgpParameters> bgpParameters = remoteOpen.getBgpParameters();
152 if (bgpParameters != null) {
153 for (final BgpParameters param : bgpParameters) {
154 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
155 final CParameters cParam = optCapa.getCParameters();
156 final CParameters1 cParam1 = cParam.augmentation(CParameters1.class);
157 if (cParam1 != null) {
158 final MultiprotocolCapability multi = cParam1.getMultiprotocolCapability();
160 final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
161 LOG.trace("Added table type to sync {}", tt);
163 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
165 final AddPathCapability addPathCap = cParam1.getAddPathCapability();
166 if (addPathCap != null) {
167 addPathCapabilitiesList.addAll(addPathCap.getAddressFamilies());
173 this.gracefulCapability = findSingleCapability(bgpParameters, "Graceful Restart",
174 CParameters1::getGracefulRestartCapability).orElse(GracefulRestartUtil.EMPTY_GR_CAPABILITY);
175 this.llGracefulCapability = findSingleCapability(bgpParameters, "Long-lived Graceful Restart",
176 CParameters1::getLlGracefulRestartCapability).orElse(GracefulRestartUtil.EMPTY_LLGR_CAPABILITY);
178 this.gracefulCapability = GracefulRestartUtil.EMPTY_GR_CAPABILITY;
179 this.llGracefulCapability = GracefulRestartUtil.EMPTY_LLGR_CAPABILITY;
182 this.sync = new BGPSynchronization(this.listener, tts);
183 this.tableTypes = tats;
184 this.addPathTypes = addPathCapabilitiesList;
186 if (!this.addPathTypes.isEmpty()) {
187 addDecoderConstraint(MultiPathSupport.class,
188 MultiPathSupportImpl.createParserMultiPathSupport(this.addPathTypes));
191 if (this.holdTimerValue != 0) {
192 channel.eventLoop().schedule(this::handleHoldTimer, this.holdTimerValue, TimeUnit.SECONDS);
193 channel.eventLoop().schedule(this::handleKeepaliveTimer, this.keepAlive, TimeUnit.SECONDS);
195 this.bgpId = remoteOpen.getBgpIdentifier();
196 this.sessionState.advertizeCapabilities(this.holdTimerValue, channel.remoteAddress(), channel.localAddress(),
197 this.tableTypes, bgpParameters);
200 private static <T extends ChildOf<MpCapabilities>> Optional<T> findSingleCapability(
201 final List<BgpParameters> bgpParameters, final String name, final Function<CParameters1, T> extractor) {
202 final List<T> found = new ArrayList<>(1);
203 for (BgpParameters bgpParams : bgpParameters) {
204 for (OptionalCapabilities optCapability : bgpParams.nonnullOptionalCapabilities()) {
205 final CParameters cparam = optCapability.getCParameters();
206 if (cparam != null) {
207 final CParameters1 augment = cparam.augmentation(CParameters1.class);
208 if (augment != null) {
209 final T capa = extractor.apply(augment);
218 final Set<T> set = ImmutableSet.copyOf(found);
219 switch (set.size()) {
221 LOG.debug("{} capability not advertised.", name);
222 return Optional.empty();
224 return Optional.of(found.get(0));
226 LOG.warn("Multiple instances of {} capability advertised: {}, ignoring.", name, set);
227 return Optional.empty();
232 * Set the extend message coder for current channel.
233 * The reason for separating this part from constructor is, in #channel.pipeline().replace(..), the
234 * invokeChannelRead() will be invoked after the original message coder handler got removed. And there
235 * is chance that before the session instance is fully initiated (constructor returns), a KeepAlive
236 * message arrived already in the channel buffer. Thus #AbstractBGPSessionNegotiator.handleMessage(..)
237 * gets invoked again and a deadlock is caused. A BGP final state machine error will happen as BGP
238 * negotiator is still in OPEN_SENT state as the session constructor hasn't returned yet.
240 public synchronized void setChannelExtMsgCoder(final Open remoteOpen) {
241 final boolean enableExMess = BgpExtendedMessageUtil.advertizedBgpExtendedMessageCapability(remoteOpen);
243 this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER,
244 BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
249 public synchronized void close() {
250 if (this.state != State.IDLE) {
251 if (!this.terminationReasonNotified) {
252 this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode())
253 .setErrorSubcode(BGPError.CEASE.getSubcode()).build());
255 this.closeWithoutMessage();
260 * Handles incoming message based on their type.
262 * @param msg incoming message
264 synchronized void handleMessage(final Notification msg) {
265 if (this.state == State.IDLE) {
269 // Update last reception time
270 this.lastMessageReceivedAt = System.nanoTime();
272 if (msg instanceof Open) {
273 // Open messages should not be present here
274 this.terminate(new BGPDocumentedException(null, BGPError.FSM_ERROR));
275 } else if (msg instanceof Notify) {
276 final Notify notify = (Notify) msg;
277 // Notifications are handled internally
278 LOG.info("Session closed because Notification message received: {} / {}, data={}",
279 notify.getErrorCode(),
280 notify.getErrorSubcode(),
281 notify.getData() != null ? ByteBufUtil.hexDump(notify.getData()) : null);
282 notifyTerminationReasonAndCloseWithoutMessage(notify.getErrorCode(), notify.getErrorSubcode());
283 } else if (msg instanceof Keepalive) {
284 // Keepalives are handled internally
285 LOG.trace("Received KeepAlive message.");
287 if (this.kaCounter >= 2) {
288 this.sync.kaReceived();
290 } else if (msg instanceof RouteRefresh) {
291 this.listener.onMessage(this, msg);
292 } else if (msg instanceof Update) {
293 this.listener.onMessage(this, msg);
294 this.sync.updReceived((Update) msg);
296 LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
299 this.sessionState.messageReceived(msg);
300 } catch (final BGPDocumentedException e) {
305 private synchronized void notifyTerminationReasonAndCloseWithoutMessage(
306 final Short errorCode,
307 final Short errorSubcode) {
308 this.terminationReasonNotified = true;
309 this.closeWithoutMessage();
310 this.listener.onSessionTerminated(this, new BGPTerminationReason(
311 BGPError.forValue(errorCode, errorSubcode)));
314 synchronized void endOfInput() {
315 if (this.state == State.UP) {
316 LOG.info(END_OF_INPUT);
317 this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
322 private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
323 future.addListener((ChannelFutureListener) f -> {
324 if (!f.isSuccess()) {
325 LOG.warn("Failed to send message {} to socket {}", msg, BGPSessionImpl.this.channel, f.cause());
327 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
330 this.lastMessageSentAt = System.nanoTime();
331 this.sessionState.messageSent(msg);
336 this.channel.flush();
339 synchronized void write(final Notification msg) {
341 writeEpilogue(this.channel.write(msg), msg);
342 } catch (final Exception e) {
343 LOG.warn("Message {} was not sent.", msg, e);
347 synchronized ChannelFuture writeAndFlush(final Notification msg) {
349 return writeEpilogue(this.channel.writeAndFlush(msg), msg);
351 return this.channel.newFailedFuture(new NonWritableChannelException());
355 public synchronized void closeWithoutMessage() {
356 if (this.state == State.IDLE) {
359 LOG.info("Closing session: {}", this);
360 this.channel.close().addListener((ChannelFutureListener) future
361 -> Preconditions.checkArgument(future.isSuccess(), "Channel failed to close: %s", future.cause()));
362 this.state = State.IDLE;
364 this.sessionState.setSessionState(this.state);
368 * Closes BGP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
369 * modified, because he initiated the closing. (To prevent concurrent modification exception).
371 * @param e BGPDocumentedException
374 synchronized void terminate(final BGPDocumentedException e) {
375 final BGPError error = e.getError();
376 final byte[] data = e.getData();
377 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(error.getCode())
378 .setErrorSubcode(error.getSubcode());
379 if (data != null && data.length != 0) {
380 builder.setData(data);
382 this.writeAndFlush(builder.build());
383 notifyTerminationReasonAndCloseWithoutMessage(error.getCode(), error.getSubcode());
386 private void removePeerSession() {
387 if (this.peerRegistry != null) {
388 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
393 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
394 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
395 * which the message was received. If the session was closed by the time this method starts to execute (the session
396 * state will become IDLE), then rescheduling won't occur.
398 private synchronized void handleHoldTimer() {
399 if (this.state == State.IDLE) {
403 final long ct = System.nanoTime();
404 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
406 if (ct >= nextHold) {
407 LOG.debug("HoldTimer expired. {}", new Date());
408 this.terminate(new BGPDocumentedException(BGPError.HOLD_TIMER_EXPIRED));
410 this.channel.eventLoop().schedule(this::handleHoldTimer, nextHold - ct, TimeUnit.NANOSECONDS);
415 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
416 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
417 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
418 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
420 private synchronized void handleKeepaliveTimer() {
421 if (this.state == State.IDLE) {
425 final long ct = System.nanoTime();
426 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
428 if (ct >= nextKeepalive) {
429 this.writeAndFlush(KEEP_ALIVE);
430 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
432 this.channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
436 public final String toString() {
437 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
440 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
441 toStringHelper.add("channel", this.channel);
442 toStringHelper.add("state", this.getState());
443 return toStringHelper;
447 public Set<BgpTableType> getAdvertisedTableTypes() {
448 return this.tableTypes;
452 public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
453 return this.addPathTypes;
457 public GracefulRestartCapability getAdvertisedGracefulRestartCapability() {
458 return this.gracefulCapability;
462 public LlGracefulRestartCapability getAdvertisedLlGracefulRestartCapability() {
463 return this.llGracefulCapability;
467 synchronized void sessionUp() {
468 this.state = State.UP;
470 this.sessionState.setSessionState(this.state);
471 this.listener.onSessionUp(this);
472 } catch (final Exception e) {
478 public synchronized State getState() {
483 public final Ipv4Address getBgpId() {
488 public final AsNumber getAsNumber() {
489 return this.asNumber;
492 private synchronized boolean isWritable() {
493 return this.channel != null && this.channel.isWritable();
496 public ChannelOutputLimiter getLimiter() {
501 public final void channelInactive(final ChannelHandlerContext ctx) {
502 LOG.debug("Channel {} inactive.", ctx.channel());
506 super.channelInactive(ctx);
507 } catch (final Exception e) {
508 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
513 protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
514 LOG.debug("Message was received: {}", msg);
515 this.handleMessage(msg);
519 public final void handlerAdded(final ChannelHandlerContext ctx) {
524 public synchronized void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
525 handleException(cause);
529 * Handle exception occurred in the BGP session. The session in error state should be closed
530 * properly so that it can be restored later.
533 void handleException(final Throwable cause) {
534 LOG.warn("BGP session encountered error", cause);
535 final Throwable docCause = cause.getCause();
536 if (docCause instanceof BGPDocumentedException) {
537 this.terminate((BGPDocumentedException) docCause);
539 this.terminate(new BGPDocumentedException(BGPError.CEASE));
544 public BGPSessionState getBGPSessionState() {
545 return this.sessionState;
549 public BGPTimersState getBGPTimersState() {
550 return this.sessionState;
554 public BGPTransportState getBGPTransportState() {
555 return this.sessionState;
559 public void registerMessagesCounter(final BGPMessagesListener bgpMessagesListener) {
560 this.sessionState.registerMessagesCounter(bgpMessagesListener);
564 public <T extends PeerConstraint> void addDecoderConstraint(final Class<T> constraintClass, final T constraint) {
565 this.channel.pipeline().get(BGPByteToMessageDecoder.class).addDecoderConstraint(constraintClass, constraint);