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