Fixed various findbugs issues in PCEP.
[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.Objects;
12 import com.google.common.base.Objects.ToStringHelper;
13 import com.google.common.base.Preconditions;
14 import io.netty.channel.Channel;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.ChannelFutureListener;
17 import io.netty.util.concurrent.Future;
18 import java.io.IOException;
19 import java.net.InetAddress;
20 import java.net.InetSocketAddress;
21 import java.util.Date;
22 import java.util.LinkedList;
23 import java.util.Queue;
24 import java.util.concurrent.TimeUnit;
25 import org.opendaylight.protocol.framework.AbstractProtocolSession;
26 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
27 import org.opendaylight.protocol.pcep.PCEPSession;
28 import org.opendaylight.protocol.pcep.PCEPSessionListener;
29 import org.opendaylight.protocol.pcep.TerminationReason;
30 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.CloseBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.KeepaliveBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.CloseMessage;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.KeepaliveMessage;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OpenMessage;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.message.CCloseMessageBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.close.object.CCloseBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.Tlvs;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Implementation of PCEPSession. (Not final for testing.)
48  */
49 @VisibleForTesting
50 public class PCEPSessionImpl extends AbstractProtocolSession<Message> implements PCEPSession, PCEPSessionRuntimeMXBean {
51     /**
52      * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
53      */
54     @VisibleForTesting
55     protected volatile long lastMessageSentAt;
56
57     /**
58      * System.nanoTime value about when was received the last message
59      */
60     private long lastMessageReceivedAt;
61
62     @VisibleForTesting
63     protected final Queue<Long> unknownMessagesTimes = new LinkedList<Long>();
64
65     private final PCEPSessionListener listener;
66
67     /**
68      * Open Object with session characteristics that were accepted by another PCE (sent from this session).
69      */
70     private final Open localOpen;
71
72     /**
73      * Open Object with session characteristics for this session (sent from another PCE).
74      */
75     private final Open remoteOpen;
76
77     private static final Logger LOG = LoggerFactory.getLogger(PCEPSessionImpl.class);
78
79     private int sentMsgCount = 0;
80
81     private int receivedMsgCount = 0;
82
83     private int maxUnknownMessages;
84
85     // True if the listener should not be notified about events
86     private boolean closed = false;
87
88     private final Channel channel;
89
90     private final Keepalive kaMessage = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
91
92     PCEPSessionImpl(final PCEPSessionListener listener, final int maxUnknownMessages, final Channel channel,
93         final Open localOpen, final Open remoteOpen) {
94         this.listener = Preconditions.checkNotNull(listener);
95         this.channel = Preconditions.checkNotNull(channel);
96         this.localOpen = Preconditions.checkNotNull(localOpen);
97         this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
98         this.lastMessageReceivedAt = System.nanoTime();
99
100         if (maxUnknownMessages != 0) {
101             this.maxUnknownMessages = maxUnknownMessages;
102         }
103
104
105         if (getDeadTimerValue() != 0) {
106             channel.eventLoop().schedule(new Runnable() {
107                 @Override
108                 public void run() {
109                     handleDeadTimer();
110                 }
111             }, getDeadTimerValue(), TimeUnit.SECONDS);
112         }
113
114         if (getKeepAliveTimerValue() != 0) {
115             channel.eventLoop().schedule(new Runnable() {
116                 @Override
117                 public void run() {
118                     handleKeepaliveTimer();
119                 }
120             }, getKeepAliveTimerValue(), TimeUnit.SECONDS);
121         }
122
123         LOG.info("Session {}[{}] <-> {}[{}] started", channel.localAddress(), localOpen.getSessionId(), channel.remoteAddress(),
124             remoteOpen.getSessionId());
125     }
126
127     /**
128      * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
129      * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
130      * which the message was received. If the session was closed by the time this method starts to execute (the session
131      * state will become IDLE), that rescheduling won't occur.
132      */
133     private synchronized void handleDeadTimer() {
134         final long ct = System.nanoTime();
135
136         final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
137
138         if (this.channel.isActive()) {
139             if (ct >= nextDead) {
140                 LOG.debug("DeadTimer expired. {}", new Date());
141                 this.terminate(TerminationReason.ExpDeadtimer);
142             } else {
143                 this.channel.eventLoop().schedule(new Runnable() {
144                     @Override
145                     public void run() {
146                         handleDeadTimer();
147                     }
148                 }, nextDead - ct, TimeUnit.NANOSECONDS);
149             }
150         }
151     }
152
153     /**
154      * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
155      * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
156      * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
157      * starts to execute (the session state will become IDLE), that rescheduling won't occur.
158      */
159     private  void handleKeepaliveTimer() {
160         final long ct = System.nanoTime();
161
162         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
163
164         if (this.channel.isActive()) {
165             if (ct >= nextKeepalive) {
166                 this.sendMessage(this.kaMessage);
167                 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
168             }
169
170             this.channel.eventLoop().schedule(new Runnable() {
171                 @Override
172                 public void run() {
173                     handleKeepaliveTimer();
174                 }
175             }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
176         }
177     }
178
179     /**
180      * Sends message to serialization.
181      *
182      * @param msg to be sent
183      */
184     @Override
185     public Future<Void> sendMessage(final Message msg) {
186         final ChannelFuture f = this.channel.writeAndFlush(msg);
187         this.lastMessageSentAt = System.nanoTime();
188         if (!(msg instanceof KeepaliveMessage)) {
189             LOG.debug("PCEP Message enqueued: {}", msg);
190         }
191         this.sentMsgCount++;
192
193         f.addListener(new ChannelFutureListener() {
194             @Override
195             public void operationComplete(final ChannelFuture 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
204         return f;
205     }
206
207     /**
208      * Closes PCEP session without sending a Close message, as the channel is no longer active.
209      */
210     @Override
211     public void close() {
212         LOG.info("Closing PCEP session: {}", this);
213         this.channel.close();
214     }
215
216     /**
217      * Closes PCEP session, cancels all timers, returns to state Idle, sends the Close Message. KeepAlive and DeadTimer
218      * are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP session from
219      * inside the session or from the listener, therefore the parent of this session should be informed.
220      */
221     @Override
222     public synchronized void close(final TerminationReason reason) {
223         LOG.info("Closing PCEP session: {}", this);
224         this.closed = true;
225         this.sendMessage(new CloseBuilder().setCCloseMessage(
226             new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason(reason.getShortValue()).build()).build()).build());
227         this.channel.close();
228     }
229
230     @Override
231     public Tlvs getRemoteTlvs() {
232         return this.remoteOpen.getTlvs();
233     }
234
235     @Override
236     public InetAddress getRemoteAddress() {
237         return ((InetSocketAddress) this.channel.remoteAddress()).getAddress();
238     }
239
240     private synchronized void terminate(final TerminationReason reason) {
241         LOG.info("Local PCEP session termination : {}", reason);
242         this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
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 synchronized void endOfInput() {
251         if (!this.closed) {
252             this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
253             this.closed = true;
254         }
255     }
256
257     private void sendErrorMessage(final PCEPErrors value) {
258         this.sendErrorMessage(value, null);
259     }
260
261     /**
262      * Sends PCEP Error Message with one PCEPError and Open Object.
263      *
264      * @param value
265      * @param open
266      */
267     private void sendErrorMessage(final PCEPErrors value, final Open open) {
268         this.sendMessage(Util.createErrorMessage(value, open));
269     }
270
271     /**
272      * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
273      * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
274      * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
275      * sent.
276      *
277      * @param error documented error in RFC5440 or draft
278      */
279     @VisibleForTesting
280     public void handleMalformedMessage(final PCEPErrors error) {
281         final long ct = System.nanoTime();
282         this.sendErrorMessage(error);
283         if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
284             this.unknownMessagesTimes.add(ct);
285             while (ct - this.unknownMessagesTimes.peek() > 60 * 1E9) {
286                 this.unknownMessagesTimes.poll();
287             }
288             if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
289                 this.terminate(TerminationReason.TooManyUnknownMsg);
290             }
291         }
292     }
293
294     /**
295      * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
296      * except KeepAlive.
297      *
298      * @param msg incoming message
299      */
300     @Override
301     public synchronized void handleMessage(final Message msg) {
302         // Update last reception time
303         this.lastMessageReceivedAt = System.nanoTime();
304         this.receivedMsgCount++;
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             this.listener.onMessage(this, msg);
323         }
324     }
325
326     /**
327      * @return the sentMsgCount
328      */
329
330     @Override
331     public final Integer getSentMsgCount() {
332         return this.sentMsgCount;
333     }
334
335     /**
336      * @return the receivedMsgCount
337      */
338
339     @Override
340     public final Integer getReceivedMsgCount() {
341         return this.receivedMsgCount;
342     }
343
344     @Override
345     public final Integer getDeadTimerValue() {
346         return Integer.valueOf(this.remoteOpen.getDeadTimer());
347     }
348
349     @Override
350     public final Integer getKeepAliveTimerValue() {
351         return Integer.valueOf(this.localOpen.getKeepalive());
352     }
353
354     @Override
355     public final String getPeerAddress() {
356         final InetSocketAddress a = (InetSocketAddress) this.channel.remoteAddress();
357         return a.getHostName();
358     }
359
360     @Override
361     public void tearDown() {
362         this.close();
363     }
364
365     @Override
366     public final String toString() {
367         return addToStringAttributes(Objects.toStringHelper(this)).toString();
368     }
369
370     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
371         toStringHelper.add("channel", this.channel);
372         toStringHelper.add("localOpen", this.localOpen);
373         toStringHelper.add("remoteOpen", this.remoteOpen);
374         return toStringHelper;
375     }
376
377     @Override
378     @VisibleForTesting
379     public void sessionUp() {
380         this.listener.onSessionUp(this);
381     }
382
383     @Override
384     public String getNodeIdentifier() {
385         return "";
386     }
387 }