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.Ticker;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
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.index.qual.NonNegative;
31 import org.checkerframework.checker.lock.qual.GuardedBy;
32 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
33 import org.opendaylight.protocol.pcep.PCEPSession;
34 import org.opendaylight.protocol.pcep.PCEPSessionListener;
35 import org.opendaylight.protocol.pcep.TerminationReason;
36 import org.opendaylight.protocol.pcep.impl.spi.Util;
37 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev181109.CloseBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev181109.Keepalive;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev181109.KeepaliveBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.stats.rev171113.pcep.session.state.LocalPref;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.stats.rev171113.pcep.session.state.Messages;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.stats.rev171113.pcep.session.state.PeerPref;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.CloseMessage;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.KeepaliveMessage;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Message;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.OpenMessage;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.PcerrMessage;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.close.message.CCloseMessageBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.close.object.CCloseBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.keepalive.message.KeepaliveMessageBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.open.object.Open;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.open.object.open.Tlvs;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Implementation of PCEPSession. (Not final for testing.)
61 public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implements PCEPSession {
62 private static final Logger LOG = LoggerFactory.getLogger(PCEPSessionImpl.class);
63 private static final long MINUTE_NANOS = TimeUnit.MINUTES.toNanos(1);
64 private static final Keepalive KEEPALIVE = new KeepaliveBuilder()
65 .setKeepaliveMessage(new KeepaliveMessageBuilder().build())
69 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
71 private volatile long lastMessageSentAt;
74 * System.nanoTime value about when was received the last message.
76 private long lastMessageReceivedAt;
78 private final Queue<Long> unknownMessagesTimes = new LinkedList<>();
80 private final PCEPSessionListener listener;
83 * Open Object with session characteristics that were accepted by another PCE (sent from this session).
85 private final Open localOpen;
88 * Open Object with session characteristics for this session (sent from another PCE).
90 private final Open remoteOpen;
92 private int maxUnknownMessages;
94 // True if the listener should not be notified about events
96 private final AtomicBoolean closed = new AtomicBoolean(false);
98 private final Channel channel;
101 private final PCEPSessionState sessionState;
103 private final Ticker ticker;
105 PCEPSessionImpl(final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
106 final Open localOpen, final Open remoteOpen) {
107 this(listener, maxUnknownMessages, channel, localOpen, remoteOpen, Ticker.systemTicker());
111 PCEPSessionImpl(final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
112 final Open localOpen, final Open remoteOpen, final Ticker ticker) {
113 this.listener = requireNonNull(listener);
114 this.channel = requireNonNull(channel);
115 this.localOpen = requireNonNull(localOpen);
116 this.remoteOpen = requireNonNull(remoteOpen);
117 this.ticker = requireNonNull(ticker);
118 lastMessageReceivedAt = ticker.read();
120 if (maxUnknownMessages != 0) {
121 this.maxUnknownMessages = maxUnknownMessages;
124 final var deadValue = getDeadTimerValue();
125 if (deadValue != 0) {
126 channel.eventLoop().schedule(this::handleDeadTimer, deadValue, TimeUnit.SECONDS);
128 final var keepAliveValue = getKeepAliveTimerValue();
129 if (keepAliveValue != 0) {
130 channel.eventLoop().schedule(this::handleKeepaliveTimer, keepAliveValue, TimeUnit.SECONDS);
133 LOG.info("Session {}[{}] <-> {}[{}] started",
134 channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(), remoteOpen.getSessionId());
135 sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
138 public final @NonNegative short getKeepAliveTimerValue() {
139 return localOpen.getKeepalive().toJava();
142 public final @NonNegative short getDeadTimerValue() {
143 return remoteOpen.getDeadTimer().toJava();
147 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
148 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
149 * which the message was received. If the session was closed by the time this method starts to execute (the session
150 * state will become IDLE), that rescheduling won't occur.
152 private synchronized void handleDeadTimer() {
153 final long ct = ticker.read();
155 final long nextDead = lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
157 if (channel.isActive()) {
158 if (ct >= nextDead) {
159 LOG.debug("DeadTimer expired. {}", new Date());
160 terminate(TerminationReason.EXP_DEADTIMER);
162 channel.eventLoop().schedule(this::handleDeadTimer, nextDead - ct, TimeUnit.NANOSECONDS);
168 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
169 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
170 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
171 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
173 private void handleKeepaliveTimer() {
174 final long ct = ticker.read();
176 long nextKeepalive = lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
178 if (channel.isActive()) {
179 if (ct >= nextKeepalive) {
180 sendMessage(KEEPALIVE);
181 nextKeepalive = lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
184 channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
189 * Handle exception occurred in the PCEP session. The session in error state should be closed
190 * properly so that it can be restored later.
193 void handleException(final Throwable cause) {
194 LOG.error("Exception captured for session {}, closing session.", this, cause);
195 terminate(TerminationReason.UNKNOWN);
199 * Sends message to serialization.
201 * @param msg to be sent
204 public Future<Void> sendMessage(final Message msg) {
205 final ChannelFuture f = channel.writeAndFlush(msg);
206 lastMessageSentAt = ticker.read();
207 sessionState.updateLastSentMsg();
208 if (!(msg instanceof KeepaliveMessage)) {
209 LOG.debug("PCEP Message enqueued: {}", msg);
211 if (msg instanceof PcerrMessage) {
212 sessionState.setLastSentError(msg);
215 f.addListener((ChannelFutureListener) arg -> {
216 if (arg.isSuccess()) {
217 LOG.trace("Message sent to socket: {}", msg);
219 LOG.debug("Message not sent: {}", msg, arg.cause());
227 Future<Void> closeChannel() {
228 LOG.info("Closing PCEP session channel: {}", channel);
229 return channel.close();
233 public synchronized boolean isClosed() {
238 * Closes PCEP session without sending a Close message, as the channel is no longer active.
241 public synchronized void close() {
246 * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
247 * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
248 * inside the session or from the listener, therefore the parent of this session should be informed.
251 public void close(final TerminationReason reason) {
252 if (closed.getAndSet(true)) {
253 LOG.debug("Session is already closed.");
256 // only send close message when the reason is provided
257 if (reason != null) {
258 LOG.info("Closing PCEP session with reason {}: {}", reason, this);
259 sendMessage(new CloseBuilder().setCCloseMessage(
260 new CCloseMessageBuilder().setCClose(new CCloseBuilder()
261 .setReason(reason.getUintValue()).build()).build()).build());
263 LOG.info("Closing PCEP session: {}", this);
269 public Tlvs getRemoteTlvs() {
270 return remoteOpen.getTlvs();
274 public InetAddress getRemoteAddress() {
275 return ((InetSocketAddress) channel.remoteAddress()).getAddress();
278 private synchronized void terminate(final TerminationReason reason) {
280 LOG.debug("Session {} is already closed.", this);
284 listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
287 synchronized void endOfInput() {
288 if (!closed.getAndSet(true)) {
289 listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
293 private void sendErrorMessage(final PCEPErrors value) {
294 this.sendErrorMessage(value, null);
298 * Sends PCEP Error Message with one PCEPError and Open Object.
300 * @param value PCEP errors value
301 * @param open Open Object
303 private void sendErrorMessage(final PCEPErrors value, final Open open) {
304 sendMessage(Util.createErrorMessage(value, open));
308 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
309 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
310 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
313 * @param error documented error in RFC5440 or draft
316 void handleMalformedMessage(final PCEPErrors error) {
317 final long ct = ticker.read();
318 this.sendErrorMessage(error);
319 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
320 unknownMessagesTimes.add(ct);
321 while (ct - unknownMessagesTimes.peek() > MINUTE_NANOS) {
322 unknownMessagesTimes.remove();
324 if (unknownMessagesTimes.size() > maxUnknownMessages) {
325 terminate(TerminationReason.TOO_MANY_UNKNOWN_MSGS);
331 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
334 * @param msg incoming message
336 public synchronized void handleMessage(final Message msg) {
338 LOG.debug("PCEP Session {} is already closed, skip handling incoming message {}", this, msg);
341 // Update last reception time
342 lastMessageReceivedAt = ticker.read();
343 sessionState.updateLastReceivedMsg();
344 if (!(msg instanceof KeepaliveMessage)) {
345 LOG.debug("PCEP message {} received.", msg);
347 // Internal message handling. The user does not see these messages
348 if (msg instanceof KeepaliveMessage) {
349 // Do nothing, the timer has been already reset
350 } else if (msg instanceof OpenMessage) {
351 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
352 } else if (msg instanceof CloseMessage) {
354 * Session is up, we are reporting all messages to user. One notable
355 * exception is CLOSE message, which needs to be converted into a
356 * session DOWN event.
359 listener.onSessionTerminated(this, new PCEPCloseTermination(TerminationReason
360 .forValue(((CloseMessage) msg).getCCloseMessage().getCClose().getReason())));
362 // This message needs to be handled by the user
363 if (msg instanceof PcerrMessage) {
364 sessionState.setLastReceivedError(msg);
366 listener.onMessage(this, msg);
371 public final String toString() {
372 return MoreObjects.toStringHelper(this)
373 .add("channel", channel)
374 .add("localOpen", localOpen)
375 .add("remoteOpen", remoteOpen)
380 @SuppressWarnings("checkstyle:IllegalCatch")
381 @SuppressFBWarnings(value = "THROWS_METHOD_THROWS_RUNTIMEEXCEPTION", justification = "Handle unexpected exceptions")
384 listener.onSessionUp(this);
385 } catch (final RuntimeException e) {
392 final Queue<Long> getUnknownMessagesTimes() {
393 return unknownMessagesTimes;
397 public Messages getMessages() {
398 return sessionState.getMessages(unknownMessagesTimes.size());
402 public LocalPref getLocalPref() {
403 return sessionState.getLocalPref();
407 public PeerPref getPeerPref() {
408 return sessionState.getPeerPref();
412 public Open getLocalOpen() {
413 return sessionState.getLocalOpen();
417 //similar to bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionImpl.java
418 public final synchronized void channelInactive(final ChannelHandlerContext ctx) throws Exception {
419 LOG.debug("Channel {} inactive.", ctx.channel());
421 super.channelInactive(ctx);
425 protected final synchronized void channelRead0(final ChannelHandlerContext ctx, final Message msg) {
426 LOG.debug("Message was received: {} from {}", msg, channel.remoteAddress());
431 public final synchronized void handlerAdded(final ChannelHandlerContext ctx) {
436 public synchronized void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
437 handleException(cause);
441 public Tlvs getLocalTlvs() {
442 return localOpen.getTlvs();