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