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