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;
51 * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
53 private static final int AS_TRANS = 23456;
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;
67 * Negotiation has not started yet.
71 * We have sent our Open message, and are waiting for the peer's Open message.
75 * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
80 * The negotiation finished.
85 AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
86 final BGPPeerRegistry registry) {
87 this.promise = requireNonNull(promise);
88 this.channel = requireNonNull(channel);
89 this.registry = registry;
92 private synchronized void startNegotiation() {
93 if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
96 // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
97 final IpAddress remoteIp = getRemoteIp();
99 // Check if peer is configured in registry before retrieving preferences
100 if (!this.registry.isPeerConfigured(remoteIp)) {
101 final BGPDocumentedException cause = new BGPDocumentedException(
102 String.format("BGP peer with ip: %s not configured, check configured peers in : %s",
103 remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
104 negotiationFailed(cause);
108 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
110 int as = preferences.getMyAs().getValue().intValue();
111 // Set as AS_TRANS if the value is bigger than 2B
112 if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
115 sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
116 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
117 if (this.state != State.FINISHED) {
118 this.state = State.OPEN_SENT;
119 this.pending = this.channel.eventLoop().schedule(() -> {
120 synchronized (AbstractBGPSessionNegotiator.this) {
121 AbstractBGPSessionNegotiator.this.pending = null;
122 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
123 AbstractBGPSessionNegotiator.this
124 .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
125 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
126 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
129 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
131 } catch (final Exception e) {
132 LOG.warn("Unexpected negotiation failure", e);
133 negotiationFailedCloseChannel(e);
137 private IpAddress getRemoteIp() {
138 final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
139 if (remoteIp.getIpv6Address() != null) {
140 return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
145 synchronized void handleMessage(final Notification msg) {
146 LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
147 switch (this.state) {
149 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
152 // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
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 * @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 * @param openMsg Open message received from remote BGP speaker
243 * @param preferences Local BGP speaker preferences
244 * @return BGP Id of device that accepted the connection
246 protected abstract Ipv4Address getSourceId(Open openMsg, BGPSessionPreferences preferences);
248 public synchronized State getState() {
252 private void negotiationSuccessful(final BGPSessionImpl session) {
253 LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
254 this.channel.pipeline().replace(this, "session", session);
255 this.promise.setSuccess(session);
258 private void negotiationFailedCloseChannel(final Throwable cause) {
259 LOG.debug("Negotiation on channel {} failed", this.channel, cause);
260 this.channel.close();
261 synchronized (AbstractBGPSessionNegotiator.this) {
262 if (this.pending != null && this.pending.isCancellable()) {
263 this.pending.cancel(true);
269 private void sendMessage(final Notification msg) {
270 this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
271 if (!f.isSuccess()) {
272 LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel,
274 negotiationFailedCloseChannel(f.cause());
276 LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
282 public final void channelActive(final ChannelHandlerContext ctx) {
283 LOG.debug("Starting session negotiation on channel {}", this.channel);
288 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
289 LOG.debug("Negotiation read invoked on channel {}", this.channel);
291 handleMessage((Notification) msg);
292 } catch (final Exception e) {
293 LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
294 negotiationFailedCloseChannel(e);
300 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
301 LOG.info("Unexpected error during negotiation", cause);
302 negotiationFailedCloseChannel(cause);