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.util.concurrent.Promise;
15 import java.util.concurrent.TimeUnit;
16 import javax.annotation.concurrent.GuardedBy;
17 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
18 import org.opendaylight.protocol.bgp.parser.BGPError;
19 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
20 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
21 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
22 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
23 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
24 import org.opendaylight.protocol.util.Values;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
34 import org.opendaylight.yangtools.yang.binding.Notification;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * Bgp Session negotiator. Common for local-to-remote and remote-to-local connections.
40 * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
42 public abstract class AbstractBGPSessionNegotiator extends AbstractSessionNegotiator<Notification, BGPSessionImpl> {
43 // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
44 protected static final int INITIAL_HOLDTIMER = 4;
47 * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
49 private static final int AS_TRANS = 23456;
54 * Negotiation has not started yet.
58 * We have sent our Open message, and are waiting for the peer's Open message.
62 * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
67 * The negotiation finished.
72 private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
73 private final BGPPeerRegistry registry;
74 private final BGPSessionValidator sessionValidator;
77 private State state = State.IDLE;
80 private BGPSessionImpl session;
82 public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
83 final BGPPeerRegistry registry, final BGPSessionValidator sessionValidator) {
84 super(promise, channel);
85 this.registry = registry;
86 this.sessionValidator = sessionValidator;
90 protected synchronized void startNegotiation() {
91 Preconditions.checkState(this.state == State.IDLE);
93 // Check if peer is configured in registry before retrieving preferences
94 if (!this.registry.isPeerConfigured(getRemoteIp())) {
95 final BGPDocumentedException cause = new BGPDocumentedException(
96 "BGP peer with ip: " + getRemoteIp()
97 + " not configured, check configured peers in : "
98 + this.registry, BGPError.CONNECTION_REJECTED);
99 negotiationFailed(cause);
103 final BGPSessionPreferences preferences = getPreferences();
105 int as = preferences.getMyAs().getValue().intValue();
106 // Set as AS_TRANS if the value is bigger than 2B
107 if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
110 this.sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
111 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
112 if (this.state != State.FINISHED) {
113 this.state = State.OPEN_SENT;
115 this.channel.eventLoop().schedule(new Runnable() {
118 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
119 AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
120 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
121 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
124 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
128 private BGPSessionPreferences getPreferences() {
129 return this.registry.getPeerPreferences(getRemoteIp());
132 private IpAddress getRemoteIp() {
133 return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
137 protected synchronized void handleMessage(final Notification msg) {
138 LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
140 switch (this.state) {
143 this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
146 if (msg instanceof Keepalive) {
147 negotiationSuccessful(this.session);
148 LOG.info("BGP Session with peer {} established successfully.", this.channel);
149 } else if (msg instanceof Notify) {
150 final Notify ntf = (Notify) msg;
151 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
153 this.state = State.FINISHED;
156 if (msg instanceof Open) {
157 final Open openObj = (Open) msg;
166 // Catch-all for unexpected message
167 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
168 this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
169 negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
170 this.state = State.FINISHED;
173 private static Notify buildErrorNotify(final BGPError err) {
174 return buildErrorNotify(err, null);
177 private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
178 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
179 if (data != null && data.length != 0) {
180 builder.setData(data);
182 return builder.build();
185 private void handleOpen(final Open openObj) {
187 this.sessionValidator.validate(openObj, getPreferences());
188 } catch (final BGPDocumentedException e) {
189 negotiationFailed(e);
194 final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()),
195 getDestinationId(openObj, getPreferences()), getAsNumber(openObj, getPreferences()));
196 this.sendMessage(new KeepaliveBuilder().build());
197 this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences(), this.registry);
198 this.state = State.OPEN_CONFIRM;
199 LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
200 } catch (final BGPDocumentedException e) {
201 LOG.warn("Channel {} negotiation failed", this.channel, e);
202 negotiationFailed(e);
207 protected void negotiationFailed(final Throwable e) {
208 LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
209 if (e instanceof BGPDocumentedException) {
210 // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
211 // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
212 this.sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
214 this.registry.removePeerSession(getRemoteIp());
215 super.negotiationFailed(e);
216 this.state = State.FINISHED;
220 * @param openMsg Open message received from remote BGP speaker
221 * @param preferences Local BGP speaker preferences
222 * @return BGP Id of device that accepted the connection
224 protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
227 * @param openMsg Open message received from remote BGP speaker
228 * @param preferences Local BGP speaker preferences
229 * @return BGP Id of device that accepted the connection
231 protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
234 * @param openMsg Open message received from remote BGP speaker
235 * @param preferences Local BGP speaker preferences
236 * @return AS Number of device that initiate connection
238 protected abstract AsNumber getAsNumber(final Open openMsg, final BGPSessionPreferences preferences);
240 public synchronized State getState() {