Merge "BUG-2448 : added more defensive lookup to node & link attributes"
[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.util.concurrent.Promise;
15 import java.util.concurrent.TimeUnit;
16 import javax.annotation.concurrent.GuardedBy;
17 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
18 import org.opendaylight.protocol.bgp.parser.BGPError;
19 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
20 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
21 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
22 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
23 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
24 import org.opendaylight.protocol.util.Values;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
33 import org.opendaylight.yangtools.yang.binding.Notification;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * Bgp Session negotiator. Common for local -> remote and remote -> local connections.
39  * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
40  */
41 public abstract class AbstractBGPSessionNegotiator extends AbstractSessionNegotiator<Notification, BGPSessionImpl> {
42     // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
43     protected static final int INITIAL_HOLDTIMER = 4;
44
45     /**
46      * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
47      */
48     private static final int AS_TRANS = 23456;
49
50     @VisibleForTesting
51     public enum State {
52         /**
53          * Negotiation has not started yet.
54          */
55         IDLE,
56         /**
57          * We have sent our Open message, and are waiting for the peer's Open message.
58          */
59         OPEN_SENT,
60         /**
61          * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
62          * Open message.
63          */
64         OPEN_CONFIRM,
65         /**
66          * The negotiation finished.
67          */
68         FINISHED,
69     }
70
71     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
72     private final BGPPeerRegistry registry;
73     private final BGPSessionValidator sessionValidator;
74
75     @GuardedBy("this")
76     private State state = State.IDLE;
77
78     @GuardedBy("this")
79     private BGPSessionImpl session;
80
81     public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
82             final BGPPeerRegistry registry, final BGPSessionValidator sessionValidator) {
83         super(promise, channel);
84         this.registry = registry;
85         this.sessionValidator = sessionValidator;
86     }
87
88     @Override
89     protected synchronized void startNegotiation() {
90         Preconditions.checkState(this.state == State.IDLE);
91
92         // Check if peer is configured in registry before retrieving preferences
93         if (!this.registry.isPeerConfigured(getRemoteIp())) {
94             final BGPDocumentedException cause = new BGPDocumentedException(
95                     "BGP peer with ip: " + getRemoteIp()
96                     + " not configured, check configured peers in : "
97                     + this.registry, BGPError.CONNECTION_REJECTED);
98             negotiationFailed(cause);
99             return;
100         }
101
102         final BGPSessionPreferences preferences = getPreferences();
103
104         int as = preferences.getMyAs().getValue().intValue();
105         // Set as AS_TRANS if the value is bigger than 2B
106         if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
107             as = AS_TRANS;
108         }
109         this.sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
110                 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
111         if (this.state != State.FINISHED) {
112             this.state = State.OPEN_SENT;
113
114             this.channel.eventLoop().schedule(new Runnable() {
115                 @Override
116                 public void run() {
117                     if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
118                         AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
119                         negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
120                         AbstractBGPSessionNegotiator.this.state = State.FINISHED;
121                     }
122                 }
123             }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
124         }
125     }
126
127     private BGPSessionPreferences getPreferences() {
128         return this.registry.getPeerPreferences(getRemoteIp());
129     }
130
131     private IpAddress getRemoteIp() {
132         return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
133     }
134
135     @Override
136     protected synchronized void handleMessage(final Notification msg) {
137         LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
138
139         switch (this.state) {
140         case FINISHED:
141         case IDLE:
142             this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
143             return;
144         case OPEN_CONFIRM:
145             if (msg instanceof Keepalive) {
146                 negotiationSuccessful(this.session);
147                 LOG.info("BGP Session with peer {} established successfully.", this.channel);
148             } else if (msg instanceof Notify) {
149                 final Notify ntf = (Notify) msg;
150                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
151             }
152             this.state = State.FINISHED;
153             return;
154         case OPEN_SENT:
155             if (msg instanceof Open) {
156                 final Open openObj = (Open) msg;
157                 handleOpen(openObj);
158                 return;
159             }
160             break;
161         default:
162             break;
163         }
164
165         // Catch-all for unexpected message
166         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
167         this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
168         negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
169         this.state = State.FINISHED;
170     }
171
172     private static Notify buildErrorNotify(final BGPError err) {
173         return buildErrorNotify(err, null);
174     }
175
176     private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
177         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
178         if (data != null && data.length != 0) {
179             builder.setData(data);
180         }
181         return builder.build();
182     }
183
184     private void handleOpen(final Open openObj) {
185         try {
186             this.sessionValidator.validate(openObj, getPreferences());
187         } catch (final BGPDocumentedException e) {
188             negotiationFailed(e);
189             return;
190         }
191
192         try {
193             final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()), getDestinationId(openObj, getPreferences()));
194             this.sendMessage(new KeepaliveBuilder().build());
195             this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences());
196             this.state = State.OPEN_CONFIRM;
197             LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
198         } catch (final BGPDocumentedException e) {
199             LOG.warn("Channel {} negotiation failed", this.channel, e);
200             negotiationFailed(e);
201         }
202     }
203
204     @Override
205     protected void negotiationFailed(final Throwable e) {
206         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
207         if (e instanceof BGPDocumentedException) {
208             // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
209             // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
210             this.sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
211         }
212         this.registry.removePeerSession(getRemoteIp());
213         super.negotiationFailed(e);
214         this.state = State.FINISHED;
215     }
216
217     /**
218      * @return BGP Id of device that accepted the connection
219      */
220     protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
221
222     /**
223      * @return BGP Id of device that initiated the connection
224      */
225     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
226
227     public synchronized State getState() {
228         return this.state;
229     }
230 }