blob: 6fe05e045b83785ca7718dc00ec5207aea59ed1e [file] [log] [blame]
SureshBR25058b72015-08-13 13:05:06 +05301/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
SureshBR25058b72015-08-13 13:05:06 +05303 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.pcep.controller.impl;
18
19import java.io.IOException;
20import java.net.InetSocketAddress;
21import java.net.SocketAddress;
22import java.nio.channels.ClosedChannelException;
23import java.util.Collections;
24import java.util.Date;
25import java.util.LinkedList;
26import java.util.List;
27import java.util.ListIterator;
28import java.util.concurrent.RejectedExecutionException;
29
30import org.jboss.netty.channel.Channel;
31import org.jboss.netty.channel.ChannelHandlerContext;
32import org.jboss.netty.channel.ChannelStateEvent;
33import org.jboss.netty.channel.ExceptionEvent;
34import org.jboss.netty.channel.MessageEvent;
35import org.jboss.netty.handler.timeout.IdleState;
36import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
37import org.jboss.netty.handler.timeout.IdleStateEvent;
38import org.jboss.netty.handler.timeout.IdleStateHandler;
39import org.jboss.netty.handler.timeout.ReadTimeoutException;
40import org.onlab.packet.IpAddress;
Priyanka Bd2b28882016-04-04 16:57:04 +053041import org.onosproject.pcep.controller.ClientCapability;
SureshBR25058b72015-08-13 13:05:06 +053042import org.onosproject.pcep.controller.PccId;
43import org.onosproject.pcep.controller.driver.PcepClientDriver;
44import org.onosproject.pcepio.exceptions.PcepParseException;
45import org.onosproject.pcepio.protocol.PcepError;
46import org.onosproject.pcepio.protocol.PcepErrorInfo;
47import org.onosproject.pcepio.protocol.PcepErrorMsg;
48import org.onosproject.pcepio.protocol.PcepErrorObject;
49import org.onosproject.pcepio.protocol.PcepFactory;
50import org.onosproject.pcepio.protocol.PcepMessage;
51import org.onosproject.pcepio.protocol.PcepOpenMsg;
52import org.onosproject.pcepio.protocol.PcepOpenObject;
53import org.onosproject.pcepio.protocol.PcepType;
54import org.onosproject.pcepio.protocol.PcepVersion;
Avantika-Huawei56c11842016-04-28 00:56:56 +053055import org.onosproject.pcepio.types.IPv4RouterIdOfLocalNodeSubTlv;
56import org.onosproject.pcepio.types.NodeAttributesTlv;
SureshBR25058b72015-08-13 13:05:06 +053057import org.onosproject.pcepio.types.PceccCapabilityTlv;
Priyanka B94395bf2016-05-21 18:39:46 +053058import org.onosproject.pcepio.types.SrPceCapabilityTlv;
SureshBR25058b72015-08-13 13:05:06 +053059import org.onosproject.pcepio.types.StatefulPceCapabilityTlv;
60import org.onosproject.pcepio.types.PcepErrorDetailInfo;
61import org.onosproject.pcepio.types.PcepValueType;
62import org.slf4j.Logger;
63import org.slf4j.LoggerFactory;
64
65/**
66 * Channel handler deals with the pcc client connection and dispatches
67 * messages from client to the appropriate locations.
68 */
69class PcepChannelHandler extends IdleStateAwareChannelHandler {
70 static final byte DEADTIMER_MAXIMUM_VALUE = (byte) 0xFF;
71 static final byte KEEPALIVE_MULTIPLE_FOR_DEADTIMER = 4;
72 private static final Logger log = LoggerFactory.getLogger(PcepChannelHandler.class);
73 private final Controller controller;
74 private PcepClientDriver pc;
75 private PccId thispccId;
76 private Channel channel;
77 private byte sessionId = 0;
78 private byte keepAliveTime;
79 private byte deadTime;
Priyanka Bd2b28882016-04-04 16:57:04 +053080 private ClientCapability capability;
SureshBR25058b72015-08-13 13:05:06 +053081 private PcepPacketStatsImpl pcepPacketStats;
82 static final int MAX_WRONG_COUNT_PACKET = 5;
83 static final int BYTE_MASK = 0xFF;
84
85 // State needs to be volatile because the HandshakeTimeoutHandler
86 // needs to check if the handshake is complete
87 private volatile ChannelState state;
88
89 // When a pcc client with a ip addresss is found (i.e we already have a
90 // connected client with the same ip), the new client is immediately
91 // disconnected. At that point netty callsback channelDisconnected() which
92 // proceeds to cleaup client state - we need to ensure that it does not cleanup
93 // client state for the older (still connected) client
94 private volatile Boolean duplicatePccIdFound;
95
96 //Indicates the pcep version used by this pcc client
97 protected PcepVersion pcepVersion;
98 protected PcepFactory factory1;
99
100 /**
101 * Create a new unconnected PcepChannelHandler.
102 * @param controller parent controller
103 */
104 PcepChannelHandler(Controller controller) {
105 this.controller = controller;
106 this.state = ChannelState.INIT;
107 factory1 = controller.getPcepMessageFactory1();
108 duplicatePccIdFound = Boolean.FALSE;
109 pcepPacketStats = new PcepPacketStatsImpl();
110 }
111
112 /**
113 * To disconnect a PCC.
114 */
115 public void disconnectClient() {
116 pc.disconnectClient();
117 }
118
119 //*************************
120 // Channel State Machine
121 //*************************
122
123 /**
124 * The state machine for handling the client/channel state. All state
125 * transitions should happen from within the state machine (and not from other
126 * parts of the code)
127 */
128 enum ChannelState {
129 /**
130 * Initial state before channel is connected.
131 */
132 INIT(false) {
133
134 },
135 /**
136 * Once the session is established, wait for open message.
137 */
138 OPENWAIT(false) {
139 @Override
140 void processPcepMessage(PcepChannelHandler h, PcepMessage m) throws IOException, PcepParseException {
141
Avantika-Huawei56c11842016-04-28 00:56:56 +0530142 log.info("Message received in OPEN WAIT State");
SureshBR25058b72015-08-13 13:05:06 +0530143
144 //check for open message
145 if (m.getType() != PcepType.OPEN) {
146 // When the message type is not open message increment the wrong packet statistics
147 h.processUnknownMsg();
148 log.debug("message is not OPEN message");
149 } else {
150
151 h.pcepPacketStats.addInPacket();
152 PcepOpenMsg pOpenmsg = (PcepOpenMsg) m;
Priyanka Bd2b28882016-04-04 16:57:04 +0530153 //Do Capability negotiation.
154 h.capabilityNegotiation(pOpenmsg);
SureshBR25058b72015-08-13 13:05:06 +0530155 log.debug("Sending handshake OPEN message");
156 h.sessionId = pOpenmsg.getPcepOpenObject().getSessionId();
157 h.pcepVersion = pOpenmsg.getPcepOpenObject().getVersion();
158
159 //setting keepalive and deadTimer
160 byte yKeepalive = pOpenmsg.getPcepOpenObject().getKeepAliveTime();
161 byte yDeadTimer = pOpenmsg.getPcepOpenObject().getDeadTime();
162 h.keepAliveTime = yKeepalive;
163 if (yKeepalive < yDeadTimer) {
164 h.deadTime = yDeadTimer;
165 } else {
166 if (DEADTIMER_MAXIMUM_VALUE > (yKeepalive * KEEPALIVE_MULTIPLE_FOR_DEADTIMER)) {
167 h.deadTime = (byte) (yKeepalive * KEEPALIVE_MULTIPLE_FOR_DEADTIMER);
168 } else {
169 h.deadTime = DEADTIMER_MAXIMUM_VALUE;
170 }
171 }
Avantika-Huawei56c11842016-04-28 00:56:56 +0530172
Avantika-Huawei7f7376a2016-05-11 17:07:50 +0530173 /*
174 * If MPLS LSR id and PCEP session socket IP addresses are not same,
175 * the MPLS LSR id will be encoded in separate TLV.
176 * We always maintain session information based on LSR ids.
177 * The socket IP is stored in channel.
178 */
Avantika-Huawei56c11842016-04-28 00:56:56 +0530179 LinkedList<PcepValueType> optionalTlvs = pOpenmsg.getPcepOpenObject().getOptionalTlv();
Avantika-Huawei3524d852016-06-04 20:44:13 +0530180 if (optionalTlvs != null) {
181 for (PcepValueType optionalTlv : optionalTlvs) {
182 if (optionalTlv instanceof NodeAttributesTlv) {
183 List<PcepValueType> subTlvs = ((NodeAttributesTlv) optionalTlv)
184 .getllNodeAttributesSubTLVs();
185 if (subTlvs == null) {
Avantika-Huawei56c11842016-04-28 00:56:56 +0530186 break;
187 }
Avantika-Huawei3524d852016-06-04 20:44:13 +0530188 for (PcepValueType subTlv : subTlvs) {
189 if (subTlv instanceof IPv4RouterIdOfLocalNodeSubTlv) {
190 h.thispccId = PccId.pccId(IpAddress
191 .valueOf(((IPv4RouterIdOfLocalNodeSubTlv) subTlv).getInt()));
192 break;
193 }
194 }
195 break;
Avantika-Huawei56c11842016-04-28 00:56:56 +0530196 }
Avantika-Huawei56c11842016-04-28 00:56:56 +0530197 }
198 }
199
200 if (h.thispccId == null) {
201 final SocketAddress address = h.channel.getRemoteAddress();
202 if (!(address instanceof InetSocketAddress)) {
203 throw new IOException("Invalid client connection. Pcc is indentifed based on IP");
204 }
205
206 final InetSocketAddress inetAddress = (InetSocketAddress) address;
207 h.thispccId = PccId.pccId(IpAddress.valueOf(inetAddress.getAddress()));
208 }
209
SureshBR25058b72015-08-13 13:05:06 +0530210 h.sendHandshakeOpenMessage();
211 h.pcepPacketStats.addOutPacket();
212 h.setState(KEEPWAIT);
SureshBR25058b72015-08-13 13:05:06 +0530213 }
214 }
215 },
216 /**
217 * Once the open messages are exchanged, wait for keep alive message.
218 */
219 KEEPWAIT(false) {
220 @Override
221 void processPcepMessage(PcepChannelHandler h, PcepMessage m) throws IOException, PcepParseException {
Avantika-Huawei56c11842016-04-28 00:56:56 +0530222 log.info("message received in KEEPWAIT state");
SureshBR25058b72015-08-13 13:05:06 +0530223 //check for keep alive message
224 if (m.getType() != PcepType.KEEP_ALIVE) {
225 // When the message type is not keep alive message increment the wrong packet statistics
226 h.processUnknownMsg();
Avantika-Huawei56c11842016-04-28 00:56:56 +0530227 log.error("message is not KEEPALIVE message");
SureshBR25058b72015-08-13 13:05:06 +0530228 } else {
229 // Set the client connected status
230 h.pcepPacketStats.addInPacket();
SureshBR25058b72015-08-13 13:05:06 +0530231 log.debug("sending keep alive message in KEEPWAIT state");
SureshBR25058b72015-08-13 13:05:06 +0530232 h.pc = h.controller.getPcepClientInstance(h.thispccId, h.sessionId, h.pcepVersion,
233 h.pcepPacketStats);
Priyanka Bd2b28882016-04-04 16:57:04 +0530234 //Get pc instance and set capabilities
235 h.pc.setCapability(h.capability);
SureshBR25058b72015-08-13 13:05:06 +0530236 // set the status of pcc as connected
237 h.pc.setConnected(true);
238 h.pc.setChannel(h.channel);
239
240 // set any other specific parameters to the pcc
241 h.pc.setPcVersion(h.pcepVersion);
242 h.pc.setPcSessionId(h.sessionId);
243 h.pc.setPcKeepAliveTime(h.keepAliveTime);
244 h.pc.setPcDeadTime(h.deadTime);
245 int keepAliveTimer = h.keepAliveTime & BYTE_MASK;
246 int deadTimer = h.deadTime & BYTE_MASK;
247 if (0 == h.keepAliveTime) {
248 h.deadTime = 0;
249 }
250 // handle keep alive and dead time
251 if (keepAliveTimer != PcepPipelineFactory.DEFAULT_KEEP_ALIVE_TIME
252 || deadTimer != PcepPipelineFactory.DEFAULT_DEAD_TIME) {
253
254 h.channel.getPipeline().replace("idle", "idle",
255 new IdleStateHandler(PcepPipelineFactory.TIMER, deadTimer, keepAliveTimer, 0));
256 }
257 log.debug("Dead timer : " + deadTimer);
258 log.debug("Keep alive time : " + keepAliveTimer);
259
260 //set the state handshake completion.
261 h.sendKeepAliveMessage();
262 h.pcepPacketStats.addOutPacket();
263 h.setHandshakeComplete(true);
264
265 if (!h.pc.connectClient()) {
266 disconnectDuplicate(h);
267 } else {
268 h.setState(ESTABLISHED);
Avantika-Huaweife44ea62016-05-27 19:21:24 +0530269 //Session is established, add a network configuration with LSR id and device capabilities.
Priyanka B94395bf2016-05-21 18:39:46 +0530270 h.addNode();
SureshBR25058b72015-08-13 13:05:06 +0530271 }
272 }
273 }
274 },
275 /**
276 * Once the keep alive messages are exchanged, the state is established.
277 */
278 ESTABLISHED(true) {
279 @Override
280 void processPcepMessage(PcepChannelHandler h, PcepMessage m) throws IOException, PcepParseException {
281
282 //h.channel.getPipeline().remove("waittimeout");
283 log.debug("Message received in established state " + m.getType());
284 //dispatch the message
285 h.dispatchMessage(m);
286 }
287 };
288 private boolean handshakeComplete;
289
290 ChannelState(boolean handshakeComplete) {
291 this.handshakeComplete = handshakeComplete;
292 }
293
294 void processPcepMessage(PcepChannelHandler h, PcepMessage m) throws IOException, PcepParseException {
295 // do nothing
296 }
297
298 /**
299 * Is this a state in which the handshake has completed.
300 *
301 * @return true if the handshake is complete
302 */
303 public boolean isHandshakeComplete() {
304 return this.handshakeComplete;
305 }
306
307 protected void disconnectDuplicate(PcepChannelHandler h) {
308 log.error("Duplicated Pcc IP or incompleted cleanup - " + "disconnecting channel {}",
309 h.getClientInfoString());
310 h.duplicatePccIdFound = Boolean.TRUE;
311 h.channel.disconnect();
312 }
313
314 /**
315 * Sets handshake complete status.
316 *
317 * @param handshakeComplete status of handshake
318 */
319 public void setHandshakeComplete(boolean handshakeComplete) {
320 this.handshakeComplete = handshakeComplete;
321 }
322
323 }
324
325 @Override
326 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
327 channel = e.getChannel();
328 log.info("PCC connected from {}", channel.getRemoteAddress());
329
330 // Wait for open message from pcc client
331 setState(ChannelState.OPENWAIT);
332 }
333
334 @Override
335 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
336 log.info("Pcc disconnected callback for pc:{}. Cleaning up ...", getClientInfoString());
337 if (thispccId != null) {
338 if (!duplicatePccIdFound) {
339 // if the disconnected client (on this ChannelHandler)
340 // was not one with a duplicate-dpid, it is safe to remove all
341 // state for it at the controller. Notice that if the disconnected
342 // client was a duplicate-ip, calling the method below would clear
343 // all state for the original client (with the same ip),
344 // which we obviously don't want.
345 log.debug("{}:removal called", getClientInfoString());
346 if (pc != null) {
347 pc.removeConnectedClient();
348 }
349 } else {
350 // A duplicate was disconnected on this ChannelHandler,
351 // this is the same client reconnecting, but the original state was
352 // not cleaned up - XXX check liveness of original ChannelHandler
353 log.debug("{}:duplicate found", getClientInfoString());
354 duplicatePccIdFound = Boolean.FALSE;
355 }
356 } else {
357 log.warn("no pccip in channelHandler registered for " + "disconnected client {}", getClientInfoString());
358 }
359 }
360
361 @Override
362 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
363 PcepErrorMsg errMsg;
364 log.info("exceptionCaught: " + e.toString());
365
366 if (e.getCause() instanceof ReadTimeoutException) {
367 if (ChannelState.OPENWAIT == state) {
368 // When ReadTimeout timer is expired in OPENWAIT state, it is considered
369 // OpenWait timer.
370 errMsg = getErrorMsg(PcepErrorDetailInfo.ERROR_TYPE_1, PcepErrorDetailInfo.ERROR_VALUE_2);
371 log.debug("Sending PCEP-ERROR message to PCC.");
372 channel.write(Collections.singletonList(errMsg));
373 channel.close();
374 state = ChannelState.INIT;
375 return;
376 } else if (ChannelState.KEEPWAIT == state) {
377 // When ReadTimeout timer is expired in KEEPWAIT state, is is considered
378 // KeepWait timer.
379 errMsg = getErrorMsg(PcepErrorDetailInfo.ERROR_TYPE_1, PcepErrorDetailInfo.ERROR_VALUE_7);
380 log.debug("Sending PCEP-ERROR message to PCC.");
381 channel.write(Collections.singletonList(errMsg));
382 channel.close();
383 state = ChannelState.INIT;
384 return;
385 }
386 } else if (e.getCause() instanceof ClosedChannelException) {
387 log.debug("Channel for pc {} already closed", getClientInfoString());
388 } else if (e.getCause() instanceof IOException) {
389 log.error("Disconnecting client {} due to IO Error: {}", getClientInfoString(), e.getCause().getMessage());
390 if (log.isDebugEnabled()) {
391 // still print stack trace if debug is enabled
392 log.debug("StackTrace for previous Exception: ", e.getCause());
393 }
394 channel.close();
395 } else if (e.getCause() instanceof PcepParseException) {
396 PcepParseException errMsgParse = (PcepParseException) e.getCause();
397 byte errorType = errMsgParse.getErrorType();
398 byte errorValue = errMsgParse.getErrorValue();
399
400 if ((errorType == (byte) 0x0) && (errorValue == (byte) 0x0)) {
401 processUnknownMsg();
402 } else {
403 errMsg = getErrorMsg(errorType, errorValue);
404 log.debug("Sending PCEP-ERROR message to PCC.");
405 channel.write(Collections.singletonList(errMsg));
406 }
407 } else if (e.getCause() instanceof RejectedExecutionException) {
408 log.warn("Could not process message: queue full");
409 } else {
410 log.error("Error while processing message from client " + getClientInfoString() + "state " + this.state);
411 channel.close();
412 }
413 }
414
415 @Override
416 public String toString() {
417 return getClientInfoString();
418 }
419
420 @Override
421 public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
422 if (!isHandshakeComplete()) {
423 return;
424 }
425
426 if (e.getState() == IdleState.READER_IDLE) {
427 // When no message is received on channel for read timeout, then close
428 // the channel
429 log.info("Disconnecting client {} due to read timeout", getClientInfoString());
430 ctx.getChannel().close();
431 } else if (e.getState() == IdleState.WRITER_IDLE) {
432 // Send keep alive message
433 log.debug("Sending keep alive message due to IdleState timeout " + pc.toString());
434 pc.sendMessage(Collections.singletonList(pc.factory().buildKeepaliveMsg().build()));
435 }
436 }
437
438 @Override
439 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
440 if (e.getMessage() instanceof List) {
441 @SuppressWarnings("unchecked")
442 List<PcepMessage> msglist = (List<PcepMessage>) e.getMessage();
443 for (PcepMessage pm : msglist) {
444 // Do the actual packet processing
445 state.processPcepMessage(this, pm);
446 }
447 } else {
448 state.processPcepMessage(this, (PcepMessage) e.getMessage());
449 }
450 }
451
452 /**
453 * To set the handshake status.
454 *
455 * @param handshakeComplete value is handshake status
456 */
457 public void setHandshakeComplete(boolean handshakeComplete) {
458 this.state.setHandshakeComplete(handshakeComplete);
459 }
460
461 /**
462 * Is this a state in which the handshake has completed.
463 *
464 * @return true if the handshake is complete
465 */
466 public boolean isHandshakeComplete() {
467 return this.state.isHandshakeComplete();
468 }
469
470 /**
471 * To handle the pcep message.
472 *
473 * @param m pcep message
474 */
475 private void dispatchMessage(PcepMessage m) {
476 pc.handleMessage(m);
477 }
478
479 /**
Avantika-Huaweife44ea62016-05-27 19:21:24 +0530480 * Adds PCEP device configuration with capabilities once session is established.
Priyanka B94395bf2016-05-21 18:39:46 +0530481 */
482 private void addNode() {
483 pc.addNode(pc);
484 }
485
486 /**
Avantika-Huaweife44ea62016-05-27 19:21:24 +0530487 * Deletes PCEP device configuration when session is disconnected.
Priyanka B94395bf2016-05-21 18:39:46 +0530488 */
489 private void deleteNode() {
490 pc.deleteNode(pc.getPccId());
491 }
492
493 /**
SureshBR25058b72015-08-13 13:05:06 +0530494 * Return a string describing this client based on the already available
495 * information (ip address and/or remote socket).
496 *
497 * @return display string
498 */
499 private String getClientInfoString() {
500 if (pc != null) {
501 return pc.toString();
502 }
503 String channelString;
504 if (channel == null || channel.getRemoteAddress() == null) {
505 channelString = "?";
506 } else {
507 channelString = channel.getRemoteAddress().toString();
508 }
509 String pccIpString;
510 // TODO : implement functionality to get pcc id string
511 pccIpString = "?";
512 return String.format("[%s PCCIP[%s]]", channelString, pccIpString);
513 }
514
515 /**
516 * Update the channels state. Only called from the state machine.
517 *
518 * @param state
519 */
520 private void setState(ChannelState state) {
521 this.state = state;
522 }
523
524 /**
525 * Send handshake open message.
526 *
527 * @throws IOException,PcepParseException
528 */
529 private void sendHandshakeOpenMessage() throws IOException, PcepParseException {
530 PcepOpenObject pcepOpenobj = factory1.buildOpenObject()
531 .setSessionId(sessionId)
532 .setKeepAliveTime(keepAliveTime)
533 .setDeadTime(deadTime)
534 .build();
535 PcepMessage msg = factory1.buildOpenMsg()
536 .setPcepOpenObj(pcepOpenobj)
537 .build();
538 log.debug("Sending OPEN message to {}", channel.getRemoteAddress());
539 channel.write(Collections.singletonList(msg));
540 }
541
Priyanka Bd2b28882016-04-04 16:57:04 +0530542 //Capability negotiation
543 private void capabilityNegotiation(PcepOpenMsg pOpenmsg) {
SureshBR25058b72015-08-13 13:05:06 +0530544 LinkedList<PcepValueType> tlvList = pOpenmsg.getPcepOpenObject().getOptionalTlv();
Priyanka Bd2b28882016-04-04 16:57:04 +0530545 boolean pceccCapability = false;
546 boolean statefulPceCapability = false;
547 boolean pcInstantiationCapability = false;
Priyanka B94395bf2016-05-21 18:39:46 +0530548 boolean labelStackCapability = false;
549 boolean srCapability = false;
SureshBR25058b72015-08-13 13:05:06 +0530550
551 ListIterator<PcepValueType> listIterator = tlvList.listIterator();
552 while (listIterator.hasNext()) {
553 PcepValueType tlv = listIterator.next();
554
555 switch (tlv.getType()) {
556 case PceccCapabilityTlv.TYPE:
Priyanka Bd2b28882016-04-04 16:57:04 +0530557 pceccCapability = true;
Priyanka B94395bf2016-05-21 18:39:46 +0530558 if (((PceccCapabilityTlv) tlv).sBit()) {
559 labelStackCapability = true;
560 }
SureshBR25058b72015-08-13 13:05:06 +0530561 break;
562 case StatefulPceCapabilityTlv.TYPE:
Priyanka Bd2b28882016-04-04 16:57:04 +0530563 statefulPceCapability = true;
SureshBR25058b72015-08-13 13:05:06 +0530564 StatefulPceCapabilityTlv stetefulPcCapTlv = (StatefulPceCapabilityTlv) tlv;
565 if (stetefulPcCapTlv.getIFlag()) {
Priyanka Bd2b28882016-04-04 16:57:04 +0530566 pcInstantiationCapability = true;
SureshBR25058b72015-08-13 13:05:06 +0530567 }
568 break;
Priyanka B94395bf2016-05-21 18:39:46 +0530569 case SrPceCapabilityTlv.TYPE:
570 srCapability = true;
571 break;
SureshBR25058b72015-08-13 13:05:06 +0530572 default:
573 continue;
574 }
575 }
Priyanka B94395bf2016-05-21 18:39:46 +0530576 this.capability = new ClientCapability(pceccCapability, statefulPceCapability, pcInstantiationCapability,
577 labelStackCapability, srCapability);
SureshBR25058b72015-08-13 13:05:06 +0530578 }
579
580 /**
581 * Send keep alive message.
582 *
583 * @throws IOException when channel is disconnected
584 * @throws PcepParseException while building keep alive message
585 */
586 private void sendKeepAliveMessage() throws IOException, PcepParseException {
587 PcepMessage msg = factory1.buildKeepaliveMsg().build();
588 log.debug("Sending KEEPALIVE message to {}", channel.getRemoteAddress());
589 channel.write(Collections.singletonList(msg));
590 }
591
592 /**
593 * Send error message and close channel with pcc.
594 */
595 private void sendErrMsgAndCloseChannel() {
596 // TODO send error message
Priyanka B94395bf2016-05-21 18:39:46 +0530597 //Remove PCEP device from topology
598 deleteNode();
SureshBR25058b72015-08-13 13:05:06 +0530599 channel.close();
600 }
601
602 /**
603 * Send error message when an invalid message is received.
604 *
605 * @throws PcepParseException while building error message
606 */
607 private void sendErrMsgForInvalidMsg() throws PcepParseException {
608 byte errorType = 0x02;
609 byte errorValue = 0x00;
610 PcepErrorMsg errMsg = getErrorMsg(errorType, errorValue);
611 channel.write(Collections.singletonList(errMsg));
612 }
613
614 /**
615 * Builds pcep error message based on error value and error type.
616 *
617 * @param errorType pcep error type
618 * @param errorValue pcep error value
619 * @return pcep error message
620 * @throws PcepParseException while bulding error message
621 */
622 public PcepErrorMsg getErrorMsg(byte errorType, byte errorValue) throws PcepParseException {
Sho SHIMIZU9b8274c2015-09-04 15:54:24 -0700623 LinkedList<PcepErrorObject> llerrObj = new LinkedList<>();
SureshBR25058b72015-08-13 13:05:06 +0530624 PcepErrorMsg errMsg;
625
626 PcepErrorObject errObj = factory1.buildPcepErrorObject()
627 .setErrorValue(errorValue)
628 .setErrorType(errorType)
629 .build();
630
631 llerrObj.add(errObj);
632
SureshBR25058b72015-08-13 13:05:06 +0530633 //If Error caught in other than Openmessage
Sho SHIMIZU9b8274c2015-09-04 15:54:24 -0700634 LinkedList<PcepError> llPcepErr = new LinkedList<>();
SureshBR25058b72015-08-13 13:05:06 +0530635
636 PcepError pcepErr = factory1.buildPcepError()
637 .setErrorObjList(llerrObj)
638 .build();
639
640 llPcepErr.add(pcepErr);
641
642 PcepErrorInfo errInfo = factory1.buildPcepErrorInfo()
643 .setPcepErrorList(llPcepErr)
644 .build();
645
646 errMsg = factory1.buildPcepErrorMsg()
647 .setPcepErrorInfo(errInfo)
648 .build();
SureshBR25058b72015-08-13 13:05:06 +0530649 return errMsg;
650 }
651
652 /**
653 * Process unknown pcep message received.
654 *
655 * @throws PcepParseException while building pcep error message
656 */
657 public void processUnknownMsg() throws PcepParseException {
658 Date now = null;
659 if (pcepPacketStats.wrongPacketCount() == 0) {
660 now = new Date();
661 pcepPacketStats.setTime(now.getTime());
662 pcepPacketStats.addWrongPacket();
663 sendErrMsgForInvalidMsg();
664 }
665
666 if (pcepPacketStats.wrongPacketCount() > 1) {
667 Date lastest = new Date();
668 pcepPacketStats.addWrongPacket();
669 //converting to seconds
670 if (((lastest.getTime() - pcepPacketStats.getTime()) / 1000) > 60) {
671 now = lastest;
672 pcepPacketStats.setTime(now.getTime());
673 pcepPacketStats.resetWrongPacket();
674 pcepPacketStats.addWrongPacket();
675 } else if (((int) (lastest.getTime() - now.getTime()) / 1000) < 60) {
676 if (MAX_WRONG_COUNT_PACKET <= pcepPacketStats.wrongPacketCount()) {
677 //reset once wrong packet count reaches MAX_WRONG_COUNT_PACKET
678 pcepPacketStats.resetWrongPacket();
679 // max wrong packets received send error message and close the session
680 sendErrMsgAndCloseChannel();
681 }
682 }
683 }
684 }
685}