BUG-7003: Remove sleeping from Tests
[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<Long>();
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(new Runnable() {
114                 @Override
115                 public void run() {
116                     handleDeadTimer();
117                 }
118             }, getDeadTimerValue(), TimeUnit.SECONDS);
119         }
120
121         if (getKeepAliveTimerValue() != 0) {
122             channel.eventLoop().schedule(new Runnable() {
123                 @Override
124                 public void run() {
125                     handleKeepaliveTimer();
126                 }
127             }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
128         }
129
130         LOG.info("Session {}[{}] <-> {}[{}] started", channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(),
131             remoteOpen.getSessionId());
132         this.sessionState = new PCEPSessionState(remoteOpen, localOpen, channel);
133     }
134
135     public final Integer getKeepAliveTimerValue() {
136         return this.localOpen.getKeepalive().intValue();
137     }
138
139     public final Integer getDeadTimerValue() {
140         return this.remoteOpen.getDeadTimer().intValue();
141     }
142
143     /**
144      * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
145      * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
146      * which the message was received. If the session was closed by the time this method starts to execute (the session
147      * state will become IDLE), that rescheduling won't occur.
148      */
149     private synchronized void handleDeadTimer() {
150         final long ct = TICKER.read();
151
152         final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
153
154         if (this.channel.isActive()) {
155             if (ct >= nextDead) {
156                 LOG.debug("DeadTimer expired. {}", new Date());
157                 this.terminate(TerminationReason.EXP_DEADTIMER);
158             } else {
159                 this.channel.eventLoop().schedule(new Runnable() {
160                     @Override
161                     public void run() {
162                         handleDeadTimer();
163                     }
164                 }, nextDead - ct, TimeUnit.NANOSECONDS);
165             }
166         }
167     }
168
169     /**
170      * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
171      * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
172      * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
173      * starts to execute (the session state will become IDLE), that rescheduling won't occur.
174      */
175     private  void handleKeepaliveTimer() {
176         final long ct = TICKER.read();
177
178         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
179
180         if (this.channel.isActive()) {
181             if (ct >= nextKeepalive) {
182                 this.sendMessage(this.kaMessage);
183                 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
184             }
185
186             this.channel.eventLoop().schedule(new Runnable() {
187                 @Override
188                 public void run() {
189                     handleKeepaliveTimer();
190                 }
191             }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
192         }
193     }
194
195     /**
196      * Sends message to serialization.
197      *
198      * @param msg to be sent
199      */
200     @Override
201     public Future<Void> sendMessage(final Message msg) {
202         final ChannelFuture f = this.channel.writeAndFlush(msg);
203         this.lastMessageSentAt = TICKER.read();
204         this.sessionState.updateLastSentMsg();
205         if (!(msg instanceof KeepaliveMessage)) {
206             LOG.debug("PCEP Message enqueued: {}", msg);
207         }
208         if (msg instanceof PcerrMessage) {
209             this.sessionState.setLastSentError(msg);
210         }
211
212         f.addListener(new ChannelFutureListener() {
213             @Override
214             public void operationComplete(final ChannelFuture arg) {
215                 if (arg.isSuccess()) {
216                     LOG.trace("Message sent to socket: {}", msg);
217                 } else {
218                     LOG.debug("Message not sent: {}", msg, arg.cause());
219                 }
220             }
221         });
222
223         return f;
224     }
225
226     /**
227      * Closes PCEP session without sending a Close message, as the channel is no longer active.
228      */
229     @Override
230     public void close() {
231         LOG.info("Closing PCEP session: {}", this);
232         this.channel.close();
233     }
234
235     /**
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.
239      */
240     @Override
241     public synchronized void close(final TerminationReason reason) {
242         LOG.info("Closing PCEP session: {}", this);
243         this.closed = true;
244         this.sendMessage(new CloseBuilder().setCCloseMessage(
245             new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
246         this.close();
247     }
248
249     @Override
250     public Tlvs getRemoteTlvs() {
251         return this.remoteOpen.getTlvs();
252     }
253
254     @Override
255     public InetAddress getRemoteAddress() {
256         return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
257     }
258
259     private synchronized void terminate(final TerminationReason reason) {
260         LOG.info("Local PCEP session termination : {}", reason);
261         this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
262         this.closed = true;
263         this.sendMessage(new CloseBuilder().setCCloseMessage(
264             new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
265         this.close();
266     }
267
268     public synchronized void endOfInput() {
269         if (!this.closed) {
270             this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
271             this.closed = true;
272         }
273     }
274
275     private void sendErrorMessage(final PCEPErrors value) {
276         this.sendErrorMessage(value, null);
277     }
278
279     /**
280      * Sends PCEP Error Message with one PCEPError and Open Object.
281      *
282      * @param value
283      * @param open
284      */
285     private void sendErrorMessage(final PCEPErrors value, final Open open) {
286         this.sendMessage(Util.createErrorMessage(value, open));
287     }
288
289     /**
290      * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
291      * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
292      * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
293      * sent.
294      *
295      * @param error documented error in RFC5440 or draft
296      */
297     @VisibleForTesting
298     public void handleMalformedMessage(final PCEPErrors error) {
299         final long ct = TICKER.read();
300         this.sendErrorMessage(error);
301         if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
302             this.unknownMessagesTimes.add(ct);
303             while ( ct - this.unknownMessagesTimes.peek() > MINUTE) {
304                 this.unknownMessagesTimes.poll();
305             }
306             if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
307                 this.terminate(TerminationReason.TOO_MANY_UNKNOWN_MSGS);
308             }
309         }
310     }
311
312     /**
313      * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
314      * except KeepAlive.
315      *
316      * @param msg incoming message
317      */
318     public synchronized void handleMessage(final Message msg) {
319         // Update last reception time
320         this.lastMessageReceivedAt = TICKER.read();
321         this.sessionState.updateLastReceivedMsg();
322         if (!(msg instanceof KeepaliveMessage)) {
323             LOG.debug("PCEP message {} received.", msg);
324         }
325         // Internal message handling. The user does not see these messages
326         if (msg instanceof KeepaliveMessage) {
327             // Do nothing, the timer has been already reset
328         } else if (msg instanceof OpenMessage) {
329             this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
330         } else if (msg instanceof CloseMessage) {
331             /*
332              * Session is up, we are reporting all messages to user. One notable
333              * exception is CLOSE message, which needs to be converted into a
334              * session DOWN event.
335              */
336             this.close();
337         } else {
338             // This message needs to be handled by the user
339             if (msg instanceof PcerrMessage) {
340                 this.sessionState.setLastReceivedError(msg);
341             }
342             this.listener.onMessage(this, msg);
343         }
344     }
345
346     @Override
347     public final String toString() {
348         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
349     }
350
351     private ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
352         toStringHelper.add("channel", this.channel);
353         toStringHelper.add("localOpen", this.localOpen);
354         toStringHelper.add("remoteOpen", this.remoteOpen);
355         return toStringHelper;
356     }
357
358     @VisibleForTesting
359     public void sessionUp() {
360         this.listener.onSessionUp(this);
361     }
362
363     @VisibleForTesting
364     protected final Queue<Long> getUnknownMessagesTimes() {
365         return this.unknownMessagesTimes;
366     }
367
368     @Override
369     public Messages getMessages() {
370         return this.sessionState.getMessages(this.unknownMessagesTimes.size());
371     }
372
373     @Override
374     public LocalPref getLocalPref() {
375         return this.sessionState.getLocalPref();
376     }
377
378     @Override
379     public PeerPref getPeerPref() {
380         return this.sessionState.getPeerPref();
381     }
382
383     @Override
384     public Class<? extends DataContainer> getImplementedInterface() {
385         throw new UnsupportedOperationException();
386     }
387
388     @Override
389     public void resetStats() {
390         this.sessionState.reset();
391     }
392
393     @Override
394     public final void channelInactive(final ChannelHandlerContext ctx) {
395         LOG.debug("Channel {} inactive.", ctx.channel());
396         this.endOfInput();
397
398         try {
399             super.channelInactive(ctx);
400         } catch (final Exception e) {
401             throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
402         }
403     }
404
405     @Override
406     protected final void channelRead0(final ChannelHandlerContext ctx, final Message msg) {
407         LOG.debug("Message was received: {}", msg);
408         this.handleMessage(msg);
409     }
410
411     @Override
412     public final void handlerAdded(final ChannelHandlerContext ctx) {
413         this.sessionUp();
414     }
415
416     @Override
417     public Tlvs localSessionCharacteristics() {
418         return this.localOpen.getTlvs();
419     }
420
421     @VisibleForTesting
422     static void setTicker(final Ticker ticker) {
423         TICKER = ticker;
424     }
425 }