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.InetAddress;
17 import java.net.InetSocketAddress;
18 import java.util.Date;
19 import java.util.LinkedList;
20 import java.util.Queue;
21 import java.util.concurrent.TimeUnit;
23 import org.opendaylight.protocol.framework.AbstractProtocolSession;
24 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
25 import org.opendaylight.protocol.pcep.PCEPErrors;
26 import org.opendaylight.protocol.pcep.PCEPSession;
27 import org.opendaylight.protocol.pcep.PCEPSessionListener;
28 import org.opendaylight.protocol.pcep.TerminationReason;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.CloseBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.CloseMessage;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.KeepaliveMessage;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OpenMessage;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OpenObject;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.message.CCloseMessageBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.message.c.close.message.CCloseBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Tlvs;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import com.google.common.annotations.VisibleForTesting;
43 import com.google.common.base.Objects;
44 import com.google.common.base.Objects.ToStringHelper;
45 import com.google.common.base.Preconditions;
48 * Implementation of PCEPSession. (Not final for testing.)
51 public class PCEPSessionImpl extends AbstractProtocolSession<Message> implements PCEPSession, PCEPSessionRuntimeMXBean {
53 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
55 protected volatile long lastMessageSentAt;
58 * System.nanoTime value about when was received the last message
60 private long lastMessageReceivedAt;
63 * Protected for testing.
65 protected int maxUnknownMessages;
67 protected final Queue<Long> unknownMessagesTimes = new LinkedList<Long>();
69 private final PCEPSessionListener listener;
72 * Open Object with session characteristics that were accepted by another PCE (sent from this session).
74 private final OpenObject localOpen;
77 * Open Object with session characteristics for this session (sent from another PCE).
79 private final OpenObject remoteOpen;
81 private static final Logger logger = LoggerFactory.getLogger(PCEPSessionImpl.class);
84 * Timer object grouping FSM Timers
86 private final Timer stateTimer;
88 private int sentMsgCount = 0;
90 private int receivedMsgCount = 0;
92 // True if the listener should not be notified about events
93 private boolean closed = false;
95 private final Channel channel;
97 private final KeepaliveMessage kaMessage = (KeepaliveMessage) new KeepaliveMessageBuilder().build();
99 PCEPSessionImpl(final Timer timer, final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
100 final OpenObject localOpen, final OpenObject remoteOpen) {
101 this.listener = Preconditions.checkNotNull(listener);
102 this.stateTimer = Preconditions.checkNotNull(timer);
103 this.channel = Preconditions.checkNotNull(channel);
104 this.localOpen = Preconditions.checkNotNull(localOpen);
105 this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
106 this.lastMessageReceivedAt = System.nanoTime();
108 if (this.maxUnknownMessages != 0) {
109 this.maxUnknownMessages = maxUnknownMessages;
112 if (getDeadTimerValue() != 0) {
113 this.stateTimer.newTimeout(new TimerTask() {
115 public void run(final Timeout timeout) throws Exception {
118 }, getDeadTimerValue(), TimeUnit.SECONDS);
121 if (getKeepAliveTimerValue() != 0) {
122 this.stateTimer.newTimeout(new TimerTask() {
124 public void run(final Timeout timeout) throws Exception {
125 handleKeepaliveTimer();
127 }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
130 logger.debug("Session started.");
134 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
135 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
136 * which the message was received. If the session was closed by the time this method starts to execute (the session
137 * state will become IDLE), that rescheduling won't occur.
139 private synchronized void handleDeadTimer() {
140 final long ct = System.nanoTime();
142 final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
144 if (this.channel.isActive()) {
145 if (ct >= nextDead) {
146 logger.debug("DeadTimer expired. " + new Date());
147 this.terminate(TerminationReason.ExpDeadtimer);
149 this.stateTimer.newTimeout(new TimerTask() {
151 public void run(final Timeout timeout) throws Exception {
154 }, nextDead - ct, TimeUnit.NANOSECONDS);
160 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
161 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
162 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
163 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
165 private synchronized void handleKeepaliveTimer() {
166 final long ct = System.nanoTime();
168 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
170 if (this.channel.isActive()) {
171 if (ct >= nextKeepalive) {
172 this.sendMessage(this.kaMessage);
173 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
176 this.stateTimer.newTimeout(new TimerTask() {
178 public void run(final Timeout timeout) throws Exception {
179 handleKeepaliveTimer();
181 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
186 * Sends message to serialization.
188 * @param msg to be sent
191 public void sendMessage(final Message msg) {
193 this.channel.writeAndFlush(msg);
194 this.lastMessageSentAt = System.nanoTime();
195 if (!(msg instanceof KeepaliveMessage)) {
196 logger.debug("Sent message: " + msg);
199 } catch (final Exception e) {
200 logger.warn("Message {} was not sent.", msg, e);
205 * Closes PCEP session without sending a Close message, as the channel is no longer active.
208 public void close() {
209 logger.trace("Closing session: {}", this);
210 this.channel.close();
214 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
215 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
216 * inside the session or from the listener, therefore the parent of this session should be informed.
219 public synchronized void close(final TerminationReason reason) {
220 logger.debug("Closing session: {}", this);
222 this.sendMessage(new CloseBuilder().setCCloseMessage(
223 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
224 this.channel.close();
228 public Tlvs getRemoteTlvs() {
229 return remoteOpen.getTlvs();
233 public InetAddress getRemoteAddress() {
234 return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
237 private synchronized void terminate(final TerminationReason reason) {
238 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
240 this.sendMessage(new CloseBuilder().setCCloseMessage(
241 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
246 public synchronized void endOfInput() {
248 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
253 private void sendErrorMessage(final PCEPErrors value) {
254 this.sendErrorMessage(value, null);
258 * Sends PCEP Error Message with one PCEPError and Open Object.
263 private void sendErrorMessage(final PCEPErrors value, final OpenObject open) {
264 this.sendMessage(Util.createErrorMessage(value, open));
268 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
269 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
270 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
273 * @param error documented error in RFC5440 or draft
276 public void handleMalformedMessage(final PCEPErrors error) {
277 final long ct = System.nanoTime();
278 this.sendErrorMessage(error);
279 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
280 this.unknownMessagesTimes.add(ct);
281 while (ct - this.unknownMessagesTimes.peek() > 60 * 1E9) {
282 this.unknownMessagesTimes.poll();
284 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
285 this.terminate(TerminationReason.TooManyUnknownMsg);
291 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
294 * @param msg incoming message
297 public void handleMessage(final Message msg) {
298 // Update last reception time
299 this.lastMessageReceivedAt = System.nanoTime();
300 this.receivedMsgCount++;
302 // Internal message handling. The user does not see these messages
303 if (msg instanceof KeepaliveMessage) {
304 // Do nothing, the timer has been already reset
305 } else if (msg instanceof OpenMessage) {
306 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
307 } else if (msg instanceof CloseMessage) {
309 * Session is up, we are reporting all messages to user. One notable
310 * exception is CLOSE message, which needs to be converted into a
311 * session DOWN event.
315 // This message needs to be handled by the user
316 this.listener.onMessage(this, msg);
321 * @return the sentMsgCount
325 public Integer getSentMsgCount() {
326 return this.sentMsgCount;
330 * @return the receivedMsgCount
334 public Integer getReceivedMsgCount() {
335 return this.receivedMsgCount;
339 public Integer getDeadTimerValue() {
340 return new Integer(this.remoteOpen.getDeadTimer());
344 public Integer getKeepAliveTimerValue() {
345 return new Integer(this.localOpen.getKeepalive());
349 public String getPeerAddress() {
350 final InetSocketAddress a = (InetSocketAddress) this.channel.remoteAddress();
351 return a.getHostName();
355 public void tearDown() {
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);
376 public String getNodeIdentifier() {
377 if (this.remoteOpen.getTlvs() == null) {
378 if (this.remoteOpen.getTlvs().getPredundancyGroupId() != null) {
379 return new String(this.remoteOpen.getTlvs().getPredundancyGroupId().getIdentifier());