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 static java.util.Objects.requireNonNull;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.Ticker;
16 import io.netty.channel.Channel;
17 import io.netty.channel.ChannelFuture;
18 import io.netty.channel.ChannelFutureListener;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.channel.SimpleChannelInboundHandler;
21 import io.netty.util.concurrent.Future;
22 import java.io.IOException;
23 import java.net.InetAddress;
24 import java.net.InetSocketAddress;
25 import java.util.Date;
26 import java.util.LinkedList;
27 import java.util.Queue;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicBoolean;
30 import org.checkerframework.checker.lock.qual.GuardedBy;
31 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
32 import org.opendaylight.protocol.pcep.PCEPSession;
33 import org.opendaylight.protocol.pcep.PCEPSessionListener;
34 import org.opendaylight.protocol.pcep.TerminationReason;
35 import org.opendaylight.protocol.pcep.impl.spi.Util;
36 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev181109.CloseBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev181109.Keepalive;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev181109.KeepaliveBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.stats.rev171113.pcep.session.state.LocalPref;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.stats.rev171113.pcep.session.state.Messages;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.stats.rev171113.pcep.session.state.PeerPref;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.CloseMessage;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.KeepaliveMessage;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Message;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.OpenMessage;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.PcerrMessage;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.close.message.CCloseMessageBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.close.object.CCloseBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.keepalive.message.KeepaliveMessageBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.open.object.Open;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.open.object.open.Tlvs;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * Implementation of PCEPSession. (Not final for testing.)
60 public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implements PCEPSession {
61 private static final long MINUTE = TimeUnit.MINUTES.toNanos(1);
62 private static Ticker TICKER = Ticker.systemTicker();
64 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
66 private volatile long lastMessageSentAt;
69 * System.nanoTime value about when was received the last message.
71 private long lastMessageReceivedAt;
73 private final Queue<Long> unknownMessagesTimes = new LinkedList<>();
75 private final PCEPSessionListener listener;
78 * Open Object with session characteristics that were accepted by another PCE (sent from this session).
80 private final Open localOpen;
83 * Open Object with session characteristics for this session (sent from another PCE).
85 private final Open remoteOpen;
87 private static final Logger LOG = LoggerFactory.getLogger(PCEPSessionImpl.class);
89 private int maxUnknownMessages;
91 // True if the listener should not be notified about events
93 private final AtomicBoolean closed = new AtomicBoolean(false);
95 private final Channel channel;
97 private final Keepalive kaMessage =
98 new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
100 private final PCEPSessionState sessionState;
102 PCEPSessionImpl(final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
103 final Open localOpen, final Open remoteOpen) {
104 this.listener = requireNonNull(listener);
105 this.channel = requireNonNull(channel);
106 this.localOpen = requireNonNull(localOpen);
107 this.remoteOpen = requireNonNull(remoteOpen);
108 this.lastMessageReceivedAt = TICKER.read();
110 if (maxUnknownMessages != 0) {
111 this.maxUnknownMessages = maxUnknownMessages;
115 if (getDeadTimerValue() != 0) {
116 channel.eventLoop().schedule(this::handleDeadTimer, getDeadTimerValue(), TimeUnit.SECONDS);
119 if (getKeepAliveTimerValue() != 0) {
120 channel.eventLoop().schedule(this::handleKeepaliveTimer, getKeepAliveTimerValue(), TimeUnit.SECONDS);
123 LOG.info("Session {}[{}] <-> {}[{}] started",
124 channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(), remoteOpen.getSessionId());
125 this.sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
128 public final Integer getKeepAliveTimerValue() {
129 return this.localOpen.getKeepalive().intValue();
132 public final Integer getDeadTimerValue() {
133 return this.remoteOpen.getDeadTimer().intValue();
137 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
138 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
139 * which the message was received. If the session was closed by the time this method starts to execute (the session
140 * state will become IDLE), that rescheduling won't occur.
142 private synchronized void handleDeadTimer() {
143 final long ct = TICKER.read();
145 final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
147 if (this.channel.isActive()) {
148 if (ct >= nextDead) {
149 LOG.debug("DeadTimer expired. {}", new Date());
150 this.terminate(TerminationReason.EXP_DEADTIMER);
152 this.channel.eventLoop().schedule(this::handleDeadTimer, nextDead - ct, TimeUnit.NANOSECONDS);
158 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
159 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
160 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
161 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
163 private void handleKeepaliveTimer() {
164 final long ct = TICKER.read();
166 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
168 if (this.channel.isActive()) {
169 if (ct >= nextKeepalive) {
170 this.sendMessage(this.kaMessage);
171 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
174 this.channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
179 * Handle exception occurred in the PCEP session. The session in error state should be closed
180 * properly so that it can be restored later.
183 void handleException(final Throwable cause) {
184 LOG.error("Exception captured for session {}, closing session.", this, cause);
185 terminate(TerminationReason.UNKNOWN);
189 * Sends message to serialization.
191 * @param msg to be sent
194 public Future<Void> sendMessage(final Message msg) {
195 final ChannelFuture f = this.channel.writeAndFlush(msg);
196 this.lastMessageSentAt = TICKER.read();
197 this.sessionState.updateLastSentMsg();
198 if (!(msg instanceof KeepaliveMessage)) {
199 LOG.debug("PCEP Message enqueued: {}", msg);
201 if (msg instanceof PcerrMessage) {
202 this.sessionState.setLastSentError(msg);
205 f.addListener((ChannelFutureListener) arg -> {
206 if (arg.isSuccess()) {
207 LOG.trace("Message sent to socket: {}", msg);
209 LOG.debug("Message not sent: {}", msg, arg.cause());
217 ChannelFuture closeChannel() {
218 LOG.info("Closing PCEP session channel: {}", this.channel);
219 return this.channel.close();
223 public synchronized boolean isClosed() {
224 return this.closed.get();
228 * Closes PCEP session without sending a Close message, as the channel is no longer active.
231 public synchronized void close() {
236 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
237 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
238 * inside the session or from the listener, therefore the parent of this session should be informed.
241 public void close(final TerminationReason reason) {
242 if (this.closed.getAndSet(true)) {
243 LOG.debug("Session is already closed.");
246 // only send close message when the reason is provided
247 if (reason != null) {
248 LOG.info("Closing PCEP session with reason {}: {}", reason, this);
249 sendMessage(new CloseBuilder().setCCloseMessage(
250 new CCloseMessageBuilder().setCClose(new CCloseBuilder()
251 .setReason(reason.getShortValue()).build()).build()).build());
253 LOG.info("Closing PCEP session: {}", this);
259 public Tlvs getRemoteTlvs() {
260 return this.remoteOpen.getTlvs();
264 public InetAddress getRemoteAddress() {
265 return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
268 private synchronized void terminate(final TerminationReason reason) {
269 if (this.closed.get()) {
270 LOG.debug("Session {} is already closed.", this);
274 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
277 synchronized void endOfInput() {
278 if (!this.closed.getAndSet(true)) {
279 this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
283 private void sendErrorMessage(final PCEPErrors value) {
284 this.sendErrorMessage(value, null);
288 * Sends PCEP Error Message with one PCEPError and Open Object.
290 * @param value PCEP errors value
291 * @param open Open Object
293 private void sendErrorMessage(final PCEPErrors value, final Open open) {
294 this.sendMessage(Util.createErrorMessage(value, open));
298 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
299 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
300 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
303 * @param error documented error in RFC5440 or draft
306 void handleMalformedMessage(final PCEPErrors error) {
307 final long ct = TICKER.read();
308 this.sendErrorMessage(error);
309 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
310 this.unknownMessagesTimes.add(ct);
311 while (ct - this.unknownMessagesTimes.peek() > MINUTE) {
312 this.unknownMessagesTimes.remove();
314 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
315 this.terminate(TerminationReason.TOO_MANY_UNKNOWN_MSGS);
321 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
324 * @param msg incoming message
326 public synchronized void handleMessage(final Message msg) {
327 if (this.closed.get()) {
328 LOG.debug("PCEP Session {} is already closed, skip handling incoming message {}", this, msg);
331 // Update last reception time
332 this.lastMessageReceivedAt = TICKER.read();
333 this.sessionState.updateLastReceivedMsg();
334 if (!(msg instanceof KeepaliveMessage)) {
335 LOG.debug("PCEP message {} received.", msg);
337 // Internal message handling. The user does not see these messages
338 if (msg instanceof KeepaliveMessage) {
339 // Do nothing, the timer has been already reset
340 } else if (msg instanceof OpenMessage) {
341 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
342 } else if (msg instanceof CloseMessage) {
344 * Session is up, we are reporting all messages to user. One notable
345 * exception is CLOSE message, which needs to be converted into a
346 * session DOWN event.
349 this.listener.onSessionTerminated(this, new PCEPCloseTermination(TerminationReason
350 .forValue(((CloseMessage) msg).getCCloseMessage().getCClose().getReason().toJava())));
352 // This message needs to be handled by the user
353 if (msg instanceof PcerrMessage) {
354 this.sessionState.setLastReceivedError(msg);
356 this.listener.onMessage(this, msg);
361 public final String toString() {
362 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
365 private ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
366 toStringHelper.add("channel", this.channel);
367 toStringHelper.add("localOpen", this.localOpen);
368 toStringHelper.add("remoteOpen", this.remoteOpen);
369 return toStringHelper;
375 this.listener.onSessionUp(this);
376 } catch (final Exception e) {
383 final Queue<Long> getUnknownMessagesTimes() {
384 return this.unknownMessagesTimes;
388 public Messages getMessages() {
389 return this.sessionState.getMessages(this.unknownMessagesTimes.size());
393 public LocalPref getLocalPref() {
394 return this.sessionState.getLocalPref();
398 public PeerPref getPeerPref() {
399 return this.sessionState.getPeerPref();
403 public Open getLocalOpen() {
404 return this.sessionState.getLocalOpen();
408 public final synchronized void channelInactive(final ChannelHandlerContext ctx) {
409 LOG.debug("Channel {} inactive.", ctx.channel());
413 super.channelInactive(ctx);
414 } catch (final Exception e) {
415 throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
420 protected final synchronized void channelRead0(final ChannelHandlerContext ctx, final Message msg) {
421 LOG.debug("Message was received: {}", msg);
426 public final synchronized void handlerAdded(final ChannelHandlerContext ctx) {
431 public synchronized void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
432 handleException(cause);
436 public Tlvs getLocalTlvs() {
437 return this.localOpen.getTlvs();
441 static void setTicker(final Ticker ticker) {