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 com.google.common.base.Ticker;
15 import io.netty.channel.Channel;
16 import io.netty.channel.ChannelFuture;
17 import io.netty.channel.ChannelFutureListener;
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.SimpleChannelInboundHandler;
20 import io.netty.util.concurrent.Future;
21 import java.io.IOException;
22 import java.net.InetAddress;
23 import java.net.InetSocketAddress;
24 import java.util.Date;
25 import java.util.LinkedList;
26 import java.util.Queue;
27 import java.util.concurrent.TimeUnit;
28 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
29 import org.opendaylight.protocol.pcep.PCEPSession;
30 import org.opendaylight.protocol.pcep.PCEPSessionListener;
31 import org.opendaylight.protocol.pcep.TerminationReason;
32 import org.opendaylight.protocol.pcep.impl.spi.Util;
33 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.LocalPref;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.Messages;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.stats.rev141006.pcep.session.state.PeerPref;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.CloseBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.KeepaliveBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.CloseMessage;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.KeepaliveMessage;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OpenMessage;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.PcerrMessage;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.message.CCloseMessageBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.object.CCloseBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.Tlvs;
50 import org.opendaylight.yangtools.yang.binding.DataContainer;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * Implementation of PCEPSession. (Not final for testing.)
58 public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implements PCEPSession {
59 private static final long MINUTE = TimeUnit.MINUTES.toNanos(1);
60 private static Ticker TICKER = Ticker.systemTicker();
62 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
65 protected volatile long lastMessageSentAt;
68 * System.nanoTime value about when was received the last message
70 private long lastMessageReceivedAt;
72 private final Queue<Long> unknownMessagesTimes = new LinkedList<>();
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 LOG = LoggerFactory.getLogger(PCEPSessionImpl.class);
88 private int maxUnknownMessages;
90 // True if the listener should not be notified about events
91 private boolean closed = false;
93 private final Channel channel;
95 private final Keepalive kaMessage = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
97 private final PCEPSessionState sessionState;
99 PCEPSessionImpl(final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
100 final Open localOpen, final Open remoteOpen) {
101 this.listener = Preconditions.checkNotNull(listener);
102 this.channel = Preconditions.checkNotNull(channel);
103 this.localOpen = Preconditions.checkNotNull(localOpen);
104 this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
105 this.lastMessageReceivedAt = TICKER.read();
107 if (maxUnknownMessages != 0) {
108 this.maxUnknownMessages = maxUnknownMessages;
112 if (getDeadTimerValue() != 0) {
113 channel.eventLoop().schedule(this::handleDeadTimer, getDeadTimerValue(), TimeUnit.SECONDS);
116 if (getKeepAliveTimerValue() != 0) {
117 channel.eventLoop().schedule(this::handleKeepaliveTimer, getKeepAliveTimerValue(), TimeUnit.SECONDS);
120 LOG.info("Session {}[{}] <-> {}[{}] started", channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(),
121 remoteOpen.getSessionId());
122 this.sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
125 public final Integer getKeepAliveTimerValue() {
126 return this.localOpen.getKeepalive().intValue();
129 public final Integer getDeadTimerValue() {
130 return this.remoteOpen.getDeadTimer().intValue();
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 = TICKER.read();
142 final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
144 if (this.channel.isActive()) {
145 if (ct >= nextDead) {
146 LOG.debug("DeadTimer expired. {}", new Date());
147 this.terminate(TerminationReason.EXP_DEADTIMER);
149 this.channel.eventLoop().schedule(this::handleDeadTimer, nextDead - ct, TimeUnit.NANOSECONDS);
155 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
156 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
157 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
158 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
160 private void handleKeepaliveTimer() {
161 final long ct = TICKER.read();
163 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
165 if (this.channel.isActive()) {
166 if (ct >= nextKeepalive) {
167 this.sendMessage(this.kaMessage);
168 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
171 this.channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
176 * Sends message to serialization.
178 * @param msg to be sent
181 public Future<Void> sendMessage(final Message msg) {
182 final ChannelFuture f = this.channel.writeAndFlush(msg);
183 this.lastMessageSentAt = TICKER.read();
184 this.sessionState.updateLastSentMsg();
185 if (!(msg instanceof KeepaliveMessage)) {
186 LOG.debug("PCEP Message enqueued: {}", msg);
188 if (msg instanceof PcerrMessage) {
189 this.sessionState.setLastSentError(msg);
192 f.addListener((ChannelFutureListener) arg -> {
193 if (arg.isSuccess()) {
194 LOG.trace("Message sent to socket: {}", msg);
196 LOG.debug("Message not sent: {}", msg, arg.cause());
204 ChannelFuture closeChannel() {
205 LOG.info("Closing PCEP session: {}", this);
206 return this.channel.close();
210 * Closes PCEP session without sending a Close message, as the channel is no longer active.
213 public void close() {
214 LOG.info("Closing PCEP session: {}", this);
219 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
220 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
221 * inside the session or from the listener, therefore the parent of this session should be informed.
224 public synchronized void close(final TerminationReason reason) {
225 LOG.info("Closing PCEP session: {}", this);
227 this.sendMessage(new CloseBuilder().setCCloseMessage(
228 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
233 public Tlvs getRemoteTlvs() {
234 return this.remoteOpen.getTlvs();
238 public InetAddress getRemoteAddress() {
239 return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
242 private synchronized void closeWithoutMessage(final TerminationReason reason) {
243 LOG.info("Closing PCEP session without sending msg: {}", reason);
244 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
249 private synchronized void terminate(final TerminationReason reason) {
250 LOG.info("Local PCEP session termination : {}", reason);
251 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
253 this.sendMessage(new CloseBuilder().setCCloseMessage(
254 new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
258 public synchronized void endOfInput() {
260 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
265 private void sendErrorMessage(final PCEPErrors value) {
266 this.sendErrorMessage(value, null);
270 * Sends PCEP Error Message with one PCEPError and Open Object.
275 private void sendErrorMessage(final PCEPErrors value, final Open open) {
276 this.sendMessage(Util.createErrorMessage(value, open));
280 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
281 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
282 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
285 * @param error documented error in RFC5440 or draft
288 public void handleMalformedMessage(final PCEPErrors error) {
289 final long ct = TICKER.read();
290 this.sendErrorMessage(error);
291 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
292 this.unknownMessagesTimes.add(ct);
293 while ( ct - this.unknownMessagesTimes.peek() > MINUTE) {
294 this.unknownMessagesTimes.poll();
296 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
297 this.terminate(TerminationReason.TOO_MANY_UNKNOWN_MSGS);
303 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
306 * @param msg incoming message
308 public synchronized void handleMessage(final Message msg) {
309 // Update last reception time
310 this.lastMessageReceivedAt = TICKER.read();
311 this.sessionState.updateLastReceivedMsg();
312 if (!(msg instanceof KeepaliveMessage)) {
313 LOG.debug("PCEP message {} received.", msg);
315 // Internal message handling. The user does not see these messages
316 if (msg instanceof KeepaliveMessage) {
317 // Do nothing, the timer has been already reset
318 } else if (msg instanceof OpenMessage) {
319 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
320 } else if (msg instanceof CloseMessage) {
322 * Session is up, we are reporting all messages to user. One notable
323 * exception is CLOSE message, which needs to be converted into a
324 * session DOWN event.
326 this.closeWithoutMessage(TerminationReason.forValue(((CloseMessage) msg).getCCloseMessage().getCClose().getReason()));
328 // This message needs to be handled by the user
329 if (msg instanceof PcerrMessage) {
330 this.sessionState.setLastReceivedError(msg);
332 this.listener.onMessage(this, msg);
337 public final String toString() {
338 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
341 private ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
342 toStringHelper.add("channel", this.channel);
343 toStringHelper.add("localOpen", this.localOpen);
344 toStringHelper.add("remoteOpen", this.remoteOpen);
345 return toStringHelper;
349 public void sessionUp() {
350 this.listener.onSessionUp(this);
354 protected final Queue<Long> getUnknownMessagesTimes() {
355 return this.unknownMessagesTimes;
359 public Messages getMessages() {
360 return this.sessionState.getMessages(this.unknownMessagesTimes.size());
364 public LocalPref getLocalPref() {
365 return this.sessionState.getLocalPref();
369 public PeerPref getPeerPref() {
370 return this.sessionState.getPeerPref();
374 public Class<? extends DataContainer> getImplementedInterface() {
375 throw new UnsupportedOperationException();
379 public void resetStats() {
380 this.sessionState.reset();
384 public final void channelInactive(final ChannelHandlerContext ctx) {
385 LOG.debug("Channel {} inactive.", ctx.channel());
389 super.channelInactive(ctx);
390 } catch (final Exception e) {
391 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
396 protected final void channelRead0(final ChannelHandlerContext ctx, final Message msg) {
397 LOG.debug("Message was received: {}", msg);
398 this.handleMessage(msg);
402 public final void handlerAdded(final ChannelHandlerContext ctx) {
407 public Tlvs localSessionCharacteristics() {
408 return this.localOpen.getTlvs();
412 static void setTicker(final Ticker ticker) {