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;
16 import io.netty.channel.Channel;
18 import java.io.IOException;
19 import java.util.Date;
21 import java.util.concurrent.TimeUnit;
23 import javax.annotation.concurrent.GuardedBy;
25 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
26 import org.opendaylight.protocol.bgp.parser.BGPError;
27 import org.opendaylight.protocol.bgp.parser.BGPSession;
28 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
29 import org.opendaylight.protocol.bgp.parser.BGPTerminationReason;
30 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
31 import org.opendaylight.protocol.framework.AbstractProtocolSession;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.CParameters;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.c.parameters.MultiprotocolCase;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
45 import org.opendaylight.yangtools.yang.binding.Notification;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 public class BGPSessionImpl extends AbstractProtocolSession<Notification> implements BGPSession {
52 private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
54 private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
57 * Internal session state.
61 * The session object is created by the negotiator in OpenConfirm state. While in this state, the session object
62 * is half-alive, e.g. the timers are running, but the session is not completely up, e.g. it has not been
63 * announced to the listener. If the session is torn down in this state, we do not inform the listener.
67 * The session has been completely established.
71 * The session has been closed. It will not be resurrected.
77 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
80 protected long lastMessageSentAt;
83 * System.nanoTime value about when was received the last message
85 private long lastMessageReceivedAt;
87 private final BGPSessionListener listener;
89 private final BGPSynchronization sync;
91 private int kaCounter = 0;
93 private final Channel channel;
96 private State state = State.OpenConfirm;
98 private final Set<BgpTableType> tableTypes;
99 private final int holdTimerValue;
100 private final int keepAlive;
101 private final AsNumber asNumber;
102 private final Ipv4Address bgpId;
104 public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer) {
105 this.listener = Preconditions.checkNotNull(listener);
106 this.channel = Preconditions.checkNotNull(channel);
107 this.holdTimerValue = (remoteOpen.getHoldTimer() < localHoldTimer) ? remoteOpen.getHoldTimer() : localHoldTimer;
108 LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
109 this.keepAlive = this.holdTimerValue / 3;
110 this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
112 final Set<TablesKey> tts = Sets.newHashSet();
113 final Set<BgpTableType> tats = Sets.newHashSet();
114 if (remoteOpen.getBgpParameters() != null) {
115 for (final BgpParameters param : remoteOpen.getBgpParameters()) {
116 final CParameters cp = param.getCParameters();
117 if (cp instanceof MultiprotocolCase) {
118 final TablesKey tt = new TablesKey(((MultiprotocolCase) cp).getMultiprotocolCapability().getAfi(), ((MultiprotocolCase) cp).getMultiprotocolCapability().getSafi());
119 LOG.trace("Added table type to sync {}", tt);
121 tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
126 this.sync = new BGPSynchronization(this, this.listener, tts);
127 this.tableTypes = tats;
129 if (this.holdTimerValue != 0) {
130 channel.eventLoop().schedule(new Runnable() {
135 }, this.holdTimerValue, TimeUnit.SECONDS);
137 channel.eventLoop().schedule(new Runnable() {
140 handleKeepaliveTimer();
142 }, this.keepAlive, TimeUnit.SECONDS);
144 this.bgpId = remoteOpen.getBgpIdentifier();
148 public synchronized void close() {
149 LOG.info("Closing session: {}", this);
150 if (this.state != State.Idle) {
151 this.sendMessage(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).build());
152 this.channel.close();
153 this.state = State.Idle;
158 * Handles incoming message based on their type.
160 * @param msg incoming message
163 public void handleMessage(final Notification msg) {
164 // Update last reception time
165 this.lastMessageReceivedAt = System.nanoTime();
167 if (msg instanceof Open) {
168 // Open messages should not be present here
169 this.terminate(BGPError.FSM_ERROR);
170 } else if (msg instanceof Notify) {
171 // Notifications are handled internally
172 LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
173 ((Notify) msg).getErrorSubcode());
174 this.closeWithoutMessage();
175 this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
176 ((Notify) msg).getErrorSubcode())));
177 } else if (msg instanceof Keepalive) {
178 // Keepalives are handled internally
179 LOG.trace("Received KeepAlive messsage.");
181 if (this.kaCounter >= 2) {
182 this.sync.kaReceived();
185 // All others are passed up
186 this.listener.onMessage(this, msg);
187 this.sync.updReceived((Update) msg);
192 public synchronized void endOfInput() {
193 if (this.state == State.Up) {
194 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
198 void sendMessage(final Notification msg) {
200 this.channel.writeAndFlush(msg);
201 this.lastMessageSentAt = System.nanoTime();
202 LOG.debug("Sent message: {}", msg);
203 } catch (final Exception e) {
204 LOG.warn("Message {} was not sent.", msg, e);
208 private synchronized void closeWithoutMessage() {
209 LOG.debug("Closing session: {}", this);
210 this.channel.close();
211 this.state = State.Idle;
215 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
216 * modified, because he initiated the closing. (To prevent concurrent modification exception).
220 private void terminate(final BGPError error) {
221 this.sendMessage(new NotifyBuilder().setErrorCode(error.getCode()).setErrorSubcode(error.getSubcode()).build());
222 this.closeWithoutMessage();
224 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
228 * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
229 * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
230 * which the message was received. If the session was closed by the time this method starts to execute (the session
231 * state will become IDLE), then rescheduling won't occur.
233 private synchronized void handleHoldTimer() {
234 if (this.state == State.Idle) {
238 final long ct = System.nanoTime();
239 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
241 if (ct >= nextHold) {
242 LOG.debug("HoldTimer expired. {}", new Date());
243 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
245 this.channel.eventLoop().schedule(new Runnable() {
250 }, nextHold - ct, TimeUnit.NANOSECONDS);
255 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
256 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
257 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
258 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
260 private synchronized void handleKeepaliveTimer() {
261 if (this.state == State.Idle) {
265 final long ct = System.nanoTime();
266 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
268 if (ct >= nextKeepalive) {
269 this.sendMessage(KEEP_ALIVE);
270 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
272 this.channel.eventLoop().schedule(new Runnable() {
275 handleKeepaliveTimer();
277 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
281 public final String toString() {
282 return addToStringAttributes(Objects.toStringHelper(this)).toString();
285 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
286 toStringHelper.add("channel", this.channel);
287 toStringHelper.add("state", this.state);
288 return toStringHelper;
292 public Set<BgpTableType> getAdvertisedTableTypes() {
293 return this.tableTypes;
297 protected synchronized void sessionUp() {
298 this.state = State.Up;
299 this.listener.onSessionUp(this);
302 public synchronized State getState() {
307 public final Ipv4Address getBgpId() {
312 public final AsNumber getAsNumber() {
313 return this.asNumber;