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 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 io.netty.channel.Channel;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.ChannelFutureListener;
17 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;
25 import org.opendaylight.protocol.framework.AbstractProtocolSession;
26 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
27 import org.opendaylight.protocol.pcep.PCEPSession;
28 import org.opendaylight.protocol.pcep.PCEPSessionListener;
29 import org.opendaylight.protocol.pcep.TerminationReason;
30 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.LocalPref;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.Messages;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.PeerPref;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.CloseBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.KeepaliveBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.CloseMessage;
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.OpenMessage;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.PcerrMessage;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.message.CCloseMessageBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.object.CCloseBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.Tlvs;
47 import org.opendaylight.yangtools.yang.binding.DataContainer;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Implementation of PCEPSession. (Not final for testing.)
55 public class PCEPSessionImpl extends AbstractProtocolSession<Message> implements PCEPSession {
57 * 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;
67 private 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 Open localOpen;
77 * Open Object with session characteristics for this session (sent from another PCE).
79 private final Open remoteOpen;
81 private static final Logger LOG = LoggerFactory.getLogger(PCEPSessionImpl.class);
83 private int maxUnknownMessages;
85 // True if the listener should not be notified about events
86 private boolean closed = false;
88 private final Channel channel;
90 private final Keepalive kaMessage = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
92 private final PCEPSessionState sessionState;
94 PCEPSessionImpl(final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
95 final Open localOpen, final Open remoteOpen) {
96 this.listener = Preconditions.checkNotNull(listener);
97 this.channel = Preconditions.checkNotNull(channel);
98 this.localOpen = Preconditions.checkNotNull(localOpen);
99 this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
100 this.lastMessageReceivedAt = System.nanoTime();
102 if (maxUnknownMessages != 0) {
103 this.maxUnknownMessages = maxUnknownMessages;
107 if (getDeadTimerValue() != 0) {
108 channel.eventLoop().schedule(new Runnable() {
113 }, getDeadTimerValue(), TimeUnit.SECONDS);
116 if (getKeepAliveTimerValue() != 0) {
117 channel.eventLoop().schedule(new Runnable() {
120 handleKeepaliveTimer();
122 }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
125 LOG.info("Session {}[{}] <-> {}[{}] started", channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(),
126 remoteOpen.getSessionId());
127 this.sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
130 public Integer getKeepAliveTimerValue() {
131 return this.localOpen.getKeepalive().intValue();
134 public Integer getDeadTimerValue() {
135 return this.remoteOpen.getDeadTimer().intValue();
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 LOG.debug("DeadTimer expired. {}", new Date());
152 this.terminate(TerminationReason.ExpDeadtimer);
154 this.channel.eventLoop().schedule(new Runnable() {
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 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.channel.eventLoop().schedule(new Runnable() {
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 this.sessionState.updateLastSentMsg();
200 if (!(msg instanceof KeepaliveMessage)) {
201 LOG.debug("PCEP Message enqueued: {}", msg);
203 if (msg instanceof PcerrMessage) {
204 this.sessionState.setLastSentError(msg);
207 f.addListener(new ChannelFutureListener() {
209 public void operationComplete(final ChannelFuture arg) {
210 if (arg.isSuccess()) {
211 LOG.trace("Message sent to socket: {}", msg);
213 LOG.debug("Message not sent: {}", msg, arg.cause());
222 * Closes PCEP session without sending a Close message, as the channel is no longer active.
225 public void close() {
226 LOG.info("Closing PCEP session: {}", this);
227 this.channel.close();
231 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
232 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
233 * inside the session or from the listener, therefore the parent of this session should be informed.
236 public synchronized void close(final TerminationReason reason) {
237 LOG.info("Closing PCEP session: {}", this);
239 this.sendMessage(new CloseBuilder().setCCloseMessage(
240 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
245 public Tlvs getRemoteTlvs() {
246 return this.remoteOpen.getTlvs();
250 public InetAddress getRemoteAddress() {
251 return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
254 private synchronized void terminate(final TerminationReason reason) {
255 LOG.info("Local PCEP session termination : {}", reason);
256 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
258 this.sendMessage(new CloseBuilder().setCCloseMessage(
259 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
264 public synchronized void endOfInput() {
266 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
271 private void sendErrorMessage(final PCEPErrors value) {
272 this.sendErrorMessage(value, null);
276 * Sends PCEP Error Message with one PCEPError and Open Object.
281 private void sendErrorMessage(final PCEPErrors value, final Open open) {
282 this.sendMessage(Util.createErrorMessage(value, open));
286 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
287 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
288 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
291 * @param error documented error in RFC5440 or draft
294 public void handleMalformedMessage(final PCEPErrors error) {
295 final long ct = System.nanoTime();
296 this.sendErrorMessage(error);
297 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
298 this.unknownMessagesTimes.add(ct);
299 while (ct - this.unknownMessagesTimes.peek() > 60 * 1E9) {
300 this.unknownMessagesTimes.poll();
302 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
303 this.terminate(TerminationReason.TooManyUnknownMsg);
309 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
312 * @param msg incoming message
315 public synchronized void handleMessage(final Message msg) {
316 // Update last reception time
317 this.lastMessageReceivedAt = System.nanoTime();
318 this.sessionState.updateLastReceivedMsg();
319 if (!(msg instanceof KeepaliveMessage)) {
320 LOG.debug("PCEP message {} received.", msg);
322 // Internal message handling. The user does not see these messages
323 if (msg instanceof KeepaliveMessage) {
324 // Do nothing, the timer has been already reset
325 } else if (msg instanceof OpenMessage) {
326 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
327 } else if (msg instanceof CloseMessage) {
329 * Session is up, we are reporting all messages to user. One notable
330 * exception is CLOSE message, which needs to be converted into a
331 * session DOWN event.
335 // This message needs to be handled by the user
336 if (msg instanceof PcerrMessage) {
337 this.sessionState.setLastReceivedError(msg);
339 this.listener.onMessage(this, msg);
344 public final String toString() {
345 return addToStringAttributes(Objects.toStringHelper(this)).toString();
348 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
349 toStringHelper.add("channel", this.channel);
350 toStringHelper.add("localOpen", this.localOpen);
351 toStringHelper.add("remoteOpen", this.remoteOpen);
352 return toStringHelper;
357 public void sessionUp() {
358 this.listener.onSessionUp(this);
362 protected final Queue<Long> getUnknownMessagesTimes() {
363 return this.unknownMessagesTimes;
367 public Messages getMessages() {
368 return this.sessionState.getMessages(this.unknownMessagesTimes.size());
372 public LocalPref getLocalPref() {
373 return this.sessionState.getLocalPref();
377 public PeerPref getPeerPref() {
378 return this.sessionState.getPeerPref();
382 public Class<? extends DataContainer> getImplementedInterface() {
383 throw new UnsupportedOperationException();
386 public void resetStats() {
387 this.sessionState.reset();