Fixed some sonar warnings.
[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.channel.ChannelFuture;
12 import io.netty.channel.ChannelFutureListener;
13 import io.netty.util.Timeout;
14 import io.netty.util.Timer;
15 import io.netty.util.TimerTask;
16 import io.netty.util.concurrent.Promise;
17
18 import java.util.List;
19 import java.util.concurrent.TimeUnit;
20
21 import javax.annotation.concurrent.GuardedBy;
22
23 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
24 import org.opendaylight.protocol.bgp.parser.BGPError;
25 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
27 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
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.yangtools.yang.binding.Notification;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.common.annotations.VisibleForTesting;
40 import com.google.common.base.Preconditions;
41
42 public final class BGPSessionNegotiator extends AbstractSessionNegotiator<Notification, BGPSessionImpl> {
43         // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
44         protected static final int INITIAL_HOLDTIMER = 4;
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 LOG = 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 Open 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         private void writeMessage(final Object o) {
90                 this.channel.writeAndFlush(o).addListener(new ChannelFutureListener() {
91                         @Override
92                         public void operationComplete(final ChannelFuture f) throws Exception {
93                                 if (f.isSuccess()) {
94                                         LOG.debug("Message {} sent to socket", o);
95                                 } else {
96                                         LOG.info("Failed to send message {}", o, f.cause());
97                                 }
98                         }
99                 });
100         }
101
102         @Override
103         protected void startNegotiation() {
104                 Preconditions.checkState(this.state == State.Idle);
105                 this.writeMessage(new OpenBuilder().setMyAsNumber(this.localPref.getMyAs()).setHoldTimer(this.localPref.getHoldTime()).setBgpIdentifier(
106                                 this.localPref.getBgpId()).setBgpParameters(this.localPref.getParams()).build());
107                 this.state = State.OpenSent;
108
109                 final Object lock = this;
110                 this.timer.newTimeout(new TimerTask() {
111                         @Override
112                         public void run(final Timeout timeout) throws Exception {
113                                 synchronized (lock) {
114                                         if (BGPSessionNegotiator.this.state != State.Finished) {
115                                                 BGPSessionNegotiator.this.writeMessage(new NotifyBuilder().setErrorCode(BGPError.HOLD_TIMER_EXPIRED.getCode()).setErrorSubcode(
116                                                                 BGPError.HOLD_TIMER_EXPIRED.getSubcode()).build());
117                                                 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
118                                                 BGPSessionNegotiator.this.state = State.Finished;
119                                         }
120                                 }
121                         }
122                 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
123         }
124
125         @Override
126         protected synchronized void handleMessage(final Notification msg) {
127                 LOG.debug("Channel {} handling message in state {}", this.channel, this.state);
128
129                 switch (this.state) {
130                 case Finished:
131                 case Idle:
132                         final Notify fsmError = new NotifyBuilder().setErrorCode(BGPError.FSM_ERROR.getCode()).setErrorSubcode(
133                                         BGPError.FSM_ERROR.getSubcode()).build();
134                         this.writeMessage(fsmError);
135                 case OpenConfirm:
136                         if (msg instanceof Keepalive) {
137                                 negotiationSuccessful(this.session);
138                         } else if (msg instanceof Notify) {
139                                 final Notify ntf = (Notify) msg;
140                                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
141                         }
142                         this.state = State.Finished;
143                         return;
144                 case OpenSent:
145                         if (msg instanceof Open) {
146                                 final Open openObj = (Open) msg;
147                                 handleOpen(openObj);
148                                 return;
149                         }
150                         break;
151                 }
152
153                 // Catch-all for unexpected message
154                 LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
155                 this.writeMessage(new NotifyBuilder().setErrorCode(BGPError.FSM_ERROR.getCode()).setErrorSubcode(BGPError.FSM_ERROR.getSubcode()).build());
156                 negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
157                 this.state = State.Finished;
158         }
159
160         private void handleOpen(final Open openObj) {
161                 final List<BgpParameters> prefs = openObj.getBgpParameters();
162                 if (prefs != null && !prefs.isEmpty() && prefs.containsAll(this.localPref.getParams())) {
163                         this.remotePref = openObj;
164                         this.writeMessage(new KeepaliveBuilder().build());
165                         this.session = new BGPSessionImpl(this.timer, this.listener, this.channel, this.remotePref);
166                         this.state = State.OpenConfirm;
167                         LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, this.remotePref);
168                         return;
169                 }
170                 final Notify ntf = new NotifyBuilder().setErrorCode(BGPError.UNSPECIFIC_OPEN_ERROR.getCode()).setErrorSubcode(
171                                 BGPError.UNSPECIFIC_OPEN_ERROR.getSubcode()).build();
172                 this.writeMessage(ntf);
173                 negotiationFailed(new BGPDocumentedException("Open message unacceptable. 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 }