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.pcep.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.net.InetSocketAddress;
17 import java.util.ArrayList;
18 import java.util.Date;
19 import java.util.LinkedList;
20 import java.util.List;
21 import java.util.Queue;
22 import java.util.concurrent.TimeUnit;
24 import org.opendaylight.protocol.framework.AbstractProtocolSession;
25 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
26 import org.opendaylight.protocol.pcep.PCEPErrors;
27 import org.opendaylight.protocol.pcep.PCEPMessage;
28 import org.opendaylight.protocol.pcep.PCEPSession;
29 import org.opendaylight.protocol.pcep.PCEPSessionListener;
30 import org.opendaylight.protocol.pcep.PCEPTlv;
31 import org.opendaylight.protocol.pcep.message.PCEPCloseMessage;
32 import org.opendaylight.protocol.pcep.message.PCEPErrorMessage;
33 import org.opendaylight.protocol.pcep.message.PCEPKeepAliveMessage;
34 import org.opendaylight.protocol.pcep.message.PCEPOpenMessage;
35 import org.opendaylight.protocol.pcep.object.PCEPCloseObject;
36 import org.opendaylight.protocol.pcep.object.PCEPCloseObject.Reason;
37 import org.opendaylight.protocol.pcep.object.PCEPErrorObject;
38 import org.opendaylight.protocol.pcep.object.PCEPOpenObject;
39 import org.opendaylight.protocol.pcep.tlv.NodeIdentifierTlv;
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;
49 * Implementation of PCEPSession. (Not final for testing.)
52 public class PCEPSessionImpl extends AbstractProtocolSession<PCEPMessage> implements PCEPSession, PCEPSessionRuntimeMXBean {
54 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
56 protected volatile long lastMessageSentAt;
59 * System.nanoTime value about when was received the last message
61 private long lastMessageReceivedAt;
64 * Protected for testing.
66 protected int maxUnknownMessages;
68 protected final Queue<Long> unknownMessagesTimes = new LinkedList<Long>();
70 private final PCEPSessionListener listener;
73 * Open Object with session characteristics that were accepted by another PCE (sent from this session).
75 private final PCEPOpenObject localOpen;
78 * Open Object with session characteristics for this session (sent from another PCE).
80 private final PCEPOpenObject remoteOpen;
82 private static final Logger logger = LoggerFactory.getLogger(PCEPSessionImpl.class);
85 * Timer object grouping FSM Timers
87 private final Timer stateTimer;
89 private int sentMsgCount = 0;
91 private int receivedMsgCount = 0;
93 // True if the listener should not be notified about events
94 private boolean closed = false;
96 private final Channel channel;
98 PCEPSessionImpl(final Timer timer, final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
99 final PCEPOpenObject localOpen, final PCEPOpenObject remoteOpen) {
100 this.listener = Preconditions.checkNotNull(listener);
101 this.stateTimer = Preconditions.checkNotNull(timer);
102 this.channel = Preconditions.checkNotNull(channel);
103 this.localOpen = Preconditions.checkNotNull(localOpen);
104 this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
105 this.lastMessageReceivedAt = System.nanoTime();
107 if (this.maxUnknownMessages != 0) {
108 this.maxUnknownMessages = maxUnknownMessages;
111 if (getDeadTimerValue() != 0) {
112 this.stateTimer.newTimeout(new TimerTask() {
114 public void run(final Timeout timeout) throws Exception {
117 }, getDeadTimerValue(), TimeUnit.SECONDS);
120 if (getKeepAliveTimerValue() != 0) {
121 this.stateTimer.newTimeout(new TimerTask() {
123 public void run(final Timeout timeout) throws Exception {
124 handleKeepaliveTimer();
126 }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
129 logger.debug("Session started.");
133 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
134 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
135 * which the message was received. If the session was closed by the time this method starts to execute (the session
136 * state will become IDLE), that rescheduling won't occur.
138 private synchronized void handleDeadTimer() {
139 final long ct = System.nanoTime();
141 final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
143 if (this.channel.isActive()) {
144 if (ct >= nextDead) {
145 logger.debug("DeadTimer expired. " + new Date());
146 this.terminate(Reason.EXP_DEADTIMER);
148 this.stateTimer.newTimeout(new TimerTask() {
150 public void run(final Timeout timeout) throws Exception {
153 }, nextDead - ct, TimeUnit.NANOSECONDS);
159 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
160 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
161 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
162 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
164 private synchronized void handleKeepaliveTimer() {
165 final long ct = System.nanoTime();
167 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
169 if (this.channel.isActive()) {
170 if (ct >= nextKeepalive) {
171 this.sendMessage(new PCEPKeepAliveMessage());
172 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
175 this.stateTimer.newTimeout(new TimerTask() {
177 public void run(final Timeout timeout) throws Exception {
178 handleKeepaliveTimer();
180 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
185 * Sends message to serialization.
187 * @param msg to be sent
190 public void sendMessage(final PCEPMessage msg) {
192 this.channel.writeAndFlush(msg);
193 this.lastMessageSentAt = System.nanoTime();
194 if (!(msg instanceof PCEPKeepAliveMessage)) {
195 logger.debug("Sent message: " + msg);
198 } catch (final Exception e) {
199 logger.warn("Message {} was not sent.", msg, e);
204 * Closes PCEP session without sending a Close message, as the channel is no longer active.
207 public void close() {
208 logger.trace("Closing session: {}", this);
209 this.channel.close();
213 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
214 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
215 * inside the session or from the listener, therefore the parent of this session should be informed.
218 public synchronized void close(final PCEPCloseObject.Reason reason) {
219 logger.debug("Closing session: {}", this);
221 this.sendMessage(new PCEPCloseMessage(new PCEPCloseObject(reason)));
222 this.channel.close();
225 private synchronized void terminate(final PCEPCloseObject.Reason reason) {
226 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
228 this.sendMessage(new PCEPCloseMessage(new PCEPCloseObject(reason)));
233 public synchronized void endOfInput() {
235 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
240 private void sendErrorMessage(final PCEPErrors value) {
241 this.sendErrorMessage(value, null);
245 * Sends PCEP Error Message with one PCEPError and Open Object.
250 private void sendErrorMessage(final PCEPErrors value, final PCEPOpenObject open) {
251 final PCEPErrorObject error = new PCEPErrorObject(value);
252 final List<PCEPErrorObject> errors = new ArrayList<PCEPErrorObject>();
254 this.sendMessage(new PCEPErrorMessage(open, errors, null));
258 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
259 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
260 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
263 * @param error documented error in RFC5440 or draft
266 public void handleMalformedMessage(final PCEPErrors error) {
267 final long ct = System.nanoTime();
268 this.sendErrorMessage(error);
269 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
270 this.unknownMessagesTimes.add(ct);
271 while (ct - this.unknownMessagesTimes.peek() > 60 * 1E9) {
272 this.unknownMessagesTimes.poll();
274 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
275 this.terminate(Reason.TOO_MANY_UNKNOWN_MSG);
281 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
284 * @param msg incoming message
287 public void handleMessage(final PCEPMessage msg) {
288 // Update last reception time
289 this.lastMessageReceivedAt = System.nanoTime();
290 this.receivedMsgCount++;
292 // Internal message handling. The user does not see these messages
293 if (msg instanceof PCEPKeepAliveMessage) {
294 // Do nothing, the timer has been already reset
295 } else if (msg instanceof PCEPOpenMessage) {
296 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
297 } else if (msg instanceof PCEPCloseMessage) {
299 * Session is up, we are reporting all messages to user. One notable
300 * exception is CLOSE message, which needs to be converted into a
301 * session DOWN event.
305 // This message needs to be handled by the user
306 this.listener.onMessage(this, msg);
311 * @return the sentMsgCount
315 public Integer getSentMsgCount() {
316 return this.sentMsgCount;
320 * @return the receivedMsgCount
324 public Integer getReceivedMsgCount() {
325 return this.receivedMsgCount;
329 public Integer getDeadTimerValue() {
330 return this.remoteOpen.getDeadTimerValue();
334 public Integer getKeepAliveTimerValue() {
335 return this.localOpen.getKeepAliveTimerValue();
339 public String getPeerAddress() {
340 final InetSocketAddress a = (InetSocketAddress) this.channel.remoteAddress();
341 return a.getHostName();
345 public void tearDown() {
350 public String getNodeIdentifier() {
351 for (final PCEPTlv tlv : this.remoteOpen.getTlvs()) {
352 if (tlv instanceof NodeIdentifierTlv) {
353 return tlv.toString();
360 public final String toString() {
361 return addToStringAttributes(Objects.toStringHelper(this)).toString();
364 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
365 toStringHelper.add("localOpen", this.localOpen);
366 toStringHelper.add("remoteOpen", this.remoteOpen);
367 return toStringHelper;
371 protected void sessionUp() {
372 this.listener.onSessionUp(this);