Merge "BUG-108: defensive AbstractAdjRIBsIn"
[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.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.BGPSessionPreferences;
25 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev130918.LinkstateAddressFamily;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev130918.LinkstateSubsequentAddressFamily;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Keepalive;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.KeepaliveBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Notify;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.NotifyBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Open;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.OpenBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.open.BgpParameters;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.open.bgp.parameters.CParameters;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130918.open.bgp.parameters.c.parameters.CMultiprotocol;
37 import org.opendaylight.yangtools.yang.binding.Notification;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import com.google.common.annotations.VisibleForTesting;
42 import com.google.common.base.Preconditions;
43
44 public final class BGPSessionNegotiator extends AbstractSessionNegotiator<Notification, BGPSessionImpl> {
45         // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
46         // FIXME to actual value
47         protected static final int INITIAL_HOLDTIMER = 1;
48
49         @VisibleForTesting
50         public enum State {
51                 /**
52                  * Negotiation has not started yet.
53                  */
54                 Idle,
55                 /**
56                  * We have sent our Open message, and are waiting for the peer's Open message.
57                  */
58                 OpenSent,
59                 /**
60                  * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
61                  * Open message.
62                  */
63                 OpenConfirm,
64                 /**
65                  * The negotiation finished.
66                  */
67                 Finished,
68         }
69
70         private static final Logger logger = LoggerFactory.getLogger(BGPSessionNegotiator.class);
71         private final BGPSessionListener listener;
72         private final Timer timer;
73         private final BGPSessionPreferences localPref;
74
75         @GuardedBy("this")
76         private Open remotePref;
77
78         @GuardedBy("this")
79         private State state = State.Idle;
80
81         @GuardedBy("this")
82         private BGPSessionImpl session;
83
84         public BGPSessionNegotiator(final Timer timer, final Promise<BGPSessionImpl> promise, final Channel channel,
85                         final BGPSessionPreferences initialPrefs, final BGPSessionListener listener) {
86                 super(promise, channel);
87                 this.listener = Preconditions.checkNotNull(listener);
88                 this.localPref = Preconditions.checkNotNull(initialPrefs);
89                 this.timer = Preconditions.checkNotNull(timer);
90         }
91
92         @Override
93         protected void startNegotiation() {
94                 Preconditions.checkState(this.state == State.Idle);
95                 this.channel.writeAndFlush(new OpenBuilder().setMyAsNumber(this.localPref.getMyAs()).setHoldTimer(this.localPref.getHoldTime()).setBgpIdentifier(
96                                 this.localPref.getBgpId()).setBgpParameters(this.localPref.getParams()).build());
97                 this.state = State.OpenSent;
98
99                 final Object lock = this;
100                 this.timer.newTimeout(new TimerTask() {
101                         @Override
102                         public void run(final Timeout timeout) throws Exception {
103                                 synchronized (lock) {
104                                         if (BGPSessionNegotiator.this.state != State.Finished) {
105                                                 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
106                                                 BGPSessionNegotiator.this.channel.writeAndFlush(new NotifyBuilder().setErrorCode(
107                                                                 BGPError.HOLD_TIMER_EXPIRED.getCode()).setErrorSubcode(BGPError.HOLD_TIMER_EXPIRED.getSubcode()).build());
108                                                 BGPSessionNegotiator.this.state = State.Finished;
109                                         }
110                                 }
111                         }
112                 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
113         }
114
115         @Override
116         protected synchronized void handleMessage(final Notification msg) {
117                 logger.debug("Channel {} handling message in state {}", this.channel, this.state);
118
119                 switch (this.state) {
120                 case Finished:
121                 case Idle:
122                         final Notify fsmError = new NotifyBuilder().setErrorCode(BGPError.FSM_ERROR.getCode()).setErrorSubcode(
123                                         BGPError.FSM_ERROR.getSubcode()).build();
124                         this.channel.writeAndFlush(fsmError);
125                 case OpenConfirm:
126                         if (msg instanceof Keepalive) {
127                                 negotiationSuccessful(this.session);
128                         } else if (msg instanceof Notify) {
129                                 final Notify ntf = (Notify) msg;
130                                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
131                         }
132                         this.state = State.Finished;
133                         return;
134                 case OpenSent:
135                         if (msg instanceof Open) {
136                                 final Open openObj = (Open) msg;
137                                 handleOpen(openObj);
138                                 return;
139                         }
140                         break;
141                 }
142
143                 // Catch-all for unexpected message
144                 logger.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
145                 this.channel.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.FSM_ERROR.getCode()).setErrorSubcode(
146                                 BGPError.FSM_ERROR.getSubcode()).build());
147                 negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
148                 this.state = State.Finished;
149         }
150
151         private void handleOpen(final Open openObj) {
152                 final List<BgpParameters> prefs = openObj.getBgpParameters();
153                 if (prefs != null && !prefs.isEmpty()) {
154                         for (final BgpParameters param : openObj.getBgpParameters()) {
155                                 final CParameters cap = param.getCParameters();
156                                 // FIXME: the reference to linkstate should be moved to config subsystem!
157
158                                 if (cap instanceof CMultiprotocol
159                                                 && ((CMultiprotocol) cap).getMultiprotocolCapability().getAfi() == LinkstateAddressFamily.class
160                                                 && ((CMultiprotocol) cap).getMultiprotocolCapability().getSafi() == LinkstateSubsequentAddressFamily.class) {
161                                         this.remotePref = openObj;
162                                         this.channel.writeAndFlush(new KeepaliveBuilder().build());
163                                         this.session = new BGPSessionImpl(this.timer, this.listener, this.channel, this.remotePref);
164                                         this.state = State.OpenConfirm;
165                                         logger.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, this.remotePref);
166                                         return;
167                                 }
168                         }
169                 }
170                 final Notify ntf = new NotifyBuilder().setErrorCode(BGPError.UNSPECIFIC_OPEN_ERROR.getCode()).setErrorSubcode(
171                                 BGPError.UNSPECIFIC_OPEN_ERROR.getSubcode()).build();
172                 this.channel.writeAndFlush(ntf);
173                 negotiationFailed(new BGPDocumentedException("Linkstate capability is not configured on router. Check the configuration of BGP speaker.", BGPError.forValue(
174                                 ntf.getErrorCode(), ntf.getErrorSubcode())));
175                 this.state = State.Finished;
176         }
177
178         public synchronized State getState() {
179                 return this.state;
180         }
181 }