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.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Sets;
16 import io.netty.channel.Channel;
17 import io.netty.channel.ChannelFuture;
18 import io.netty.channel.ChannelFutureListener;
19 import java.io.IOException;
20 import java.util.Date;
22 import java.util.concurrent.TimeUnit;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
25 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
26 import org.opendaylight.protocol.bgp.parser.BGPError;
27 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
28 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
29 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
30 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
31 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
32 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
33 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
34 import org.opendaylight.protocol.framework.AbstractProtocolSession;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.OptionalCapabilities;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.optional.capabilities.CParameters;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCase;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
49 import org.opendaylight.yangtools.yang.binding.Notification;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession, BGPSessionStatistics {
56 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
58 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
60 private static final int KA_TO_DEADTIMER_RATIO = 3;
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.
86 private long lastMessageSentAt;
89 * System.nanoTime value about when was received the last message
91 private long lastMessageReceivedAt;
93 private final BGPSessionListener listener;
95 private final BGPSynchronization sync;
97 private int kaCounter = 0;
99 private final Channel channel;
102 private State state = State.OPEN_CONFIRM;
104 private final Set<BgpTableType> tableTypes;
105 private final int holdTimerValue;
106 private final int keepAlive;
107 private final AsNumber asNumber;
108 private final Ipv4Address bgpId;
109 private final BGPPeerRegistry peerRegistry;
111 private BGPSessionStats sessionStats;
113 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences,
114 final BGPPeerRegistry peerRegitry) {
115 this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegitry);
116 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes);
119 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer,
120 final BGPPeerRegistry peerRegitry) {
121 this.listener = Preconditions.checkNotNull(listener);
122 this.channel = Preconditions.checkNotNull(channel);
123 this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
124 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
125 this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
126 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
127 this.peerRegistry = peerRegitry;
129 final Set<TablesKey> tts = Sets.newHashSet();
130 final Set<BgpTableType> tats = Sets.newHashSet();
131 if (remoteOpen.getBgpParameters() != null) {
132 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
133 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
134 final CParameters cp = optCapa.getCParameters();
135 if (cp instanceof MultiprotocolCase) {
136 final TablesKey tt = new TablesKey(((MultiprotocolCase) cp).getMultiprotocolCapability().getAfi(),
137 ((MultiprotocolCase) cp).getMultiprotocolCapability().getSafi());
138 LOG.trace("Added table type to sync {}", tt);
140 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
146 this.sync = new BGPSynchronization(this, this.listener, tts);
147 this.tableTypes = tats;
149 if (this.holdTimerValue != 0) {
150 channel.eventLoop().schedule(new Runnable() {
155 }, this.holdTimerValue, TimeUnit.SECONDS);
157 channel.eventLoop().schedule(new Runnable() {
160 handleKeepaliveTimer();
162 }, this.keepAlive, TimeUnit.SECONDS);
164 this.bgpId = remoteOpen.getBgpIdentifier();
165 this.sessionStats = new BGPSessionStats(remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.<BGPSessionPreferences>absent(),
170 public synchronized void close() {
171 LOG.info("Closing session: {}", this);
173 if (this.state != State.IDLE) {
174 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(
175 BGPError.CEASE.getSubcode()).build());
177 this.channel.close();
178 this.state = State.IDLE;
183 * Handles incoming message based on their type.
185 * @param msg incoming message
188 public synchronized void handleMessage(final Notification msg) {
189 // Update last reception time
190 this.lastMessageReceivedAt = System.nanoTime();
191 this.sessionStats.updateReceivedMsgTotal();
193 if (msg instanceof Open) {
194 // Open messages should not be present here
195 this.terminate(BGPError.FSM_ERROR);
196 } else if (msg instanceof Notify) {
197 // Notifications are handled internally
198 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
199 ((Notify) msg).getErrorSubcode());
200 this.closeWithoutMessage();
201 this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
202 ((Notify) msg).getErrorSubcode())));
203 this.sessionStats.updateReceivedMsgErr((Notify) msg);
204 } else if (msg instanceof Keepalive) {
205 // Keepalives are handled internally
206 LOG.trace("Received KeepAlive messsage.");
208 this.sessionStats.updateReceivedMsgKA();
209 if (this.kaCounter >= 2) {
210 this.sync.kaReceived();
213 // All others are passed up
214 this.listener.onMessage(this, msg);
215 this.sync.updReceived((Update) msg);
216 this.sessionStats.updateReceivedMsgUpd();
221 public synchronized void endOfInput() {
222 if (this.state == State.UP) {
223 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
227 synchronized void sendMessage(final Notification msg) {
229 this.channel.writeAndFlush(msg).addListener(
230 new ChannelFutureListener() {
232 public void operationComplete(final ChannelFuture f) {
233 if (!f.isSuccess()) {
234 LOG.info("Failed to send message {} to socket {}", msg, f.cause(), BGPSessionImpl.this.channel);
236 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
240 this.lastMessageSentAt = System.nanoTime();
241 this.sessionStats.updateSentMsgTotal();
242 if (msg instanceof Update) {
243 this.sessionStats.updateSentMsgUpd();
244 } else if (msg instanceof Notify) {
245 this.sessionStats.updateSentMsgErr((Notify) msg);
247 } catch (final Exception e) {
248 LOG.warn("Message {} was not sent.", msg, e);
252 private synchronized void closeWithoutMessage() {
253 LOG.debug("Closing session: {}", this);
255 this.channel.close();
256 this.state = State.IDLE;
260 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
261 * modified, because he initiated the closing. (To prevent concurrent modification exception).
265 private void terminate(final BGPError error) {
266 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
267 this.closeWithoutMessage();
269 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
272 private void removePeerSession() {
273 if (this.peerRegistry != null) {
274 this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
279 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
280 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
281 * which the message was received. If the session was closed by the time this method starts to execute (the session
282 * state will become IDLE), then rescheduling won't occur.
284 private synchronized void handleHoldTimer() {
285 if (this.state == State.IDLE) {
289 final long ct = System.nanoTime();
290 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
292 if (ct >= nextHold) {
293 LOG.debug("HoldTimer expired. {}", new Date());
294 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
296 this.channel.eventLoop().schedule(new Runnable() {
301 }, nextHold - ct, TimeUnit.NANOSECONDS);
306 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
307 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
308 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
309 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
311 private synchronized void handleKeepaliveTimer() {
312 if (this.state == State.IDLE) {
316 final long ct = System.nanoTime();
317 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
319 if (ct >= nextKeepalive) {
320 this.sendMessage(KEEP_ALIVE);
321 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
322 this.sessionStats.updateSentMsgKA();
324 this.channel.eventLoop().schedule(new Runnable() {
327 handleKeepaliveTimer();
329 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
333 public final String toString() {
334 return addToStringAttributes(Objects.toStringHelper(this)).toString();
337 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
338 toStringHelper.add("channel", this.channel);
339 toStringHelper.add("state", this.getState());
340 return toStringHelper;
344 public Set<BgpTableType> getAdvertisedTableTypes() {
345 return this.tableTypes;
349 protected synchronized void sessionUp() {
350 this.sessionStats.startSessionStopwatch();
351 this.state = State.UP;
352 this.listener.onSessionUp(this);
355 public synchronized State getState() {
360 public final Ipv4Address getBgpId() {
365 public final AsNumber getAsNumber() {
366 return this.asNumber;
369 synchronized boolean isWritable() {
370 return this.channel != null && this.channel.isWritable();
373 void schedule(final Runnable task) {
374 Preconditions.checkState(this.channel != null);
375 this.channel.eventLoop().submit(task);
379 protected synchronized void setLastMessageSentAt(final long lastMessageSentAt) {
380 this.lastMessageSentAt = lastMessageSentAt;
384 public synchronized BgpSessionState getBgpSesionState() {
385 return this.sessionStats.getBgpSessionState(this.state);
389 public synchronized void resetSessionStats() {
390 this.sessionStats.resetStats();