2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.pcep.impl;
10 import io.netty.channel.ChannelHandlerContext;
12 import java.io.IOException;
13 import java.util.ArrayList;
14 import java.util.Date;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Queue;
18 import java.util.Timer;
19 import java.util.TimerTask;
21 import org.opendaylight.protocol.framework.DeserializerException;
22 import org.opendaylight.protocol.framework.DocumentedException;
23 import org.opendaylight.protocol.framework.ProtocolMessage;
24 import org.opendaylight.protocol.framework.ProtocolMessageFactory;
25 import org.opendaylight.protocol.framework.ProtocolSession;
26 import org.opendaylight.protocol.framework.ProtocolSessionOutboundHandler;
27 import org.opendaylight.protocol.framework.SessionParent;
28 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
29 import org.opendaylight.protocol.pcep.PCEPConnection;
30 import org.opendaylight.protocol.pcep.PCEPDeserializerException;
31 import org.opendaylight.protocol.pcep.PCEPErrorTermination;
32 import org.opendaylight.protocol.pcep.PCEPErrors;
33 import org.opendaylight.protocol.pcep.PCEPMessage;
34 import org.opendaylight.protocol.pcep.PCEPSession;
35 import org.opendaylight.protocol.pcep.PCEPSessionListener;
36 import org.opendaylight.protocol.pcep.PCEPSessionPreferences;
37 import org.opendaylight.protocol.pcep.PCEPSessionProposalChecker;
38 import org.opendaylight.protocol.pcep.PCEPTlv;
39 import org.opendaylight.protocol.pcep.impl.message.PCEPRawMessage;
40 import org.opendaylight.protocol.pcep.message.PCEPCloseMessage;
41 import org.opendaylight.protocol.pcep.message.PCEPErrorMessage;
42 import org.opendaylight.protocol.pcep.message.PCEPKeepAliveMessage;
43 import org.opendaylight.protocol.pcep.message.PCEPOpenMessage;
44 import org.opendaylight.protocol.pcep.object.PCEPCloseObject;
45 import org.opendaylight.protocol.pcep.object.PCEPCloseObject.Reason;
46 import org.opendaylight.protocol.pcep.object.PCEPErrorObject;
47 import org.opendaylight.protocol.pcep.object.PCEPOpenObject;
48 import org.opendaylight.protocol.pcep.tlv.NodeIdentifierTlv;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Implementation of PCEPSession. (Not final for testing.)
55 class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntimeMXBean {
58 * KeepAlive Timer is to be scheduled periodically, each time it starts, it sends KeepAlive Message.
60 private class KeepAliveTimer extends TimerTask {
61 private final PCEPSessionImpl parent;
63 public KeepAliveTimer(final PCEPSessionImpl parent) {
69 this.parent.handleKeepaliveTimer();
74 * DeadTimer is to be scheduled periodically, when it expires, it closes PCEP session.
76 private class DeadTimer extends TimerTask {
77 private final PCEPSessionImpl parent;
79 public DeadTimer(final PCEPSessionImpl parent) {
85 this.parent.handleDeadtimer();
90 * OpenWaitTimer runs just once, but can be rescheduled or canceled before expiration. When it expires, it sends an
91 * error message (1, 2)
93 private class OpenWaitTimer extends TimerTask {
95 private final PCEPSessionImpl parent;
97 public OpenWaitTimer(final PCEPSessionImpl parent) {
103 this.parent.handleOpenWait();
108 * KeepWaitTimer runs just once, but can be rescheduled or canceled before expiration. When it expires, it sends an
109 * error message (1, 7)
111 private class KeepWaitTimer extends TimerTask {
113 private final PCEPSessionImpl parent;
115 public KeepWaitTimer(final PCEPSessionImpl parent) {
116 this.parent = parent;
121 this.parent.handleKeepWait();
126 * Possible states for Finite State Machine
129 IDLE, OPEN_WAIT, KEEP_WAIT, UP
135 public static final int OPEN_WAIT_TIMER_VALUE = 60;
137 public static final int KEEP_WAIT_TIMER_VALUE = 60;
139 public int KEEP_ALIVE_TIMER_VALUE = 3;
141 public int DEAD_TIMER_VALUE = 4 * this.KEEP_ALIVE_TIMER_VALUE;
144 * Actual state of the FSM.
148 private OpenWaitTimer openWaitTimer;
150 private KeepWaitTimer keepWaitTimer;
153 * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
155 protected long lastMessageSentAt;
158 * System.nanoTime value about when was received the last message
160 private long lastMessageReceivedAt;
162 private boolean localOK = false;
164 private boolean remoteOK = false;
166 private boolean openRetry = false;
168 private final int sessionId;
171 * Protected for testing.
173 protected int maxUnknownMessages = 5;
175 protected final Queue<Long> unknownMessagesTimes = new LinkedList<Long>();
177 private final PCEPSessionListener listener;
179 private PCEPSessionProposalChecker checker = null;
182 * Open Object with session characteristics that were accepted by another PCE (sent from this session).
184 private PCEPOpenObject localOpen = null;
187 * Open Object with session characteristics for this session (sent from another PCE).
189 private PCEPOpenObject remoteOpen = null;
191 private static final Logger logger = LoggerFactory.getLogger(PCEPSessionImpl.class);
194 * Timer object grouping FSM Timers
196 private final Timer stateTimer;
198 private final SessionParent parent;
200 private final PCEPMessageFactory factory;
202 private int sentMsgCount = 0;
204 private int receivedMsgCount = 0;
206 private final String peerAddress;
208 private final ProtocolSessionOutboundHandler handler;
210 private final ChannelHandlerContext ctx;
212 PCEPSessionImpl(final SessionParent parent, final Timer timer, final PCEPConnection connection, final PCEPMessageFactory factory,
213 final int maxUnknownMessages, final int sessionId, final ChannelHandlerContext ctx) {
214 this.state = State.IDLE;
215 this.listener = connection.getListener();
216 this.checker = connection.getProposalChecker();
217 this.sessionId = sessionId;
218 this.localOpen = connection.getProposal().getOpenObject();
219 this.peerAddress = connection.getPeerAddress().getHostString();
220 this.stateTimer = timer;
221 this.parent = parent;
222 this.factory = factory;
224 if (this.maxUnknownMessages != 0)
225 this.maxUnknownMessages = maxUnknownMessages;
226 this.handler = new ProtocolSessionOutboundHandler(this);
230 public void startSession() {
231 logger.debug("Session started.");
232 this.sendMessage(new PCEPOpenMessage(this.localOpen));
233 this.restartOpenWait();
234 this.changeState(State.OPEN_WAIT);
238 * OpenWait timer can be canceled or rescheduled before its expiration. When it expires, it sends particular
239 * PCEPErrorMessage and closes PCEP session.
241 private synchronized void handleOpenWait() {
242 if (this.state != State.IDLE) {
243 this.terminate(PCEPErrors.NO_OPEN_BEFORE_EXP_OPENWAIT); // 1, 1
248 * KeepWait timer can be canceled or rescheduled before its expiration. When it expires, it sends particular
249 * PCEPErrorMessage and closes PCEP session.
251 private synchronized void handleKeepWait() {
252 if (this.state != State.IDLE) {
253 this.terminate(PCEPErrors.NO_MSG_BEFORE_EXP_KEEPWAIT); // 1, 7
258 * If DeadTimer expires, the session ends. If a message (whichever) was received during this period, the DeadTimer
259 * will be rescheduled by DEAD_TIMER_VALUE + the time that has passed from the start of the DeadTimer to the time at
260 * which the message was received. If the session was closed by the time this method starts to execute (the session
261 * state will become IDLE), that rescheduling won't occur.
263 private synchronized void handleDeadtimer() {
264 final long ct = System.nanoTime();
266 final long nextDead = (long) (this.lastMessageReceivedAt + (this.DEAD_TIMER_VALUE * 1E9));
268 if (this.state != State.IDLE) {
269 if (ct >= nextDead) {
270 logger.debug("DeadTimer expired. " + new Date());
271 this.terminate(Reason.EXP_DEADTIMER);
275 this.stateTimer.schedule(new DeadTimer(this), (long) ((nextDead - ct) / 1E6));
280 * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
281 * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
282 * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
283 * starts to execute (the session state will become IDLE), that rescheduling won't occur.
285 private synchronized void handleKeepaliveTimer() {
286 final long ct = System.nanoTime();
288 long nextKeepalive = (long) (this.lastMessageSentAt + (this.KEEP_ALIVE_TIMER_VALUE * 1E9));
290 if (this.state != State.IDLE) {
291 if (ct >= nextKeepalive) {
292 this.sendMessage(new PCEPKeepAliveMessage());
293 nextKeepalive = (long) (this.lastMessageSentAt + (this.KEEP_ALIVE_TIMER_VALUE * 1E9));
296 this.stateTimer.schedule(new KeepAliveTimer(this), (long) ((nextKeepalive - ct) / 1E6));
300 private void changeState(final State finalState) {
301 switch (finalState) {
303 logger.debug("Changed to state: " + State.IDLE);
304 this.state = State.IDLE;
307 logger.debug("Changed to state: " + State.OPEN_WAIT);
308 if (this.state == State.UP) {
309 throw new IllegalArgumentException("Cannot change state from " + this.state + " to " + State.OPEN_WAIT);
311 this.state = State.OPEN_WAIT;
314 logger.debug("Changed to state: " + State.KEEP_WAIT);
315 if (this.state == State.UP || this.state == State.IDLE) {
316 throw new IllegalArgumentException("Cannot change state from " + this.state + " to " + State.KEEP_WAIT);
318 this.state = State.KEEP_WAIT;
321 logger.debug("Changed to state: " + State.UP);
322 if (this.state == State.IDLE || this.state == State.UP) {
323 throw new IllegalArgumentException("Cannot change state from " + this.state + " to " + State.UP);
325 this.state = State.UP;
330 private void restartOpenWait() {
331 if (this.state == State.OPEN_WAIT && this.openWaitTimer != null) {
332 this.openWaitTimer.cancel();
334 this.openWaitTimer = new OpenWaitTimer(this);
335 this.stateTimer.schedule(this.openWaitTimer, OPEN_WAIT_TIMER_VALUE * 1000);
338 private void restartKeepWaitTimer() {
339 if (this.state == State.KEEP_WAIT && this.keepWaitTimer != null) {
340 this.keepWaitTimer.cancel();
342 this.keepWaitTimer = new KeepWaitTimer(this);
343 this.stateTimer.schedule(this.keepWaitTimer, KEEP_WAIT_TIMER_VALUE * 1000);
347 * Makes a callback to check if the session characteristics that FSM received, are acceptable.
349 * @param keepAliveTimerValue
350 * @param deadTimerValue
354 private boolean checkSessionCharacteristics(final PCEPOpenObject openObj) {
355 return this.checker.checkSessionCharacteristics(new PCEPSessionPreferences(openObj));
358 private PCEPOpenObject getNewProposal() {
359 return this.checker.getNewProposal(new PCEPSessionPreferences(this.localOpen)).getOpenObject();
363 * Sends message to serialization.
365 * @param msg to be sent
368 public void sendMessage(final PCEPMessage msg) {
370 this.handler.writeDown(this.ctx, msg);
371 this.lastMessageSentAt = System.nanoTime();
372 if (!(msg instanceof PCEPKeepAliveMessage))
373 logger.debug("Sent message: " + msg);
375 } catch (final Exception e) {
376 logger.warn("Message {} was not sent.", msg, e);
380 private void commonClose() {
381 this.changeState(State.IDLE);
382 this.parent.onSessionClosed(this);
386 * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
387 * modified, because he initiated the closing. (To prevent concurrent modification exception).
391 void closeWithoutMessage() {
392 logger.debug("Closing session: {}", this);
397 * Closes PCEP session, cancels all timers, returns to state Idle WITHOUT sending the Close Message. KeepAlive and
398 * DeadTimer are cancelled if the state of the session changes to IDLE. This method is used to close the PCEP
399 * session from inside the session or from the listener, therefore the parent of this session should be informed.
400 * The only closing reason is UNKNOWN.
403 public synchronized void close() {
404 logger.debug("Closing session: {}", this);
405 this.sendMessage(new PCEPCloseMessage(new PCEPCloseObject(Reason.UNKNOWN)));
409 private void terminate(final PCEPCloseObject.Reason reason) {
410 this.sendMessage(new PCEPCloseMessage(new PCEPCloseObject(reason)));
411 this.closeWithoutMessage();
412 this.listener.onSessionTerminated(this, new PCEPCloseTermination(reason));
415 private void terminate(final PCEPErrors error) {
416 this.sendErrorMessage(error);
417 this.closeWithoutMessage();
418 this.listener.onSessionTerminated(this, new PCEPErrorTermination(error));
422 public void endOfInput() {
423 if (this.state != State.IDLE) {
424 this.listener.onSessionDown(this, null, new IOException("End of input detected. Close the session."));
429 public int maximumMessageSize() {
433 private void sendErrorMessage(final PCEPErrors value) {
434 this.sendErrorMessage(value, null);
438 * Sends PCEP Error Message with one PCEPError and Open Object.
443 private void sendErrorMessage(final PCEPErrors value, final PCEPOpenObject open) {
444 final PCEPErrorObject error = new PCEPErrorObject(value);
445 final List<PCEPErrorObject> errors = new ArrayList<PCEPErrorObject>();
447 this.sendMessage(new PCEPErrorMessage(open, errors, null));
451 public void handleMalformedMessage(final DeserializerException e) {
457 public void handleMalformedMessage(final DocumentedException e) {
463 * The fact, that a message is malformed, comes from parser. In case of unrecognized message a particular error is
464 * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
465 * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
468 * @param error documented error in RFC5440 or draft
470 public void handleMalformedMessage(final PCEPErrors error) {
471 final long ct = System.nanoTime();
472 this.sendErrorMessage(error);
473 if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
474 this.unknownMessagesTimes.add(ct);
475 while (ct - this.unknownMessagesTimes.peek() > 60 * 1E9) {
476 this.unknownMessagesTimes.poll();
478 if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
479 this.terminate(Reason.TOO_MANY_UNKNOWN_MSG);
485 * In case of syntactic error or some parsing error, the session needs to be closed with the Reason: malformed
486 * message. The user needs to be notified about this error.
488 * @param e exception that was thrown from parser
490 public void handleMalformedMessage(final Exception e) {
491 logger.warn("PCEP byte stream corruption detected", e);
492 this.terminate(Reason.MALFORMED_MSG);
496 * Open message should be handled only if the FSM is in OPEN_WAIT state.
500 private void handleOpenMessage(final PCEPOpenMessage msg) {
501 this.remoteOpen = msg.getOpenObject();
502 logger.debug("Received message: " + msg.toString());
503 if (this.state != State.OPEN_WAIT) {
504 this.sendErrorMessage(PCEPErrors.ATTEMPT_2ND_SESSION);
507 final Boolean result = this.checkSessionCharacteristics(this.remoteOpen);
508 if (result == null) {
509 this.terminate(PCEPErrors.NON_ACC_NON_NEG_SESSION_CHAR); // 1, 3
512 this.DEAD_TIMER_VALUE = this.remoteOpen.getDeadTimerValue();
513 this.KEEP_ALIVE_TIMER_VALUE = this.remoteOpen.getKeepAliveTimerValue();
514 logger.debug("Session chars are acceptable. Overwriting: deadtimer: " + this.DEAD_TIMER_VALUE + "keepalive: "
515 + this.KEEP_ALIVE_TIMER_VALUE);
516 this.remoteOK = true;
517 this.openWaitTimer.cancel();
518 this.sendMessage(new PCEPKeepAliveMessage());
519 // if the timer is not disabled
520 if (this.KEEP_ALIVE_TIMER_VALUE != 0) {
521 this.stateTimer.schedule(new KeepAliveTimer(this), this.KEEP_ALIVE_TIMER_VALUE * 1000);
524 // if the timer is not disabled
525 if (this.DEAD_TIMER_VALUE != 0) {
526 this.stateTimer.schedule(new DeadTimer(this), this.DEAD_TIMER_VALUE * 1000);
528 this.changeState(State.UP);
529 this.listener.onSessionUp(this, this.localOpen, this.remoteOpen);
531 this.restartKeepWaitTimer();
532 this.changeState(State.KEEP_WAIT);
535 } else if (!result) {
536 this.localOpen = this.getNewProposal();
537 if (this.openRetry) {
538 this.terminate(PCEPErrors.SECOND_OPEN_MSG); // 1, 5
540 this.openRetry = true;
541 this.sendErrorMessage(PCEPErrors.NON_ACC_NEG_SESSION_CHAR, this.localOpen); // 1, 4
543 this.restartOpenWait();
544 this.changeState(State.OPEN_WAIT);
546 this.restartKeepWaitTimer();
547 this.changeState(State.KEEP_WAIT);
554 * Error message should be handled in FSM if its state is KEEP_WAIT, otherwise it is just passed to session listener
559 private void handleErrorMessage(final PCEPErrorMessage msg) {
560 this.remoteOpen = msg.getOpenObject();
561 final Boolean result = this.checkSessionCharacteristics(this.remoteOpen);
562 if (result == null || !result) {
563 this.terminate(PCEPErrors.PCERR_NON_ACC_SESSION_CHAR); // 1, 6
566 this.KEEP_ALIVE_TIMER_VALUE = this.remoteOpen.getKeepAliveTimerValue();
567 this.DEAD_TIMER_VALUE = this.remoteOpen.getDeadTimerValue();
568 logger.debug("New values for keepalive: " + this.remoteOpen.getKeepAliveTimerValue() + " deadtimer "
569 + this.remoteOpen.getDeadTimerValue());
570 this.sendMessage(new PCEPOpenMessage(this.remoteOpen));
572 this.restartKeepWaitTimer();
573 this.changeState(State.KEEP_WAIT);
575 this.keepWaitTimer.cancel();
576 this.restartOpenWait();
577 this.changeState(State.OPEN_WAIT);
583 * KeepAlive message should be explicitly parsed in FSM when its state is KEEP_WAIT. Otherwise is handled by the
584 * KeepAliveTimer or it's invalid.
586 private void handleKeepAliveMessage() {
587 if (this.state == State.KEEP_WAIT) {
589 this.keepWaitTimer.cancel();
591 if (this.DEAD_TIMER_VALUE != 0) {
592 this.stateTimer.schedule(new DeadTimer(this), this.DEAD_TIMER_VALUE * 1000);
594 this.changeState(State.UP);
595 this.listener.onSessionUp(this, this.localOpen, this.remoteOpen);
597 this.restartOpenWait();
598 this.changeState(State.OPEN_WAIT);
604 * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
607 * @param msg incoming message
610 public void handleMessage(final ProtocolMessage msg) {
611 // Update last reception time
612 final PCEPMessage pcepMsg = (PCEPMessage) msg;
614 this.lastMessageReceivedAt = System.nanoTime();
615 this.receivedMsgCount++;
617 if (pcepMsg instanceof PCEPRawMessage) {
618 List<PCEPMessage> msgs;
620 msgs = PCEPMessageValidator.getValidator(((PCEPRawMessage) pcepMsg).getMsgType()).validate(
621 ((PCEPRawMessage) pcepMsg).getAllObjects());
622 for (final PCEPMessage tmpMsg : msgs) {
623 this.handleMessage(tmpMsg);
625 } catch (final PCEPDeserializerException e) {
626 logger.error("Malformed message, terminating. ", e);
627 this.terminate(Reason.MALFORMED_MSG);
632 // Keepalives are handled internally
633 if (pcepMsg instanceof PCEPKeepAliveMessage) {
634 this.handleKeepAliveMessage();
638 // Open messages are handled internally
639 if (pcepMsg instanceof PCEPOpenMessage) {
640 this.handleOpenMessage((PCEPOpenMessage) pcepMsg);
645 * During initial handshake we handle all the messages.
647 if (this.state != State.UP) {
649 * In KEEP_WAIT, an Error message is a valid thing to see, because
650 * it is used in negotiation.
652 if (pcepMsg instanceof PCEPErrorMessage && this.state == State.KEEP_WAIT
653 && ((PCEPErrorMessage) pcepMsg).getOpenObject() != null) {
654 this.handleErrorMessage((PCEPErrorMessage) pcepMsg);
659 * OPEN and KEEPALIVE messages are handled at the top. ERROR
660 * messages are handled in the specific case of KEEP_WAIT above, so
661 * anything else is invalid here.
663 this.terminate(PCEPErrors.NON_OR_INVALID_OPEN_MSG);
668 * Session is up, we are reporting all messages to user. One notable
669 * exception is CLOSE message, which needs to be converted into a
670 * session DOWN event.
672 if (pcepMsg instanceof PCEPCloseMessage) {
673 this.listener.onSessionTerminated(this, new PCEPCloseTermination(((PCEPCloseMessage) pcepMsg).getCloseObject().getReason()));
674 this.closeWithoutMessage();
677 this.listener.onMessage(this, pcepMsg);
681 public ProtocolMessageFactory getMessageFactory() {
686 public void onConnectionFailed(final IOException e) {
687 logger.info("Connection failed before finishing: {}", e.getMessage(), e);
688 this.listener.onSessionDown(this, new PCEPCloseObject(Reason.UNKNOWN), e);
692 * @return the sentMsgCount
696 public Integer getSentMsgCount() {
697 return this.sentMsgCount;
701 * @return the receivedMsgCount
705 public Integer getReceivedMsgCount() {
706 return this.receivedMsgCount;
710 public Integer getDeadTimerValue() {
711 return this.DEAD_TIMER_VALUE;
715 public Integer getKeepAliveTimerValue() {
716 return this.KEEP_ALIVE_TIMER_VALUE;
720 public String getPeerAddress() {
721 return this.peerAddress;
725 public void tearDown() throws IOException {
730 public String getNodeIdentifier() {
731 if (!this.remoteOpen.getTlvs().isEmpty()) {
732 final PCEPTlv tlv = this.remoteOpen.getTlvs().iterator().next();
733 if (tlv != null && tlv instanceof NodeIdentifierTlv) {
734 return tlv.toString();
741 public String toString() {
742 final StringBuilder builder = new StringBuilder();
743 builder.append("PCEPSessionImpl [state=");
744 builder.append(this.state);
745 builder.append(", localOK=");
746 builder.append(this.localOK);
747 builder.append(", remoteOK=");
748 builder.append(this.remoteOK);
749 builder.append(", openRetry=");
750 builder.append(this.openRetry);
751 builder.append(", sessionId=");
752 builder.append(this.sessionId);
753 builder.append(", checker=");
754 builder.append(this.checker);
755 builder.append(", localOpen=");
756 builder.append(this.localOpen);
757 builder.append(", remoteOpen=");
758 builder.append(this.remoteOpen);
760 return builder.toString();