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