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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Objects.ToStringHelper;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.Sets;
15 import io.netty.channel.Channel;
16 import java.io.IOException;
17 import java.util.Date;
19 import java.util.concurrent.TimeUnit;
20 import javax.annotation.concurrent.GuardedBy;
21 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
22 import org.opendaylight.protocol.bgp.parser.BGPError;
23 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
24 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
25 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
26 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
27 import org.opendaylight.protocol.framework.AbstractProtocolSession;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.CParameters;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.c.parameters.MultiprotocolCase;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
41 import org.opendaylight.yangtools.yang.binding.Notification;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
48 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
50 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
53 * Internal session state.
57 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
58 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
59 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
63 * The session has been completely established.
67 * The session has been closed. It will not be resurrected.
73 * System.nanoTime value about when was sent the last message.
76 private long lastMessageSentAt;
79 * System.nanoTime value about when was received the last message
81 private long lastMessageReceivedAt;
83 private final BGPSessionListener listener;
85 private final BGPSynchronization sync;
87 private int kaCounter = 0;
89 private final Channel channel;
92 private State state = State.OpenConfirm;
94 private final Set<BgpTableType> tableTypes;
95 private final int holdTimerValue;
96 private final int keepAlive;
97 private final AsNumber asNumber;
98 private final Ipv4Address bgpId;
100 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer) {
101 this.listener = Preconditions.checkNotNull(listener);
102 this.channel = Preconditions.checkNotNull(channel);
103 this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
104 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
105 this.keepAlive = this.holdTimerValue / 3;
106 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
108 final Set<TablesKey> tts = Sets.newHashSet();
109 final Set<BgpTableType> tats = Sets.newHashSet();
110 if (remoteOpen.getBgpParameters() != null) {
111 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
112 final CParameters cp = param.getCParameters();
113 if (cp instanceof MultiprotocolCase) {
114 final TablesKey tt = new TablesKey(((MultiprotocolCase) cp).getMultiprotocolCapability().getAfi(), ((MultiprotocolCase) cp).getMultiprotocolCapability().getSafi());
115 LOG.trace("Added table type to sync {}", tt);
117 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
122 this.sync = new BGPSynchronization(this, this.listener, tts);
123 this.tableTypes = tats;
125 if (this.holdTimerValue != 0) {
126 channel.eventLoop().schedule(new Runnable() {
131 }, this.holdTimerValue, TimeUnit.SECONDS);
133 channel.eventLoop().schedule(new Runnable() {
136 handleKeepaliveTimer();
138 }, this.keepAlive, TimeUnit.SECONDS);
140 this.bgpId = remoteOpen.getBgpIdentifier();
144 public synchronized void close() {
145 LOG.info("Closing session: {}", this);
146 if (this.state != State.Idle) {
147 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).build());
148 this.channel.close();
149 this.state = State.Idle;
154 * Handles incoming message based on their type.
156 * @param msg incoming message
159 public synchronized void handleMessage(final Notification msg) {
160 // Update last reception time
161 this.lastMessageReceivedAt = System.nanoTime();
163 if (msg instanceof Open) {
164 // Open messages should not be present here
165 this.terminate(BGPError.FSM_ERROR);
166 } else if (msg instanceof Notify) {
167 // Notifications are handled internally
168 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
169 ((Notify) msg).getErrorSubcode());
170 this.closeWithoutMessage();
171 this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
172 ((Notify) msg).getErrorSubcode())));
173 } else if (msg instanceof Keepalive) {
174 // Keepalives are handled internally
175 LOG.trace("Received KeepAlive messsage.");
177 if (this.kaCounter >= 2) {
178 this.sync.kaReceived();
181 // All others are passed up
182 this.listener.onMessage(this, msg);
183 this.sync.updReceived((Update) msg);
188 public synchronized void endOfInput() {
189 if (this.state == State.Up) {
190 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
194 synchronized void sendMessage(final Notification msg) {
196 this.channel.writeAndFlush(msg);
197 this.lastMessageSentAt = System.nanoTime();
198 LOG.debug("Sent message: {}", msg);
199 } catch (final Exception e) {
200 LOG.warn("Message {} was not sent.", msg, e);
204 private synchronized void closeWithoutMessage() {
205 LOG.debug("Closing session: {}", this);
206 this.channel.close();
207 this.state = State.Idle;
211 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
212 * modified, because he initiated the closing. (To prevent concurrent modification exception).
216 private void terminate(final BGPError error) {
217 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
218 this.closeWithoutMessage();
220 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
224 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
225 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
226 * which the message was received. If the session was closed by the time this method starts to execute (the session
227 * state will become IDLE), then rescheduling won't occur.
229 private synchronized void handleHoldTimer() {
230 if (this.state == State.Idle) {
234 final long ct = System.nanoTime();
235 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
237 if (ct >= nextHold) {
238 LOG.debug("HoldTimer expired. {}", new Date());
239 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
241 this.channel.eventLoop().schedule(new Runnable() {
246 }, nextHold - ct, TimeUnit.NANOSECONDS);
251 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
252 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
253 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
254 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
256 private synchronized void handleKeepaliveTimer() {
257 if (this.state == State.Idle) {
261 final long ct = System.nanoTime();
262 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
264 if (ct >= nextKeepalive) {
265 this.sendMessage(KEEP_ALIVE);
266 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
268 this.channel.eventLoop().schedule(new Runnable() {
271 handleKeepaliveTimer();
273 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
277 public final String toString() {
278 return addToStringAttributes(Objects.toStringHelper(this)).toString();
281 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
282 toStringHelper.add("channel", this.channel);
283 toStringHelper.add("state", this.getState());
284 return toStringHelper;
288 public Set<BgpTableType> getAdvertisedTableTypes() {
289 return this.tableTypes;
293 protected synchronized void sessionUp() {
294 this.state = State.Up;
295 this.listener.onSessionUp(this);
298 public synchronized State getState() {
303 public final Ipv4Address getBgpId() {
308 public final AsNumber getAsNumber() {
309 return this.asNumber;
312 synchronized boolean isWritable() {
313 return channel != null && channel.isWritable();
316 synchronized void schedule(final Runnable task) {
317 Preconditions.checkState(channel != null);
318 channel.eventLoop().submit(task);
323 protected void setLastMessageSentAt(final long lastMessageSentAt) {
324 this.lastMessageSentAt = lastMessageSentAt;