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.BGPTerminationReason;
26 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
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.BgpTableType;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130918.open.bgp.parameters.c.parameters.CMultiprotocol;
37 import org.opendaylight.yangtools.yang.binding.Notification;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 import com.google.common.annotations.VisibleForTesting;
42 import com.google.common.base.Objects;
43 import com.google.common.base.Objects.ToStringHelper;
44 import com.google.common.base.Preconditions;
45 import com.google.common.collect.Sets;
48 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
50 private static final Logger logger = LoggerFactory.getLogger(BGPSessionImpl.class);
52 private static final int DEFAULT_HOLD_TIMER_VALUE = 15;
54 private static final Notification keepalive = new KeepaliveBuilder().build();
56 public static int HOLD_TIMER_VALUE = DEFAULT_HOLD_TIMER_VALUE; // 240
59 * Internal session state.
63 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
64 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
65 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
69 * The session has been completely established.
73 * The session has been closed. It will not be resurrected.
79 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
81 protected long lastMessageSentAt;
84 * System.nanoTime value about when was received the last message
86 private long lastMessageReceivedAt;
88 private final BGPSessionListener listener;
91 * Timer object grouping FSM Timers
93 private final Timer stateTimer;
95 private final BGPSynchronization sync;
97 private int kaCounter = 0;
99 private final Channel channel;
102 private State state = State.OpenConfirm;
104 private final int keepAlive;
106 private final Set<BgpTableType> tableTypes;
108 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final Open remoteOpen) {
109 this.listener = Preconditions.checkNotNull(listener);
110 this.stateTimer = Preconditions.checkNotNull(timer);
111 this.channel = Preconditions.checkNotNull(channel);
112 this.keepAlive = remoteOpen.getHoldTimer() / 3;
114 final Set<BgpTableType> tts = Sets.newHashSet();
115 if (remoteOpen.getBgpParameters() != null) {
116 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
117 if (param instanceof CParameters) {
118 final CParameters cp = (CParameters) param;
119 final BgpTableType tt = new BgpTableTypeImpl(((CMultiprotocol) cp).getMultiprotocolCapability().getAfi(), ((CMultiprotocol) cp).getMultiprotocolCapability().getSafi());
125 this.sync = new BGPSynchronization(this, this.listener, tts);
126 this.tableTypes = tts;
128 if (remoteOpen.getHoldTimer() != 0) {
129 this.stateTimer.newTimeout(new TimerTask() {
132 public void run(final Timeout timeout) throws Exception {
135 }, remoteOpen.getHoldTimer(), TimeUnit.SECONDS);
137 this.stateTimer.newTimeout(new TimerTask() {
139 public void run(final Timeout timeout) throws Exception {
140 handleKeepaliveTimer();
142 }, this.keepAlive, TimeUnit.SECONDS);
147 public synchronized void close() {
148 logger.debug("Closing session: {}", this);
149 if (this.state != State.Idle) {
150 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).build());
151 this.channel.close();
152 this.state = State.Idle;
157 * Handles incoming message based on their type.
159 * @param msg incoming message
162 public void handleMessage(final Notification msg) {
163 // Update last reception time
164 this.lastMessageReceivedAt = System.nanoTime();
166 if (msg instanceof Open) {
167 // Open messages should not be present here
168 this.terminate(BGPError.FSM_ERROR);
169 } else if (msg instanceof Notify) {
170 // Notifications are handled internally
171 logger.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
172 ((Notify) msg).getErrorSubcode());
173 this.closeWithoutMessage();
174 this.listener.onSessionTerminated(this,
175 new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(), ((Notify) msg).getErrorSubcode())));
176 } else if (msg instanceof Keepalive) {
177 // Keepalives are handled internally
178 logger.debug("Received KeepAlive messsage.");
180 if (this.kaCounter >= 2) {
181 this.sync.kaReceived();
184 // All others are passed up
185 this.listener.onMessage(this, msg);
190 public synchronized void endOfInput() {
191 if (this.state == State.Up) {
192 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
196 void sendMessage(final Notification msg) {
198 this.channel.writeAndFlush(msg);
199 this.lastMessageSentAt = System.nanoTime();
200 logger.debug("Sent message: {}", msg);
201 } catch (final Exception e) {
202 logger.warn("Message {} was not sent.", msg, e);
206 private synchronized void closeWithoutMessage() {
207 logger.debug("Closing session: {}", this);
208 this.channel.close();
209 this.state = State.Idle;
213 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
214 * modified, because he initiated the closing. (To prevent concurrent modification exception).
218 private void terminate(final BGPError error) {
219 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
220 this.closeWithoutMessage();
222 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
226 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
227 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
228 * which the message was received. If the session was closed by the time this method starts to execute (the session
229 * state will become IDLE), then rescheduling won't occur.
231 private synchronized void handleHoldTimer() {
232 if (this.state == State.Idle) {
236 final long ct = System.nanoTime();
237 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
239 if (ct >= nextHold) {
240 logger.debug("HoldTimer expired. " + new Date());
241 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
243 this.stateTimer.newTimeout(new TimerTask() {
245 public void run(final Timeout timeout) throws Exception {
248 }, nextHold - ct, TimeUnit.NANOSECONDS);
253 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
254 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
255 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
256 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
258 private synchronized void handleKeepaliveTimer() {
259 if (this.state == State.Idle) {
263 final long ct = System.nanoTime();
264 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
266 if (ct >= nextKeepalive) {
267 this.sendMessage(keepalive);
268 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
270 this.stateTimer.newTimeout(new TimerTask() {
272 public void run(final Timeout timeout) throws Exception {
273 handleKeepaliveTimer();
275 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
279 final public String toString() {
280 return addToStringAttributes(Objects.toStringHelper(this)).toString();
283 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
284 toStringHelper.add("channel", this.channel);
285 toStringHelper.add("state", this.state);
286 return toStringHelper;
290 public Set<BgpTableType> getAdvertisedTableTypes() {
291 return this.tableTypes;
295 protected synchronized void sessionUp() {
296 this.state = State.Up;
297 this.listener.onSessionUp(this);
300 public synchronized State getState() {