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 java.util.concurrent.TimeUnit;
20 import javax.annotation.concurrent.GuardedBy;
21 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
22 import org.opendaylight.protocol.bgp.parser.BGPError;
23 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
24 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
25 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
26 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
27 import org.opendaylight.protocol.util.Values;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
36 import org.opendaylight.yangtools.yang.binding.Notification;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
41 * Bgp Session negotiator. Common for local-to-remote and remote-to-local connections.
42 * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
44 public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandlerAdapter implements SessionNegotiator {
45 // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
46 private static final int INITIAL_HOLDTIMER = 4;
49 * @see <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;
56 * Negotiation has not started yet.
60 * We have sent our Open message, and are waiting for the peer's Open message.
64 * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
69 * The negotiation finished.
74 private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
75 private final BGPPeerRegistry registry;
76 private final Promise<BGPSessionImpl> promise;
77 private final Channel channel;
79 private State state = State.IDLE;
82 private BGPSessionImpl session;
84 public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
85 final BGPPeerRegistry registry) {
86 this.promise = Preconditions.checkNotNull(promise);
87 this.channel = Preconditions.checkNotNull(channel);
88 this.registry = registry;
91 private synchronized void startNegotiation() {
92 // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
93 Preconditions.checkState(this.state == State.IDLE || this.state == State.OPEN_CONFIRM);
94 final IpAddress remoteIp = getRemoteIp();
96 // Check if peer is configured in registry before retrieving preferences
97 if (!this.registry.isPeerConfigured(remoteIp)) {
98 final BGPDocumentedException cause = new BGPDocumentedException(
99 String.format("BGP peer with ip: %s not configured, check configured peers in : %s", remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
100 negotiationFailed(cause);
104 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
106 int as = preferences.getMyAs().getValue().intValue();
107 // Set as AS_TRANS if the value is bigger than 2B
108 if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
111 sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
112 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
113 if (this.state != State.FINISHED) {
114 this.state = State.OPEN_SENT;
116 this.channel.eventLoop().schedule(new Runnable() {
119 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
120 AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
121 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
122 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
125 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
129 private IpAddress getRemoteIp() {
130 return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
133 protected synchronized void handleMessage(final Notification msg) {
134 LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
136 switch (this.state) {
138 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
141 // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
142 if (msg instanceof Open) {
143 handleOpen((Open) msg);
146 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
149 if (msg instanceof Keepalive) {
150 negotiationSuccessful(this.session);
151 LOG.info("BGP Session with peer {} established successfully.", this.channel);
152 } else if (msg instanceof Notify) {
153 final Notify ntf = (Notify) msg;
154 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
156 this.state = State.FINISHED;
159 if (msg instanceof Open) {
160 handleOpen((Open) msg);
168 // Catch-all for unexpected message
169 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
170 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
171 negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
172 this.state = State.FINISHED;
175 private static Notify buildErrorNotify(final BGPError err) {
176 return buildErrorNotify(err, null);
179 private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
180 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
181 if (data != null && data.length != 0) {
182 builder.setData(data);
184 return builder.build();
187 private void handleOpen(final Open openObj) {
188 final IpAddress remoteIp = getRemoteIp();
189 final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
191 final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences), getDestinationId(openObj, preferences), openObj);
192 sendMessage(new KeepaliveBuilder().build());
193 this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
194 this.state = State.OPEN_CONFIRM;
195 LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
196 } catch (final BGPDocumentedException e) {
197 LOG.warn("Channel {} negotiation failed", this.channel, e);
198 negotiationFailed(e);
202 private void negotiationFailed(final Throwable e) {
203 LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
204 if (e instanceof BGPDocumentedException) {
205 // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
206 // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
207 sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
209 this.registry.removePeerSession(getRemoteIp());
210 negotiationFailedCloseChannel(e);
211 this.state = State.FINISHED;
215 * @param openMsg Open message received from remote BGP speaker
216 * @param preferences Local BGP speaker preferences
217 * @return BGP Id of device that accepted the connection
219 protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
222 * @param openMsg Open message received from remote BGP speaker
223 * @param preferences Local BGP speaker preferences
224 * @return BGP Id of device that accepted the connection
226 protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
228 public synchronized State getState() {
232 private void negotiationSuccessful(final BGPSessionImpl session) {
233 LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
234 this.channel.pipeline().replace(this, "session", session);
235 this.promise.setSuccess(session);
238 private void negotiationFailedCloseChannel(final Throwable cause) {
239 LOG.debug("Negotiation on channel {} failed", this.channel, cause);
240 this.channel.close();
241 this.promise.setFailure(cause);
244 private void sendMessage(final Notification msg) {
245 this.channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
247 public void operationComplete(final ChannelFuture f) {
248 if (!f.isSuccess()) {
249 LOG.warn("Failed to send message {}", msg, f.cause());
250 negotiationFailedCloseChannel(f.cause());
252 LOG.trace("Message {} sent to socket", msg);
260 public final void channelActive(final ChannelHandlerContext ctx) {
261 LOG.debug("Starting session negotiation on channel {}", this.channel);
265 } catch (final Exception e) {
266 LOG.warn("Unexpected negotiation failure", e);
267 negotiationFailedCloseChannel(e);
273 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
274 LOG.debug("Negotiation read invoked on channel {}", this.channel);
277 handleMessage((Notification) msg);
278 } catch (final Exception e) {
279 LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
280 negotiationFailedCloseChannel(e);
286 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
287 LOG.info("Unexpected error during negotiation", cause);
288 negotiationFailedCloseChannel(cause);