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