Merge "BUG-2109 : cleaned BGP sessions on session closed."
[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         OpenSent,
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         OpenConfirm,
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.CEASE);
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.OpenSent;
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 OpenConfirm:
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 OpenSent:
155             if (msg instanceof Open) {
156                 final Open openObj = (Open) msg;
157                 handleOpen(openObj);
158                 return;
159             }
160             break;
161         }
162
163         // Catch-all for unexpected message
164         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
165         this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
166         negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
167         this.state = State.Finished;
168     }
169
170     private static Notify buildErrorNotify(final BGPError err) {
171         return new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode()).build();
172     }
173
174     private void handleOpen(final Open openObj) {
175         try {
176             this.sessionValidator.validate(openObj, getPreferences());
177         } catch (final BGPDocumentedException e) {
178             negotiationFailed(e);
179             return;
180         }
181
182         try {
183             final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()), getDestinationId(openObj, getPreferences()));
184             this.sendMessage(new KeepaliveBuilder().build());
185             this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences().getHoldTime());
186             this.state = State.OpenConfirm;
187             LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
188         } catch (final BGPDocumentedException e) {
189             LOG.warn("Channel {} negotiation failed", this.channel, e);
190             negotiationFailed(e);
191         }
192     }
193
194     @Override
195     protected void negotiationFailed(final Throwable e) {
196         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
197         if (e instanceof BGPDocumentedException) {
198             // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
199             // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
200             this.sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError()));
201         }
202         super.negotiationFailed(e);
203         this.state = State.Finished;
204     }
205
206     /**
207      * @return BGP Id of device that accepted the connection
208      */
209     protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
210
211     /**
212      * @return BGP Id of device that initiated the connection
213      */
214     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
215
216     public synchronized State getState() {
217         return this.state;
218     }
219 }