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 com.google.common.base.Preconditions;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.ByteBufUtil;
13 import io.netty.channel.ChannelFuture;
14 import io.netty.channel.ChannelFutureListener;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.handler.codec.ByteToMessageDecoder;
17 import java.util.ArrayList;
18 import java.util.List;
19 import org.opendaylight.protocol.pcep.spi.MessageRegistry;
20 import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
21 import org.opendaylight.protocol.pcep.spi.PCEPMessageConstants;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * A PCEP message parser which also does validation.
29 public final class PCEPByteToMessageDecoder extends ByteToMessageDecoder {
30 private static final Logger LOG = LoggerFactory.getLogger(PCEPByteToMessageDecoder.class);
32 private final MessageRegistry registry;
34 public PCEPByteToMessageDecoder(final MessageRegistry registry) {
35 this.registry = Preconditions.checkNotNull(registry);
39 protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
40 if (!in.isReadable()) {
41 LOG.debug("No more content in incoming buffer.");
46 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
48 final List<Message> errors = new ArrayList<>();
51 out.add(parse(in, errors));
52 } catch (final PCEPDeserializerException e) {
53 LOG.debug("Failed to decode protocol message", e);
55 in.discardReadBytes();
57 if (!errors.isEmpty()) {
58 // We have a bunch of messages, send them out
59 for (final Object e : errors) {
60 ctx.channel().writeAndFlush(e).addListener((ChannelFutureListener) f -> {
62 LOG.warn("Failed to send message {} to socket {}", e, ctx.channel(), f.cause());
64 LOG.trace("Message {} sent to socket {}", e, ctx.channel());
71 private Message parse(final ByteBuf buffer, final List<Message> errors) throws PCEPDeserializerException {
73 final int type = buffer.readUnsignedByte();
74 final int msgLength = buffer.readUnsignedShort();
75 final int actualLength = buffer.readableBytes();
76 final ByteBuf msgBody = buffer.slice();
77 if (actualLength != msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH) {
78 throw new PCEPDeserializerException("Body size " + actualLength + " does not match header size "
79 + (msgLength - PCEPMessageConstants.COMMON_HEADER_LENGTH));
81 buffer.skipBytes(actualLength);
82 return this.registry.parseMessage(type, msgBody, errors);