2 * Copyright (c) 2014 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 io.netty.channel.Channel;
14 import io.netty.channel.ChannelFutureListener;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.ChannelInboundHandlerAdapter;
17 import io.netty.util.concurrent.Promise;
18 import io.netty.util.concurrent.ScheduledFuture;
19 import java.util.concurrent.TimeUnit;
20 import org.checkerframework.checker.lock.qual.GuardedBy;
21 import org.checkerframework.checker.lock.qual.Holding;
22 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
23 import org.opendaylight.protocol.bgp.parser.BGPError;
24 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
26 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
27 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
28 import org.opendaylight.protocol.util.Ipv6Util;
29 import org.opendaylight.protocol.util.Values;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Keepalive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.KeepaliveBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Notify;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.NotifyBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.OpenBuilder;
38 import org.opendaylight.yangtools.yang.binding.Notification;
39 import org.opendaylight.yangtools.yang.common.Uint16;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * Bgp Session negotiator. Common for local-to-remote and remote-to-local connections.
45 * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
47 abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandlerAdapter implements SessionNegotiator {
48 // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
49 private static final int INITIAL_HOLDTIMER = 4;
51 // <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
53 static final Uint16 AS_TRANS = Uint16.valueOf(23456).intern();
54 private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
55 private final BGPPeerRegistry registry;
56 private final Promise<BGPSessionImpl> promise;
57 private final Channel channel;
59 private State state = State.IDLE;
61 private BGPSessionImpl session;
63 private ScheduledFuture<?> pending;
68 * Negotiation has not started yet.
72 * We have sent our Open message, and are waiting for the peer's Open message.
76 * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
81 * The negotiation finished.
86 AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
87 final BGPPeerRegistry registry) {
88 this.promise = requireNonNull(promise);
89 this.channel = requireNonNull(channel);
90 this.registry = registry;
93 @SuppressWarnings("checkstyle:illegalCatch")
94 private synchronized void startNegotiation() {
95 if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
98 // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
99 final IpAddress remoteIp = getRemoteIp();
101 // Check if peer is configured in registry before retrieving preferences
102 if (!this.registry.isPeerConfigured(remoteIp)) {
103 final BGPDocumentedException cause = new BGPDocumentedException(
104 String.format("BGP peer with ip: %s not configured, check configured peers in : %s",
105 remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
106 negotiationFailed(cause);
110 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
111 final Uint16 as = openASNumber(preferences.getMyAs().getValue().longValue());
112 sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
113 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
114 if (this.state != State.FINISHED) {
115 this.state = State.OPEN_SENT;
116 this.pending = this.channel.eventLoop().schedule(() -> {
117 synchronized (AbstractBGPSessionNegotiator.this) {
118 AbstractBGPSessionNegotiator.this.pending = null;
119 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
120 AbstractBGPSessionNegotiator.this
121 .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
122 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
123 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
126 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
128 } catch (final Exception e) {
129 LOG.warn("Unexpected negotiation failure", e);
130 negotiationFailedCloseChannel(e);
134 private IpAddress getRemoteIp() {
135 final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
136 if (remoteIp.getIpv6Address() != null) {
137 return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
142 synchronized void handleMessage(final Notification msg) {
143 LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
144 switch (this.state) {
146 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
149 // to avoid race condition when Open message was sent by the peer before startNegotiation could be
151 if (msg instanceof Open) {
153 handleOpen((Open) msg);
156 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
159 if (msg instanceof Keepalive) {
160 negotiationSuccessful();
161 LOG.info("BGP Session with peer {} established successfully.", this.channel);
162 } else if (msg instanceof Notify) {
163 final Notify ntf = (Notify) msg;
164 negotiationFailed(new BGPDocumentedException("Peer refusal",
165 BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
167 this.state = State.FINISHED;
170 if (msg instanceof Open) {
171 handleOpen((Open) msg);
179 // Catch-all for unexpected message
180 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
181 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
182 negotiationFailed(new BGPDocumentedException("Unexpected message channel: "
183 + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
184 this.state = State.FINISHED;
187 private static Notify buildErrorNotify(final BGPError err) {
188 return buildErrorNotify(err, null);
191 private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
192 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
193 if (data != null && data.length != 0) {
194 builder.setData(data);
196 return builder.build();
199 private synchronized void handleOpen(final Open openObj) {
200 final IpAddress remoteIp = getRemoteIp();
201 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
203 final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences),
204 getDestinationId(openObj, preferences), openObj);
205 sendMessage(new KeepaliveBuilder().build());
206 this.state = State.OPEN_CONFIRM;
207 this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
208 this.session.setChannelExtMsgCoder(openObj);
209 LOG.debug("Channel {} moved to OPEN_CONFIRM state with remote proposal {}", this.channel, openObj);
210 } catch (final BGPDocumentedException e) {
211 LOG.warn("Channel {} negotiation failed", this.channel, e);
212 negotiationFailed(e);
216 private synchronized void negotiationFailed(final Throwable cause) {
217 LOG.warn("Channel {} negotiation failed: {}", this.channel, cause.getMessage());
218 if (cause instanceof BGPDocumentedException) {
219 // although sendMessage() can also result in calling this method, it won't create a cycle.
220 // In case sendMessage() fails to deliver the message, this method gets called with different
221 // exception (definitely not with BGPDocumentedException).
222 sendMessage(buildErrorNotify(((BGPDocumentedException) cause).getError(),
223 ((BGPDocumentedException) cause).getData()));
225 if (this.state == State.OPEN_CONFIRM) {
226 this.registry.removePeerSession(getRemoteIp());
228 negotiationFailedCloseChannel(cause);
229 this.state = State.FINISHED;
233 * Get destination identifier.
235 * @param openMsg Open message received from remote BGP speaker
236 * @param preferences Local BGP speaker preferences
237 * @return BGP Id of device that accepted the connection
239 protected abstract Ipv4Address getDestinationId(Open openMsg, BGPSessionPreferences preferences);
242 * Get source identifier.
244 * @param openMsg Open message received from remote BGP speaker
245 * @param preferences Local BGP speaker preferences
246 * @return BGP Id of device that accepted the connection
248 protected abstract Ipv4Address getSourceId(Open openMsg, BGPSessionPreferences preferences);
250 public synchronized State getState() {
255 private void negotiationSuccessful() {
256 LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
257 this.channel.pipeline().replace(this, "session", session);
258 this.promise.setSuccess(session);
261 private void negotiationFailedCloseChannel(final Throwable cause) {
262 LOG.debug("Negotiation on channel {} failed", this.channel, cause);
263 this.channel.close();
264 synchronized (AbstractBGPSessionNegotiator.this) {
265 if (this.pending != null && this.pending.isCancellable()) {
266 this.pending.cancel(true);
272 private void sendMessage(final Notification msg) {
273 this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
274 if (!f.isSuccess()) {
275 LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel,
277 negotiationFailedCloseChannel(f.cause());
279 LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
285 public final void channelActive(final ChannelHandlerContext ctx) {
286 LOG.debug("Starting session negotiation on channel {}", this.channel);
291 @SuppressWarnings("checkstyle:illegalCatch")
292 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
293 LOG.debug("Negotiation read invoked on channel {}", this.channel);
295 handleMessage((Notification) msg);
296 } catch (final Exception e) {
297 LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
298 negotiationFailedCloseChannel(e);
304 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
305 LOG.info("Unexpected error during negotiation", cause);
306 negotiationFailedCloseChannel(cause);
310 static Uint16 openASNumber(final long configuredASNumber) {
311 // Return AS_TRANS if the value is bigger than 2B.
312 return configuredASNumber > Values.UNSIGNED_SHORT_MAX_VALUE ? AS_TRANS : Uint16.valueOf(configuredASNumber);