BUG-7964: IllegalStateException under testReconectClient test
[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 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;
53
54 /**
55  * Implementation of PCEPSession. (Not final for testing.)
56  */
57 @VisibleForTesting
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();
61     /**
62      * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
63      */
64     @VisibleForTesting
65     protected volatile long lastMessageSentAt;
66
67     /**
68      * System.nanoTime value about when was received the last message
69      */
70     private long lastMessageReceivedAt;
71
72     private final Queue<Long> unknownMessagesTimes = new LinkedList<>();
73
74     private final PCEPSessionListener listener;
75
76     /**
77      * Open Object with session characteristics that were accepted by another PCE (sent from this session).
78      */
79     private final Open localOpen;
80
81     /**
82      * Open Object with session characteristics for this session (sent from another PCE).
83      */
84     private final Open remoteOpen;
85
86     private static final Logger LOG = LoggerFactory.getLogger(PCEPSessionImpl.class);
87
88     private int maxUnknownMessages;
89
90     // True if the listener should not be notified about events
91     private boolean closed = false;
92
93     private final Channel channel;
94
95     private final Keepalive kaMessage = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
96
97     private final PCEPSessionState sessionState;
98
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();
106
107         if (maxUnknownMessages != 0) {
108             this.maxUnknownMessages = maxUnknownMessages;
109         }
110
111
112         if (getDeadTimerValue() != 0) {
113             channel.eventLoop().schedule(this::handleDeadTimer, getDeadTimerValue(), TimeUnit.SECONDS);
114         }
115
116         if (getKeepAliveTimerValue() != 0) {
117             channel.eventLoop().schedule(this::handleKeepaliveTimer, getKeepAliveTimerValue(), TimeUnit.SECONDS);
118         }
119
120         LOG.info("Session {}[{}] <-> {}[{}] started", channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(),
121             remoteOpen.getSessionId());
122         this.sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
123     }
124
125     public final Integer getKeepAliveTimerValue() {
126         return this.localOpen.getKeepalive().intValue();
127     }
128
129     public final Integer getDeadTimerValue() {
130         return this.remoteOpen.getDeadTimer().intValue();
131     }
132
133     /**
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.
138      */
139     private synchronized void handleDeadTimer() {
140         final long ct = TICKER.read();
141
142         final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
143
144         if (this.channel.isActive()) {
145             if (ct >= nextDead) {
146                 LOG.debug("DeadTimer expired. {}", new Date());
147                 this.terminate(TerminationReason.EXP_DEADTIMER);
148             } else {
149                 this.channel.eventLoop().schedule(this::handleDeadTimer, nextDead - ct, TimeUnit.NANOSECONDS);
150             }
151         }
152     }
153
154     /**
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.
159      */
160     private  void handleKeepaliveTimer() {
161         final long ct = TICKER.read();
162
163         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
164
165         if (this.channel.isActive()) {
166             if (ct >= nextKeepalive) {
167                 this.sendMessage(this.kaMessage);
168                 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
169             }
170
171             this.channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
172         }
173     }
174
175     /**
176      * Sends message to serialization.
177      *
178      * @param msg to be sent
179      */
180     @Override
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);
187         }
188         if (msg instanceof PcerrMessage) {
189             this.sessionState.setLastSentError(msg);
190         }
191
192         f.addListener((ChannelFutureListener) arg -> {
193             if (arg.isSuccess()) {
194                 LOG.trace("Message sent to socket: {}", msg);
195             } else {
196                 LOG.debug("Message not sent: {}", msg, arg.cause());
197             }
198         });
199
200         return f;
201     }
202
203     @VisibleForTesting
204     ChannelFuture closeChannel() {
205         LOG.info("Closing PCEP session: {}", this);
206         return this.channel.close();
207     }
208
209     /**
210      * Closes PCEP session without sending a Close message, as the channel is no longer active.
211      */
212     @Override
213     public void close() {
214         LOG.info("Closing PCEP session: {}", this);
215         closeChannel();
216     }
217
218     /**
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.
222      */
223     @Override
224     public synchronized void close(final TerminationReason reason) {
225         LOG.info("Closing PCEP session: {}", this);
226         this.closed = true;
227         this.sendMessage(new CloseBuilder().setCCloseMessage(
228             new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
229         this.close();
230     }
231
232     @Override
233     public Tlvs getRemoteTlvs() {
234         return this.remoteOpen.getTlvs();
235     }
236
237     @Override
238     public InetAddress getRemoteAddress() {
239         return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
240     }
241
242     private synchronized void terminate(final TerminationReason reason) {
243         LOG.info("Local PCEP session termination : {}", reason);
244         this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
245         this.closed = true;
246         this.sendMessage(new CloseBuilder().setCCloseMessage(
247             new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
248         this.close();
249     }
250
251     public synchronized void endOfInput() {
252         if (!this.closed) {
253             this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
254             this.closed = true;
255         }
256     }
257
258     private void sendErrorMessage(final PCEPErrors value) {
259         this.sendErrorMessage(value, null);
260     }
261
262     /**
263      * Sends PCEP Error Message with one PCEPError and Open Object.
264      *
265      * @param value
266      * @param open
267      */
268     private void sendErrorMessage(final PCEPErrors value, final Open open) {
269         this.sendMessage(Util.createErrorMessage(value, open));
270     }
271
272     /**
273      * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
274      * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
275      * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
276      * sent.
277      *
278      * @param error documented error in RFC5440 or draft
279      */
280     @VisibleForTesting
281     public void handleMalformedMessage(final PCEPErrors error) {
282         final long ct = TICKER.read();
283         this.sendErrorMessage(error);
284         if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
285             this.unknownMessagesTimes.add(ct);
286             while ( ct - this.unknownMessagesTimes.peek() > MINUTE) {
287                 this.unknownMessagesTimes.poll();
288             }
289             if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
290                 this.terminate(TerminationReason.TOO_MANY_UNKNOWN_MSGS);
291             }
292         }
293     }
294
295     /**
296      * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
297      * except KeepAlive.
298      *
299      * @param msg incoming message
300      */
301     public synchronized void handleMessage(final Message msg) {
302         // Update last reception time
303         this.lastMessageReceivedAt = TICKER.read();
304         this.sessionState.updateLastReceivedMsg();
305         if (!(msg instanceof KeepaliveMessage)) {
306             LOG.debug("PCEP message {} received.", msg);
307         }
308         // Internal message handling. The user does not see these messages
309         if (msg instanceof KeepaliveMessage) {
310             // Do nothing, the timer has been already reset
311         } else if (msg instanceof OpenMessage) {
312             this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
313         } else if (msg instanceof CloseMessage) {
314             /*
315              * Session is up, we are reporting all messages to user. One notable
316              * exception is CLOSE message, which needs to be converted into a
317              * session DOWN event.
318              */
319             this.close();
320         } else {
321             // This message needs to be handled by the user
322             if (msg instanceof PcerrMessage) {
323                 this.sessionState.setLastReceivedError(msg);
324             }
325             this.listener.onMessage(this, msg);
326         }
327     }
328
329     @Override
330     public final String toString() {
331         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
332     }
333
334     private ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
335         toStringHelper.add("channel", this.channel);
336         toStringHelper.add("localOpen", this.localOpen);
337         toStringHelper.add("remoteOpen", this.remoteOpen);
338         return toStringHelper;
339     }
340
341     @VisibleForTesting
342     public void sessionUp() {
343         this.listener.onSessionUp(this);
344     }
345
346     @VisibleForTesting
347     protected final Queue<Long> getUnknownMessagesTimes() {
348         return this.unknownMessagesTimes;
349     }
350
351     @Override
352     public Messages getMessages() {
353         return this.sessionState.getMessages(this.unknownMessagesTimes.size());
354     }
355
356     @Override
357     public LocalPref getLocalPref() {
358         return this.sessionState.getLocalPref();
359     }
360
361     @Override
362     public PeerPref getPeerPref() {
363         return this.sessionState.getPeerPref();
364     }
365
366     @Override
367     public Class<? extends DataContainer> getImplementedInterface() {
368         throw new UnsupportedOperationException();
369     }
370
371     @Override
372     public void resetStats() {
373         this.sessionState.reset();
374     }
375
376     @Override
377     public final void channelInactive(final ChannelHandlerContext ctx) {
378         LOG.debug("Channel {} inactive.", ctx.channel());
379         this.endOfInput();
380
381         try {
382             super.channelInactive(ctx);
383         } catch (final Exception e) {
384             throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
385         }
386     }
387
388     @Override
389     protected final void channelRead0(final ChannelHandlerContext ctx, final Message msg) {
390         LOG.debug("Message was received: {}", msg);
391         this.handleMessage(msg);
392     }
393
394     @Override
395     public final void handlerAdded(final ChannelHandlerContext ctx) {
396         this.sessionUp();
397     }
398
399     @Override
400     public Tlvs localSessionCharacteristics() {
401         return this.localOpen.getTlvs();
402     }
403
404     @VisibleForTesting
405     static void setTicker(final Ticker ticker) {
406         TICKER = ticker;
407     }
408 }