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