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.PCEPSession;
28 import org.opendaylight.protocol.pcep.PCEPSessionListener;
29 import org.opendaylight.protocol.pcep.PCEPTlv;
30 import org.opendaylight.protocol.pcep.message.PCEPCloseMessage;
31 import org.opendaylight.protocol.pcep.message.PCEPErrorMessage;
32 import org.opendaylight.protocol.pcep.message.PCEPOpenMessage;
33 import org.opendaylight.protocol.pcep.object.PCEPCloseObject;
34 import org.opendaylight.protocol.pcep.object.PCEPCloseObject.Reason;
35 import org.opendaylight.protocol.pcep.object.PCEPErrorObject;
36 import org.opendaylight.protocol.pcep.object.PCEPOpenObject;
37 import org.opendaylight.protocol.pcep.tlv.NodeIdentifierTlv;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.KeepaliveMessage;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
44 import com.google.common.annotations.VisibleForTesting;
45 import com.google.common.base.Objects;
46 import com.google.common.base.Objects.ToStringHelper;
47 import com.google.common.base.Preconditions;
50 * Implementation of PCEPSession. (Not final for testing.)
53 public class PCEPSessionImpl extends AbstractProtocolSession<Message> implements PCEPSession, PCEPSessionRuntimeMXBean {
55 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
57 protected volatile long lastMessageSentAt;
60 * System.nanoTime value about when was received the last message
62 private long lastMessageReceivedAt;
65 * Protected for testing.
67 protected int maxUnknownMessages;
69 protected final Queue<Long> unknownMessagesTimes = new LinkedList<Long>();
71 private final PCEPSessionListener listener;
74 * Open Object with session characteristics that were accepted by another PCE (sent from this session).
76 private final PCEPOpenObject localOpen;
79 * Open Object with session characteristics for this session (sent from another PCE).
81 private final PCEPOpenObject remoteOpen;
83 private static final Logger logger = LoggerFactory.getLogger(PCEPSessionImpl.class);
86 * Timer object grouping FSM Timers
88 private final Timer stateTimer;
90 private int sentMsgCount = 0;
92 private int receivedMsgCount = 0;
94 // True if the listener should not be notified about events
95 private boolean closed = false;
97 private final Channel channel;
99 private final KeepaliveMessage kaMessage = (KeepaliveMessage) new KeepaliveMessageBuilder().build();
101 PCEPSessionImpl(final Timer timer, final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
102 final PCEPOpenObject localOpen, final PCEPOpenObject remoteOpen) {
103 this.listener = Preconditions.checkNotNull(listener);
104 this.stateTimer = Preconditions.checkNotNull(timer);
105 this.channel = Preconditions.checkNotNull(channel);
106 this.localOpen = Preconditions.checkNotNull(localOpen);
107 this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
108 this.lastMessageReceivedAt = System.nanoTime();
110 if (this.maxUnknownMessages != 0) {
111 this.maxUnknownMessages = maxUnknownMessages;
114 if (getDeadTimerValue() != 0) {
115 this.stateTimer.newTimeout(new TimerTask() {
117 public void run(final Timeout timeout) throws Exception {
120 }, getDeadTimerValue(), TimeUnit.SECONDS);
123 if (getKeepAliveTimerValue() != 0) {
124 this.stateTimer.newTimeout(new TimerTask() {
126 public void run(final Timeout timeout) throws Exception {
127 handleKeepaliveTimer();
129 }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
132 logger.debug("Session started.");
136 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
137 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
138 * which the message was received. If the session was closed by the time this method starts to execute (the session
139 * state will become IDLE), that rescheduling won't occur.
141 private synchronized void handleDeadTimer() {
142 final long ct = System.nanoTime();
144 final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
146 if (this.channel.isActive()) {
147 if (ct >= nextDead) {
148 logger.debug("DeadTimer expired. " + new Date());
149 this.terminate(Reason.EXP_DEADTIMER);
151 this.stateTimer.newTimeout(new TimerTask() {
153 public void run(final Timeout timeout) throws Exception {
156 }, nextDead - ct, TimeUnit.NANOSECONDS);
162 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
163 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
164 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
165 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
167 private synchronized void handleKeepaliveTimer() {
168 final long ct = System.nanoTime();
170 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
172 if (this.channel.isActive()) {
173 if (ct >= nextKeepalive) {
174 this.sendMessage(this.kaMessage);
175 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
178 this.stateTimer.newTimeout(new TimerTask() {
180 public void run(final Timeout timeout) throws Exception {
181 handleKeepaliveTimer();
183 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
188 * Sends message to serialization.
190 * @param msg to be sent
193 public void sendMessage(final Message msg) {
195 this.channel.writeAndFlush(msg);
196 this.lastMessageSentAt = System.nanoTime();
197 if (!(msg instanceof KeepaliveMessage)) {
198 logger.debug("Sent message: " + msg);
201 } catch (final Exception e) {
202 logger.warn("Message {} was not sent.", msg, e);
207 * Closes PCEP session without sending a Close message, as the channel is no longer active.
210 public void close() {
211 logger.trace("Closing session: {}", this);
212 this.channel.close();
216 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
217 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
218 * inside the session or from the listener, therefore the parent of this session should be informed.
221 public synchronized void close(final PCEPCloseObject.Reason reason) {
222 logger.debug("Closing session: {}", this);
224 // FIXME: just to get rid of compilation errors
225 this.sendMessage((Message) new PCEPCloseMessage(new PCEPCloseObject(reason)));
226 this.channel.close();
229 private synchronized void terminate(final PCEPCloseObject.Reason reason) {
230 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
232 // FIXME: just to get rid of compilation errors
233 this.sendMessage((Message) new PCEPCloseMessage(new PCEPCloseObject(reason)));
238 public synchronized void endOfInput() {
240 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
245 private void sendErrorMessage(final PCEPErrors value) {
246 this.sendErrorMessage(value, null);
250 * Sends PCEP Error Message with one PCEPError and Open Object.
255 private void sendErrorMessage(final PCEPErrors value, final PCEPOpenObject open) {
256 final PCEPErrorObject error = new PCEPErrorObject(value);
257 final List<PCEPErrorObject> errors = new ArrayList<PCEPErrorObject>();
259 // FIXME: just to get rid of compilation errors
260 this.sendMessage((Message) new PCEPErrorMessage(open, errors, null));
264 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
265 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
266 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
269 * @param error documented error in RFC5440 or draft
272 public void handleMalformedMessage(final PCEPErrors error) {
273 final long ct = System.nanoTime();
274 this.sendErrorMessage(error);
275 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
276 this.unknownMessagesTimes.add(ct);
277 while (ct - this.unknownMessagesTimes.peek() > 60 * 1E9) {
278 this.unknownMessagesTimes.poll();
280 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
281 this.terminate(Reason.TOO_MANY_UNKNOWN_MSG);
287 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
290 * @param msg incoming message
293 public void handleMessage(final Message msg) {
294 // Update last reception time
295 this.lastMessageReceivedAt = System.nanoTime();
296 this.receivedMsgCount++;
298 // Internal message handling. The user does not see these messages
299 if (msg instanceof KeepaliveMessage) {
300 // Do nothing, the timer has been already reset
301 } else if (msg instanceof PCEPOpenMessage) {
302 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
303 } else if (msg instanceof PCEPCloseMessage) {
305 * Session is up, we are reporting all messages to user. One notable
306 * exception is CLOSE message, which needs to be converted into a
307 * session DOWN event.
311 // This message needs to be handled by the user
312 this.listener.onMessage(this, msg);
317 * @return the sentMsgCount
321 public Integer getSentMsgCount() {
322 return this.sentMsgCount;
326 * @return the receivedMsgCount
330 public Integer getReceivedMsgCount() {
331 return this.receivedMsgCount;
335 public Integer getDeadTimerValue() {
336 return this.remoteOpen.getDeadTimerValue();
340 public Integer getKeepAliveTimerValue() {
341 return this.localOpen.getKeepAliveTimerValue();
345 public String getPeerAddress() {
346 final InetSocketAddress a = (InetSocketAddress) this.channel.remoteAddress();
347 return a.getHostName();
351 public void tearDown() {
356 public String getNodeIdentifier() {
357 for (final PCEPTlv tlv : this.remoteOpen.getTlvs()) {
358 if (tlv instanceof NodeIdentifierTlv) {
359 return tlv.toString();
366 public final String toString() {
367 return addToStringAttributes(Objects.toStringHelper(this)).toString();
370 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
371 toStringHelper.add("localOpen", this.localOpen);
372 toStringHelper.add("remoteOpen", this.remoteOpen);
373 return toStringHelper;
377 protected void sessionUp() {
378 this.listener.onSessionUp(this);