d2580f525d58bff9366d98cac1a764621c968f3e
[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 io.netty.channel.Channel;
11 import io.netty.util.Timeout;
12 import io.netty.util.Timer;
13 import io.netty.util.TimerTask;
14 import io.netty.util.concurrent.Promise;
15
16 import java.util.List;
17 import java.util.concurrent.TimeUnit;
18
19 import javax.annotation.concurrent.GuardedBy;
20
21 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
22 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
23 import org.opendaylight.protocol.bgp.parser.BGPError;
24 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
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.AsNumber;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
36 import org.opendaylight.yangtools.yang.binding.Notification;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import com.google.common.annotations.VisibleForTesting;
41 import com.google.common.base.Preconditions;
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(
103                                 this.localPref.getHoldTime()).setBgpIdentifier(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                         // FIXME: is something missing here? (at least an explanation why fall-through is okay
130                 case OpenConfirm:
131                         if (msg instanceof Keepalive) {
132                                 negotiationSuccessful(this.session);
133                         } else if (msg instanceof Notify) {
134                                 final Notify ntf = (Notify) msg;
135                                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
136                         }
137                         this.state = State.Finished;
138                         return;
139                 case OpenSent:
140                         if (msg instanceof Open) {
141                                 final Open openObj = (Open) msg;
142                                 handleOpen(openObj);
143                                 return;
144                         }
145                         break;
146                 }
147
148                 // Catch-all for unexpected message
149                 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
150                 this.sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
151                 negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
152                 this.state = State.Finished;
153         }
154
155         private static Notify buildErrorNotify(final BGPError err) {
156                 return new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode()).build();
157         }
158
159         private void handleOpen(final Open openObj) {
160                 final AsNumber as = AsNumberUtil.advertizedAsNumber(openObj);
161                 if (!this.remoteAs.equals(as)) {
162                         LOG.info("Unexpected remote AS number. Expecting {}, got {}", this.remoteAs, as);
163                         this.sendMessage(buildErrorNotify(BGPError.BAD_PEER_AS));
164                         negotiationFailed(new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS));
165                         this.state = State.Finished;
166                         return;
167                 }
168
169                 final List<BgpParameters> prefs = openObj.getBgpParameters();
170                 if (prefs != null && !prefs.isEmpty()) {
171                         if (!prefs.containsAll(this.localPref.getParams())) {
172                                 LOG.info("Open message session parameters differ, session still accepted.");
173                         }
174                         this.sendMessage(new KeepaliveBuilder().build());
175                         this.session = new BGPSessionImpl(this.timer, this.listener, this.channel, openObj, this.localPref.getHoldTime());
176                         this.state = State.OpenConfirm;
177                         LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
178                         return;
179                 }
180
181                 this.sendMessage(buildErrorNotify(BGPError.UNSPECIFIC_OPEN_ERROR));
182                 negotiationFailed(new BGPDocumentedException("Open message unacceptable. Check the configuration of BGP speaker.", BGPError.UNSPECIFIC_OPEN_ERROR));
183                 this.state = State.Finished;
184         }
185
186         public synchronized State getState() {
187                 return this.state;
188         }
189 }