BUG-3888 : refactoring, removed unused session validators
[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.AsNumberUtil;
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.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 Promise<BGPSessionImpl> promise;
79     private final Channel channel;
80     @GuardedBy("this")
81     private State state = State.IDLE;
82
83     @GuardedBy("this")
84     private BGPSessionImpl session;
85
86     public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
87             final BGPPeerRegistry registry) {
88         this.promise = Preconditions.checkNotNull(promise);
89         this.channel = Preconditions.checkNotNull(channel);
90         this.registry = registry;
91     }
92
93     private synchronized void startNegotiation() {
94         // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
95         Preconditions.checkState(this.state == State.IDLE || this.state == State.OPEN_CONFIRM);
96
97         // Check if peer is configured in registry before retrieving preferences
98         if (!this.registry.isPeerConfigured(getRemoteIp())) {
99             final BGPDocumentedException cause = new BGPDocumentedException(
100                     "BGP peer with ip: " + getRemoteIp()
101                     + " not configured, check configured peers in : "
102                     + this.registry, BGPError.CONNECTION_REJECTED);
103             negotiationFailed(cause);
104             return;
105         }
106
107         final BGPSessionPreferences preferences = getPreferences();
108
109         int as = preferences.getMyAs().getValue().intValue();
110         // Set as AS_TRANS if the value is bigger than 2B
111         if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
112             as = AS_TRANS;
113         }
114         sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
115                 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
116         if (this.state != State.FINISHED) {
117             this.state = State.OPEN_SENT;
118
119             this.channel.eventLoop().schedule(new Runnable() {
120                 @Override
121                 public void run() {
122                     if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
123                         AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
124                         negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
125                         AbstractBGPSessionNegotiator.this.state = State.FINISHED;
126                     }
127                 }
128             }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
129         }
130     }
131
132     private BGPSessionPreferences getPreferences() {
133         return this.registry.getPeerPreferences(getRemoteIp());
134     }
135
136     private IpAddress getRemoteIp() {
137         return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
138     }
139
140     protected synchronized void handleMessage(final Notification msg) {
141         LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
142
143         switch (this.state) {
144         case FINISHED:
145             sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
146             return;
147         case IDLE:
148             // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
149             if (msg instanceof Open) {
150                 handleOpen((Open) msg);
151                 return;
152             }
153             sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
154             return;
155         case OPEN_CONFIRM:
156             if (msg instanceof Keepalive) {
157                 negotiationSuccessful(this.session);
158                 LOG.info("BGP Session with peer {} established successfully.", this.channel);
159             } else if (msg instanceof Notify) {
160                 final Notify ntf = (Notify) msg;
161                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
162             }
163             this.state = State.FINISHED;
164             return;
165         case OPEN_SENT:
166             if (msg instanceof Open) {
167                 handleOpen((Open) msg);
168                 return;
169             }
170             break;
171         default:
172             break;
173         }
174
175         // Catch-all for unexpected message
176         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
177         sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
178         negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
179         this.state = State.FINISHED;
180     }
181
182     private static Notify buildErrorNotify(final BGPError err) {
183         return buildErrorNotify(err, null);
184     }
185
186     private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
187         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
188         if (data != null && data.length != 0) {
189             builder.setData(data);
190         }
191         return builder.build();
192     }
193
194     private void handleOpen(final Open openObj) {
195         try {
196             final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()), getDestinationId(openObj, getPreferences()), getAsNumber(openObj, getPreferences()), openObj);
197             sendMessage(new KeepaliveBuilder().build());
198             this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences(), this.registry);
199             this.state = State.OPEN_CONFIRM;
200             LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
201         } catch (final BGPDocumentedException e) {
202             LOG.warn("Channel {} negotiation failed", this.channel, e);
203             negotiationFailed(e);
204         }
205     }
206
207     private 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             sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
213         }
214         this.registry.removePeerSession(getRemoteIp());
215         negotiationFailedCloseChannel(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 AsNumber getAsNumber(final Open openMsg, final BGPSessionPreferences preferences) {
239         return AsNumberUtil.advertizedAsNumber(openMsg);
240     }
241
242     public synchronized State getState() {
243         return this.state;
244     }
245
246     private void negotiationSuccessful(final BGPSessionImpl session) {
247         LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
248         this.channel.pipeline().replace(this, "session", session);
249         this.promise.setSuccess(session);
250     }
251
252     private void negotiationFailedCloseChannel(final Throwable cause) {
253         LOG.debug("Negotiation on channel {} failed", this.channel, cause);
254         this.channel.close();
255         this.promise.setFailure(cause);
256     }
257
258     private void sendMessage(final Notification msg) {
259         this.channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
260             @Override
261             public void operationComplete(final ChannelFuture f) {
262                 if (!f.isSuccess()) {
263                     LOG.info("Failed to send message {}", msg, f.cause());
264                     negotiationFailedCloseChannel(f.cause());
265                 } else {
266                     LOG.trace("Message {} sent to socket", msg);
267                 }
268
269             }
270         });
271     }
272
273     @Override
274     public final void channelActive(final ChannelHandlerContext ctx) {
275         LOG.debug("Starting session negotiation on channel {}", this.channel);
276
277         try {
278             startNegotiation();
279         } catch (final Exception e) {
280             LOG.warn("Unexpected negotiation failure", e);
281             negotiationFailedCloseChannel(e);
282         }
283
284     }
285
286     @Override
287     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
288         LOG.debug("Negotiation read invoked on channel {}", this.channel);
289
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 }