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.MoreObjects;
12 import com.google.common.base.MoreObjects.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.channel.ChannelHandlerContext;
18 import io.netty.channel.SimpleChannelInboundHandler;
19 import io.netty.util.concurrent.Future;
20 import java.io.IOException;
21 import java.net.InetAddress;
22 import java.net.InetSocketAddress;
23 import java.util.Date;
24 import java.util.LinkedList;
25 import java.util.Queue;
26 import java.util.concurrent.TimeUnit;
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.impl.spi.Util;
32 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.LocalPref;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.Messages;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.PeerPref;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.CloseBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.KeepaliveBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.CloseMessage;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.KeepaliveMessage;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OpenMessage;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.PcerrMessage;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.message.CCloseMessageBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.object.CCloseBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.Tlvs;
49 import org.opendaylight.yangtools.yang.binding.DataContainer;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Implementation of PCEPSession. (Not final for testing.)
57 public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implements PCEPSession {
59 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
62 protected volatile long lastMessageSentAt;
65 * System.nanoTime value about when was received the last message
67 private long lastMessageReceivedAt;
69 private 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 Open localOpen;
79 * Open Object with session characteristics for this session (sent from another PCE).
81 private final Open remoteOpen;
83 private static final Logger LOG = LoggerFactory.getLogger(PCEPSessionImpl.class);
85 private int maxUnknownMessages;
87 // True if the listener should not be notified about events
88 private boolean closed = false;
90 private final Channel channel;
92 private final Keepalive kaMessage = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
94 private final PCEPSessionState sessionState;
96 PCEPSessionImpl(final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
97 final Open localOpen, final Open remoteOpen) {
98 this.listener = Preconditions.checkNotNull(listener);
99 this.channel = Preconditions.checkNotNull(channel);
100 this.localOpen = Preconditions.checkNotNull(localOpen);
101 this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
102 this.lastMessageReceivedAt = System.nanoTime();
104 if (maxUnknownMessages != 0) {
105 this.maxUnknownMessages = maxUnknownMessages;
109 if (getDeadTimerValue() != 0) {
110 channel.eventLoop().schedule(new Runnable() {
115 }, getDeadTimerValue(), TimeUnit.SECONDS);
118 if (getKeepAliveTimerValue() != 0) {
119 channel.eventLoop().schedule(new Runnable() {
122 handleKeepaliveTimer();
124 }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
127 LOG.info("Session {}[{}] <-> {}[{}] started", channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(),
128 remoteOpen.getSessionId());
129 this.sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
132 public final Integer getKeepAliveTimerValue() {
133 return this.localOpen.getKeepalive().intValue();
136 public final Integer getDeadTimerValue() {
137 return this.remoteOpen.getDeadTimer().intValue();
141 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
142 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
143 * which the message was received. If the session was closed by the time this method starts to execute (the session
144 * state will become IDLE), that rescheduling won't occur.
146 private synchronized void handleDeadTimer() {
147 final long ct = System.nanoTime();
149 final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
151 if (this.channel.isActive()) {
152 if (ct >= nextDead) {
153 LOG.debug("DeadTimer expired. {}", new Date());
154 this.terminate(TerminationReason.EXP_DEADTIMER);
156 this.channel.eventLoop().schedule(new Runnable() {
161 }, nextDead - ct, TimeUnit.NANOSECONDS);
167 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
168 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
169 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
170 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
172 private void handleKeepaliveTimer() {
173 final long ct = System.nanoTime();
175 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
177 if (this.channel.isActive()) {
178 if (ct >= nextKeepalive) {
179 this.sendMessage(this.kaMessage);
180 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
183 this.channel.eventLoop().schedule(new Runnable() {
186 handleKeepaliveTimer();
188 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
193 * Sends message to serialization.
195 * @param msg to be sent
198 public Future<Void> sendMessage(final Message msg) {
199 final ChannelFuture f = this.channel.writeAndFlush(msg);
200 this.lastMessageSentAt = System.nanoTime();
201 this.sessionState.updateLastSentMsg();
202 if (!(msg instanceof KeepaliveMessage)) {
203 LOG.debug("PCEP Message enqueued: {}", msg);
205 if (msg instanceof PcerrMessage) {
206 this.sessionState.setLastSentError(msg);
209 f.addListener(new ChannelFutureListener() {
211 public void operationComplete(final ChannelFuture arg) {
212 if (arg.isSuccess()) {
213 LOG.trace("Message sent to socket: {}", msg);
215 LOG.debug("Message not sent: {}", msg, arg.cause());
224 * Closes PCEP session without sending a Close message, as the channel is no longer active.
227 public void close() {
228 LOG.info("Closing PCEP session: {}", this);
229 this.channel.close();
233 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
234 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
235 * inside the session or from the listener, therefore the parent of this session should be informed.
238 public synchronized void close(final TerminationReason reason) {
239 LOG.info("Closing PCEP session: {}", this);
241 this.sendMessage(new CloseBuilder().setCCloseMessage(
242 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
247 public Tlvs getRemoteTlvs() {
248 return this.remoteOpen.getTlvs();
252 public InetAddress getRemoteAddress() {
253 return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
256 private synchronized void terminate(final TerminationReason reason) {
257 LOG.info("Local PCEP session termination : {}", reason);
258 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
260 this.sendMessage(new CloseBuilder().setCCloseMessage(
261 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
265 public synchronized void endOfInput() {
267 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
272 private void sendErrorMessage(final PCEPErrors value) {
273 this.sendErrorMessage(value, null);
277 * Sends PCEP Error Message with one PCEPError and Open Object.
282 private void sendErrorMessage(final PCEPErrors value, final Open open) {
283 this.sendMessage(Util.createErrorMessage(value, open));
287 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
288 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
289 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
292 * @param error documented error in RFC5440 or draft
295 public void handleMalformedMessage(final PCEPErrors error) {
296 final long ct = System.nanoTime();
297 this.sendErrorMessage(error);
298 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
299 this.unknownMessagesTimes.add(ct);
300 while (ct - this.unknownMessagesTimes.peek() > TimeUnit.MINUTES.toNanos(1)) {
301 this.unknownMessagesTimes.poll();
303 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
304 this.terminate(TerminationReason.TOO_MANY_UNKNOWN_MSGS);
310 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
313 * @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(MoreObjects.toStringHelper(this)).toString();
348 private 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;
356 public void sessionUp() {
357 this.listener.onSessionUp(this);
361 protected final Queue<Long> getUnknownMessagesTimes() {
362 return this.unknownMessagesTimes;
366 public Messages getMessages() {
367 return this.sessionState.getMessages(this.unknownMessagesTimes.size());
371 public LocalPref getLocalPref() {
372 return this.sessionState.getLocalPref();
376 public PeerPref getPeerPref() {
377 return this.sessionState.getPeerPref();
381 public Class<? extends DataContainer> getImplementedInterface() {
382 throw new UnsupportedOperationException();
386 public void resetStats() {
387 this.sessionState.reset();
391 public final void channelInactive(final ChannelHandlerContext ctx) {
392 LOG.debug("Channel {} inactive.", ctx.channel());
396 super.channelInactive(ctx);
397 } catch (final Exception e) {
398 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
403 protected final void channelRead0(final ChannelHandlerContext ctx, final Message msg) {
404 LOG.debug("Message was received: {}", msg);
405 this.handleMessage(msg);
409 public final void handlerAdded(final ChannelHandlerContext ctx) {
414 public Tlvs localSessionCharacteristics() {
415 return localOpen.getTlvs();