Merge "Bug-1370: Reads message body bytes as well as exception is thrown during parsing."
[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.Timeout;
15 import io.netty.util.Timer;
16 import io.netty.util.TimerTask;
17 import io.netty.util.concurrent.Promise;
18 import java.util.concurrent.TimeUnit;
19 import javax.annotation.concurrent.GuardedBy;
20 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
21 import org.opendaylight.protocol.bgp.parser.BGPError;
22 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
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.framework.AbstractSessionNegotiator;
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 -> remote and remote -> local connections.
42  * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
43  */
44 public abstract class AbstractBGPSessionNegotiator extends AbstractSessionNegotiator<Notification, BGPSessionImpl> {
45     // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
46     protected 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         OpenSent,
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         OpenConfirm,
68         /**
69          * The negotiation finished.
70          */
71         Finished,
72     }
73
74     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
75     private final Timer timer;
76     private final BGPPeerRegistry registry;
77     private final BGPSessionValidator sessionValidator;
78
79     @GuardedBy("this")
80     private State state = State.Idle;
81
82     @GuardedBy("this")
83     private BGPSessionImpl session;
84
85     public AbstractBGPSessionNegotiator(final Timer timer, final Promise<BGPSessionImpl> promise, final Channel channel,
86                                         final BGPPeerRegistry registry, final BGPSessionValidator sessionValidator) {
87         super(promise, channel);
88         this.registry = registry;
89         this.sessionValidator = sessionValidator;
90         this.timer = Preconditions.checkNotNull(timer);
91     }
92
93     @Override
94     protected void startNegotiation() {
95         Preconditions.checkState(this.state == State.Idle);
96
97         // Check if peer is configured in registry before retrieving preferences
98         if (!registry.isPeerConfigured(getRemoteIp())) {
99             final BGPDocumentedException cause = new BGPDocumentedException(
100                     "BGP peer with ip: " + getRemoteIp()
101                             + " not configured, check configured peers in : "
102                             + registry, BGPError.CEASE);
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         this.sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
115                 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
116         this.state = State.OpenSent;
117
118         final Object lock = this;
119         this.timer.newTimeout(new TimerTask() {
120             @Override
121             public void run(final Timeout timeout) {
122                 synchronized (lock) {
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             }
130         }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
131     }
132
133     private BGPSessionPreferences getPreferences() {
134         return registry.getPeerPreferences(getRemoteIp());
135     }
136
137     private IpAddress getRemoteIp() {
138         return StrictBGPPeerRegistry.getIpAddress(channel.remoteAddress());
139     }
140
141     @Override
142     protected synchronized void handleMessage(final Notification msg) {
143         LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
144
145         switch (this.state) {
146         case Finished:
147         case Idle:
148             this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
149             return;
150         case OpenConfirm:
151             if (msg instanceof Keepalive) {
152                 negotiationSuccessful(this.session);
153                 LOG.info("BGP Session with peer {} established successfully.", this.channel);
154             } else if (msg instanceof Notify) {
155                 final Notify ntf = (Notify) msg;
156                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
157             }
158             this.state = State.Finished;
159             return;
160         case OpenSent:
161             if (msg instanceof Open) {
162                 final Open openObj = (Open) msg;
163                 handleOpen(openObj);
164                 return;
165             }
166             break;
167         }
168
169         // Catch-all for unexpected message
170         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
171         this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
172         negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
173         this.state = State.Finished;
174     }
175
176     private static Notify buildErrorNotify(final BGPError err) {
177         return new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode()).build();
178     }
179
180     private void handleOpen(final Open openObj) {
181         try {
182             sessionValidator.validate(openObj, getPreferences());
183         } catch (final BGPDocumentedException e) {
184             negotiationFailed(e);
185             return;
186         }
187
188         try {
189             final BGPSessionListener peer = registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()), getDestinationId(openObj, getPreferences()));
190             this.sendMessage(new KeepaliveBuilder().build());
191             this.session = new BGPSessionImpl(this.timer, peer, this.channel, openObj, getPreferences().getHoldTime());
192             this.state = State.OpenConfirm;
193             LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
194         } catch (final BGPDocumentedException e) {
195             LOG.warn("Channel {} negotiation failed", this.channel, e);
196             negotiationFailed(e);
197         }
198     }
199
200     private void negotiationFailed(final BGPDocumentedException e) {
201         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
202         this.sendMessage(buildErrorNotify(e.getError()));
203         super.negotiationFailed(e);
204         this.state = State.Finished;
205     }
206
207     /**
208      * @return BGP Id of device that accepted the connection
209      */
210     protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
211
212     /**
213      * @return BGP Id of device that initiated the connection
214      */
215     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
216
217     public synchronized State getState() {
218         return this.state;
219     }
220 }