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