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