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.rev130919.Keepalive;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.CParameters;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.c.parameters.MultiprotocolCase;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
38 import org.opendaylight.yangtools.yang.binding.Notification;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import com.google.common.annotations.VisibleForTesting;
43 import com.google.common.base.Objects;
44 import com.google.common.base.Objects.ToStringHelper;
45 import com.google.common.base.Preconditions;
46 import com.google.common.collect.Sets;
49 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
51 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
56 private static final int DEFAULT_HOLD_TIMER_VALUE = 15;
58 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
60 private static int holdTimerValue = DEFAULT_HOLD_TIMER_VALUE;
63 * Internal session state.
67 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
68 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
69 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
73 * The session has been completely established.
77 * The session has been closed. It will not be resurrected.
83 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
86 protected long lastMessageSentAt;
89 * System.nanoTime value about when was received the last message
91 private long lastMessageReceivedAt;
93 private final BGPSessionListener listener;
96 * Timer object grouping FSM Timers
98 private final Timer stateTimer;
100 private final BGPSynchronization sync;
102 private int kaCounter = 0;
104 private final Channel channel;
107 private State state = State.OpenConfirm;
109 private final int keepAlive;
111 private final Set<BgpTableType> tableTypes;
113 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final Open remoteOpen) {
114 this.listener = Preconditions.checkNotNull(listener);
115 this.stateTimer = Preconditions.checkNotNull(timer);
116 this.channel = Preconditions.checkNotNull(channel);
117 this.keepAlive = remoteOpen.getHoldTimer() / 3;
118 holdTimerValue = remoteOpen.getHoldTimer();
120 final Set<TablesKey> tts = Sets.newHashSet();
121 final Set<BgpTableType> tats = Sets.newHashSet();
122 if (remoteOpen.getBgpParameters() != null) {
123 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
124 if (param instanceof CParameters) {
125 final CParameters cp = (CParameters) param;
126 final TablesKey tt = new TablesKey(((MultiprotocolCase) cp).getMultiprotocolCapability().getAfi(), ((MultiprotocolCase) cp).getMultiprotocolCapability().getSafi());
128 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
133 this.sync = new BGPSynchronization(this, this.listener, tts);
134 this.tableTypes = tats;
136 if (remoteOpen.getHoldTimer() != 0) {
137 this.stateTimer.newTimeout(new TimerTask() {
140 public void run(final Timeout timeout) throws Exception {
143 }, remoteOpen.getHoldTimer(), TimeUnit.SECONDS);
145 this.stateTimer.newTimeout(new TimerTask() {
147 public void run(final Timeout timeout) throws Exception {
148 handleKeepaliveTimer();
150 }, this.keepAlive, TimeUnit.SECONDS);
155 public synchronized void close() {
156 LOG.debug("Closing session: {}", this);
157 if (this.state != State.Idle) {
158 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).build());
159 this.channel.close();
160 this.state = State.Idle;
165 * Handles incoming message based on their type.
167 * @param msg incoming message
170 public void handleMessage(final Notification msg) {
171 // Update last reception time
172 this.lastMessageReceivedAt = System.nanoTime();
174 if (msg instanceof Open) {
175 // Open messages should not be present here
176 this.terminate(BGPError.FSM_ERROR);
177 } else if (msg instanceof Notify) {
178 // Notifications are handled internally
179 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
180 ((Notify) msg).getErrorSubcode());
181 this.closeWithoutMessage();
182 this.listener.onSessionTerminated(this,
183 new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(), ((Notify) msg).getErrorSubcode())));
184 } else if (msg instanceof Keepalive) {
185 // Keepalives are handled internally
186 LOG.debug("Received KeepAlive messsage.");
188 if (this.kaCounter >= 2) {
189 this.sync.kaReceived();
192 // All others are passed up
193 this.listener.onMessage(this, msg);
198 public synchronized void endOfInput() {
199 if (this.state == State.Up) {
200 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
204 void sendMessage(final Notification msg) {
206 this.channel.writeAndFlush(msg);
207 this.lastMessageSentAt = System.nanoTime();
208 LOG.debug("Sent message: {}", msg);
209 } catch (final Exception e) {
210 LOG.warn("Message {} was not sent.", msg, e);
214 private synchronized void closeWithoutMessage() {
215 LOG.debug("Closing session: {}", this);
216 this.channel.close();
217 this.state = State.Idle;
221 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
222 * modified, because he initiated the closing. (To prevent concurrent modification exception).
226 private void terminate(final BGPError error) {
227 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
228 this.closeWithoutMessage();
230 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
234 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
235 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
236 * which the message was received. If the session was closed by the time this method starts to execute (the session
237 * state will become IDLE), then rescheduling won't occur.
239 private synchronized void handleHoldTimer() {
240 if (this.state == State.Idle) {
244 final long ct = System.nanoTime();
245 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(holdTimerValue);
247 if (ct >= nextHold) {
248 LOG.debug("HoldTimer expired. " + new Date());
249 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
251 this.stateTimer.newTimeout(new TimerTask() {
253 public void run(final Timeout timeout) throws Exception {
256 }, nextHold - ct, TimeUnit.NANOSECONDS);
261 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
262 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
263 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
264 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
266 private synchronized void handleKeepaliveTimer() {
267 if (this.state == State.Idle) {
271 final long ct = System.nanoTime();
272 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
274 if (ct >= nextKeepalive) {
275 this.sendMessage(KEEP_ALIVE);
276 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
278 this.stateTimer.newTimeout(new TimerTask() {
280 public void run(final Timeout timeout) throws Exception {
281 handleKeepaliveTimer();
283 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
287 public final String toString() {
288 return addToStringAttributes(Objects.toStringHelper(this)).toString();
291 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
292 toStringHelper.add("channel", this.channel);
293 toStringHelper.add("state", this.state);
294 return toStringHelper;
298 public Set<BgpTableType> getAdvertisedTableTypes() {
299 return this.tableTypes;
303 protected synchronized void sessionUp() {
304 this.state = State.Up;
305 this.listener.onSessionUp(this);
308 public synchronized State getState() {