Bump versions to 0.21.7-SNAPSHOT
[bgpcep.git] / pcep / impl / src / main / java / org / opendaylight / protocol / pcep / impl / PCEPSessionImpl.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.protocol.pcep.impl;
9
10 import static java.util.Objects.requireNonNull;
11
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;
56
57 /**
58  * Implementation of PCEPSession. (Not final for testing.)
59  */
60 @VisibleForTesting
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())
66         .build();
67
68     /**
69      * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
70      */
71     private volatile long lastMessageSentAt;
72
73     /**
74      * System.nanoTime value about when was received the last message.
75      */
76     private long lastMessageReceivedAt;
77
78     private final Queue<Long> unknownMessagesTimes = new LinkedList<>();
79
80     private final PCEPSessionListener listener;
81
82     /**
83      * Open Object with session characteristics that were accepted by another PCE (sent from this session).
84      */
85     private final Open localOpen;
86
87     /**
88      * Open Object with session characteristics for this session (sent from another PCE).
89      */
90     private final Open remoteOpen;
91
92     private int maxUnknownMessages;
93
94     // True if the listener should not be notified about events
95     @GuardedBy("this")
96     private final AtomicBoolean closed = new AtomicBoolean(false);
97
98     private final Channel channel;
99
100
101     private final PCEPSessionState sessionState;
102
103     private final Ticker ticker;
104
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());
108     }
109
110     @VisibleForTesting
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();
119
120         if (maxUnknownMessages != 0) {
121             this.maxUnknownMessages = maxUnknownMessages;
122         }
123
124         final var deadValue = getDeadTimerValue();
125         if (deadValue != 0) {
126             channel.eventLoop().schedule(this::handleDeadTimer, deadValue, TimeUnit.SECONDS);
127         }
128         final var keepAliveValue = getKeepAliveTimerValue();
129         if (keepAliveValue != 0) {
130             channel.eventLoop().schedule(this::handleKeepaliveTimer, keepAliveValue, TimeUnit.SECONDS);
131         }
132
133         LOG.info("Session {}[{}] <-> {}[{}] started",
134             channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(), remoteOpen.getSessionId());
135         sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
136     }
137
138     public final @NonNegative short getKeepAliveTimerValue() {
139         return localOpen.getKeepalive().toJava();
140     }
141
142     public final @NonNegative short getDeadTimerValue() {
143         return remoteOpen.getDeadTimer().toJava();
144     }
145
146     /**
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.
151      */
152     private synchronized void handleDeadTimer() {
153         final long ct = ticker.read();
154
155         final long nextDead = lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
156
157         if (channel.isActive()) {
158             if (ct >= nextDead) {
159                 LOG.debug("DeadTimer expired. {}", new Date());
160                 terminate(TerminationReason.EXP_DEADTIMER);
161             } else {
162                 channel.eventLoop().schedule(this::handleDeadTimer, nextDead - ct, TimeUnit.NANOSECONDS);
163             }
164         }
165     }
166
167     /**
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.
172      */
173     private void handleKeepaliveTimer() {
174         final long ct = ticker.read();
175
176         long nextKeepalive = lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
177
178         if (channel.isActive()) {
179             if (ct >= nextKeepalive) {
180                 sendMessage(KEEPALIVE);
181                 nextKeepalive = lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
182             }
183
184             channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
185         }
186     }
187
188     /**
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.
191      */
192     @VisibleForTesting
193     void handleException(final Throwable cause) {
194         LOG.error("Exception captured for session {}, closing session.", this, cause);
195         terminate(TerminationReason.UNKNOWN);
196     }
197
198     /**
199      * Sends message to serialization.
200      *
201      * @param msg to be sent
202      */
203     @Override
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);
210         }
211         if (msg instanceof PcerrMessage) {
212             sessionState.setLastSentError(msg);
213         }
214
215         f.addListener((ChannelFutureListener) arg -> {
216             if (arg.isSuccess()) {
217                 LOG.trace("Message sent to socket: {}", msg);
218             } else {
219                 LOG.debug("Message not sent: {}", msg, arg.cause());
220             }
221         });
222
223         return f;
224     }
225
226     @VisibleForTesting
227     Future<Void> closeChannel() {
228         LOG.info("Closing PCEP session channel: {}", channel);
229         return channel.close();
230     }
231
232     @VisibleForTesting
233     public synchronized boolean isClosed() {
234         return closed.get();
235     }
236
237     /**
238      * Closes PCEP session without sending a Close message, as the channel is no longer active.
239      */
240     @Override
241     public synchronized void close() {
242         close(null);
243     }
244
245     /**
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.
249      */
250     @Override
251     public void close(final TerminationReason reason) {
252         if (closed.getAndSet(true)) {
253             LOG.debug("Session is already closed.");
254             return;
255         }
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());
262         } else {
263             LOG.info("Closing PCEP session: {}", this);
264         }
265         closeChannel();
266     }
267
268     @Override
269     public Tlvs getRemoteTlvs() {
270         return remoteOpen.getTlvs();
271     }
272
273     @Override
274     public InetAddress getRemoteAddress() {
275         return ((InetSocketAddress) channel.remoteAddress()).getAddress();
276     }
277
278     private synchronized void terminate(final TerminationReason reason) {
279         if (closed.get()) {
280             LOG.debug("Session {} is already closed.", this);
281             return;
282         }
283         close(reason);
284         listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
285     }
286
287     synchronized void endOfInput() {
288         if (!closed.getAndSet(true)) {
289             listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
290         }
291     }
292
293     private void sendErrorMessage(final PCEPErrors value) {
294         this.sendErrorMessage(value, null);
295     }
296
297     /**
298      * Sends PCEP Error Message with one PCEPError and Open Object.
299      *
300      * @param value PCEP errors value
301      * @param open Open Object
302      */
303     private void sendErrorMessage(final PCEPErrors value, final Open open) {
304         sendMessage(Util.createErrorMessage(value, open));
305     }
306
307     /**
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
311      * sent.
312      *
313      * @param error documented error in RFC5440 or draft
314      */
315     @VisibleForTesting
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();
323             }
324             if (unknownMessagesTimes.size() > maxUnknownMessages) {
325                 terminate(TerminationReason.TOO_MANY_UNKNOWN_MSGS);
326             }
327         }
328     }
329
330     /**
331      * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
332      * except KeepAlive.
333      *
334      * @param msg incoming message
335      */
336     public synchronized void handleMessage(final Message msg) {
337         if (closed.get()) {
338             LOG.debug("PCEP Session {} is already closed, skip handling incoming message {}", this, msg);
339             return;
340         }
341         // Update last reception time
342         lastMessageReceivedAt = ticker.read();
343         sessionState.updateLastReceivedMsg();
344         if (!(msg instanceof KeepaliveMessage)) {
345             LOG.debug("PCEP message {} received.", msg);
346         }
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) {
353             /*
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.
357              */
358             close();
359             listener.onSessionTerminated(this, new PCEPCloseTermination(TerminationReason
360                     .forValue(((CloseMessage) msg).getCCloseMessage().getCClose().getReason())));
361         } else {
362             // This message needs to be handled by the user
363             if (msg instanceof PcerrMessage) {
364                 sessionState.setLastReceivedError(msg);
365             }
366             listener.onMessage(this, msg);
367         }
368     }
369
370     @Override
371     public final String toString() {
372         return MoreObjects.toStringHelper(this)
373             .add("channel", channel)
374             .add("localOpen", localOpen)
375             .add("remoteOpen", remoteOpen)
376             .toString();
377     }
378
379     @VisibleForTesting
380     @SuppressWarnings("checkstyle:IllegalCatch")
381     @SuppressFBWarnings(value = "THROWS_METHOD_THROWS_RUNTIMEEXCEPTION", justification = "Handle unexpected exceptions")
382     void sessionUp() {
383         try {
384             listener.onSessionUp(this);
385         } catch (final RuntimeException e) {
386             handleException(e);
387             throw e;
388         }
389     }
390
391     @VisibleForTesting
392     final Queue<Long> getUnknownMessagesTimes() {
393         return unknownMessagesTimes;
394     }
395
396     @Override
397     public Messages getMessages() {
398         return sessionState.getMessages(unknownMessagesTimes.size());
399     }
400
401     @Override
402     public LocalPref getLocalPref() {
403         return sessionState.getLocalPref();
404     }
405
406     @Override
407     public PeerPref getPeerPref() {
408         return sessionState.getPeerPref();
409     }
410
411     @Override
412     public Open getLocalOpen() {
413         return sessionState.getLocalOpen();
414     }
415
416     @Override
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());
420         endOfInput();
421         super.channelInactive(ctx);
422     }
423
424     @Override
425     protected final synchronized void channelRead0(final ChannelHandlerContext ctx, final Message msg) {
426         LOG.debug("Message was received: {} from {}", msg, channel.remoteAddress());
427         handleMessage(msg);
428     }
429
430     @Override
431     public final synchronized void handlerAdded(final ChannelHandlerContext ctx) {
432         sessionUp();
433     }
434
435     @Override
436     public synchronized void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
437         handleException(cause);
438     }
439
440     @Override
441     public Tlvs getLocalTlvs() {
442         return localOpen.getTlvs();
443     }
444 }