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 com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelFuture;
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.rev130919.Keepalive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.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;
58 * Negotiation has not started yet.
62 * We have sent our Open message, and are waiting for the peer's Open message.
66 * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
71 * The negotiation finished.
76 private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
77 private final BGPPeerRegistry registry;
78 private final Promise<BGPSessionImpl> promise;
79 private final Channel channel;
81 private State state = State.IDLE;
83 private BGPSessionImpl session;
85 private ScheduledFuture<?> pending;
87 AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
88 final BGPPeerRegistry registry) {
89 this.promise = Preconditions.checkNotNull(promise);
90 this.channel = Preconditions.checkNotNull(channel);
91 this.registry = registry;
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", remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
105 negotiationFailed(cause);
109 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
111 int as = preferences.getMyAs().getValue().intValue();
112 // Set as AS_TRANS if the value is bigger than 2B
113 if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
116 sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
117 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
118 if (this.state != State.FINISHED) {
119 this.state = State.OPEN_SENT;
120 this.pending = this.channel.eventLoop().schedule(new Runnable() {
123 synchronized (AbstractBGPSessionNegotiator.this) {
124 AbstractBGPSessionNegotiator.this.pending = null;
125 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
126 AbstractBGPSessionNegotiator.this
127 .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
128 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
129 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
133 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
135 } catch (final Exception e) {
136 LOG.warn("Unexpected negotiation failure", e);
137 negotiationFailedCloseChannel(e);
141 private IpAddress getRemoteIp() {
142 final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
143 if (remoteIp.getIpv6Address() != null) {
144 return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
149 protected synchronized void handleMessage(final Notification msg) {
150 LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
151 switch (this.state) {
153 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
156 // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
157 if (msg instanceof Open) {
159 handleOpen((Open) msg);
162 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
165 if (msg instanceof Keepalive) {
166 negotiationSuccessful(this.session);
167 LOG.info("BGP Session with peer {} established successfully.", this.channel);
168 } else if (msg instanceof Notify) {
169 final Notify ntf = (Notify) msg;
170 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
172 this.state = State.FINISHED;
175 if (msg instanceof Open) {
176 handleOpen((Open) msg);
184 // Catch-all for unexpected message
185 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
186 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
187 negotiationFailed(new BGPDocumentedException("Unexpected message channel: " + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
188 this.state = State.FINISHED;
191 private static Notify buildErrorNotify(final BGPError err) {
192 return buildErrorNotify(err, null);
195 private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
196 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
197 if (data != null && data.length != 0) {
198 builder.setData(data);
200 return builder.build();
203 private synchronized void handleOpen(final Open openObj) {
204 final IpAddress remoteIp = getRemoteIp();
205 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
207 final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences), getDestinationId(openObj, preferences), openObj);
208 sendMessage(new KeepaliveBuilder().build());
209 this.state = State.OPEN_CONFIRM;
210 this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
211 this.session.setChannelExtMsgCoder(openObj);
212 LOG.debug("Channel {} moved to OPEN_CONFIRM state with remote proposal {}", this.channel, openObj);
213 } catch (final BGPDocumentedException e) {
214 LOG.warn("Channel {} negotiation failed", this.channel, e);
215 negotiationFailed(e);
219 private synchronized void negotiationFailed(final Throwable e) {
220 LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
221 if (e instanceof BGPDocumentedException) {
222 // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
223 // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
224 sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
226 if (this.state == State.OPEN_CONFIRM) {
227 this.registry.removePeerSession(getRemoteIp());
229 negotiationFailedCloseChannel(e);
230 this.state = State.FINISHED;
234 * @param openMsg Open message received from remote BGP speaker
235 * @param preferences Local BGP speaker preferences
236 * @return BGP Id of device that accepted the connection
238 protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
241 * @param openMsg Open message received from remote BGP speaker
242 * @param preferences Local BGP speaker preferences
243 * @return BGP Id of device that accepted the connection
245 protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
247 public synchronized State getState() {
251 private void negotiationSuccessful(final BGPSessionImpl session) {
252 LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
253 this.channel.pipeline().replace(this, "session", session);
254 this.promise.setSuccess(session);
257 private void negotiationFailedCloseChannel(final Throwable cause) {
258 LOG.debug("Negotiation on channel {} failed", this.channel, cause);
259 this.channel.close();
260 synchronized (AbstractBGPSessionNegotiator.this) {
261 if (this.pending != null && this.pending.isCancellable()) {
262 this.pending.cancel(true);
268 private void sendMessage(final Notification msg) {
269 this.channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
271 public void operationComplete(final ChannelFuture f) {
272 if (!f.isSuccess()) {
273 LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel, f.cause());
274 negotiationFailedCloseChannel(f.cause());
276 LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
283 public final void channelActive(final ChannelHandlerContext ctx) {
284 LOG.debug("Starting session negotiation on channel {}", this.channel);
289 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
290 LOG.debug("Negotiation read invoked on channel {}", this.channel);
292 handleMessage((Notification) msg);
293 } catch (final Exception e) {
294 LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
295 negotiationFailedCloseChannel(e);
301 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
302 LOG.info("Unexpected error during negotiation", cause);
303 negotiationFailedCloseChannel(cause);