Merge "BUG-1287: migrate tests to new APIs"
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPSessionNegotiator.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12
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
19 import java.util.List;
20 import java.util.concurrent.TimeUnit;
21
22 import javax.annotation.concurrent.GuardedBy;
23
24 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
25 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
26 import org.opendaylight.protocol.bgp.parser.BGPError;
27 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
28 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
29 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
30 import org.opendaylight.protocol.util.Values;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
39 import org.opendaylight.yangtools.yang.binding.Notification;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public final class BGPSessionNegotiator extends AbstractSessionNegotiator<Notification, BGPSessionImpl> {
44     // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
45     protected static final int INITIAL_HOLDTIMER = 4;
46
47     /**
48      * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
49      */
50     private static final int AS_TRANS = 23456;
51
52     @VisibleForTesting
53     public enum State {
54         /**
55          * Negotiation has not started yet.
56          */
57         Idle,
58         /**
59          * We have sent our Open message, and are waiting for the peer's Open message.
60          */
61         OpenSent,
62         /**
63          * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
64          * Open message.
65          */
66         OpenConfirm,
67         /**
68          * The negotiation finished.
69          */
70         Finished,
71     }
72
73     private static final Logger LOG = LoggerFactory.getLogger(BGPSessionNegotiator.class);
74     private final BGPSessionPreferences localPref;
75     private final BGPSessionListener listener;
76     private final AsNumber remoteAs;
77     private final Timer timer;
78
79     @GuardedBy("this")
80     private State state = State.Idle;
81
82     @GuardedBy("this")
83     private BGPSessionImpl session;
84
85     public BGPSessionNegotiator(final Timer timer, final Promise<BGPSessionImpl> promise, final Channel channel,
86             final BGPSessionPreferences initialPrefs, final AsNumber remoteAs, final BGPSessionListener listener) {
87         super(promise, channel);
88         this.listener = Preconditions.checkNotNull(listener);
89         this.localPref = Preconditions.checkNotNull(initialPrefs);
90         this.remoteAs = Preconditions.checkNotNull(remoteAs);
91         this.timer = Preconditions.checkNotNull(timer);
92     }
93
94     @Override
95     protected void startNegotiation() {
96         Preconditions.checkState(this.state == State.Idle);
97         int as = this.localPref.getMyAs().getValue().intValue();
98         // Set as AS_TRANS if the value is bigger than 2B
99         if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
100             as = AS_TRANS;
101         }
102         this.sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(this.localPref.getHoldTime()).setBgpIdentifier(
103                 this.localPref.getBgpId()).setBgpParameters(this.localPref.getParams()).build());
104         this.state = State.OpenSent;
105
106         final Object lock = this;
107         this.timer.newTimeout(new TimerTask() {
108             @Override
109             public void run(final Timeout timeout) {
110                 synchronized (lock) {
111                     if (BGPSessionNegotiator.this.state != State.Finished) {
112                         BGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
113                         negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
114                         BGPSessionNegotiator.this.state = State.Finished;
115                     }
116                 }
117             }
118         }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
119     }
120
121     @Override
122     protected synchronized void handleMessage(final Notification msg) {
123         LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
124
125         switch (this.state) {
126         case Finished:
127         case Idle:
128             this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
129             return;
130         case OpenConfirm:
131             if (msg instanceof Keepalive) {
132                 negotiationSuccessful(this.session);
133                 LOG.info("BGP Session with peer {} established successfully.", this.channel);
134             } else if (msg instanceof Notify) {
135                 final Notify ntf = (Notify) msg;
136                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
137             }
138             this.state = State.Finished;
139             return;
140         case OpenSent:
141             if (msg instanceof Open) {
142                 final Open openObj = (Open) msg;
143                 handleOpen(openObj);
144                 return;
145             }
146             break;
147         }
148
149         // Catch-all for unexpected message
150         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
151         this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
152         negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
153         this.state = State.Finished;
154     }
155
156     private static Notify buildErrorNotify(final BGPError err) {
157         return new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode()).build();
158     }
159
160     private void handleOpen(final Open openObj) {
161         final AsNumber as = AsNumberUtil.advertizedAsNumber(openObj);
162         if (!this.remoteAs.equals(as)) {
163             LOG.warn("Unexpected remote AS number. Expecting {}, got {}", this.remoteAs, as);
164             this.sendMessage(buildErrorNotify(BGPError.BAD_PEER_AS));
165             negotiationFailed(new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS));
166             this.state = State.Finished;
167             return;
168         }
169
170         final List<BgpParameters> prefs = openObj.getBgpParameters();
171         if (prefs != null && !prefs.isEmpty()) {
172             if (!prefs.containsAll(this.localPref.getParams())) {
173                 LOG.info("BGP Open message session parameters differ, session still accepted.");
174             }
175             this.sendMessage(new KeepaliveBuilder().build());
176             this.session = new BGPSessionImpl(this.timer, this.listener, this.channel, openObj, this.localPref.getHoldTime());
177             this.state = State.OpenConfirm;
178             LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
179             return;
180         }
181
182         this.sendMessage(buildErrorNotify(BGPError.UNSPECIFIC_OPEN_ERROR));
183         negotiationFailed(new BGPDocumentedException("Open message unacceptable. Check the configuration of BGP speaker.", BGPError.UNSPECIFIC_OPEN_ERROR));
184         this.state = State.Finished;
185     }
186
187     public synchronized State getState() {
188         return this.state;
189     }
190 }