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 * Internal session state.
57 * The session object is created by the negotiator in OpenConfirm state.
58 * While in this state, the session object is half-alive, e.g. the timers
59 * are running, but the session is not completely up, e.g. it has not been
60 * announced to the listener. If the session is torn down in this state,
61 * we do not inform the listener.
65 * The session has been completely established.
69 * The session has been closed. It will not be resurrected.
75 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
77 protected long lastMessageSentAt;
80 * System.nanoTime value about when was received the last message
82 private long lastMessageReceivedAt;
84 private final BGPSessionListener listener;
87 * Timer object grouping FSM Timers
89 private final Timer stateTimer;
91 private final BGPSynchronization sync;
93 private int kaCounter = 0;
95 private final Channel channel;
98 private State state = State.OpenConfirm;
100 private final int keepAlive;
102 private final Set<BGPTableType> tableTypes;
104 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final BGPOpenMessage remoteOpen) {
105 this.listener = Preconditions.checkNotNull(listener);
106 this.stateTimer = Preconditions.checkNotNull(timer);
107 this.channel = Preconditions.checkNotNull(channel);
108 this.keepAlive = remoteOpen.getHoldTime() / 3;
110 final Set<BGPTableType> tts = Sets.newHashSet();
111 if (remoteOpen.getOptParams() != null) {
112 for (final BGPParameter param : remoteOpen.getOptParams()) {
113 if (param instanceof MultiprotocolCapability) {
114 tts.add(((MultiprotocolCapability) param).getTableType());
119 this.sync = new BGPSynchronization(this, this.listener, tts);
120 this.tableTypes = tts;
122 if (remoteOpen.getHoldTime() != 0) {
123 this.stateTimer.newTimeout(new TimerTask() {
126 public void run(final Timeout timeout) throws Exception {
129 }, remoteOpen.getHoldTime(), TimeUnit.SECONDS);
131 this.stateTimer.newTimeout(new TimerTask() {
133 public void run(final Timeout timeout) throws Exception {
134 handleKeepaliveTimer();
136 }, this.keepAlive, TimeUnit.SECONDS);
141 public synchronized void close() {
142 logger.debug("Closing session: {}", this);
143 if (this.state != State.Idle) {
144 this.sendMessage(new BGPNotificationMessage(BGPError.CEASE));
145 this.channel.close();
146 this.state = State.Idle;
151 * Handles incoming message based on their type.
153 * @param msg incoming message
156 public void handleMessage(final BGPMessage msg) {
157 // Update last reception time
158 this.lastMessageReceivedAt = System.nanoTime();
160 if (msg instanceof BGPOpenMessage) {
161 // Open messages should not be present here
162 this.terminate(BGPError.FSM_ERROR);
163 } else if (msg instanceof BGPNotificationMessage) {
164 // Notifications are handled internally
165 logger.info("Session closed because Notification message received: {}", ((BGPNotificationMessage) msg).getError());
166 this.closeWithoutMessage();
167 this.listener.onSessionTerminated(this, new BGPTerminationReason(((BGPNotificationMessage) msg).getError()));
168 } else if (msg instanceof BGPKeepAliveMessage) {
169 // Keepalives are handled internally
170 logger.debug("Received KeepAlive messsage.");
172 if (this.kaCounter >= 2) {
173 this.sync.kaReceived();
176 // All others are passed up
177 this.listener.onMessage(this, msg);
182 public synchronized void endOfInput() {
183 if (this.state == State.Up) {
184 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
188 void sendMessage(final BGPMessage msg) {
190 this.channel.writeAndFlush(msg);
191 this.lastMessageSentAt = System.nanoTime();
192 logger.debug("Sent message: {}", msg);
193 } catch (final Exception e) {
194 logger.warn("Message {} was not sent.", msg, e);
198 private synchronized void closeWithoutMessage() {
199 logger.debug("Closing session: {}", this);
200 this.channel.close();
201 this.state = State.Idle;
205 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
206 * modified, because he initiated the closing. (To prevent concurrent modification exception).
210 private void terminate(final BGPError error) {
211 this.sendMessage(new BGPNotificationMessage(error));
212 this.closeWithoutMessage();
214 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
218 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
219 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
220 * which the message was received. If the session was closed by the time this method starts to execute (the session
221 * state will become IDLE), then rescheduling won't occur.
223 private synchronized void handleHoldTimer() {
224 if (this.state == State.Idle) {
228 final long ct = System.nanoTime();
229 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
231 if (ct >= nextHold) {
232 logger.debug("HoldTimer expired. " + new Date());
233 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
235 this.stateTimer.newTimeout(new TimerTask() {
237 public void run(final Timeout timeout) throws Exception {
240 }, nextHold - ct, TimeUnit.NANOSECONDS);
245 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
246 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
247 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
248 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
250 private synchronized void handleKeepaliveTimer() {
251 if (this.state == State.Idle) {
255 final long ct = System.nanoTime();
256 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
258 if (ct >= nextKeepalive) {
259 this.sendMessage(new BGPKeepAliveMessage());
260 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
262 this.stateTimer.newTimeout(new TimerTask() {
264 public void run(final Timeout timeout) throws Exception {
265 handleKeepaliveTimer();
267 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
271 final public String toString() {
272 return addToStringAttributes(Objects.toStringHelper(this)).toString();
275 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
276 toStringHelper.add("channel", this.channel);
277 toStringHelper.add("state", this.state);
278 return toStringHelper;
282 public Set<BGPTableType> getAdvertisedTableTypes() {
283 return this.tableTypes;
287 protected synchronized void sessionUp() {
288 this.state = State.Up;
289 this.listener.onSessionUp(this);
292 public synchronized State getState() {