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