MVPN RFC6514 Extendend communities
[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 static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import io.netty.channel.Channel;
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 io.netty.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21 import javax.annotation.concurrent.GuardedBy;
22 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
23 import org.opendaylight.protocol.bgp.parser.BGPError;
24 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
26 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
27 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
28 import org.opendaylight.protocol.util.Ipv6Util;
29 import org.opendaylight.protocol.util.Values;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Keepalive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.KeepaliveBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Notify;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.NotifyBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.OpenBuilder;
38 import org.opendaylight.yangtools.yang.binding.Notification;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
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.
45  */
46 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;
49
50     /**
51      * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
52      */
53     private static final int AS_TRANS = 23456;
54
55     @VisibleForTesting
56     public enum State {
57         /**
58          * Negotiation has not started yet.
59          */
60         IDLE,
61         /**
62          * We have sent our Open message, and are waiting for the peer's Open message.
63          */
64         OPEN_SENT,
65         /**
66          * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
67          * Open message.
68          */
69         OPEN_CONFIRM,
70         /**
71          * The negotiation finished.
72          */
73         FINISHED,
74     }
75
76     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
77     private final BGPPeerRegistry registry;
78     private final Promise<BGPSessionImpl> promise;
79     private final Channel channel;
80     @GuardedBy("this")
81     private State state = State.IDLE;
82     @GuardedBy("this")
83     private BGPSessionImpl session;
84     @GuardedBy("this")
85     private ScheduledFuture<?> pending;
86
87     AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
88             final BGPPeerRegistry registry) {
89         this.promise = requireNonNull(promise);
90         this.channel = requireNonNull(channel);
91         this.registry = registry;
92     }
93
94     private synchronized void startNegotiation() {
95         if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
96             return;
97         }
98         // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
99         final IpAddress remoteIp = getRemoteIp();
100         try {
101             // Check if peer is configured in registry before retrieving preferences
102             if (!this.registry.isPeerConfigured(remoteIp)) {
103                 final BGPDocumentedException cause = new BGPDocumentedException(
104                     String.format("BGP peer with ip: %s not configured, check configured peers in : %s",
105                             remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
106                 negotiationFailed(cause);
107                 return;
108             }
109
110             final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
111
112             int as = preferences.getMyAs().getValue().intValue();
113             // Set as AS_TRANS if the value is bigger than 2B
114             if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
115                 as = AS_TRANS;
116             }
117             sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
118                 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
119             if (this.state != State.FINISHED) {
120                 this.state = State.OPEN_SENT;
121                 this.pending = this.channel.eventLoop().schedule(() -> {
122                     synchronized (AbstractBGPSessionNegotiator.this) {
123                         AbstractBGPSessionNegotiator.this.pending = null;
124                         if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
125                             AbstractBGPSessionNegotiator.this
126                                 .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
127                             negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
128                             AbstractBGPSessionNegotiator.this.state = State.FINISHED;
129                         }
130                     }
131                 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
132             }
133         } catch (final Exception e) {
134             LOG.warn("Unexpected negotiation failure", e);
135             negotiationFailedCloseChannel(e);
136         }
137     }
138
139     private IpAddress getRemoteIp() {
140         final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
141         if (remoteIp.getIpv6Address() != null) {
142             return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
143         }
144         return new IpAddress(new Ipv4Address(remoteIp.getIpv4Address()));
145     }
146
147     protected synchronized void handleMessage(final Notification msg) {
148         LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
149         switch (this.state) {
150         case FINISHED:
151             sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
152             return;
153         case IDLE:
154             // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
155             if (msg instanceof Open) {
156                 startNegotiation();
157                 handleOpen((Open) msg);
158                 return;
159             }
160             sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
161             break;
162         case OPEN_CONFIRM:
163             if (msg instanceof Keepalive) {
164                 negotiationSuccessful(this.session);
165                 LOG.info("BGP Session with peer {} established successfully.", this.channel);
166             } else if (msg instanceof Notify) {
167                 final Notify ntf = (Notify) msg;
168                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
169             }
170             this.state = State.FINISHED;
171             return;
172         case OPEN_SENT:
173             if (msg instanceof Open) {
174                 handleOpen((Open) msg);
175                 return;
176             }
177             break;
178         default:
179             break;
180         }
181
182         // Catch-all for unexpected message
183         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
184         sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
185         negotiationFailed(new BGPDocumentedException("Unexpected message channel: " + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
186         this.state = State.FINISHED;
187     }
188
189     private static Notify buildErrorNotify(final BGPError err) {
190         return buildErrorNotify(err, null);
191     }
192
193     private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
194         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
195         if (data != null && data.length != 0) {
196             builder.setData(data);
197         }
198         return builder.build();
199     }
200
201     private synchronized void handleOpen(final Open openObj) {
202         final IpAddress remoteIp = getRemoteIp();
203         final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
204         try {
205             final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences), getDestinationId(openObj, preferences), openObj);
206             sendMessage(new KeepaliveBuilder().build());
207             this.state = State.OPEN_CONFIRM;
208             this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
209             this.session.setChannelExtMsgCoder(openObj);
210             LOG.debug("Channel {} moved to OPEN_CONFIRM state with remote proposal {}", this.channel, openObj);
211         } catch (final BGPDocumentedException e) {
212             LOG.warn("Channel {} negotiation failed", this.channel, e);
213             negotiationFailed(e);
214         }
215     }
216
217     private synchronized void negotiationFailed(final Throwable e) {
218         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
219         if (e instanceof BGPDocumentedException) {
220             // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
221             // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
222             sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
223         }
224         if (this.state == State.OPEN_CONFIRM) {
225             this.registry.removePeerSession(getRemoteIp());
226         }
227         negotiationFailedCloseChannel(e);
228         this.state = State.FINISHED;
229     }
230
231     /**
232      * @param openMsg Open message received from remote BGP speaker
233      * @param preferences Local BGP speaker preferences
234      * @return BGP Id of device that accepted the connection
235      */
236     protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
237
238     /**
239      * @param openMsg Open message received from remote BGP speaker
240      * @param preferences Local BGP speaker preferences
241      * @return BGP Id of device that accepted the connection
242      */
243     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
244
245     public synchronized State getState() {
246         return this.state;
247     }
248
249     private void negotiationSuccessful(final BGPSessionImpl session) {
250         LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
251         this.channel.pipeline().replace(this, "session", session);
252         this.promise.setSuccess(session);
253     }
254
255     private void negotiationFailedCloseChannel(final Throwable cause) {
256         LOG.debug("Negotiation on channel {} failed", this.channel, cause);
257         this.channel.close();
258         synchronized (AbstractBGPSessionNegotiator.this) {
259             if (this.pending != null && this.pending.isCancellable()) {
260                 this.pending.cancel(true);
261                 this.pending = null;
262             }
263         }
264     }
265
266     private void sendMessage(final Notification msg) {
267         this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
268             if (!f.isSuccess()) {
269                 LOG.warn("Failed to send message {} to channel {}", msg,  AbstractBGPSessionNegotiator.this.channel, f.cause());
270                 negotiationFailedCloseChannel(f.cause());
271             } else {
272                 LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
273             }
274         });
275     }
276
277     @Override
278     public final void channelActive(final ChannelHandlerContext ctx) {
279         LOG.debug("Starting session negotiation on channel {}", this.channel);
280         startNegotiation();
281     }
282
283     @Override
284     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
285         LOG.debug("Negotiation read invoked on channel {}", this.channel);
286         try {
287             handleMessage((Notification) msg);
288         } catch (final Exception e) {
289             LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
290             negotiationFailedCloseChannel(e);
291         }
292
293     }
294
295     @Override
296     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
297         LOG.info("Unexpected error during negotiation", cause);
298         negotiationFailedCloseChannel(cause);
299     }
300 }