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.impl.spi.BGPSessionValidator;
26 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
27 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
28 import org.opendaylight.protocol.util.Values;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.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 public 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 BGPSessionValidator sessionValidator;
79 private final Promise<BGPSessionImpl> promise;
80 private final Channel channel;
82 private State state = State.IDLE;
85 private BGPSessionImpl session;
87 public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
88 final BGPPeerRegistry registry, final BGPSessionValidator sessionValidator) {
89 this.promise = Preconditions.checkNotNull(promise);
90 this.channel = Preconditions.checkNotNull(channel);
91 this.registry = registry;
92 this.sessionValidator = sessionValidator;
95 private synchronized void startNegotiation() {
96 // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
97 Preconditions.checkState(this.state == State.IDLE || this.state == State.OPEN_CONFIRM);
99 // Check if peer is configured in registry before retrieving preferences
100 if (!this.registry.isPeerConfigured(getRemoteIp())) {
101 final BGPDocumentedException cause = new BGPDocumentedException(
102 "BGP peer with ip: " + getRemoteIp()
103 + " not configured, check configured peers in : "
104 + this.registry, BGPError.CONNECTION_REJECTED);
105 negotiationFailed(cause);
109 final BGPSessionPreferences preferences = getPreferences();
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;
121 this.channel.eventLoop().schedule(new Runnable() {
124 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
125 AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
126 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
127 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
130 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
134 private BGPSessionPreferences getPreferences() {
135 return this.registry.getPeerPreferences(getRemoteIp());
138 private IpAddress getRemoteIp() {
139 return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
142 protected synchronized void handleMessage(final Notification msg) {
143 LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
145 switch (this.state) {
147 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
150 // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
151 if (msg instanceof Open) {
152 handleOpen((Open) msg);
155 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
158 if (msg instanceof Keepalive) {
159 negotiationSuccessful(this.session);
160 LOG.info("BGP Session with peer {} established successfully.", this.channel);
161 } else if (msg instanceof Notify) {
162 final Notify ntf = (Notify) msg;
163 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
165 this.state = State.FINISHED;
168 if (msg instanceof Open) {
169 handleOpen((Open) msg);
177 // Catch-all for unexpected message
178 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
179 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
180 negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
181 this.state = State.FINISHED;
184 private static Notify buildErrorNotify(final BGPError err) {
185 return buildErrorNotify(err, null);
188 private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
189 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
190 if (data != null && data.length != 0) {
191 builder.setData(data);
193 return builder.build();
196 private void handleOpen(final Open openObj) {
198 this.sessionValidator.validate(openObj, getPreferences());
199 } catch (final BGPDocumentedException e) {
200 negotiationFailed(e);
205 final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()), getDestinationId(openObj, getPreferences()), getAsNumber(openObj, getPreferences()), openObj);
206 sendMessage(new KeepaliveBuilder().build());
207 this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences(), this.registry);
208 this.state = State.OPEN_CONFIRM;
209 LOG.debug("Channel {} moved to OpenConfirm 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 void negotiationFailed(final Throwable e) {
217 LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
218 if (e instanceof BGPDocumentedException) {
219 // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
220 // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
221 sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
223 this.registry.removePeerSession(getRemoteIp());
224 negotiationFailedCloseChannel(e);
225 this.state = State.FINISHED;
229 * @param openMsg Open message received from remote BGP speaker
230 * @param preferences Local BGP speaker preferences
231 * @return BGP Id of device that accepted the connection
233 protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
236 * @param openMsg Open message received from remote BGP speaker
237 * @param preferences Local BGP speaker preferences
238 * @return BGP Id of device that accepted the connection
240 protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
243 * @param openMsg Open message received from remote BGP speaker
244 * @param preferences Local BGP speaker preferences
245 * @return AS Number of device that initiate connection
247 protected abstract AsNumber getAsNumber(final Open openMsg, final BGPSessionPreferences preferences);
249 public synchronized State getState() {
253 private void negotiationSuccessful(final BGPSessionImpl session) {
254 LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
255 this.channel.pipeline().replace(this, "session", session);
256 this.promise.setSuccess(session);
259 private void negotiationFailedCloseChannel(final Throwable cause) {
260 LOG.debug("Negotiation on channel {} failed", this.channel, cause);
261 this.channel.close();
262 this.promise.setFailure(cause);
265 private void sendMessage(final Notification msg) {
266 this.channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
268 public void operationComplete(final ChannelFuture f) {
269 if (!f.isSuccess()) {
270 LOG.info("Failed to send message {}", msg, f.cause());
271 negotiationFailedCloseChannel(f.cause());
273 LOG.trace("Message {} sent to socket", msg);
281 public final void channelActive(final ChannelHandlerContext ctx) {
282 LOG.debug("Starting session negotiation on channel {}", this.channel);
286 } catch (final Exception e) {
287 LOG.warn("Unexpected negotiation failure", e);
288 negotiationFailedCloseChannel(e);
294 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
295 LOG.debug("Negotiation read invoked on channel {}", this.channel);
298 handleMessage((Notification) msg);
299 } catch (final Exception e) {
300 LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
301 negotiationFailedCloseChannel(e);
307 public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
308 LOG.info("Unexpected error during negotiation", cause);
309 negotiationFailedCloseChannel(cause);