Search in sources :

Example 31 with SubscriptionData

use of org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData in project rocketmq by apache.

the class AdminBrokerProcessor method getConsumeStats.

private RemotingCommand getConsumeStats(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final GetConsumeStatsRequestHeader requestHeader = (GetConsumeStatsRequestHeader) request.decodeCommandCustomHeader(GetConsumeStatsRequestHeader.class);
    ConsumeStats consumeStats = new ConsumeStats();
    Set<String> topics = new HashSet<String>();
    if (UtilAll.isBlank(requestHeader.getTopic())) {
        topics = this.brokerController.getConsumerOffsetManager().whichTopicByConsumer(requestHeader.getConsumerGroup());
    } else {
        topics.add(requestHeader.getTopic());
    }
    for (String topic : topics) {
        TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(topic);
        if (null == topicConfig) {
            log.warn("consumeStats, topic config not exist, {}", topic);
            continue;
        }
        {
            SubscriptionData findSubscriptionData = this.brokerController.getConsumerManager().findSubscriptionData(requestHeader.getConsumerGroup(), topic);
            if (null == findSubscriptionData && this.brokerController.getConsumerManager().findSubscriptionDataCount(requestHeader.getConsumerGroup()) > 0) {
                log.warn("consumeStats, the consumer group[{}], topic[{}] not exist", requestHeader.getConsumerGroup(), topic);
                continue;
            }
        }
        for (int i = 0; i < topicConfig.getReadQueueNums(); i++) {
            MessageQueue mq = new MessageQueue();
            mq.setTopic(topic);
            mq.setBrokerName(this.brokerController.getBrokerConfig().getBrokerName());
            mq.setQueueId(i);
            OffsetWrapper offsetWrapper = new OffsetWrapper();
            long brokerOffset = this.brokerController.getMessageStore().getMaxOffsetInQueue(topic, i);
            if (brokerOffset < 0)
                brokerOffset = 0;
            long consumerOffset = this.brokerController.getConsumerOffsetManager().queryOffset(requestHeader.getConsumerGroup(), topic, i);
            if (consumerOffset < 0)
                consumerOffset = 0;
            offsetWrapper.setBrokerOffset(brokerOffset);
            offsetWrapper.setConsumerOffset(consumerOffset);
            long timeOffset = consumerOffset - 1;
            if (timeOffset >= 0) {
                long lastTimestamp = this.brokerController.getMessageStore().getMessageStoreTimeStamp(topic, i, timeOffset);
                if (lastTimestamp > 0) {
                    offsetWrapper.setLastTimestamp(lastTimestamp);
                }
            }
            consumeStats.getOffsetTable().put(mq, offsetWrapper);
        }
        double consumeTps = this.brokerController.getBrokerStatsManager().tpsGroupGetNums(requestHeader.getConsumerGroup(), topic);
        consumeTps += consumeStats.getConsumeTps();
        consumeStats.setConsumeTps(consumeTps);
    }
    byte[] body = consumeStats.encode();
    response.setBody(body);
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
Also used : ConsumeStats(org.apache.rocketmq.common.admin.ConsumeStats) GetConsumeStatsRequestHeader(org.apache.rocketmq.common.protocol.header.GetConsumeStatsRequestHeader) TopicConfig(org.apache.rocketmq.common.TopicConfig) OffsetWrapper(org.apache.rocketmq.common.admin.OffsetWrapper) RemotingCommand(org.apache.rocketmq.remoting.protocol.RemotingCommand) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) SubscriptionData(org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData) HashSet(java.util.HashSet)

Example 32 with SubscriptionData

use of org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData in project rocketmq by apache.

the class PullMessageProcessor method processRequest.

private RemotingCommand processRequest(final Channel channel, RemotingCommand request, boolean brokerAllowSuspend) throws RemotingCommandException {
    RemotingCommand response = RemotingCommand.createResponseCommand(PullMessageResponseHeader.class);
    final PullMessageResponseHeader responseHeader = (PullMessageResponseHeader) response.readCustomHeader();
    final PullMessageRequestHeader requestHeader = (PullMessageRequestHeader) request.decodeCommandCustomHeader(PullMessageRequestHeader.class);
    response.setOpaque(request.getOpaque());
    log.debug("receive PullMessage request command, {}", request);
    if (!PermName.isReadable(this.brokerController.getBrokerConfig().getBrokerPermission())) {
        response.setCode(ResponseCode.NO_PERMISSION);
        response.setRemark(String.format("the broker[%s] pulling message is forbidden", this.brokerController.getBrokerConfig().getBrokerIP1()));
        return response;
    }
    SubscriptionGroupConfig subscriptionGroupConfig = this.brokerController.getSubscriptionGroupManager().findSubscriptionGroupConfig(requestHeader.getConsumerGroup());
    if (null == subscriptionGroupConfig) {
        response.setCode(ResponseCode.SUBSCRIPTION_GROUP_NOT_EXIST);
        response.setRemark(String.format("subscription group [%s] does not exist, %s", requestHeader.getConsumerGroup(), FAQUrl.suggestTodo(FAQUrl.SUBSCRIPTION_GROUP_NOT_EXIST)));
        return response;
    }
    if (!subscriptionGroupConfig.isConsumeEnable()) {
        response.setCode(ResponseCode.NO_PERMISSION);
        response.setRemark("subscription group no permission, " + requestHeader.getConsumerGroup());
        return response;
    }
    final boolean hasSuspendFlag = PullSysFlag.hasSuspendFlag(requestHeader.getSysFlag());
    final boolean hasCommitOffsetFlag = PullSysFlag.hasCommitOffsetFlag(requestHeader.getSysFlag());
    final boolean hasSubscriptionFlag = PullSysFlag.hasSubscriptionFlag(requestHeader.getSysFlag());
    final long suspendTimeoutMillisLong = hasSuspendFlag ? requestHeader.getSuspendTimeoutMillis() : 0;
    TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic());
    if (null == topicConfig) {
        log.error("the topic {} not exist, consumer: {}", requestHeader.getTopic(), RemotingHelper.parseChannelRemoteAddr(channel));
        response.setCode(ResponseCode.TOPIC_NOT_EXIST);
        response.setRemark(String.format("topic[%s] not exist, apply first please! %s", requestHeader.getTopic(), FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL)));
        return response;
    }
    if (!PermName.isReadable(topicConfig.getPerm())) {
        response.setCode(ResponseCode.NO_PERMISSION);
        response.setRemark("the topic[" + requestHeader.getTopic() + "] pulling message is forbidden");
        return response;
    }
    if (requestHeader.getQueueId() < 0 || requestHeader.getQueueId() >= topicConfig.getReadQueueNums()) {
        String errorInfo = String.format("queueId[%d] is illegal, topic:[%s] topicConfig.readQueueNums:[%d] consumer:[%s]", requestHeader.getQueueId(), requestHeader.getTopic(), topicConfig.getReadQueueNums(), channel.remoteAddress());
        log.warn(errorInfo);
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark(errorInfo);
        return response;
    }
    SubscriptionData subscriptionData = null;
    ConsumerFilterData consumerFilterData = null;
    if (hasSubscriptionFlag) {
        try {
            subscriptionData = FilterAPI.build(requestHeader.getTopic(), requestHeader.getSubscription(), requestHeader.getExpressionType());
            if (!ExpressionType.isTagType(subscriptionData.getExpressionType())) {
                consumerFilterData = ConsumerFilterManager.build(requestHeader.getTopic(), requestHeader.getConsumerGroup(), requestHeader.getSubscription(), requestHeader.getExpressionType(), requestHeader.getSubVersion());
                assert consumerFilterData != null;
            }
        } catch (Exception e) {
            log.warn("Parse the consumer's subscription[{}] failed, group: {}", requestHeader.getSubscription(), requestHeader.getConsumerGroup());
            response.setCode(ResponseCode.SUBSCRIPTION_PARSE_FAILED);
            response.setRemark("parse the consumer's subscription failed");
            return response;
        }
    } else {
        ConsumerGroupInfo consumerGroupInfo = this.brokerController.getConsumerManager().getConsumerGroupInfo(requestHeader.getConsumerGroup());
        if (null == consumerGroupInfo) {
            log.warn("the consumer's group info not exist, group: {}", requestHeader.getConsumerGroup());
            response.setCode(ResponseCode.SUBSCRIPTION_NOT_EXIST);
            response.setRemark("the consumer's group info not exist" + FAQUrl.suggestTodo(FAQUrl.SAME_GROUP_DIFFERENT_TOPIC));
            return response;
        }
        if (!subscriptionGroupConfig.isConsumeBroadcastEnable() && consumerGroupInfo.getMessageModel() == MessageModel.BROADCASTING) {
            response.setCode(ResponseCode.NO_PERMISSION);
            response.setRemark("the consumer group[" + requestHeader.getConsumerGroup() + "] can not consume by broadcast way");
            return response;
        }
        subscriptionData = consumerGroupInfo.findSubscriptionData(requestHeader.getTopic());
        if (null == subscriptionData) {
            log.warn("the consumer's subscription not exist, group: {}, topic:{}", requestHeader.getConsumerGroup(), requestHeader.getTopic());
            response.setCode(ResponseCode.SUBSCRIPTION_NOT_EXIST);
            response.setRemark("the consumer's subscription not exist" + FAQUrl.suggestTodo(FAQUrl.SAME_GROUP_DIFFERENT_TOPIC));
            return response;
        }
        if (subscriptionData.getSubVersion() < requestHeader.getSubVersion()) {
            log.warn("The broker's subscription is not latest, group: {} {}", requestHeader.getConsumerGroup(), subscriptionData.getSubString());
            response.setCode(ResponseCode.SUBSCRIPTION_NOT_LATEST);
            response.setRemark("the consumer's subscription not latest");
            return response;
        }
        if (!ExpressionType.isTagType(subscriptionData.getExpressionType())) {
            consumerFilterData = this.brokerController.getConsumerFilterManager().get(requestHeader.getTopic(), requestHeader.getConsumerGroup());
            if (consumerFilterData == null) {
                response.setCode(ResponseCode.FILTER_DATA_NOT_EXIST);
                response.setRemark("The broker's consumer filter data is not exist!Your expression may be wrong!");
                return response;
            }
            if (consumerFilterData.getClientVersion() < requestHeader.getSubVersion()) {
                log.warn("The broker's consumer filter data is not latest, group: {}, topic: {}, serverV: {}, clientV: {}", requestHeader.getConsumerGroup(), requestHeader.getTopic(), consumerFilterData.getClientVersion(), requestHeader.getSubVersion());
                response.setCode(ResponseCode.FILTER_DATA_NOT_LATEST);
                response.setRemark("the consumer's consumer filter data not latest");
                return response;
            }
        }
    }
    if (!ExpressionType.isTagType(subscriptionData.getExpressionType()) && !this.brokerController.getBrokerConfig().isEnablePropertyFilter()) {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("The broker does not support consumer to filter message by " + subscriptionData.getExpressionType());
        return response;
    }
    MessageFilter messageFilter;
    if (this.brokerController.getBrokerConfig().isFilterSupportRetry()) {
        messageFilter = new ExpressionForRetryMessageFilter(subscriptionData, consumerFilterData, this.brokerController.getConsumerFilterManager());
    } else {
        messageFilter = new ExpressionMessageFilter(subscriptionData, consumerFilterData, this.brokerController.getConsumerFilterManager());
    }
    final GetMessageResult getMessageResult = this.brokerController.getMessageStore().getMessage(requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId(), requestHeader.getQueueOffset(), requestHeader.getMaxMsgNums(), messageFilter);
    if (getMessageResult != null) {
        response.setRemark(getMessageResult.getStatus().name());
        responseHeader.setNextBeginOffset(getMessageResult.getNextBeginOffset());
        responseHeader.setMinOffset(getMessageResult.getMinOffset());
        responseHeader.setMaxOffset(getMessageResult.getMaxOffset());
        if (getMessageResult.isSuggestPullingFromSlave()) {
            responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getWhichBrokerWhenConsumeSlowly());
        } else {
            responseHeader.setSuggestWhichBrokerId(MixAll.MASTER_ID);
        }
        switch(this.brokerController.getMessageStoreConfig().getBrokerRole()) {
            case ASYNC_MASTER:
            case SYNC_MASTER:
                break;
            case SLAVE:
                if (!this.brokerController.getBrokerConfig().isSlaveReadEnable()) {
                    response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
                    responseHeader.setSuggestWhichBrokerId(MixAll.MASTER_ID);
                }
                break;
        }
        if (this.brokerController.getBrokerConfig().isSlaveReadEnable()) {
            // consume too slow ,redirect to another machine
            if (getMessageResult.isSuggestPullingFromSlave()) {
                responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getWhichBrokerWhenConsumeSlowly());
            } else // consume ok
            {
                responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getBrokerId());
            }
        } else {
            responseHeader.setSuggestWhichBrokerId(MixAll.MASTER_ID);
        }
        switch(getMessageResult.getStatus()) {
            case FOUND:
                response.setCode(ResponseCode.SUCCESS);
                break;
            case MESSAGE_WAS_REMOVING:
                response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
                break;
            case NO_MATCHED_LOGIC_QUEUE:
            case NO_MESSAGE_IN_QUEUE:
                if (0 != requestHeader.getQueueOffset()) {
                    response.setCode(ResponseCode.PULL_OFFSET_MOVED);
                    // XXX: warn and notify me
                    log.info("the broker store no queue data, fix the request offset {} to {}, Topic: {} QueueId: {} Consumer Group: {}", requestHeader.getQueueOffset(), getMessageResult.getNextBeginOffset(), requestHeader.getTopic(), requestHeader.getQueueId(), requestHeader.getConsumerGroup());
                } else {
                    response.setCode(ResponseCode.PULL_NOT_FOUND);
                }
                break;
            case NO_MATCHED_MESSAGE:
                response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
                break;
            case OFFSET_FOUND_NULL:
                response.setCode(ResponseCode.PULL_NOT_FOUND);
                break;
            case OFFSET_OVERFLOW_BADLY:
                response.setCode(ResponseCode.PULL_OFFSET_MOVED);
                // XXX: warn and notify me
                log.info("the request offset: {} over flow badly, broker max offset: {}, consumer: {}", requestHeader.getQueueOffset(), getMessageResult.getMaxOffset(), channel.remoteAddress());
                break;
            case OFFSET_OVERFLOW_ONE:
                response.setCode(ResponseCode.PULL_NOT_FOUND);
                break;
            case OFFSET_TOO_SMALL:
                response.setCode(ResponseCode.PULL_OFFSET_MOVED);
                log.info("the request offset too small. group={}, topic={}, requestOffset={}, brokerMinOffset={}, clientIp={}", requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueOffset(), getMessageResult.getMinOffset(), channel.remoteAddress());
                break;
            default:
                assert false;
                break;
        }
        if (this.hasConsumeMessageHook()) {
            ConsumeMessageContext context = new ConsumeMessageContext();
            context.setConsumerGroup(requestHeader.getConsumerGroup());
            context.setTopic(requestHeader.getTopic());
            context.setQueueId(requestHeader.getQueueId());
            String owner = request.getExtFields().get(BrokerStatsManager.COMMERCIAL_OWNER);
            switch(response.getCode()) {
                case ResponseCode.SUCCESS:
                    int commercialBaseCount = brokerController.getBrokerConfig().getCommercialBaseCount();
                    int incValue = getMessageResult.getMsgCount4Commercial() * commercialBaseCount;
                    context.setCommercialRcvStats(BrokerStatsManager.StatsType.RCV_SUCCESS);
                    context.setCommercialRcvTimes(incValue);
                    context.setCommercialRcvSize(getMessageResult.getBufferTotalSize());
                    context.setCommercialOwner(owner);
                    break;
                case ResponseCode.PULL_NOT_FOUND:
                    if (!brokerAllowSuspend) {
                        context.setCommercialRcvStats(BrokerStatsManager.StatsType.RCV_EPOLLS);
                        context.setCommercialRcvTimes(1);
                        context.setCommercialOwner(owner);
                    }
                    break;
                case ResponseCode.PULL_RETRY_IMMEDIATELY:
                case ResponseCode.PULL_OFFSET_MOVED:
                    context.setCommercialRcvStats(BrokerStatsManager.StatsType.RCV_EPOLLS);
                    context.setCommercialRcvTimes(1);
                    context.setCommercialOwner(owner);
                    break;
                default:
                    assert false;
                    break;
            }
            this.executeConsumeMessageHookBefore(context);
        }
        switch(response.getCode()) {
            case ResponseCode.SUCCESS:
                this.brokerController.getBrokerStatsManager().incGroupGetNums(requestHeader.getConsumerGroup(), requestHeader.getTopic(), getMessageResult.getMessageCount());
                this.brokerController.getBrokerStatsManager().incGroupGetSize(requestHeader.getConsumerGroup(), requestHeader.getTopic(), getMessageResult.getBufferTotalSize());
                this.brokerController.getBrokerStatsManager().incBrokerGetNums(getMessageResult.getMessageCount());
                if (this.brokerController.getBrokerConfig().isTransferMsgByHeap()) {
                    final long beginTimeMills = this.brokerController.getMessageStore().now();
                    final byte[] r = this.readGetMessageResult(getMessageResult, requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId());
                    this.brokerController.getBrokerStatsManager().incGroupGetLatency(requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId(), (int) (this.brokerController.getMessageStore().now() - beginTimeMills));
                    response.setBody(r);
                } else {
                    try {
                        FileRegion fileRegion = new ManyMessageTransfer(response.encodeHeader(getMessageResult.getBufferTotalSize()), getMessageResult);
                        channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                getMessageResult.release();
                                if (!future.isSuccess()) {
                                    log.error("transfer many message by pagecache failed, {}", channel.remoteAddress(), future.cause());
                                }
                            }
                        });
                    } catch (Throwable e) {
                        log.error("transfer many message by pagecache exception", e);
                        getMessageResult.release();
                    }
                    response = null;
                }
                break;
            case ResponseCode.PULL_NOT_FOUND:
                if (brokerAllowSuspend && hasSuspendFlag) {
                    long pollingTimeMills = suspendTimeoutMillisLong;
                    if (!this.brokerController.getBrokerConfig().isLongPollingEnable()) {
                        pollingTimeMills = this.brokerController.getBrokerConfig().getShortPollingTimeMills();
                    }
                    String topic = requestHeader.getTopic();
                    long offset = requestHeader.getQueueOffset();
                    int queueId = requestHeader.getQueueId();
                    PullRequest pullRequest = new PullRequest(request, channel, pollingTimeMills, this.brokerController.getMessageStore().now(), offset, subscriptionData, messageFilter);
                    this.brokerController.getPullRequestHoldService().suspendPullRequest(topic, queueId, pullRequest);
                    response = null;
                    break;
                }
            case ResponseCode.PULL_RETRY_IMMEDIATELY:
                break;
            case ResponseCode.PULL_OFFSET_MOVED:
                if (this.brokerController.getMessageStoreConfig().getBrokerRole() != BrokerRole.SLAVE || this.brokerController.getMessageStoreConfig().isOffsetCheckInSlave()) {
                    MessageQueue mq = new MessageQueue();
                    mq.setTopic(requestHeader.getTopic());
                    mq.setQueueId(requestHeader.getQueueId());
                    mq.setBrokerName(this.brokerController.getBrokerConfig().getBrokerName());
                    OffsetMovedEvent event = new OffsetMovedEvent();
                    event.setConsumerGroup(requestHeader.getConsumerGroup());
                    event.setMessageQueue(mq);
                    event.setOffsetRequest(requestHeader.getQueueOffset());
                    event.setOffsetNew(getMessageResult.getNextBeginOffset());
                    this.generateOffsetMovedEvent(event);
                    log.warn("PULL_OFFSET_MOVED:correction offset. topic={}, groupId={}, requestOffset={}, newOffset={}, suggestBrokerId={}", requestHeader.getTopic(), requestHeader.getConsumerGroup(), event.getOffsetRequest(), event.getOffsetNew(), responseHeader.getSuggestWhichBrokerId());
                } else {
                    responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getBrokerId());
                    response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
                    log.warn("PULL_OFFSET_MOVED:none correction. topic={}, groupId={}, requestOffset={}, suggestBrokerId={}", requestHeader.getTopic(), requestHeader.getConsumerGroup(), requestHeader.getQueueOffset(), responseHeader.getSuggestWhichBrokerId());
                }
                break;
            default:
                assert false;
        }
    } else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("store getMessage return null");
    }
    boolean storeOffsetEnable = brokerAllowSuspend;
    storeOffsetEnable = storeOffsetEnable && hasCommitOffsetFlag;
    storeOffsetEnable = storeOffsetEnable && this.brokerController.getMessageStoreConfig().getBrokerRole() != BrokerRole.SLAVE;
    if (storeOffsetEnable) {
        this.brokerController.getConsumerOffsetManager().commitOffset(RemotingHelper.parseChannelRemoteAddr(channel), requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId(), requestHeader.getCommitOffset());
    }
    return response;
}
Also used : PullRequest(org.apache.rocketmq.broker.longpolling.PullRequest) ExpressionForRetryMessageFilter(org.apache.rocketmq.broker.filter.ExpressionForRetryMessageFilter) ConsumerGroupInfo(org.apache.rocketmq.broker.client.ConsumerGroupInfo) SubscriptionGroupConfig(org.apache.rocketmq.common.subscription.SubscriptionGroupConfig) RemotingCommand(org.apache.rocketmq.remoting.protocol.RemotingCommand) ManyMessageTransfer(org.apache.rocketmq.broker.pagecache.ManyMessageTransfer) OffsetMovedEvent(org.apache.rocketmq.common.protocol.topic.OffsetMovedEvent) FileRegion(io.netty.channel.FileRegion) ConsumerFilterData(org.apache.rocketmq.broker.filter.ConsumerFilterData) ChannelFuture(io.netty.channel.ChannelFuture) GetMessageResult(org.apache.rocketmq.store.GetMessageResult) ExpressionMessageFilter(org.apache.rocketmq.broker.filter.ExpressionMessageFilter) TopicConfig(org.apache.rocketmq.common.TopicConfig) ChannelFutureListener(io.netty.channel.ChannelFutureListener) RemotingCommandException(org.apache.rocketmq.remoting.exception.RemotingCommandException) PullMessageResponseHeader(org.apache.rocketmq.common.protocol.header.PullMessageResponseHeader) PullMessageRequestHeader(org.apache.rocketmq.common.protocol.header.PullMessageRequestHeader) ConsumeMessageContext(org.apache.rocketmq.broker.mqtrace.ConsumeMessageContext) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) SubscriptionData(org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData) ExpressionForRetryMessageFilter(org.apache.rocketmq.broker.filter.ExpressionForRetryMessageFilter) MessageFilter(org.apache.rocketmq.store.MessageFilter) ExpressionMessageFilter(org.apache.rocketmq.broker.filter.ExpressionMessageFilter)

Example 33 with SubscriptionData

use of org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData in project rocketmq by apache.

the class MessageStoreWithFilterTest method testGetMessage_withFilterBitMapAndConsumerChanged.

@Test
public void testGetMessage_withFilterBitMapAndConsumerChanged() throws Exception {
    List<MessageExtBrokerInner> msgs = putMsg(master, topicCount, msgPerTopic);
    Thread.sleep(200);
    // reset consumer;
    String topic = "topic" + 0;
    String resetGroup = "CID_" + 2;
    String normalGroup = "CID_" + 3;
    {
        // reset CID_2@topic0 to get all messages.
        SubscriptionData resetSubData = new SubscriptionData();
        resetSubData.setExpressionType(ExpressionType.SQL92);
        resetSubData.setTopic(topic);
        resetSubData.setClassFilterMode(false);
        resetSubData.setSubString("a is not null OR a is null");
        ConsumerFilterData resetFilterData = ConsumerFilterManager.build(topic, resetGroup, resetSubData.getSubString(), resetSubData.getExpressionType(), System.currentTimeMillis());
        GetMessageResult resetGetResult = master.getMessage(resetGroup, topic, queueId, 0, 1000, new ExpressionMessageFilter(resetSubData, resetFilterData, filterManager));
        try {
            assertThat(resetGetResult).isNotNull();
            List<MessageExtBrokerInner> filteredMsgs = filtered(msgs, resetFilterData);
            assertThat(resetGetResult.getMessageBufferList().size()).isEqualTo(filteredMsgs.size());
        } finally {
            resetGetResult.release();
        }
    }
    {
        ConsumerFilterData normalFilterData = filterManager.get(topic, normalGroup);
        assertThat(normalFilterData).isNotNull();
        assertThat(normalFilterData.getBornTime()).isLessThan(System.currentTimeMillis());
        SubscriptionData normalSubData = new SubscriptionData();
        normalSubData.setExpressionType(normalFilterData.getExpressionType());
        normalSubData.setTopic(topic);
        normalSubData.setClassFilterMode(false);
        normalSubData.setSubString(normalFilterData.getExpression());
        List<MessageExtBrokerInner> filteredMsgs = filtered(msgs, normalFilterData);
        GetMessageResult normalGetResult = master.getMessage(normalGroup, topic, queueId, 0, 1000, new ExpressionMessageFilter(normalSubData, normalFilterData, filterManager));
        try {
            assertThat(normalGetResult).isNotNull();
            assertThat(normalGetResult.getMessageBufferList().size()).isEqualTo(filteredMsgs.size());
        } finally {
            normalGetResult.release();
        }
    }
}
Also used : GetMessageResult(org.apache.rocketmq.store.GetMessageResult) SubscriptionData(org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData) ArrayList(java.util.ArrayList) List(java.util.List) MessageExtBrokerInner(org.apache.rocketmq.store.MessageExtBrokerInner) Test(org.junit.Test)

Example 34 with SubscriptionData

use of org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData in project rocketmq by apache.

the class FilterAPITest method testBuildTagSome.

@Test
public void testBuildTagSome() {
    try {
        SubscriptionData subscriptionData = FilterAPI.build("TOPIC", "A || B", ExpressionType.TAG);
        assertThat(subscriptionData).isNotNull();
        assertThat(subscriptionData.getTopic()).isEqualTo("TOPIC");
        assertThat(subscriptionData.getSubString()).isEqualTo("A || B");
        assertThat(ExpressionType.isTagType(subscriptionData.getExpressionType())).isTrue();
        assertThat(subscriptionData.getTagsSet()).isNotNull();
        assertThat(subscriptionData.getTagsSet()).containsExactly("A", "B");
    } catch (Exception e) {
        e.printStackTrace();
        assertThat(Boolean.FALSE).isTrue();
    }
}
Also used : SubscriptionData(org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData) Test(org.junit.Test)

Example 35 with SubscriptionData

use of org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData in project rocketmq by apache.

the class FilterAPITest method testBuildSQL.

@Test
public void testBuildSQL() {
    try {
        SubscriptionData subscriptionData = FilterAPI.build("TOPIC", "a is not null", ExpressionType.SQL92);
        assertThat(subscriptionData).isNotNull();
        assertThat(subscriptionData.getTopic()).isEqualTo("TOPIC");
        assertThat(subscriptionData.getExpressionType()).isEqualTo(ExpressionType.SQL92);
    } catch (Exception e) {
        e.printStackTrace();
        assertThat(Boolean.FALSE).isTrue();
    }
}
Also used : SubscriptionData(org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData) Test(org.junit.Test)

Aggregations

SubscriptionData (org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData)77 MQBrokerException (org.apache.rocketmq.client.exception.MQBrokerException)24 MQClientException (org.apache.rocketmq.client.exception.MQClientException)24 RemotingException (org.apache.rocketmq.remoting.exception.RemotingException)24 MessageQueue (org.apache.rocketmq.common.message.MessageQueue)18 HashSet (java.util.HashSet)16 ArrayList (java.util.ArrayList)14 List (java.util.List)12 Entry (java.util.Map.Entry)12 ConsumerConnection (org.apache.rocketmq.common.protocol.body.ConsumerConnection)12 RemotingCommand (org.apache.rocketmq.remoting.protocol.RemotingCommand)12 HashMap (java.util.HashMap)10 Connection (org.apache.rocketmq.common.protocol.body.Connection)10 ConsumeStatus (org.apache.rocketmq.common.protocol.body.ConsumeStatus)10 ConsumerRunningInfo (org.apache.rocketmq.common.protocol.body.ConsumerRunningInfo)10 ProcessQueueInfo (org.apache.rocketmq.common.protocol.body.ProcessQueueInfo)10 Test (org.junit.Test)9 Field (java.lang.reflect.Field)8 MQClientAPIImpl (org.apache.rocketmq.client.impl.MQClientAPIImpl)8 MQClientInstance (org.apache.rocketmq.client.impl.factory.MQClientInstance)8