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.channel.ChannelFuture;
12 import io.netty.channel.ChannelFutureListener;
13 import io.netty.util.Timeout;
14 import io.netty.util.Timer;
15 import io.netty.util.TimerTask;
16 import io.netty.util.concurrent.Future;
18 import java.io.IOException;
19 import java.net.InetAddress;
20 import java.net.InetSocketAddress;
21 import java.util.Date;
22 import java.util.LinkedList;
23 import java.util.Queue;
24 import java.util.concurrent.TimeUnit;
26 import org.opendaylight.protocol.framework.AbstractProtocolSession;
27 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
28 import org.opendaylight.protocol.pcep.PCEPSession;
29 import org.opendaylight.protocol.pcep.PCEPSessionListener;
30 import org.opendaylight.protocol.pcep.TerminationReason;
31 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.CloseBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.KeepaliveBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.CloseMessage;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.KeepaliveMessage;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OpenMessage;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.message.CCloseMessageBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.object.CCloseBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.Tlvs;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 import com.google.common.annotations.VisibleForTesting;
48 import com.google.common.base.Objects;
49 import com.google.common.base.Objects.ToStringHelper;
50 import com.google.common.base.Preconditions;
53 * Implementation of PCEPSession. (Not final for testing.)
56 public class PCEPSessionImpl extends AbstractProtocolSession<Message> implements PCEPSession, PCEPSessionRuntimeMXBean {
58 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
60 protected volatile long lastMessageSentAt;
63 * System.nanoTime value about when was received the last message
65 private long lastMessageReceivedAt;
68 * Protected for testing.
70 protected int maxUnknownMessages;
72 protected final Queue<Long> unknownMessagesTimes = new LinkedList<Long>();
74 private final PCEPSessionListener listener;
77 * Open Object with session characteristics that were accepted by another PCE (sent from this session).
79 private final Open localOpen;
82 * Open Object with session characteristics for this session (sent from another PCE).
84 private final Open remoteOpen;
86 private static final Logger logger = LoggerFactory.getLogger(PCEPSessionImpl.class);
89 * Timer object grouping FSM Timers
91 private final Timer stateTimer;
93 private int sentMsgCount = 0;
95 private int receivedMsgCount = 0;
97 // True if the listener should not be notified about events
98 private boolean closed = false;
100 private final Channel channel;
102 private final Keepalive kaMessage = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
104 PCEPSessionImpl(final Timer timer, final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
105 final Open localOpen, final Open remoteOpen) {
106 this.listener = Preconditions.checkNotNull(listener);
107 this.stateTimer = Preconditions.checkNotNull(timer);
108 this.channel = Preconditions.checkNotNull(channel);
109 this.localOpen = Preconditions.checkNotNull(localOpen);
110 this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
111 this.lastMessageReceivedAt = System.nanoTime();
113 if (this.maxUnknownMessages != 0) {
114 this.maxUnknownMessages = maxUnknownMessages;
117 if (getDeadTimerValue() != 0) {
118 this.stateTimer.newTimeout(new TimerTask() {
120 public void run(final Timeout timeout) throws Exception {
123 }, getDeadTimerValue(), TimeUnit.SECONDS);
126 if (getKeepAliveTimerValue() != 0) {
127 this.stateTimer.newTimeout(new TimerTask() {
129 public void run(final Timeout timeout) throws Exception {
130 handleKeepaliveTimer();
132 }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
135 logger.debug("Session started.");
139 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
140 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
141 * which the message was received. If the session was closed by the time this method starts to execute (the session
142 * state will become IDLE), that rescheduling won't occur.
144 private synchronized void handleDeadTimer() {
145 final long ct = System.nanoTime();
147 final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
149 if (this.channel.isActive()) {
150 if (ct >= nextDead) {
151 logger.debug("DeadTimer expired. " + new Date());
152 this.terminate(TerminationReason.ExpDeadtimer);
154 this.stateTimer.newTimeout(new TimerTask() {
156 public void run(final Timeout timeout) throws Exception {
159 }, nextDead - ct, TimeUnit.NANOSECONDS);
165 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
166 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
167 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
168 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
170 private synchronized void handleKeepaliveTimer() {
171 final long ct = System.nanoTime();
173 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
175 if (this.channel.isActive()) {
176 if (ct >= nextKeepalive) {
177 this.sendMessage(this.kaMessage);
178 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
181 this.stateTimer.newTimeout(new TimerTask() {
183 public void run(final Timeout timeout) throws Exception {
184 handleKeepaliveTimer();
186 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
191 * Sends message to serialization.
193 * @param msg to be sent
196 public Future<Void> sendMessage(final Message msg) {
197 final ChannelFuture f = this.channel.writeAndFlush(msg);
198 this.lastMessageSentAt = System.nanoTime();
199 if (!(msg instanceof KeepaliveMessage)) {
200 logger.debug("Message enqueued: {}", msg);
204 f.addListener(new ChannelFutureListener() {
206 public void operationComplete(final ChannelFuture arg) {
207 if (arg.isSuccess()) {
208 logger.debug("Message sent to socket: {}", msg);
210 logger.debug("Message not sent: {}", msg, arg.cause());
219 * Closes PCEP session without sending a Close message, as the channel is no longer active.
222 public void close() {
223 logger.trace("Closing session: {}", this);
224 this.channel.close();
228 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
229 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
230 * inside the session or from the listener, therefore the parent of this session should be informed.
233 public synchronized void close(final TerminationReason reason) {
234 logger.debug("Closing session: {}", this);
236 this.sendMessage(new CloseBuilder().setCCloseMessage(
237 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
238 this.channel.close();
242 public Tlvs getRemoteTlvs() {
243 return this.remoteOpen.getTlvs();
247 public InetAddress getRemoteAddress() {
248 return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
251 private synchronized void terminate(final TerminationReason reason) {
252 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
254 this.sendMessage(new CloseBuilder().setCCloseMessage(
255 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
260 public synchronized void endOfInput() {
262 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
267 private void sendErrorMessage(final PCEPErrors value) {
268 this.sendErrorMessage(value, null);
272 * Sends PCEP Error Message with one PCEPError and Open Object.
277 private void sendErrorMessage(final PCEPErrors value, final Open open) {
278 this.sendMessage(Util.createErrorMessage(value, open));
282 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
283 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
284 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
287 * @param error documented error in RFC5440 or draft
290 public void handleMalformedMessage(final PCEPErrors error) {
291 final long ct = System.nanoTime();
292 this.sendErrorMessage(error);
293 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
294 this.unknownMessagesTimes.add(ct);
295 while (ct - this.unknownMessagesTimes.peek() > 60 * 1E9) {
296 this.unknownMessagesTimes.poll();
298 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
299 this.terminate(TerminationReason.TooManyUnknownMsg);
305 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
308 * @param msg incoming message
311 public void handleMessage(final Message msg) {
312 // Update last reception time
313 this.lastMessageReceivedAt = System.nanoTime();
314 this.receivedMsgCount++;
316 // Internal message handling. The user does not see these messages
317 if (msg instanceof KeepaliveMessage) {
318 // Do nothing, the timer has been already reset
319 } else if (msg instanceof OpenMessage) {
320 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
321 } else if (msg instanceof CloseMessage) {
323 * Session is up, we are reporting all messages to user. One notable
324 * exception is CLOSE message, which needs to be converted into a
325 * session DOWN event.
329 // This message needs to be handled by the user
330 this.listener.onMessage(this, msg);
335 * @return the sentMsgCount
339 public Integer getSentMsgCount() {
340 return this.sentMsgCount;
344 * @return the receivedMsgCount
348 public Integer getReceivedMsgCount() {
349 return this.receivedMsgCount;
353 public Integer getDeadTimerValue() {
354 return new Integer(this.remoteOpen.getDeadTimer());
358 public Integer getKeepAliveTimerValue() {
359 return new Integer(this.localOpen.getKeepalive());
363 public String getPeerAddress() {
364 final InetSocketAddress a = (InetSocketAddress) this.channel.remoteAddress();
365 return a.getHostName();
369 public void tearDown() {
374 public final String toString() {
375 return addToStringAttributes(Objects.toStringHelper(this)).toString();
378 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
379 toStringHelper.add("localOpen", this.localOpen);
380 toStringHelper.add("remoteOpen", this.remoteOpen);
381 return toStringHelper;
385 protected void sessionUp() {
386 this.listener.onSessionUp(this);
390 public String getNodeIdentifier() {
391 if (this.remoteOpen.getTlvs() == null) {
392 if (this.remoteOpen.getTlvs().getPredundancyGroupId() != null) {
393 return new String(this.remoteOpen.getTlvs().getPredundancyGroupId().getIdentifier());