Search in sources :

Example 1 with ByteBufCodedInputStream

use of org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream in project incubator-pulsar by apache.

the class Commands method parseMessageMetadata.

public static MessageMetadata parseMessageMetadata(ByteBuf buffer) {
    try {
        // initially reader-index may point to start_of_checksum : increment reader-index to start_of_metadata to parse
        // metadata
        skipChecksumIfPresent(buffer);
        int metadataSize = (int) buffer.readUnsignedInt();
        int writerIndex = buffer.writerIndex();
        buffer.writerIndex(buffer.readerIndex() + metadataSize);
        ByteBufCodedInputStream stream = ByteBufCodedInputStream.get(buffer);
        MessageMetadata.Builder messageMetadataBuilder = MessageMetadata.newBuilder();
        MessageMetadata res = messageMetadataBuilder.mergeFrom(stream, null).build();
        buffer.writerIndex(writerIndex);
        messageMetadataBuilder.recycle();
        stream.recycle();
        return res;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) ByteBufCodedInputStream(org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream) IOException(java.io.IOException)

Example 2 with ByteBufCodedInputStream

use of org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream in project incubator-pulsar by apache.

the class Commands method deSerializeSingleMessageInBatch.

public static ByteBuf deSerializeSingleMessageInBatch(ByteBuf uncompressedPayload, PulsarApi.SingleMessageMetadata.Builder singleMessageMetadataBuilder, int index, int batchSize) throws IOException {
    int singleMetaSize = (int) uncompressedPayload.readUnsignedInt();
    int writerIndex = uncompressedPayload.writerIndex();
    int beginIndex = uncompressedPayload.readerIndex() + singleMetaSize;
    uncompressedPayload.writerIndex(beginIndex);
    ByteBufCodedInputStream stream = ByteBufCodedInputStream.get(uncompressedPayload);
    PulsarApi.SingleMessageMetadata singleMessageMetadata = singleMessageMetadataBuilder.mergeFrom(stream, null).build();
    int singleMessagePayloadSize = singleMessageMetadata.getPayloadSize();
    uncompressedPayload.markReaderIndex();
    ByteBuf singleMessagePayload = uncompressedPayload.slice(uncompressedPayload.readerIndex(), singleMessagePayloadSize);
    singleMessagePayload.retain();
    uncompressedPayload.writerIndex(writerIndex);
    uncompressedPayload.resetReaderIndex();
    // reader now points to beginning of payload read; so move it past message payload just read
    if (index < batchSize) {
        uncompressedPayload.readerIndex(uncompressedPayload.readerIndex() + singleMessagePayloadSize);
    }
    return singleMessagePayload;
}
Also used : ByteBufCodedInputStream(org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream) PulsarApi(org.apache.pulsar.common.api.proto.PulsarApi) ByteBuf(io.netty.buffer.ByteBuf)

Example 3 with ByteBufCodedInputStream

use of org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream in project incubator-pulsar by apache.

the class PulsarDecoder method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // Get a buffer that contains the full frame
    ByteBuf buffer = (ByteBuf) msg;
    BaseCommand cmd = null;
    BaseCommand.Builder cmdBuilder = null;
    try {
        // De-serialize the command
        int cmdSize = (int) buffer.readUnsignedInt();
        int writerIndex = buffer.writerIndex();
        buffer.writerIndex(buffer.readerIndex() + cmdSize);
        ByteBufCodedInputStream cmdInputStream = ByteBufCodedInputStream.get(buffer);
        cmdBuilder = BaseCommand.newBuilder();
        cmd = cmdBuilder.mergeFrom(cmdInputStream, null).build();
        buffer.writerIndex(writerIndex);
        cmdInputStream.recycle();
        if (log.isDebugEnabled()) {
            log.debug("[{}] Received cmd {}", ctx.channel().remoteAddress(), cmd.getType());
        }
        messageReceived();
        switch(cmd.getType()) {
            case PARTITIONED_METADATA:
                checkArgument(cmd.hasPartitionMetadata());
                handlePartitionMetadataRequest(cmd.getPartitionMetadata());
                cmd.getPartitionMetadata().recycle();
                break;
            case PARTITIONED_METADATA_RESPONSE:
                checkArgument(cmd.hasPartitionMetadataResponse());
                handlePartitionResponse(cmd.getPartitionMetadataResponse());
                cmd.getPartitionMetadataResponse().recycle();
                break;
            case LOOKUP:
                checkArgument(cmd.hasLookupTopic());
                handleLookup(cmd.getLookupTopic());
                cmd.getLookupTopic().recycle();
                break;
            case LOOKUP_RESPONSE:
                checkArgument(cmd.hasLookupTopicResponse());
                handleLookupResponse(cmd.getLookupTopicResponse());
                cmd.getLookupTopicResponse().recycle();
                break;
            case ACK:
                checkArgument(cmd.hasAck());
                handleAck(cmd.getAck());
                cmd.getAck().getMessageId().recycle();
                cmd.getAck().recycle();
                break;
            case CLOSE_CONSUMER:
                checkArgument(cmd.hasCloseConsumer());
                handleCloseConsumer(cmd.getCloseConsumer());
                cmd.getCloseConsumer().recycle();
                break;
            case CLOSE_PRODUCER:
                checkArgument(cmd.hasCloseProducer());
                handleCloseProducer(cmd.getCloseProducer());
                cmd.getCloseProducer().recycle();
                break;
            case CONNECT:
                checkArgument(cmd.hasConnect());
                handleConnect(cmd.getConnect());
                cmd.getConnect().recycle();
                break;
            case CONNECTED:
                checkArgument(cmd.hasConnected());
                handleConnected(cmd.getConnected());
                cmd.getConnected().recycle();
                break;
            case ERROR:
                checkArgument(cmd.hasError());
                handleError(cmd.getError());
                cmd.getError().recycle();
                break;
            case FLOW:
                checkArgument(cmd.hasFlow());
                handleFlow(cmd.getFlow());
                cmd.getFlow().recycle();
                break;
            case MESSAGE:
                {
                    checkArgument(cmd.hasMessage());
                    handleMessage(cmd.getMessage(), buffer);
                    cmd.getMessage().recycle();
                    break;
                }
            case PRODUCER:
                checkArgument(cmd.hasProducer());
                handleProducer(cmd.getProducer());
                cmd.getProducer().recycle();
                break;
            case SEND:
                {
                    checkArgument(cmd.hasSend());
                    // Store a buffer marking the content + headers
                    ByteBuf headersAndPayload = buffer.markReaderIndex();
                    handleSend(cmd.getSend(), headersAndPayload);
                    cmd.getSend().recycle();
                    break;
                }
            case SEND_ERROR:
                checkArgument(cmd.hasSendError());
                handleSendError(cmd.getSendError());
                cmd.getSendError().recycle();
                break;
            case SEND_RECEIPT:
                checkArgument(cmd.hasSendReceipt());
                handleSendReceipt(cmd.getSendReceipt());
                cmd.getSendReceipt().recycle();
                break;
            case SUBSCRIBE:
                checkArgument(cmd.hasSubscribe());
                handleSubscribe(cmd.getSubscribe());
                cmd.getSubscribe().recycle();
                break;
            case SUCCESS:
                checkArgument(cmd.hasSuccess());
                handleSuccess(cmd.getSuccess());
                cmd.getSuccess().recycle();
                break;
            case PRODUCER_SUCCESS:
                checkArgument(cmd.hasProducerSuccess());
                handleProducerSuccess(cmd.getProducerSuccess());
                cmd.getProducerSuccess().recycle();
                break;
            case UNSUBSCRIBE:
                checkArgument(cmd.hasUnsubscribe());
                handleUnsubscribe(cmd.getUnsubscribe());
                cmd.getUnsubscribe().recycle();
                break;
            case SEEK:
                checkArgument(cmd.hasSeek());
                handleSeek(cmd.getSeek());
                cmd.getSeek().recycle();
                break;
            case PING:
                checkArgument(cmd.hasPing());
                handlePing(cmd.getPing());
                cmd.getPing().recycle();
                break;
            case PONG:
                checkArgument(cmd.hasPong());
                handlePong(cmd.getPong());
                cmd.getPong().recycle();
                break;
            case REDELIVER_UNACKNOWLEDGED_MESSAGES:
                checkArgument(cmd.hasRedeliverUnacknowledgedMessages());
                handleRedeliverUnacknowledged(cmd.getRedeliverUnacknowledgedMessages());
                cmd.getRedeliverUnacknowledgedMessages().recycle();
                break;
            case CONSUMER_STATS:
                checkArgument(cmd.hasConsumerStats());
                handleConsumerStats(cmd.getConsumerStats());
                cmd.getConsumerStats().recycle();
                break;
            case CONSUMER_STATS_RESPONSE:
                checkArgument(cmd.hasConsumerStatsResponse());
                handleConsumerStatsResponse(cmd.getConsumerStatsResponse());
                cmd.getConsumerStatsResponse().recycle();
                break;
            case REACHED_END_OF_TOPIC:
                checkArgument(cmd.hasReachedEndOfTopic());
                handleReachedEndOfTopic(cmd.getReachedEndOfTopic());
                cmd.getReachedEndOfTopic().recycle();
                break;
            case GET_LAST_MESSAGE_ID:
                checkArgument(cmd.hasGetLastMessageId());
                handleGetLastMessageId(cmd.getGetLastMessageId());
                cmd.getGetLastMessageId().recycle();
                break;
            case GET_LAST_MESSAGE_ID_RESPONSE:
                checkArgument(cmd.hasGetLastMessageIdResponse());
                handleGetLastMessageIdSuccess(cmd.getGetLastMessageIdResponse());
                cmd.getGetLastMessageIdResponse().recycle();
                break;
            case ACTIVE_CONSUMER_CHANGE:
                handleActiveConsumerChange(cmd.getActiveConsumerChange());
                cmd.getActiveConsumerChange().recycle();
                break;
            case GET_TOPICS_OF_NAMESPACE:
                checkArgument(cmd.hasGetTopicsOfNamespace());
                handleGetTopicsOfNamespace(cmd.getGetTopicsOfNamespace());
                cmd.getGetTopicsOfNamespace().recycle();
                break;
            case GET_TOPICS_OF_NAMESPACE_RESPONSE:
                checkArgument(cmd.hasGetTopicsOfNamespaceResponse());
                handleGetTopicsOfNamespaceSuccess(cmd.getGetTopicsOfNamespaceResponse());
                cmd.getGetTopicsOfNamespaceResponse().recycle();
                break;
        }
    } finally {
        if (cmdBuilder != null) {
            cmdBuilder.recycle();
        }
        if (cmd != null) {
            cmd.recycle();
        }
        buffer.release();
    }
}
Also used : BaseCommand(org.apache.pulsar.common.api.proto.PulsarApi.BaseCommand) ByteBufCodedInputStream(org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream) ByteBuf(io.netty.buffer.ByteBuf)

Example 4 with ByteBufCodedInputStream

use of org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream in project incubator-pulsar by apache.

the class PersistentDispatcherFailoverConsumerTest method setup.

@BeforeMethod
public void setup() throws Exception {
    ServiceConfiguration svcConfig = spy(new ServiceConfiguration());
    PulsarService pulsar = spy(new PulsarService(svcConfig));
    doReturn(svcConfig).when(pulsar).getConfiguration();
    mlFactoryMock = mock(ManagedLedgerFactory.class);
    doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory();
    ZooKeeper mockZk = createMockZooKeeper();
    doReturn(mockZk).when(pulsar).getZkClient();
    doReturn(createMockBookKeeper(mockZk)).when(pulsar).getBookKeeperClient();
    configCacheService = mock(ConfigurationCacheService.class);
    @SuppressWarnings("unchecked") ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
    LocalZooKeeperCacheService zkCache = mock(LocalZooKeeperCacheService.class);
    doReturn(CompletableFuture.completedFuture(Optional.empty())).when(zkDataCache).getAsync(any());
    doReturn(zkDataCache).when(zkCache).policiesCache();
    doReturn(zkDataCache).when(configCacheService).policiesCache();
    doReturn(configCacheService).when(pulsar).getConfigurationCache();
    doReturn(zkCache).when(pulsar).getLocalZkCacheService();
    brokerService = spy(new BrokerService(pulsar));
    doReturn(brokerService).when(pulsar).getBrokerService();
    consumerChanges = new LinkedBlockingQueue<>();
    this.channelCtx = mock(ChannelHandlerContext.class);
    doAnswer(invocationOnMock -> {
        ByteBuf buf = invocationOnMock.getArgumentAt(0, ByteBuf.class);
        ByteBuf cmdBuf = buf.retainedSlice(4, buf.writerIndex() - 4);
        try {
            int cmdSize = (int) cmdBuf.readUnsignedInt();
            int writerIndex = cmdBuf.writerIndex();
            cmdBuf.writerIndex(cmdBuf.readerIndex() + cmdSize);
            ByteBufCodedInputStream cmdInputStream = ByteBufCodedInputStream.get(cmdBuf);
            BaseCommand.Builder cmdBuilder = BaseCommand.newBuilder();
            BaseCommand cmd = cmdBuilder.mergeFrom(cmdInputStream, null).build();
            cmdBuilder.recycle();
            cmdBuf.writerIndex(writerIndex);
            cmdInputStream.recycle();
            if (cmd.hasActiveConsumerChange()) {
                consumerChanges.put(cmd.getActiveConsumerChange());
            }
            cmd.recycle();
        } finally {
            cmdBuf.release();
        }
        return null;
    }).when(channelCtx).writeAndFlush(any(), any());
    serverCnx = spy(new ServerCnx(brokerService));
    doReturn(true).when(serverCnx).isActive();
    doReturn(true).when(serverCnx).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnx).clientAddress();
    when(serverCnx.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v12.getNumber());
    when(serverCnx.ctx()).thenReturn(channelCtx);
    serverCnxWithOldVersion = spy(new ServerCnx(brokerService));
    doReturn(true).when(serverCnxWithOldVersion).isActive();
    doReturn(true).when(serverCnxWithOldVersion).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnxWithOldVersion).clientAddress();
    when(serverCnxWithOldVersion.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v11.getNumber());
    when(serverCnxWithOldVersion.ctx()).thenReturn(channelCtx);
    NamespaceService nsSvc = mock(NamespaceService.class);
    doReturn(nsSvc).when(pulsar).getNamespaceService();
    doReturn(true).when(nsSvc).isServiceUnitOwned(any(NamespaceBundle.class));
    doReturn(true).when(nsSvc).isServiceUnitActive(any(TopicName.class));
    setupMLAsyncCallbackMocks();
}
Also used : NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) Policies(org.apache.pulsar.common.policies.data.Policies) BaseCommand(org.apache.pulsar.common.api.proto.PulsarApi.BaseCommand) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) TopicName(org.apache.pulsar.common.naming.TopicName) ZooKeeper(org.apache.zookeeper.ZooKeeper) MockedPulsarServiceBaseTest.createMockZooKeeper(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.createMockZooKeeper) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) PulsarService(org.apache.pulsar.broker.PulsarService) NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ConfigurationCacheService(org.apache.pulsar.broker.cache.ConfigurationCacheService) ByteBufCodedInputStream(org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream) LocalZooKeeperCacheService(org.apache.pulsar.broker.cache.LocalZooKeeperCacheService) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 5 with ByteBufCodedInputStream

use of org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream in project incubator-pulsar by apache.

the class ByteBufCodedInputStreamTest method testWritingDouble.

@Test
public void testWritingDouble() throws IOException {
    ByteBuf buf = Unpooled.buffer();
    buf.clear();
    ByteBufCodedOutputStream outputStream = ByteBufCodedOutputStream.get(buf);
    outputStream.writeDouble(12, 23d);
    outputStream.writeDouble(15, 13.13d);
    outputStream.writeDouble(1, -0.003d);
    ByteBufCodedInputStream inputStream = ByteBufCodedInputStream.get(buf);
    assertEquals(WireFormat.getTagFieldNumber(inputStream.readTag()), 12);
    assertEquals(inputStream.readDouble(), 23d);
    assertEquals(WireFormat.getTagFieldNumber(inputStream.readTag()), 15);
    assertEquals(inputStream.readDouble(), 13.13d);
    assertEquals(WireFormat.getTagFieldNumber(inputStream.readTag()), 1);
    assertEquals(inputStream.readDouble(), -0.003d);
}
Also used : ByteBufCodedInputStream(org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream) ByteBuf(io.netty.buffer.ByteBuf) ByteBufCodedOutputStream(org.apache.pulsar.common.util.protobuf.ByteBufCodedOutputStream) Test(org.testng.annotations.Test)

Aggregations

ByteBufCodedInputStream (org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream)8 ByteBuf (io.netty.buffer.ByteBuf)5 IOException (java.io.IOException)4 PulsarApi (org.apache.pulsar.common.api.proto.PulsarApi)2 BaseCommand (org.apache.pulsar.common.api.proto.PulsarApi.BaseCommand)2 MessageIdData (org.apache.pulsar.common.api.proto.PulsarApi.MessageIdData)2 Test (org.testng.annotations.Test)2 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)1 UninitializedMessageException (com.google.protobuf.UninitializedMessageException)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 InetSocketAddress (java.net.InetSocketAddress)1 ManagedLedgerFactory (org.apache.bookkeeper.mledger.ManagedLedgerFactory)1 PulsarService (org.apache.pulsar.broker.PulsarService)1 ServiceConfiguration (org.apache.pulsar.broker.ServiceConfiguration)1 MockedPulsarServiceBaseTest.createMockZooKeeper (org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.createMockZooKeeper)1 ConfigurationCacheService (org.apache.pulsar.broker.cache.ConfigurationCacheService)1 LocalZooKeeperCacheService (org.apache.pulsar.broker.cache.LocalZooKeeperCacheService)1 NamespaceService (org.apache.pulsar.broker.namespace.NamespaceService)1 MessageMetadata (org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata)1 NamespaceBundle (org.apache.pulsar.common.naming.NamespaceBundle)1