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