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