Bug 3117 - Capability Parameter Parse Issue
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPSessionImpl.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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Sets;
16 import io.netty.channel.Channel;
17 import io.netty.channel.ChannelFuture;
18 import io.netty.channel.ChannelFutureListener;
19 import java.io.IOException;
20 import java.util.Date;
21 import java.util.Set;
22 import java.util.concurrent.TimeUnit;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
25 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
26 import org.opendaylight.protocol.bgp.parser.BGPError;
27 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
28 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
29 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
30 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
31 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
32 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
33 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
34 import org.opendaylight.protocol.framework.AbstractProtocolSession;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.OptionalCapabilities;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.optional.capabilities.CParameters;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapability;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
50 import org.opendaylight.yangtools.yang.binding.Notification;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 @VisibleForTesting
55 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession, BGPSessionStatistics {
56
57     private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
58
59     private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
60
61     private static final int KA_TO_DEADTIMER_RATIO = 3;
62
63     /**
64      * Internal session state.
65      */
66     public enum State {
67         /**
68          * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
69          * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
70          * announced to the listener. If the session is torn down in this state, we do not inform the listener.
71          */
72         OPEN_CONFIRM,
73         /**
74          * The session has been completely established.
75          */
76         UP,
77         /**
78          * The session has been closed. It will not be resurrected.
79          */
80         IDLE,
81     }
82
83     /**
84      * System.nanoTime value about when was sent the last message.
85      */
86     @VisibleForTesting
87     private long lastMessageSentAt;
88
89     /**
90      * System.nanoTime value about when was received the last message
91      */
92     private long lastMessageReceivedAt;
93
94     private final BGPSessionListener listener;
95
96     private final BGPSynchronization sync;
97
98     private int kaCounter = 0;
99
100     private final Channel channel;
101
102     @GuardedBy("this")
103     private State state = State.OPEN_CONFIRM;
104
105     private final Set<BgpTableType> tableTypes;
106     private final int holdTimerValue;
107     private final int keepAlive;
108     private final AsNumber asNumber;
109     private final Ipv4Address bgpId;
110     private final BGPPeerRegistry peerRegistry;
111     private final ChannelOutputLimiter limiter;
112
113     private BGPSessionStats sessionStats;
114
115     public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences,
116             final BGPPeerRegistry peerRegistry) {
117         this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
118         this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes);
119     }
120
121     public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer,
122             final BGPPeerRegistry peerRegistry) {
123         this.listener = Preconditions.checkNotNull(listener);
124         this.channel = Preconditions.checkNotNull(channel);
125         this.limiter = new ChannelOutputLimiter(this);
126         this.channel.pipeline().addLast(this.limiter);
127         this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
128         LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
129         this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
130         this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
131         this.peerRegistry = peerRegistry;
132
133         final Set<TablesKey> tts = Sets.newHashSet();
134         final Set<BgpTableType> tats = Sets.newHashSet();
135         if (remoteOpen.getBgpParameters() != null) {
136             for (final BgpParameters param : remoteOpen.getBgpParameters()) {
137                 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
138                     final CParameters cParam = optCapa.getCParameters();
139                     if ( cParam.getAugmentation(CParameters1.class) == null ||
140                             cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() == null ) {
141                         continue;
142                     }
143                     final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability();
144                     final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
145                     LOG.trace("Added table type to sync {}", tt);
146                     tts.add(tt);
147                     tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
148                 }
149             }
150         }
151
152         this.sync = new BGPSynchronization(this.listener, tts);
153         this.tableTypes = tats;
154
155         if (this.holdTimerValue != 0) {
156             channel.eventLoop().schedule(new Runnable() {
157                 @Override
158                 public void run() {
159                     handleHoldTimer();
160                 }
161             }, this.holdTimerValue, TimeUnit.SECONDS);
162
163             channel.eventLoop().schedule(new Runnable() {
164                 @Override
165                 public void run() {
166                     handleKeepaliveTimer();
167                 }
168             }, this.keepAlive, TimeUnit.SECONDS);
169         }
170         this.bgpId = remoteOpen.getBgpIdentifier();
171         this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
172                 this.tableTypes);
173     }
174
175     @Override
176     public synchronized void close() {
177         LOG.info("Closing session: {}", this);
178
179         if (this.state != State.IDLE) {
180             this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(
181                     BGPError.CEASE.getSubcode()).build());
182             removePeerSession();
183             this.channel.close();
184             this.state = State.IDLE;
185         }
186     }
187
188     /**
189      * Handles incoming message based on their type.
190      *
191      * @param msg incoming message
192      */
193     @Override
194     public synchronized void handleMessage(final Notification msg) {
195         // Update last reception time
196         this.lastMessageReceivedAt = System.nanoTime();
197         this.sessionStats.updateReceivedMsgTotal();
198
199         if (msg instanceof Open) {
200             // Open messages should not be present here
201             this.terminate(BGPError.FSM_ERROR);
202         } else if (msg instanceof Notify) {
203             // Notifications are handled internally
204             LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
205                 ((Notify) msg).getErrorSubcode());
206             this.closeWithoutMessage();
207             this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
208                 ((Notify) msg).getErrorSubcode())));
209             this.sessionStats.updateReceivedMsgErr((Notify) msg);
210         } else if (msg instanceof Keepalive) {
211             // Keepalives are handled internally
212             LOG.trace("Received KeepAlive messsage.");
213             this.kaCounter++;
214             this.sessionStats.updateReceivedMsgKA();
215             if (this.kaCounter >= 2) {
216                 this.sync.kaReceived();
217             }
218         } else {
219             // All others are passed up
220             this.listener.onMessage(this, msg);
221             this.sync.updReceived((Update) msg);
222             this.sessionStats.updateReceivedMsgUpd();
223         }
224     }
225
226     @Override
227     public synchronized void endOfInput() {
228         if (this.state == State.UP) {
229             this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
230         }
231     }
232
233     @GuardedBy("this")
234     private void writeEpilogue(final ChannelFuture future, final Notification msg) {
235         future.addListener(
236             new ChannelFutureListener() {
237                 @Override
238                 public void operationComplete(final ChannelFuture f) {
239                     if (!f.isSuccess()) {
240                         LOG.info("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
241                     } else {
242                         LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
243                     }
244                 }
245             });
246         this.lastMessageSentAt = System.nanoTime();
247         this.sessionStats.updateSentMsgTotal();
248         if (msg instanceof Update) {
249             this.sessionStats.updateSentMsgUpd();
250         } else if (msg instanceof Notify) {
251             this.sessionStats.updateSentMsgErr((Notify) msg);
252         }
253     }
254
255     void flush() {
256         this.channel.flush();
257     }
258
259     synchronized void write(final Notification msg) {
260         try {
261             writeEpilogue(this.channel.write(msg), msg);
262         } catch (final Exception e) {
263             LOG.warn("Message {} was not sent.", msg, e);
264         }
265     }
266
267     synchronized void writeAndFlush(final Notification msg) {
268         writeEpilogue(this.channel.writeAndFlush(msg), msg);
269     }
270
271     private synchronized void closeWithoutMessage() {
272         LOG.debug("Closing session: {}", this);
273         removePeerSession();
274         this.channel.close();
275         this.state = State.IDLE;
276     }
277
278     /**
279      * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
280      * modified, because he initiated the closing. (To prevent concurrent modification exception).
281      *
282      * @param closeObject
283      */
284     private void terminate(final BGPError error) {
285         this.writeAndFlush(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
286         this.closeWithoutMessage();
287
288         this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
289     }
290
291     private void removePeerSession() {
292         if (this.peerRegistry != null) {
293             this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
294         }
295     }
296
297     /**
298      * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
299      * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
300      * which the message was received. If the session was closed by the time this method starts to execute (the session
301      * state will become IDLE), then rescheduling won't occur.
302      */
303     private synchronized void handleHoldTimer() {
304         if (this.state == State.IDLE) {
305             return;
306         }
307
308         final long ct = System.nanoTime();
309         final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
310
311         if (ct >= nextHold) {
312             LOG.debug("HoldTimer expired. {}", new Date());
313             this.terminate(BGPError.HOLD_TIMER_EXPIRED);
314         } else {
315             this.channel.eventLoop().schedule(new Runnable() {
316                 @Override
317                 public void run() {
318                     handleHoldTimer();
319                 }
320             }, nextHold - ct, TimeUnit.NANOSECONDS);
321         }
322     }
323
324     /**
325      * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
326      * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
327      * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
328      * starts to execute (the session state will become IDLE), that rescheduling won't occur.
329      */
330     private synchronized void handleKeepaliveTimer() {
331         if (this.state == State.IDLE) {
332             return;
333         }
334
335         final long ct = System.nanoTime();
336         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
337
338         if (ct >= nextKeepalive) {
339             this.writeAndFlush(KEEP_ALIVE);
340             nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
341             this.sessionStats.updateSentMsgKA();
342         }
343         this.channel.eventLoop().schedule(new Runnable() {
344             @Override
345             public void run() {
346                 handleKeepaliveTimer();
347             }
348         }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
349     }
350
351     @Override
352     public final String toString() {
353         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
354     }
355
356     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
357         toStringHelper.add("channel", this.channel);
358         toStringHelper.add("state", this.getState());
359         return toStringHelper;
360     }
361
362     @Override
363     public Set<BgpTableType> getAdvertisedTableTypes() {
364         return this.tableTypes;
365     }
366
367     @Override
368     protected synchronized void sessionUp() {
369         this.sessionStats.startSessionStopwatch();
370         this.state = State.UP;
371         this.listener.onSessionUp(this);
372     }
373
374     public synchronized State getState() {
375         return this.state;
376     }
377
378     @Override
379     public final Ipv4Address getBgpId() {
380         return this.bgpId;
381     }
382
383     @Override
384     public final AsNumber getAsNumber() {
385         return this.asNumber;
386     }
387
388     synchronized boolean isWritable() {
389         return this.channel != null && this.channel.isWritable();
390     }
391
392     void schedule(final Runnable task) {
393         Preconditions.checkState(this.channel != null);
394         this.channel.eventLoop().submit(task);
395     }
396
397     @VisibleForTesting
398     protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
399         this.lastMessageSentAt = lastMessageSentAt;
400     }
401
402     @Override
403     public synchronized BgpSessionState getBgpSesionState() {
404         return this.sessionStats.getBgpSessionState(this.state);
405     }
406
407     @Override
408     public synchronized void resetSessionStats() {
409         this.sessionStats.resetStats();
410     }
411
412     ChannelOutputLimiter getLimiter() {
413         return this.limiter;
414     }
415 }