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.Update;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.CParameters;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.c.parameters.MultiprotocolCase;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
39 import org.opendaylight.yangtools.yang.binding.Notification;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 import com.google.common.annotations.VisibleForTesting;
44 import com.google.common.base.Objects;
45 import com.google.common.base.Objects.ToStringHelper;
46 import com.google.common.base.Preconditions;
47 import com.google.common.collect.Sets;
50 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
52 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
57 private static final int DEFAULT_HOLD_TIMER_VALUE = 15;
59 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
61 private static int holdTimerValue = DEFAULT_HOLD_TIMER_VALUE;
64 * Internal session state.
68 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
69 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
70 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
74 * The session has been completely established.
78 * The session has been closed. It will not be resurrected.
84 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
87 protected long lastMessageSentAt;
90 * System.nanoTime value about when was received the last message
92 private long lastMessageReceivedAt;
94 private final BGPSessionListener listener;
97 * Timer object grouping FSM Timers
99 private final Timer stateTimer;
101 private final BGPSynchronization sync;
103 private int kaCounter = 0;
105 private final Channel channel;
108 private State state = State.OpenConfirm;
110 private final int keepAlive;
112 private final Set<BgpTableType> tableTypes;
114 BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final Open remoteOpen) {
115 this.listener = Preconditions.checkNotNull(listener);
116 this.stateTimer = Preconditions.checkNotNull(timer);
117 this.channel = Preconditions.checkNotNull(channel);
118 this.keepAlive = remoteOpen.getHoldTimer() / 3;
119 holdTimerValue = remoteOpen.getHoldTimer();
121 final Set<TablesKey> tts = Sets.newHashSet();
122 final Set<BgpTableType> tats = Sets.newHashSet();
123 if (remoteOpen.getBgpParameters() != null) {
124 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
125 final CParameters cp = param.getCParameters();
126 if (cp instanceof MultiprotocolCase) {
127 final TablesKey tt = new TablesKey(((MultiprotocolCase) cp).getMultiprotocolCapability().getAfi(), ((MultiprotocolCase) cp).getMultiprotocolCapability().getSafi());
128 LOG.trace("Added table type to sync {}", tt);
130 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
135 this.sync = new BGPSynchronization(this, this.listener, tts);
136 this.tableTypes = tats;
138 if (remoteOpen.getHoldTimer() != 0) {
139 this.stateTimer.newTimeout(new TimerTask() {
142 public void run(final Timeout timeout) throws Exception {
145 }, remoteOpen.getHoldTimer(), TimeUnit.SECONDS);
147 this.stateTimer.newTimeout(new TimerTask() {
149 public void run(final Timeout timeout) throws Exception {
150 handleKeepaliveTimer();
152 }, this.keepAlive, TimeUnit.SECONDS);
157 public synchronized void close() {
158 LOG.debug("Closing session: {}", this);
159 if (this.state != State.Idle) {
160 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).build());
161 this.channel.close();
162 this.state = State.Idle;
167 * Handles incoming message based on their type.
169 * @param msg incoming message
172 public void handleMessage(final Notification msg) {
173 // Update last reception time
174 this.lastMessageReceivedAt = System.nanoTime();
176 if (msg instanceof Open) {
177 // Open messages should not be present here
178 this.terminate(BGPError.FSM_ERROR);
179 } else if (msg instanceof Notify) {
180 // Notifications are handled internally
181 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
182 ((Notify) msg).getErrorSubcode());
183 this.closeWithoutMessage();
184 this.listener.onSessionTerminated(this,
185 new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(), ((Notify) msg).getErrorSubcode())));
186 } else if (msg instanceof Keepalive) {
187 // Keepalives are handled internally
188 LOG.debug("Received KeepAlive messsage.");
190 if (this.kaCounter >= 2) {
191 this.sync.kaReceived();
194 // All others are passed up
195 this.listener.onMessage(this, msg);
196 this.sync.updReceived((Update) msg);
201 public synchronized void endOfInput() {
202 if (this.state == State.Up) {
203 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
207 void sendMessage(final Notification msg) {
209 this.channel.writeAndFlush(msg);
210 this.lastMessageSentAt = System.nanoTime();
211 LOG.debug("Sent message: {}", msg);
212 } catch (final Exception e) {
213 LOG.warn("Message {} was not sent.", msg, e);
217 private synchronized void closeWithoutMessage() {
218 LOG.debug("Closing session: {}", this);
219 this.channel.close();
220 this.state = State.Idle;
224 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
225 * modified, because he initiated the closing. (To prevent concurrent modification exception).
229 private void terminate(final BGPError error) {
230 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
231 this.closeWithoutMessage();
233 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
237 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
238 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
239 * which the message was received. If the session was closed by the time this method starts to execute (the session
240 * state will become IDLE), then rescheduling won't occur.
242 private synchronized void handleHoldTimer() {
243 if (this.state == State.Idle) {
247 final long ct = System.nanoTime();
248 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(holdTimerValue);
250 if (ct >= nextHold) {
251 LOG.debug("HoldTimer expired. " + new Date());
252 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
254 this.stateTimer.newTimeout(new TimerTask() {
256 public void run(final Timeout timeout) throws Exception {
259 }, nextHold - ct, TimeUnit.NANOSECONDS);
264 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
265 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
266 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
267 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
269 private synchronized void handleKeepaliveTimer() {
270 if (this.state == State.Idle) {
274 final long ct = System.nanoTime();
275 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
277 if (ct >= nextKeepalive) {
278 this.sendMessage(KEEP_ALIVE);
279 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
281 this.stateTimer.newTimeout(new TimerTask() {
283 public void run(final Timeout timeout) throws Exception {
284 handleKeepaliveTimer();
286 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
290 public final String toString() {
291 return addToStringAttributes(Objects.toStringHelper(this)).toString();
294 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
295 toStringHelper.add("channel", this.channel);
296 toStringHelper.add("state", this.state);
297 return toStringHelper;
301 public Set<BgpTableType> getAdvertisedTableTypes() {
302 return this.tableTypes;
306 protected synchronized void sessionUp() {
307 this.state = State.Up;
308 this.listener.onSessionUp(this);
311 public synchronized State getState() {