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.BGPMessage;
25 import org.opendaylight.protocol.bgp.parser.BGPParameter;
26 import org.opendaylight.protocol.bgp.parser.BGPSession;
27 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
28 import org.opendaylight.protocol.bgp.parser.BGPTerminationReason;
29 import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
30 import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
31 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
32 import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
33 import org.opendaylight.protocol.framework.AbstractProtocolSession;
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<BGPMessage> 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 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
55 protected long lastMessageSentAt;
58 * System.nanoTime value about when was received the last message
60 private long lastMessageReceivedAt;
62 private final BGPSessionListener listener;
65 * Timer object grouping FSM Timers
67 private final Timer stateTimer;
69 private final BGPSynchronization sync;
71 private int kaCounter = 0;
73 private final Channel channel;
76 private boolean closed = false;
78 private final short keepAlive;
80 private final Set<BGPTableType> tableTypes;
82 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final short keepAlive,
83 final BGPOpenMessage remoteOpen) {
84 this.listener = Preconditions.checkNotNull(listener);
85 this.stateTimer = Preconditions.checkNotNull(timer);
86 this.channel = Preconditions.checkNotNull(channel);
87 this.keepAlive = keepAlive;
89 final Set<BGPTableType> tts = Sets.newHashSet();
90 if (remoteOpen.getOptParams() != null) {
91 for (final BGPParameter param : remoteOpen.getOptParams()) {
92 if (param instanceof MultiprotocolCapability) {
93 tts.add(((MultiprotocolCapability) param).getTableType());
98 this.sync = new BGPSynchronization(this, this.listener, tts);
99 this.tableTypes = tts;
101 if (remoteOpen.getHoldTime() != 0) {
102 this.stateTimer.newTimeout(new TimerTask() {
105 public void run(final Timeout timeout) throws Exception {
108 }, remoteOpen.getHoldTime(), TimeUnit.SECONDS);
110 this.stateTimer.newTimeout(new TimerTask() {
112 public void run(final Timeout timeout) throws Exception {
113 handleKeepaliveTimer();
115 }, keepAlive, TimeUnit.SECONDS);
120 public synchronized void close() {
121 logger.debug("Closing session: {}", this);
123 this.sendMessage(new BGPNotificationMessage(BGPError.CEASE));
124 this.channel.close();
130 * Handles incoming message based on their type.
132 * @param msg incoming message
135 public void handleMessage(final BGPMessage msg) {
136 // Update last reception time
137 this.lastMessageReceivedAt = System.nanoTime();
139 if (msg instanceof BGPOpenMessage) {
140 // Open messages should not be present here
141 this.terminate(BGPError.FSM_ERROR);
142 } else if (msg instanceof BGPNotificationMessage) {
143 // Notifications are handled internally
144 logger.info("Session closed because Notification message received: {}", ((BGPNotificationMessage) msg).getError());
145 this.closeWithoutMessage();
146 this.listener.onSessionTerminated(this, new BGPTerminationReason(((BGPNotificationMessage) msg).getError()));
147 } else if (msg instanceof BGPKeepAliveMessage) {
148 // Keepalives are handled internally
149 logger.debug("Received KeepAlive messsage.");
151 if (this.kaCounter >= 2) {
152 this.sync.kaReceived();
155 // All others are passed up
156 this.listener.onMessage(this, msg);
161 public synchronized void endOfInput() {
163 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
167 void sendMessage(final BGPMessage msg) {
169 this.channel.writeAndFlush(msg);
170 this.lastMessageSentAt = System.nanoTime();
171 logger.debug("Sent message: {}", msg);
172 } catch (final Exception e) {
173 logger.warn("Message {} was not sent.", msg, e);
177 private synchronized void closeWithoutMessage() {
178 logger.debug("Closing session: {}", this);
179 this.channel.close();
184 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
185 * modified, because he initiated the closing. (To prevent concurrent modification exception).
189 private void terminate(final BGPError error) {
190 this.sendMessage(new BGPNotificationMessage(error));
191 this.closeWithoutMessage();
192 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
196 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
197 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
198 * which the message was received. If the session was closed by the time this method starts to execute (the session
199 * state will become IDLE), then rescheduling won't occur.
201 private synchronized void handleHoldTimer() {
202 final long ct = System.nanoTime();
204 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
207 if (ct >= nextHold) {
208 logger.debug("HoldTimer expired. " + new Date());
209 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
211 this.stateTimer.newTimeout(new TimerTask() {
213 public void run(final Timeout timeout) throws Exception {
216 }, nextHold - ct, TimeUnit.NANOSECONDS);
222 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
223 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
224 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
225 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
227 private synchronized void handleKeepaliveTimer() {
228 final long ct = System.nanoTime();
230 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
233 if (ct >= nextKeepalive) {
234 this.sendMessage(new BGPKeepAliveMessage());
235 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
237 this.stateTimer.newTimeout(new TimerTask() {
239 public void run(final Timeout timeout) throws Exception {
240 handleKeepaliveTimer();
242 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
247 final public String toString() {
248 return addToStringAttributes(Objects.toStringHelper(this)).toString();
251 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
252 toStringHelper.add("channel", this.channel);
253 toStringHelper.add("closed", this.closed);
254 return toStringHelper;
258 public Set<BGPTableType> getAdvertisedTableTypes() {
259 return this.tableTypes;
263 protected void sessionUp() {
264 this.listener.onSessionUp(this);