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