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.BGPSession;
24 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
25 import org.opendaylight.protocol.bgp.parser.BGPTableType;
26 import org.opendaylight.protocol.bgp.parser.BGPTerminationReason;
27 import org.opendaylight.protocol.framework.AbstractProtocolSession;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Keepalive;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.KeepaliveBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Notify;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.NotifyBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.Open;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.open.BgpParameters;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130918.open.bgp.parameters.CParameters;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130918.open.bgp.parameters.c.parameters.CMultiprotocol;
36 import org.opendaylight.yangtools.yang.binding.Notification;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
40 import com.google.common.annotations.VisibleForTesting;
41 import com.google.common.base.Objects;
42 import com.google.common.base.Objects.ToStringHelper;
43 import com.google.common.base.Preconditions;
44 import com.google.common.collect.Sets;
47 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
49 private static final Logger logger = LoggerFactory.getLogger(BGPSessionImpl.class);
51 private static final int DEFAULT_HOLD_TIMER_VALUE = 15;
53 private static final Notification keepalive = new KeepaliveBuilder().build();
55 public static int HOLD_TIMER_VALUE = DEFAULT_HOLD_TIMER_VALUE; // 240
58 * Internal session state.
62 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
63 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
64 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
68 * The session has been completely established.
72 * The session has been closed. It will not be resurrected.
78 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
80 protected long lastMessageSentAt;
83 * System.nanoTime value about when was received the last message
85 private long lastMessageReceivedAt;
87 private final BGPSessionListener listener;
90 * Timer object grouping FSM Timers
92 private final Timer stateTimer;
94 private final BGPSynchronization sync;
96 private int kaCounter = 0;
98 private final Channel channel;
101 private State state = State.OpenConfirm;
103 private final int keepAlive;
105 private final Set<BGPTableType> tableTypes;
107 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final Open remoteOpen) {
108 this.listener = Preconditions.checkNotNull(listener);
109 this.stateTimer = Preconditions.checkNotNull(timer);
110 this.channel = Preconditions.checkNotNull(channel);
111 this.keepAlive = remoteOpen.getHoldTimer() / 3;
113 final Set<BGPTableType> tts = Sets.newHashSet();
114 if (remoteOpen.getBgpParameters() != null) {
115 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
116 if (param instanceof CParameters) {
117 final CParameters cp = (CParameters) param;
118 final BGPTableType tt = new BGPTableType(((CMultiprotocol) cp).getMultiprotocolCapability().getAfi(), ((CMultiprotocol) cp).getMultiprotocolCapability().getSafi());
124 this.sync = new BGPSynchronization(this, this.listener, tts);
125 this.tableTypes = tts;
127 if (remoteOpen.getHoldTimer() != 0) {
128 this.stateTimer.newTimeout(new TimerTask() {
131 public void run(final Timeout timeout) throws Exception {
134 }, remoteOpen.getHoldTimer(), TimeUnit.SECONDS);
136 this.stateTimer.newTimeout(new TimerTask() {
138 public void run(final Timeout timeout) throws Exception {
139 handleKeepaliveTimer();
141 }, this.keepAlive, TimeUnit.SECONDS);
146 public synchronized void close() {
147 logger.debug("Closing session: {}", this);
148 if (this.state != State.Idle) {
149 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).build());
150 this.channel.close();
151 this.state = State.Idle;
156 * Handles incoming message based on their type.
158 * @param msg incoming message
161 public void handleMessage(final Notification msg) {
162 // Update last reception time
163 this.lastMessageReceivedAt = System.nanoTime();
165 if (msg instanceof Open) {
166 // Open messages should not be present here
167 this.terminate(BGPError.FSM_ERROR);
168 } else if (msg instanceof Notify) {
169 // Notifications are handled internally
170 logger.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
171 ((Notify) msg).getErrorSubcode());
172 this.closeWithoutMessage();
173 this.listener.onSessionTerminated(this,
174 new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(), ((Notify) msg).getErrorSubcode())));
175 } else if (msg instanceof Keepalive) {
176 // Keepalives are handled internally
177 logger.debug("Received KeepAlive messsage.");
179 if (this.kaCounter >= 2) {
180 this.sync.kaReceived();
183 // All others are passed up
184 this.listener.onMessage(this, msg);
189 public synchronized void endOfInput() {
190 if (this.state == State.Up) {
191 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
195 void sendMessage(final Notification msg) {
197 this.channel.writeAndFlush(msg);
198 this.lastMessageSentAt = System.nanoTime();
199 logger.debug("Sent message: {}", msg);
200 } catch (final Exception e) {
201 logger.warn("Message {} was not sent.", msg, e);
205 private synchronized void closeWithoutMessage() {
206 logger.debug("Closing session: {}", this);
207 this.channel.close();
208 this.state = State.Idle;
212 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
213 * modified, because he initiated the closing. (To prevent concurrent modification exception).
217 private void terminate(final BGPError error) {
218 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
219 this.closeWithoutMessage();
221 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
225 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
226 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
227 * which the message was received. If the session was closed by the time this method starts to execute (the session
228 * state will become IDLE), then rescheduling won't occur.
230 private synchronized void handleHoldTimer() {
231 if (this.state == State.Idle) {
235 final long ct = System.nanoTime();
236 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
238 if (ct >= nextHold) {
239 logger.debug("HoldTimer expired. " + new Date());
240 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
242 this.stateTimer.newTimeout(new TimerTask() {
244 public void run(final Timeout timeout) throws Exception {
247 }, nextHold - ct, TimeUnit.NANOSECONDS);
252 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
253 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
254 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
255 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
257 private synchronized void handleKeepaliveTimer() {
258 if (this.state == State.Idle) {
262 final long ct = System.nanoTime();
263 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
265 if (ct >= nextKeepalive) {
266 this.sendMessage(keepalive);
267 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
269 this.stateTimer.newTimeout(new TimerTask() {
271 public void run(final Timeout timeout) throws Exception {
272 handleKeepaliveTimer();
274 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
278 final public String toString() {
279 return addToStringAttributes(Objects.toStringHelper(this)).toString();
282 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
283 toStringHelper.add("channel", this.channel);
284 toStringHelper.add("state", this.state);
285 return toStringHelper;
289 public Set<BGPTableType> getAdvertisedTableTypes() {
290 return this.tableTypes;
294 protected synchronized void sessionUp() {
295 this.state = State.Up;
296 this.listener.onSessionUp(this);
299 public synchronized State getState() {