BUG: Fix Sonar Issues
[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.channel.ChannelFuture;
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 java.util.concurrent.TimeUnit;
20 import javax.annotation.concurrent.GuardedBy;
21 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
22 import org.opendaylight.protocol.bgp.parser.BGPError;
23 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
24 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
26 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
27 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
28 import org.opendaylight.protocol.util.Values;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.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 public 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 BGPSessionValidator sessionValidator;
79     private final Promise<BGPSessionImpl> promise;
80     private final Channel channel;
81     @GuardedBy("this")
82     private State state = State.IDLE;
83
84     @GuardedBy("this")
85     private BGPSessionImpl session;
86
87     public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
88             final BGPPeerRegistry registry, final BGPSessionValidator sessionValidator) {
89         this.promise = Preconditions.checkNotNull(promise);
90         this.channel = Preconditions.checkNotNull(channel);
91         this.registry = registry;
92         this.sessionValidator = sessionValidator;
93     }
94
95     private synchronized void startNegotiation() {
96         Preconditions.checkState(this.state == State.IDLE);
97
98         // Check if peer is configured in registry before retrieving preferences
99         if (!this.registry.isPeerConfigured(getRemoteIp())) {
100             final BGPDocumentedException cause = new BGPDocumentedException(
101                     "BGP peer with ip: " + getRemoteIp()
102                     + " not configured, check configured peers in : "
103                     + this.registry, BGPError.CONNECTION_REJECTED);
104             negotiationFailed(cause);
105             return;
106         }
107
108         final BGPSessionPreferences preferences = getPreferences();
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         this.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
120             this.channel.eventLoop().schedule(new Runnable() {
121                 @Override
122                 public void run() {
123                     if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
124                         AbstractBGPSessionNegotiator.this.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     }
132
133     private BGPSessionPreferences getPreferences() {
134         return this.registry.getPeerPreferences(getRemoteIp());
135     }
136
137     private IpAddress getRemoteIp() {
138         return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
139     }
140
141     protected synchronized void handleMessage(final Notification msg) {
142         LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
143
144         switch (this.state) {
145         case FINISHED:
146         case IDLE:
147             this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
148             return;
149         case OPEN_CONFIRM:
150             if (msg instanceof Keepalive) {
151                 negotiationSuccessful(this.session);
152                 LOG.info("BGP Session with peer {} established successfully.", this.channel);
153             } else if (msg instanceof Notify) {
154                 final Notify ntf = (Notify) msg;
155                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
156             }
157             this.state = State.FINISHED;
158             return;
159         case OPEN_SENT:
160             if (msg instanceof Open) {
161                 final Open openObj = (Open) msg;
162                 handleOpen(openObj);
163                 return;
164             }
165             break;
166         default:
167             break;
168         }
169
170         // Catch-all for unexpected message
171         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
172         this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
173         negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
174         this.state = State.FINISHED;
175     }
176
177     private static Notify buildErrorNotify(final BGPError err) {
178         return buildErrorNotify(err, null);
179     }
180
181     private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
182         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
183         if (data != null && data.length != 0) {
184             builder.setData(data);
185         }
186         return builder.build();
187     }
188
189     private void handleOpen(final Open openObj) {
190         try {
191             this.sessionValidator.validate(openObj, getPreferences());
192         } catch (final BGPDocumentedException e) {
193             negotiationFailed(e);
194             return;
195         }
196
197         try {
198             final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()),
199                     getDestinationId(openObj, getPreferences()), getAsNumber(openObj, getPreferences()));
200             this.sendMessage(new KeepaliveBuilder().build());
201             this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences(), this.registry);
202             this.state = State.OPEN_CONFIRM;
203             LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
204         } catch (final BGPDocumentedException e) {
205             LOG.warn("Channel {} negotiation failed", this.channel, e);
206             negotiationFailed(e);
207         }
208     }
209
210     private void negotiationFailed(final Throwable e) {
211         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
212         if (e instanceof BGPDocumentedException) {
213             // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
214             // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
215             this.sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
216         }
217         this.registry.removePeerSession(getRemoteIp());
218         negotiationFailedCloseChannel(e);
219         this.state = State.FINISHED;
220     }
221
222     /**
223      * @param openMsg Open message received from remote BGP speaker
224      * @param preferences Local BGP speaker preferences
225      * @return BGP Id of device that accepted the connection
226      */
227     protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
228
229     /**
230      * @param openMsg Open message received from remote BGP speaker
231      * @param preferences Local BGP speaker preferences
232      * @return BGP Id of device that accepted the connection
233      */
234     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
235
236     /**
237      * @param openMsg Open message received from remote BGP speaker
238      * @param preferences Local BGP speaker preferences
239      * @return AS Number of device that initiate connection
240      */
241     protected abstract AsNumber getAsNumber(final Open openMsg, final BGPSessionPreferences preferences);
242
243     public synchronized State getState() {
244         return this.state;
245     }
246
247     private void negotiationSuccessful(BGPSessionImpl session) {
248         LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
249         channel.pipeline().replace(this, "session", session);
250         promise.setSuccess(session);
251     }
252
253     private void negotiationFailedCloseChannel(Throwable cause) {
254         LOG.debug("Negotiation on channel {} failed", this.channel, cause);
255         channel.close();
256         promise.setFailure(cause);
257     }
258
259     private void sendMessage(final Notification msg) {
260         channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
261             @Override
262             public void operationComplete(ChannelFuture f) {
263                 if (!f.isSuccess()) {
264                     LOG.info("Failed to send message {}", msg, f.cause());
265                     negotiationFailedCloseChannel(f.cause());
266                 } else {
267                     LOG.trace("Message {} sent to socket", msg);
268                 }
269
270             }
271         });
272     }
273
274     @Override
275     public final void channelActive(ChannelHandlerContext ctx) {
276         LOG.debug("Starting session negotiation on channel {}", this.channel);
277
278         try {
279             this.startNegotiation();
280         } catch (final Exception e) {
281             LOG.warn("Unexpected negotiation failure", e);
282             negotiationFailedCloseChannel(e);
283         }
284
285     }
286
287     @Override
288     public final void channelRead(ChannelHandlerContext ctx, Object msg) {
289         LOG.debug("Negotiation read invoked on channel {}", this.channel);
290
291         try {
292             handleMessage((Notification) msg);
293         } catch (Exception e) {
294             LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
295             negotiationFailedCloseChannel(e);
296         }
297
298     }
299
300     @Override
301     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
302         LOG.info("Unexpected error during negotiation", cause);
303         negotiationFailedCloseChannel(cause);
304     }
305 }