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