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.parser.BGPError;
23 import org.opendaylight.protocol.bgp.parser.BGPParameter;
24 import org.opendaylight.protocol.bgp.parser.BGPSession;
25 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
26 import org.opendaylight.protocol.bgp.parser.BGPTableType;
27 import org.opendaylight.protocol.bgp.parser.BGPTerminationReason;
28 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
29 import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
30 import org.opendaylight.protocol.framework.AbstractProtocolSession;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Keepalive;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.KeepaliveBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Notify;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.NotifyBuilder;
35 import org.opendaylight.yangtools.yang.binding.Notification;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 import com.google.common.annotations.VisibleForTesting;
40 import com.google.common.base.Objects;
41 import com.google.common.base.Objects.ToStringHelper;
42 import com.google.common.base.Preconditions;
43 import com.google.common.collect.Sets;
46 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
48 private static final Logger logger = LoggerFactory.getLogger(BGPSessionImpl.class);
50 private static final int DEFAULT_HOLD_TIMER_VALUE = 15;
52 private static final Notification keepalive = new KeepaliveBuilder().build();
54 public static int HOLD_TIMER_VALUE = DEFAULT_HOLD_TIMER_VALUE; // 240
57 * Internal session state.
61 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
62 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
63 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
67 * The session has been completely established.
71 * The session has been closed. It will not be resurrected.
77 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
79 protected long lastMessageSentAt;
82 * System.nanoTime value about when was received the last message
84 private long lastMessageReceivedAt;
86 private final BGPSessionListener listener;
89 * Timer object grouping FSM Timers
91 private final Timer stateTimer;
93 private final BGPSynchronization sync;
95 private int kaCounter = 0;
97 private final Channel channel;
100 private State state = State.OpenConfirm;
102 private final int keepAlive;
104 private final Set<BGPTableType> tableTypes;
106 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final BGPOpenMessage remoteOpen) {
107 this.listener = Preconditions.checkNotNull(listener);
108 this.stateTimer = Preconditions.checkNotNull(timer);
109 this.channel = Preconditions.checkNotNull(channel);
110 this.keepAlive = remoteOpen.getHoldTime() / 3;
112 final Set<BGPTableType> tts = Sets.newHashSet();
113 if (remoteOpen.getOptParams() != null) {
114 for (final BGPParameter param : remoteOpen.getOptParams()) {
115 if (param instanceof MultiprotocolCapability) {
116 tts.add(((MultiprotocolCapability) param).getTableType());
121 this.sync = new BGPSynchronization(this, this.listener, tts);
122 this.tableTypes = tts;
124 if (remoteOpen.getHoldTime() != 0) {
125 this.stateTimer.newTimeout(new TimerTask() {
128 public void run(final Timeout timeout) throws Exception {
131 }, remoteOpen.getHoldTime(), TimeUnit.SECONDS);
133 this.stateTimer.newTimeout(new TimerTask() {
135 public void run(final Timeout timeout) throws Exception {
136 handleKeepaliveTimer();
138 }, this.keepAlive, TimeUnit.SECONDS);
143 public synchronized void close() {
144 logger.debug("Closing session: {}", this);
145 if (this.state != State.Idle) {
146 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).build());
147 this.channel.close();
148 this.state = State.Idle;
153 * Handles incoming message based on their type.
155 * @param msg incoming message
158 public void handleMessage(final Notification msg) {
159 // Update last reception time
160 this.lastMessageReceivedAt = System.nanoTime();
162 if (msg instanceof BGPOpenMessage) {
163 // Open messages should not be present here
164 this.terminate(BGPError.FSM_ERROR);
165 } else if (msg instanceof Notify) {
166 // Notifications are handled internally
167 logger.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
168 ((Notify) msg).getErrorSubcode());
169 this.closeWithoutMessage();
170 this.listener.onSessionTerminated(this,
171 new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(), ((Notify) msg).getErrorSubcode())));
172 } else if (msg instanceof Keepalive) {
173 // Keepalives are handled internally
174 logger.debug("Received KeepAlive messsage.");
176 if (this.kaCounter >= 2) {
177 this.sync.kaReceived();
180 // All others are passed up
181 this.listener.onMessage(this, msg);
186 public synchronized void endOfInput() {
187 if (this.state == State.Up) {
188 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
192 void sendMessage(final Notification msg) {
194 this.channel.writeAndFlush(msg);
195 this.lastMessageSentAt = System.nanoTime();
196 logger.debug("Sent message: {}", msg);
197 } catch (final Exception e) {
198 logger.warn("Message {} was not sent.", msg, e);
202 private synchronized void closeWithoutMessage() {
203 logger.debug("Closing session: {}", this);
204 this.channel.close();
205 this.state = State.Idle;
209 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
210 * modified, because he initiated the closing. (To prevent concurrent modification exception).
214 private void terminate(final BGPError error) {
215 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
216 this.closeWithoutMessage();
218 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
222 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
223 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
224 * which the message was received. If the session was closed by the time this method starts to execute (the session
225 * state will become IDLE), then rescheduling won't occur.
227 private synchronized void handleHoldTimer() {
228 if (this.state == State.Idle) {
232 final long ct = System.nanoTime();
233 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
235 if (ct >= nextHold) {
236 logger.debug("HoldTimer expired. " + new Date());
237 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
239 this.stateTimer.newTimeout(new TimerTask() {
241 public void run(final Timeout timeout) throws Exception {
244 }, nextHold - ct, TimeUnit.NANOSECONDS);
249 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
250 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
251 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
252 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
254 private synchronized void handleKeepaliveTimer() {
255 if (this.state == State.Idle) {
259 final long ct = System.nanoTime();
260 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
262 if (ct >= nextKeepalive) {
263 this.sendMessage(keepalive);
264 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
266 this.stateTimer.newTimeout(new TimerTask() {
268 public void run(final Timeout timeout) throws Exception {
269 handleKeepaliveTimer();
271 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
275 final public String toString() {
276 return addToStringAttributes(Objects.toStringHelper(this)).toString();
279 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
280 toStringHelper.add("channel", this.channel);
281 toStringHelper.add("state", this.state);
282 return toStringHelper;
286 public Set<BGPTableType> getAdvertisedTableTypes() {
287 return this.tableTypes;
291 protected synchronized void sessionUp() {
292 this.state = State.Up;
293 this.listener.onSessionUp(this);
296 public synchronized State getState() {