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