2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.bgp.rib.impl;
10 import io.netty.channel.Channel;
11 import io.netty.util.Timeout;
12 import io.netty.util.Timer;
13 import io.netty.util.TimerTask;
15 import java.io.IOException;
16 import java.util.Date;
18 import java.util.concurrent.TimeUnit;
20 import javax.annotation.concurrent.GuardedBy;
22 import org.opendaylight.protocol.bgp.concepts.BGPTableType;
23 import org.opendaylight.protocol.bgp.parser.BGPError;
24 import org.opendaylight.protocol.bgp.parser.BGPParameter;
25 import org.opendaylight.protocol.bgp.parser.BGPSession;
26 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
27 import org.opendaylight.protocol.bgp.parser.BGPTerminationReason;
28 import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
29 import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
30 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
31 import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
32 import org.opendaylight.protocol.framework.AbstractProtocolSession;
33 import org.opendaylight.yangtools.yang.binding.Notification;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
37 import com.google.common.annotations.VisibleForTesting;
38 import com.google.common.base.Objects;
39 import com.google.common.base.Objects.ToStringHelper;
40 import com.google.common.base.Preconditions;
41 import com.google.common.collect.Sets;
44 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
46 private static final Logger logger = LoggerFactory.getLogger(BGPSessionImpl.class);
48 private static final int DEFAULT_HOLD_TIMER_VALUE = 15;
50 public static int HOLD_TIMER_VALUE = DEFAULT_HOLD_TIMER_VALUE; // 240
53 * Internal session state.
57 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
58 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
59 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
63 * The session has been completely established.
67 * The session has been closed. It will not be resurrected.
73 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
75 protected long lastMessageSentAt;
78 * System.nanoTime value about when was received the last message
80 private long lastMessageReceivedAt;
82 private final BGPSessionListener listener;
85 * Timer object grouping FSM Timers
87 private final Timer stateTimer;
89 private final BGPSynchronization sync;
91 private int kaCounter = 0;
93 private final Channel channel;
96 private State state = State.OpenConfirm;
98 private final int keepAlive;
100 private final Set<BGPTableType> tableTypes;
102 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final BGPOpenMessage remoteOpen) {
103 this.listener = Preconditions.checkNotNull(listener);
104 this.stateTimer = Preconditions.checkNotNull(timer);
105 this.channel = Preconditions.checkNotNull(channel);
106 this.keepAlive = remoteOpen.getHoldTime() / 3;
108 final Set<BGPTableType> tts = Sets.newHashSet();
109 if (remoteOpen.getOptParams() != null) {
110 for (final BGPParameter param : remoteOpen.getOptParams()) {
111 if (param instanceof MultiprotocolCapability) {
112 tts.add(((MultiprotocolCapability) param).getTableType());
117 this.sync = new BGPSynchronization(this, this.listener, tts);
118 this.tableTypes = tts;
120 if (remoteOpen.getHoldTime() != 0) {
121 this.stateTimer.newTimeout(new TimerTask() {
124 public void run(final Timeout timeout) throws Exception {
127 }, remoteOpen.getHoldTime(), TimeUnit.SECONDS);
129 this.stateTimer.newTimeout(new TimerTask() {
131 public void run(final Timeout timeout) throws Exception {
132 handleKeepaliveTimer();
134 }, this.keepAlive, TimeUnit.SECONDS);
139 public synchronized void close() {
140 logger.debug("Closing session: {}", this);
141 if (this.state != State.Idle) {
142 this.sendMessage(new BGPNotificationMessage(BGPError.CEASE));
143 this.channel.close();
144 this.state = State.Idle;
149 * Handles incoming message based on their type.
151 * @param msg incoming message
154 public void handleMessage(final Notification msg) {
155 // Update last reception time
156 this.lastMessageReceivedAt = System.nanoTime();
158 if (msg instanceof BGPOpenMessage) {
159 // Open messages should not be present here
160 this.terminate(BGPError.FSM_ERROR);
161 } else if (msg instanceof BGPNotificationMessage) {
162 // Notifications are handled internally
163 logger.info("Session closed because Notification message received: {}", ((BGPNotificationMessage) msg).getError());
164 this.closeWithoutMessage();
165 this.listener.onSessionTerminated(this, new BGPTerminationReason(((BGPNotificationMessage) msg).getError()));
166 } else if (msg instanceof BGPKeepAliveMessage) {
167 // Keepalives are handled internally
168 logger.debug("Received KeepAlive messsage.");
170 if (this.kaCounter >= 2) {
171 this.sync.kaReceived();
174 // All others are passed up
175 this.listener.onMessage(this, msg);
180 public synchronized void endOfInput() {
181 if (this.state == State.Up) {
182 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
186 void sendMessage(final Notification msg) {
188 this.channel.writeAndFlush(msg);
189 this.lastMessageSentAt = System.nanoTime();
190 logger.debug("Sent message: {}", msg);
191 } catch (final Exception e) {
192 logger.warn("Message {} was not sent.", msg, e);
196 private synchronized void closeWithoutMessage() {
197 logger.debug("Closing session: {}", this);
198 this.channel.close();
199 this.state = State.Idle;
203 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
204 * modified, because he initiated the closing. (To prevent concurrent modification exception).
208 private void terminate(final BGPError error) {
209 this.sendMessage(new BGPNotificationMessage(error));
210 this.closeWithoutMessage();
212 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
216 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
217 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
218 * which the message was received. If the session was closed by the time this method starts to execute (the session
219 * state will become IDLE), then rescheduling won't occur.
221 private synchronized void handleHoldTimer() {
222 if (this.state == State.Idle) {
226 final long ct = System.nanoTime();
227 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
229 if (ct >= nextHold) {
230 logger.debug("HoldTimer expired. " + new Date());
231 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
233 this.stateTimer.newTimeout(new TimerTask() {
235 public void run(final Timeout timeout) throws Exception {
238 }, nextHold - ct, TimeUnit.NANOSECONDS);
243 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
244 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
245 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
246 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
248 private synchronized void handleKeepaliveTimer() {
249 if (this.state == State.Idle) {
253 final long ct = System.nanoTime();
254 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
256 if (ct >= nextKeepalive) {
257 this.sendMessage(new BGPKeepAliveMessage());
258 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
260 this.stateTimer.newTimeout(new TimerTask() {
262 public void run(final Timeout timeout) throws Exception {
263 handleKeepaliveTimer();
265 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
269 final public String toString() {
270 return addToStringAttributes(Objects.toStringHelper(this)).toString();
273 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
274 toStringHelper.add("channel", this.channel);
275 toStringHelper.add("state", this.state);
276 return toStringHelper;
280 public Set<BGPTableType> getAdvertisedTableTypes() {
281 return this.tableTypes;
285 protected synchronized void sessionUp() {
286 this.state = State.Up;
287 this.listener.onSessionUp(this);
290 public synchronized State getState() {