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