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