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
9 package org.opendaylight.protocol.bgp.rib.impl;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelFutureListener;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import io.netty.util.concurrent.Promise;
19 import io.netty.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21 import javax.annotation.concurrent.GuardedBy;
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.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * Bgp Session negotiator. Common for local-to-remote and remote-to-local connections.
44 * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
46 abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandlerAdapter implements SessionNegotiator {
47 // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
48 private static final int INITIAL_HOLDTIMER = 4;
50 // <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
51 private static final int AS_TRANS = 23456;
52 private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
53 private final BGPPeerRegistry registry;
54 private final Promise<BGPSessionImpl> promise;
55 private final Channel channel;
57 private State state = State.IDLE;
59 private BGPSessionImpl session;
61 private ScheduledFuture<?> pending;
66 * Negotiation has not started yet.
70 * We have sent our Open message, and are waiting for the peer's Open message.
74 * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
79 * The negotiation finished.
84 AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
85 final BGPPeerRegistry registry) {
86 this.promise = requireNonNull(promise);
87 this.channel = requireNonNull(channel);
88 this.registry = registry;
91 private synchronized void startNegotiation() {
92 if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
95 // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
96 final IpAddress remoteIp = getRemoteIp();
98 // Check if peer is configured in registry before retrieving preferences
99 if (!this.registry.isPeerConfigured(remoteIp)) {
100 final BGPDocumentedException cause = new BGPDocumentedException(
101 String.format("BGP peer with ip: %s not configured, check configured peers in : %s",
102 remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
103 negotiationFailed(cause);
107 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
109 int as = preferences.getMyAs().getValue().intValue();
110 // Set as AS_TRANS if the value is bigger than 2B
111 if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
114 sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
115 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
116 if (this.state != State.FINISHED) {
117 this.state = State.OPEN_SENT;
118 this.pending = this.channel.eventLoop().schedule(() -> {
119 synchronized (AbstractBGPSessionNegotiator.this) {
120 AbstractBGPSessionNegotiator.this.pending = null;
121 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
122 AbstractBGPSessionNegotiator.this
123 .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
124 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
125 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
128 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
130 } catch (final Exception e) {
131 LOG.warn("Unexpected negotiation failure", e);
132 negotiationFailedCloseChannel(e);
136 private IpAddress getRemoteIp() {
137 final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
138 if (remoteIp.getIpv6Address() != null) {
139 return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
144 synchronized void handleMessage(final Notification msg) {
145 LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
146 switch (this.state) {
148 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
151 // to avoid race condition when Open message was sent by the peer before startNegotiation could be
153 if (msg instanceof Open) {
155 handleOpen((Open) msg);
158 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
161 if (msg instanceof Keepalive) {
162 negotiationSuccessful(this.session);
163 LOG.info("BGP Session with peer {} established successfully.", this.channel);
164 } else if (msg instanceof Notify) {
165 final Notify ntf = (Notify) msg;
166 negotiationFailed(new BGPDocumentedException("Peer refusal",
167 BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
169 this.state = State.FINISHED;
172 if (msg instanceof Open) {
173 handleOpen((Open) msg);
181 // Catch-all for unexpected message
182 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
183 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
184 negotiationFailed(new BGPDocumentedException("Unexpected message channel: "
185 + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
186 this.state = State.FINISHED;
189 private static Notify buildErrorNotify(final BGPError err) {
190 return buildErrorNotify(err, null);
193 private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
194 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
195 if (data != null && data.length != 0) {
196 builder.setData(data);
198 return builder.build();
201 private synchronized void handleOpen(final Open openObj) {
202 final IpAddress remoteIp = getRemoteIp();
203 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
205 final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences),
206 getDestinationId(openObj, preferences), openObj);
207 sendMessage(new KeepaliveBuilder().build());
208 this.state = State.OPEN_CONFIRM;
209 this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
210 this.session.setChannelExtMsgCoder(openObj);
211 LOG.debug("Channel {} moved to OPEN_CONFIRM state with remote proposal {}", this.channel, openObj);
212 } catch (final BGPDocumentedException e) {
213 LOG.warn("Channel {} negotiation failed", this.channel, e);
214 negotiationFailed(e);
218 private synchronized void negotiationFailed(final Throwable e) {
219 LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
220 if (e instanceof BGPDocumentedException) {
221 // although sendMessage() can also result in calling this method, it won't create a cycle.
222 // In case sendMessage() fails to deliver the message, this method gets called with different
223 // exception (definitely not with BGPDocumentedException).
224 sendMessage(buildErrorNotify(((BGPDocumentedException) e).getError(),
225 ((BGPDocumentedException) e).getData()));
227 if (this.state == State.OPEN_CONFIRM) {
228 this.registry.removePeerSession(getRemoteIp());
230 negotiationFailedCloseChannel(e);
231 this.state = State.FINISHED;
235 * Get destination identifier.
237 * @param openMsg Open message received from remote BGP speaker
238 * @param preferences Local BGP speaker preferences
239 * @return BGP Id of device that accepted the connection
241 protected abstract Ipv4Address getDestinationId(Open openMsg, BGPSessionPreferences preferences);
244 * Get source identifier.
246 * @param openMsg Open message received from remote BGP speaker
247 * @param preferences Local BGP speaker preferences
248 * @return BGP Id of device that accepted the connection
250 protected abstract Ipv4Address getSourceId(Open openMsg, BGPSessionPreferences preferences);
252 public synchronized State getState() {
256 private void negotiationSuccessful(final BGPSessionImpl session) {
257 LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
258 this.channel.pipeline().replace(this, "session", session);
259 this.promise.setSuccess(session);
262 private void negotiationFailedCloseChannel(final Throwable cause) {
263 LOG.debug("Negotiation on channel {} failed", this.channel, cause);
264 this.channel.close();
265 synchronized (AbstractBGPSessionNegotiator.this) {
266 if (this.pending != null && this.pending.isCancellable()) {
267 this.pending.cancel(true);
273 private void sendMessage(final Notification msg) {
274 this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
275 if (!f.isSuccess()) {
276 LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel,
278 negotiationFailedCloseChannel(f.cause());
280 LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
286 public final void channelActive(final ChannelHandlerContext ctx) {
287 LOG.debug("Starting session negotiation on channel {}", this.channel);
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);