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