1389359b2cd89b0dd3794293a6d329a084262516
[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     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
55     private final BGPPeerRegistry registry;
56     private final Promise<BGPSessionImpl> promise;
57     private final Channel channel;
58     @GuardedBy("this")
59     private State state = State.IDLE;
60     @GuardedBy("this")
61     private BGPSessionImpl session;
62     @GuardedBy("this")
63     private ScheduledFuture<?> pending;
64
65     @VisibleForTesting
66     public enum State {
67         /**
68          * Negotiation has not started yet.
69          */
70         IDLE,
71         /**
72          * We have sent our Open message, and are waiting for the peer's Open message.
73          */
74         OPEN_SENT,
75         /**
76          * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
77          * Open message.
78          */
79         OPEN_CONFIRM,
80         /**
81          * The negotiation finished.
82          */
83         FINISHED,
84     }
85
86     AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
87             final BGPPeerRegistry registry) {
88         this.promise = requireNonNull(promise);
89         this.channel = requireNonNull(channel);
90         this.registry = registry;
91     }
92
93     private synchronized void startNegotiation() {
94         if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
95             return;
96         }
97         // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
98         final IpAddress remoteIp = getRemoteIp();
99         try {
100             // Check if peer is configured in registry before retrieving preferences
101             if (!this.registry.isPeerConfigured(remoteIp)) {
102                 final BGPDocumentedException cause = new BGPDocumentedException(
103                         String.format("BGP peer with ip: %s not configured, check configured peers in : %s",
104                                 remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
105                 negotiationFailed(cause);
106                 return;
107             }
108
109             final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
110
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) {
114                 as = AS_TRANS;
115             }
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;
120                 this.pending = this.channel.eventLoop().schedule(() -> {
121                     synchronized (AbstractBGPSessionNegotiator.this) {
122                         AbstractBGPSessionNegotiator.this.pending = null;
123                         if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
124                             AbstractBGPSessionNegotiator.this
125                                     .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
126                             negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
127                             AbstractBGPSessionNegotiator.this.state = State.FINISHED;
128                         }
129                     }
130                 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
131             }
132         } catch (final Exception e) {
133             LOG.warn("Unexpected negotiation failure", e);
134             negotiationFailedCloseChannel(e);
135         }
136     }
137
138     private IpAddress getRemoteIp() {
139         final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
140         if (remoteIp.getIpv6Address() != null) {
141             return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
142         }
143         return remoteIp;
144     }
145
146     synchronized void handleMessage(final Notification msg) {
147         LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
148         switch (this.state) {
149             case FINISHED:
150                 sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
151                 return;
152             case IDLE:
153                 // to avoid race condition when Open message was sent by the peer before startNegotiation could be
154                 // 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",
169                             BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
170                 }
171                 this.state = State.FINISHED;
172                 return;
173             case OPEN_SENT:
174                 if (msg instanceof Open) {
175                     handleOpen((Open) msg);
176                     return;
177                 }
178                 break;
179             default:
180                 break;
181         }
182
183         // Catch-all for unexpected message
184         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
185         sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
186         negotiationFailed(new BGPDocumentedException("Unexpected message channel: "
187                 + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
188         this.state = State.FINISHED;
189     }
190
191     private static Notify buildErrorNotify(final BGPError err) {
192         return buildErrorNotify(err, null);
193     }
194
195     private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
196         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
197         if (data != null && data.length != 0) {
198             builder.setData(data);
199         }
200         return builder.build();
201     }
202
203     private synchronized void handleOpen(final Open openObj) {
204         final IpAddress remoteIp = getRemoteIp();
205         final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
206         try {
207             final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences),
208                     getDestinationId(openObj, preferences), openObj);
209             sendMessage(new KeepaliveBuilder().build());
210             this.state = State.OPEN_CONFIRM;
211             this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
212             this.session.setChannelExtMsgCoder(openObj);
213             LOG.debug("Channel {} moved to OPEN_CONFIRM state with remote proposal {}", this.channel, openObj);
214         } catch (final BGPDocumentedException e) {
215             LOG.warn("Channel {} negotiation failed", this.channel, e);
216             negotiationFailed(e);
217         }
218     }
219
220     private synchronized void negotiationFailed(final Throwable e) {
221         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
222         if (e instanceof BGPDocumentedException) {
223             // although sendMessage() can also result in calling this method, it won't create a cycle.
224             // In case sendMessage() fails to deliver the message, this method gets called with different
225             // exception (definitely not with BGPDocumentedException).
226             sendMessage(buildErrorNotify(((BGPDocumentedException) e).getError(),
227                     ((BGPDocumentedException) e).getData()));
228         }
229         if (this.state == State.OPEN_CONFIRM) {
230             this.registry.removePeerSession(getRemoteIp());
231         }
232         negotiationFailedCloseChannel(e);
233         this.state = State.FINISHED;
234     }
235
236     /**
237      * @param openMsg Open message received from remote BGP speaker
238      * @param preferences Local BGP speaker preferences
239      * @return BGP Id of device that accepted the connection
240      */
241     protected abstract Ipv4Address getDestinationId(Open openMsg, BGPSessionPreferences preferences);
242
243     /**
244      * @param openMsg Open message received from remote BGP speaker
245      * @param preferences Local BGP speaker preferences
246      * @return BGP Id of device that accepted the connection
247      */
248     protected abstract Ipv4Address getSourceId(Open openMsg, BGPSessionPreferences preferences);
249
250     public synchronized State getState() {
251         return this.state;
252     }
253
254     private void negotiationSuccessful(final BGPSessionImpl session) {
255         LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
256         this.channel.pipeline().replace(this, "session", session);
257         this.promise.setSuccess(session);
258     }
259
260     private void negotiationFailedCloseChannel(final Throwable cause) {
261         LOG.debug("Negotiation on channel {} failed", this.channel, cause);
262         this.channel.close();
263         synchronized (AbstractBGPSessionNegotiator.this) {
264             if (this.pending != null && this.pending.isCancellable()) {
265                 this.pending.cancel(true);
266                 this.pending = null;
267             }
268         }
269     }
270
271     private void sendMessage(final Notification msg) {
272         this.channel.writeAndFlush(msg).addListener((ChannelFutureListener) f -> {
273             if (!f.isSuccess()) {
274                 LOG.warn("Failed to send message {} to channel {}", msg, AbstractBGPSessionNegotiator.this.channel,
275                         f.cause());
276                 negotiationFailedCloseChannel(f.cause());
277             } else {
278                 LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
279             }
280         });
281     }
282
283     @Override
284     public final void channelActive(final ChannelHandlerContext ctx) {
285         LOG.debug("Starting session negotiation on channel {}", this.channel);
286         startNegotiation();
287     }
288
289     @Override
290     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
291         LOG.debug("Negotiation read invoked on channel {}", this.channel);
292         try {
293             handleMessage((Notification) msg);
294         } catch (final Exception e) {
295             LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
296             negotiationFailedCloseChannel(e);
297         }
298
299     }
300
301     @Override
302     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
303         LOG.info("Unexpected error during negotiation", cause);
304         negotiationFailedCloseChannel(cause);
305     }
306 }