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.IpAddress;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
33 import org.opendaylight.yangtools.yang.binding.Notification;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * Bgp Session negotiator. Common for local -> remote and remote -> local connections.
39 * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
41 public abstract class AbstractBGPSessionNegotiator extends AbstractSessionNegotiator<Notification, BGPSessionImpl> {
42 // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
43 protected static final int INITIAL_HOLDTIMER = 4;
46 * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
48 private static final int AS_TRANS = 23456;
53 * Negotiation has not started yet.
57 * We have sent our Open message, and are waiting for the peer's Open message.
61 * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
66 * The negotiation finished.
71 private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
72 private final BGPPeerRegistry registry;
73 private final BGPSessionValidator sessionValidator;
76 private State state = State.IDLE;
79 private BGPSessionImpl session;
81 public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
82 final BGPPeerRegistry registry, final BGPSessionValidator sessionValidator) {
83 super(promise, channel);
84 this.registry = registry;
85 this.sessionValidator = sessionValidator;
89 protected synchronized void startNegotiation() {
90 Preconditions.checkState(this.state == State.IDLE);
92 // Check if peer is configured in registry before retrieving preferences
93 if (!this.registry.isPeerConfigured(getRemoteIp())) {
94 final BGPDocumentedException cause = new BGPDocumentedException(
95 "BGP peer with ip: " + getRemoteIp()
96 + " not configured, check configured peers in : "
97 + this.registry, BGPError.CONNECTION_REJECTED);
98 negotiationFailed(cause);
102 final BGPSessionPreferences preferences = getPreferences();
104 int as = preferences.getMyAs().getValue().intValue();
105 // Set as AS_TRANS if the value is bigger than 2B
106 if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
109 this.sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
110 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
111 if (this.state != State.FINISHED) {
112 this.state = State.OPEN_SENT;
114 this.channel.eventLoop().schedule(new Runnable() {
117 if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
118 AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
119 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
120 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
123 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
127 private BGPSessionPreferences getPreferences() {
128 return this.registry.getPeerPreferences(getRemoteIp());
131 private IpAddress getRemoteIp() {
132 return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
136 protected synchronized void handleMessage(final Notification msg) {
137 LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
139 switch (this.state) {
142 this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
145 if (msg instanceof Keepalive) {
146 negotiationSuccessful(this.session);
147 LOG.info("BGP Session with peer {} established successfully.", this.channel);
148 } else if (msg instanceof Notify) {
149 final Notify ntf = (Notify) msg;
150 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
152 this.state = State.FINISHED;
155 if (msg instanceof Open) {
156 final Open openObj = (Open) msg;
165 // Catch-all for unexpected message
166 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
167 this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
168 negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
169 this.state = State.FINISHED;
172 private static Notify buildErrorNotify(final BGPError err) {
173 return buildErrorNotify(err, null);
176 private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
177 final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
178 if (data != null && data.length != 0) {
179 builder.setData(data);
181 return builder.build();
184 private void handleOpen(final Open openObj) {
186 this.sessionValidator.validate(openObj, getPreferences());
187 } catch (final BGPDocumentedException e) {
188 negotiationFailed(e);
193 final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()), getDestinationId(openObj, getPreferences()));
194 this.sendMessage(new KeepaliveBuilder().build());
195 this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences(), this.registry);
196 this.state = State.OPEN_CONFIRM;
197 LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
198 } catch (final BGPDocumentedException e) {
199 LOG.warn("Channel {} negotiation failed", this.channel, e);
200 negotiationFailed(e);
205 protected void negotiationFailed(final Throwable e) {
206 LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
207 if (e instanceof BGPDocumentedException) {
208 // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
209 // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
210 this.sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
212 this.registry.removePeerSession(getRemoteIp());
213 super.negotiationFailed(e);
214 this.state = State.FINISHED;
218 * @return BGP Id of device that accepted the connection
220 protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
223 * @return BGP Id of device that initiated the connection
225 protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
227 public synchronized State getState() {