Bug-2229: RFC6286 - AS-wide Unique BGP Identifier
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AbstractBGPSessionNegotiator.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.protocol.bgp.rib.impl;
10
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;
37
38 /**
39  * Bgp Session negotiator. Common for local -> remote and remote -> local connections.
40  * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
41  */
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;
45
46     /**
47      * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
48      */
49     private static final int AS_TRANS = 23456;
50
51     @VisibleForTesting
52     public enum State {
53         /**
54          * Negotiation has not started yet.
55          */
56         IDLE,
57         /**
58          * We have sent our Open message, and are waiting for the peer's Open message.
59          */
60         OPEN_SENT,
61         /**
62          * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
63          * Open message.
64          */
65         OPEN_CONFIRM,
66         /**
67          * The negotiation finished.
68          */
69         FINISHED,
70     }
71
72     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
73     private final BGPPeerRegistry registry;
74     private final BGPSessionValidator sessionValidator;
75
76     @GuardedBy("this")
77     private State state = State.IDLE;
78
79     @GuardedBy("this")
80     private BGPSessionImpl session;
81
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;
87     }
88
89     @Override
90     protected synchronized void startNegotiation() {
91         Preconditions.checkState(this.state == State.IDLE);
92
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);
100             return;
101         }
102
103         final BGPSessionPreferences preferences = getPreferences();
104
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) {
108             as = AS_TRANS;
109         }
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;
114
115             this.channel.eventLoop().schedule(new Runnable() {
116                 @Override
117                 public void run() {
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;
122                     }
123                 }
124             }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
125         }
126     }
127
128     private BGPSessionPreferences getPreferences() {
129         return this.registry.getPeerPreferences(getRemoteIp());
130     }
131
132     private IpAddress getRemoteIp() {
133         return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
134     }
135
136     @Override
137     protected synchronized void handleMessage(final Notification msg) {
138         LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
139
140         switch (this.state) {
141         case FINISHED:
142         case IDLE:
143             this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
144             return;
145         case OPEN_CONFIRM:
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())));
152             }
153             this.state = State.FINISHED;
154             return;
155         case OPEN_SENT:
156             if (msg instanceof Open) {
157                 final Open openObj = (Open) msg;
158                 handleOpen(openObj);
159                 return;
160             }
161             break;
162         default:
163             break;
164         }
165
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;
171     }
172
173     private static Notify buildErrorNotify(final BGPError err) {
174         return buildErrorNotify(err, null);
175     }
176
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);
181         }
182         return builder.build();
183     }
184
185     private void handleOpen(final Open openObj) {
186         try {
187             this.sessionValidator.validate(openObj, getPreferences());
188         } catch (final BGPDocumentedException e) {
189             negotiationFailed(e);
190             return;
191         }
192
193         try {
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);
203         }
204     }
205
206     @Override
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()));
213         }
214         this.registry.removePeerSession(getRemoteIp());
215         super.negotiationFailed(e);
216         this.state = State.FINISHED;
217     }
218
219     /**
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
223      */
224     protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
225
226     /**
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
230      */
231     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
232
233     /**
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
237      */
238     protected abstract AsNumber getAsNumber(final Open openMsg, final BGPSessionPreferences preferences);
239
240     public synchronized State getState() {
241         return this.state;
242     }
243 }