org.apache.rocketmq.common.protocol.ResponseCode Java Examples

The following examples show how to use org.apache.rocketmq.common.protocol.ResponseCode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MQClientAPIImpl.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public Set<MessageQueue> lockBatchMQ(
    final String addr,
    final LockBatchRequestBody requestBody,
    final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.LOCK_BATCH_MQ, null);

    request.setBody(requestBody.encode());
    RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
        request, timeoutMillis);
    switch (response.getCode()) {
        case ResponseCode.SUCCESS: {
            LockBatchResponseBody responseBody = LockBatchResponseBody.decode(response.getBody(), LockBatchResponseBody.class);
            Set<MessageQueue> messageQueues = responseBody.getLockOKMQSet();
            return messageQueues;
        }
        default:
            break;
    }

    throw new MQBrokerException(response.getCode(), response.getRemark());
}
 
Example #2
Source File: MQClientAPIImpl.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
public boolean cleanExpiredConsumeQueue(final String addr,
    long timeoutMillis) throws MQClientException, RemotingConnectException,
    RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_EXPIRED_CONSUMEQUEUE, null);
    RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
        request, timeoutMillis);
    switch (response.getCode()) {
        case ResponseCode.SUCCESS: {
            return true;
        }
        default:
            break;
    }

    throw new MQClientException(response.getCode(), response.getRemark());
}
 
Example #3
Source File: AdminBrokerProcessor.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
/**
 * 获取指定MessageQueue的分布式锁
 *
 * @param ctx
 * @param request
 * @return
 * @throws RemotingCommandException
 */
private RemotingCommand lockBatchMQ(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    LockBatchRequestBody requestBody = LockBatchRequestBody.decode(request.getBody(), LockBatchRequestBody.class);

    Set<MessageQueue> lockOKMQSet = this.brokerController.getRebalanceLockManager().tryLockBatch(
        requestBody.getConsumerGroup(),
        requestBody.getMqSet(),
        requestBody.getClientId());

    LockBatchResponseBody responseBody = new LockBatchResponseBody();
    responseBody.setLockOKMQSet(lockOKMQSet);

    response.setBody(responseBody.encode());
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #4
Source File: MQClientAPIImpl.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
public List<QueueTimeSpan> queryConsumeTimeSpan(final String addr, final String topic, final String group,
    final long timeoutMillis)
    throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
    MQBrokerException {
    QueryConsumeTimeSpanRequestHeader requestHeader = new QueryConsumeTimeSpanRequestHeader();
    requestHeader.setTopic(topic);
    requestHeader.setGroup(group);

    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUME_TIME_SPAN, requestHeader);

    RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
        request, timeoutMillis);
    switch (response.getCode()) {
        case ResponseCode.SUCCESS: {
            QueryConsumeTimeSpanBody consumeTimeSpanBody = GroupList.decode(response.getBody(), QueryConsumeTimeSpanBody.class);
            return consumeTimeSpanBody.getConsumeTimeSpanSet();
        }
        default:
            break;
    }

    throw new MQBrokerException(response.getCode(), response.getRemark());
}
 
Example #5
Source File: DefaultRequestProcessor.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private RemotingCommand wipeWritePermOfBroker(ChannelHandlerContext ctx,
    RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(WipeWritePermOfBrokerResponseHeader.class);
    final WipeWritePermOfBrokerResponseHeader responseHeader = (WipeWritePermOfBrokerResponseHeader) response.readCustomHeader();
    final WipeWritePermOfBrokerRequestHeader requestHeader =
        (WipeWritePermOfBrokerRequestHeader) request.decodeCommandCustomHeader(WipeWritePermOfBrokerRequestHeader.class);

    int wipeTopicCnt = this.namesrvController.getRouteInfoManager().wipeWritePermOfBrokerByLock(requestHeader.getBrokerName());

    log.info("wipe write perm of broker[{}], client: {}, {}",
        requestHeader.getBrokerName(),
        RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
        wipeTopicCnt);

    responseHeader.setWipeTopicCount(wipeTopicCnt);
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #6
Source File: AdminBrokerProcessor.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
private RemotingCommand getAllDelayOffset(ChannelHandlerContext ctx, RemotingCommand request) {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    String content = ((DefaultMessageStore) this.brokerController.getMessageStore()).getScheduleMessageService().encode();
    if (content != null && content.length() > 0) {
        try {
            response.setBody(content.getBytes(MixAll.DEFAULT_CHARSET));
        } catch (UnsupportedEncodingException e) {
            log.error("get all delay offset from master error.", e);

            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("UnsupportedEncodingException " + e);
            return response;
        }
    } else {
        log.error("No delay offset in this broker, client: {} ", ctx.channel().remoteAddress());
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("No delay offset in this broker");
        return response;
    }

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);

    return response;
}
 
Example #7
Source File: AdminBrokerProcessor.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
private RemotingCommand searchOffsetByTimestamp(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(SearchOffsetResponseHeader.class);
    final SearchOffsetResponseHeader responseHeader = (SearchOffsetResponseHeader) response.readCustomHeader();
    final SearchOffsetRequestHeader requestHeader =
        (SearchOffsetRequestHeader) request.decodeCommandCustomHeader(SearchOffsetRequestHeader.class);

    //通过时间得到offset
    long offset = this.brokerController.getMessageStore().getOffsetInQueueByTime(requestHeader.getTopic(), requestHeader.getQueueId(),
        requestHeader.getTimestamp());

    responseHeader.setOffset(offset);

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #8
Source File: DefaultRequestProcessorTest.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessRequest_UnregisterBroker() throws RemotingCommandException, NoSuchFieldException, IllegalAccessException {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(null);

    //Register broker
    RemotingCommand regRequest = genSampleRegisterCmd(true);
    defaultRequestProcessor.processRequest(ctx, regRequest);

    //Unregister broker
    RemotingCommand unregRequest = genSampleRegisterCmd(false);
    RemotingCommand unregResponse = defaultRequestProcessor.processRequest(ctx, unregRequest);

    assertThat(unregResponse.getCode()).isEqualTo(ResponseCode.SUCCESS);
    assertThat(unregResponse.getRemark()).isNull();

    RouteInfoManager routes = namesrvController.getRouteInfoManager();
    Field brokerAddrTable = RouteInfoManager.class.getDeclaredField("brokerAddrTable");
    brokerAddrTable.setAccessible(true);

    assertThat((Map) brokerAddrTable.get(routes)).isNotEmpty();
}
 
Example #9
Source File: DefaultRequestProcessor.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public RemotingCommand unregisterBroker(ChannelHandlerContext ctx,
    RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final UnRegisterBrokerRequestHeader requestHeader =
        (UnRegisterBrokerRequestHeader) request.decodeCommandCustomHeader(UnRegisterBrokerRequestHeader.class);

    this.namesrvController.getRouteInfoManager().unregisterBroker(
        requestHeader.getClusterName(),
        requestHeader.getBrokerAddr(),
        requestHeader.getBrokerName(),
        requestHeader.getBrokerId());

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #10
Source File: DefaultRequestProcessor.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
private RemotingCommand getKVListByNamespace(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final GetKVListByNamespaceRequestHeader requestHeader =
        (GetKVListByNamespaceRequestHeader)request.decodeCommandCustomHeader(GetKVListByNamespaceRequestHeader.class);

    byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(
        requestHeader.getNamespace());
    if (null != jsonValue) {
        response.setBody(jsonValue);
        response.setCode(ResponseCode.SUCCESS);
        response.setRemark(null);
        return response;
    }

    response.setCode(ResponseCode.QUERY_NOT_FOUND);
    response.setRemark("No config item, Namespace: " + requestHeader.getNamespace());
    return response;
}
 
Example #11
Source File: DefaultRequestProcessor.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
private RemotingCommand getConfig(ChannelHandlerContext ctx, RemotingCommand request) {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    String content = this.namesrvController.getConfiguration().getAllConfigsFormatString();
    if (content != null && content.length() > 0) {
        try {
            response.setBody(content.getBytes(MixAll.DEFAULT_CHARSET));
        } catch (UnsupportedEncodingException e) {
            log.error("getConfig error, ", e);
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("UnsupportedEncodingException " + e);
            return response;
        }
    }

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #12
Source File: AbstractOMSProducer.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
OMSRuntimeException checkProducerException(String topic, String msgId, Throwable e) {
    if (e instanceof MQClientException) {
        if (e.getCause() != null) {
            if (e.getCause() instanceof RemotingTimeoutException) {
                return new OMSTimeOutException("-1", String.format("Send message to broker timeout, %dms, Topic=%s, msgId=%s",
                    this.rocketmqProducer.getSendMsgTimeout(), topic, msgId), e);
            } else if (e.getCause() instanceof MQBrokerException || e.getCause() instanceof RemotingConnectException) {
                MQBrokerException brokerException = (MQBrokerException) e.getCause();
                return new OMSRuntimeException("-1", String.format("Received a broker exception, Topic=%s, msgId=%s, %s",
                    topic, msgId, brokerException.getErrorMessage()), e);
            }
        }
        // Exception thrown by local.
        else {
            MQClientException clientException = (MQClientException) e;
            if (-1 == clientException.getResponseCode()) {
                return new OMSRuntimeException("-1", String.format("Topic does not exist, Topic=%s, msgId=%s",
                    topic, msgId), e);
            } else if (ResponseCode.MESSAGE_ILLEGAL == clientException.getResponseCode()) {
                return new OMSMessageFormatException("-1", String.format("A illegal message for RocketMQ, Topic=%s, msgId=%s",
                    topic, msgId), e);
            }
        }
    }
    return new OMSRuntimeException("-1", "Send message to RocketMQ broker failed.", e);
}
 
Example #13
Source File: DefaultMQAdminExtImpl.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Override
public ConsumerConnection examineConsumerConnectionInfo(
    String consumerGroup) throws InterruptedException, MQBrokerException,
    RemotingException, MQClientException {
    ConsumerConnection result = new ConsumerConnection();
    String topic = MixAll.getRetryTopic(consumerGroup);
    List<BrokerData> brokers = this.examineTopicRouteInfo(topic).getBrokerDatas();
    BrokerData brokerData = brokers.get(random.nextInt(brokers.size()));
    String addr = null;
    if (brokerData != null) {
        addr = brokerData.selectBrokerAddr();
        if (StringUtils.isNotBlank(addr)) {
            result = this.mqClientInstance.getMQClientAPIImpl().getConsumerConnectionList(addr, consumerGroup, timeoutMillis);
        }
    }

    if (result.getConnectionSet().isEmpty()) {
        log.warn("the consumer group not online. brokerAddr={}, group={}", addr, consumerGroup);
        throw new MQClientException(ResponseCode.CONSUMER_NOT_ONLINE, "Not found the consumer group connection");
    }

    return result;
}
 
Example #14
Source File: AdminBrokerProcessor.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private RemotingCommand getAllDelayOffset(ChannelHandlerContext ctx, RemotingCommand request) {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    String content = ((DefaultMessageStore) this.brokerController.getMessageStore()).getScheduleMessageService().encode();
    if (content != null && content.length() > 0) {
        try {
            response.setBody(content.getBytes(MixAll.DEFAULT_CHARSET));
        } catch (UnsupportedEncodingException e) {
            log.error("get all delay offset from master error.", e);

            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("UnsupportedEncodingException " + e);
            return response;
        }
    } else {
        log.error("No delay offset in this broker, client: {} ", ctx.channel().remoteAddress());
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("No delay offset in this broker");
        return response;
    }

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);

    return response;
}
 
Example #15
Source File: SendMessageProcessorTest.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessRequest_Transaction() throws RemotingCommandException {
    brokerController.setTransactionalMessageService(transactionMsgService);
    when(brokerController.getTransactionalMessageService().prepareMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
    RemotingCommand request = createSendTransactionMsgCommand(RequestCode.SEND_MESSAGE);
    final RemotingCommand[] response = new RemotingCommand[1];
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            response[0] = invocation.getArgument(0);
            return null;
        }
    }).when(handlerContext).writeAndFlush(any(Object.class));
    RemotingCommand responseToReturn = sendMessageProcessor.processRequest(handlerContext, request);
    if (responseToReturn != null) {
        assertThat(response[0]).isNull();
        response[0] = responseToReturn;
    }
    assertThat(response[0].getCode()).isEqualTo(ResponseCode.SUCCESS);

}
 
Example #16
Source File: MQClientAPIImpl.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public void unlockBatchMQ(//
                          final String addr, //
                          final UnlockBatchRequestBody requestBody, //
                          final long timeoutMillis, //
                          final boolean oneway//
) throws RemotingException, MQBrokerException, InterruptedException {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNLOCK_BATCH_MQ, null);

    request.setBody(requestBody.encode());

    if (oneway) {
        this.remotingClient.invokeOneway(addr, request, timeoutMillis);
    } else {
        RemotingCommand response = this.remotingClient
            .invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
        switch (response.getCode()) {
            case ResponseCode.SUCCESS: {
                return;
            }
            default:
                break;
        }

        throw new MQBrokerException(response.getCode(), response.getRemark());
    }
}
 
Example #17
Source File: MQClientAPIImpl.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
private PullResult processPullResponse(final RemotingCommand response) throws MQBrokerException, RemotingCommandException {
    PullStatus pullStatus = PullStatus.NO_NEW_MSG;
    switch (response.getCode()) {
        case ResponseCode.SUCCESS:
            pullStatus = PullStatus.FOUND;
            break;
        case ResponseCode.PULL_NOT_FOUND:
            pullStatus = PullStatus.NO_NEW_MSG;
            break;
        case ResponseCode.PULL_RETRY_IMMEDIATELY:
            pullStatus = PullStatus.NO_MATCHED_MSG;
            break;
        case ResponseCode.PULL_OFFSET_MOVED:
            pullStatus = PullStatus.OFFSET_ILLEGAL;
            break;

        default:
            throw new MQBrokerException(response.getCode(), response.getRemark());
    }

    PullMessageResponseHeader responseHeader =
        (PullMessageResponseHeader) response.decodeCommandCustomHeader(PullMessageResponseHeader.class);

    return new PullResultExt(pullStatus, responseHeader.getNextBeginOffset(), responseHeader.getMinOffset(),
        responseHeader.getMaxOffset(), null, responseHeader.getSuggestWhichBrokerId(), response.getBody());
}
 
Example #18
Source File: DefaultRequestProcessorTest.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessRequest_RegisterBroker() throws RemotingCommandException,
    NoSuchFieldException, IllegalAccessException {
    RemotingCommand request = genSampleRegisterCmd(true);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(null);

    RemotingCommand response = defaultRequestProcessor.processRequest(ctx, request);

    assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
    assertThat(response.getRemark()).isNull();

    RouteInfoManager routes = namesrvController.getRouteInfoManager();
    Field brokerAddrTable = RouteInfoManager.class.getDeclaredField("brokerAddrTable");
    brokerAddrTable.setAccessible(true);

    BrokerData broker = new BrokerData();
    broker.setBrokerName("broker");
    broker.setBrokerAddrs((HashMap) Maps.newHashMap(new Long(2333), "10.10.1.1"));

    assertThat((Map) brokerAddrTable.get(routes))
        .contains(new HashMap.SimpleEntry("broker", broker));
}
 
Example #19
Source File: DefaultRequestProcessor.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
private RemotingCommand wipeWritePermOfBroker(ChannelHandlerContext ctx,
    RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(WipeWritePermOfBrokerResponseHeader.class);
    final WipeWritePermOfBrokerResponseHeader responseHeader = (WipeWritePermOfBrokerResponseHeader) response.readCustomHeader();
    final WipeWritePermOfBrokerRequestHeader requestHeader =
        (WipeWritePermOfBrokerRequestHeader) request.decodeCommandCustomHeader(WipeWritePermOfBrokerRequestHeader.class);

    int wipeTopicCnt = this.namesrvController.getRouteInfoManager().wipeWritePermOfBrokerByLock(requestHeader.getBrokerName());

    log.info("wipe write perm of broker[{}], client: {}, {}",
        requestHeader.getBrokerName(),
        RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
        wipeTopicCnt);

    responseHeader.setWipeTopicCount(wipeTopicCnt);
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #20
Source File: ClientRemotingProcessor.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private RemotingCommand getConsumerRunningInfo(ChannelHandlerContext ctx,
    RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final GetConsumerRunningInfoRequestHeader requestHeader =
        (GetConsumerRunningInfoRequestHeader) request.decodeCommandCustomHeader(GetConsumerRunningInfoRequestHeader.class);

    ConsumerRunningInfo consumerRunningInfo = this.mqClientFactory.consumerRunningInfo(requestHeader.getConsumerGroup());
    if (null != consumerRunningInfo) {
        if (requestHeader.isJstackEnable()) {
            Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
            String jstack = UtilAll.jstack(map);
            consumerRunningInfo.setJstack(jstack);
        }

        response.setCode(ResponseCode.SUCCESS);
        response.setBody(consumerRunningInfo.encode());
    } else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark(String.format("The Consumer Group <%s> not exist in this consumer", requestHeader.getConsumerGroup()));
    }

    return response;
}
 
Example #21
Source File: DefaultRequestProcessorTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessRequest_UnregisterBroker() throws RemotingCommandException, NoSuchFieldException, IllegalAccessException {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(null);

    //Register broker
    RemotingCommand regRequest = genSampleRegisterCmd(true);
    defaultRequestProcessor.processRequest(ctx, regRequest);

    //Unregister broker
    RemotingCommand unregRequest = genSampleRegisterCmd(false);
    RemotingCommand unregResponse = defaultRequestProcessor.processRequest(ctx, unregRequest);

    assertThat(unregResponse.getCode()).isEqualTo(ResponseCode.SUCCESS);
    assertThat(unregResponse.getRemark()).isNull();

    RouteInfoManager routes = namesrvController.getRouteInfoManager();
    Field brokerAddrTable = RouteInfoManager.class.getDeclaredField("brokerAddrTable");
    brokerAddrTable.setAccessible(true);

    assertThat((Map) brokerAddrTable.get(routes)).isNotEmpty();
}
 
Example #22
Source File: DefaultMQAdminExtImpl.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
@Override
public ConsumerConnection examineConsumerConnectionInfo(
    String consumerGroup) throws InterruptedException, MQBrokerException,
    RemotingException, MQClientException {
    ConsumerConnection result = new ConsumerConnection();
    String topic = MixAll.getRetryTopic(consumerGroup);
    List<BrokerData> brokers = this.examineTopicRouteInfo(topic).getBrokerDatas();
    BrokerData brokerData = brokers.get(random.nextInt(brokers.size()));
    String addr = null;
    if (brokerData != null) {
        addr = brokerData.selectBrokerAddr();
        if (StringUtils.isNotBlank(addr)) {
            result = this.mqClientInstance.getMQClientAPIImpl().getConsumerConnectionList(addr, consumerGroup, timeoutMillis);
        }
    }

    if (result.getConnectionSet().isEmpty()) {
        log.warn("the consumer group not online. brokerAddr={}, group={}", addr, consumerGroup);
        throw new MQClientException(ResponseCode.CONSUMER_NOT_ONLINE, "Not found the consumer group connection");
    }

    return result;
}
 
Example #23
Source File: MQClientAPIImpl.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public void unlockBatchMQ(
    final String addr,
    final UnlockBatchRequestBody requestBody,
    final long timeoutMillis,
    final boolean oneway
) throws RemotingException, MQBrokerException, InterruptedException {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNLOCK_BATCH_MQ, null);

    request.setBody(requestBody.encode());

    if (oneway) {
        this.remotingClient.invokeOneway(addr, request, timeoutMillis);
    } else {
        RemotingCommand response = this.remotingClient
            .invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
        switch (response.getCode()) {
            case ResponseCode.SUCCESS: {
                return;
            }
            default:
                break;
        }

        throw new MQBrokerException(response.getCode(), response.getRemark());
    }
}
 
Example #24
Source File: DefaultRequestProcessorTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessRequest_DeleteKVConfig() throws RemotingCommandException {
    namesrvController.getKvConfigManager().putKVConfig("namespace", "key", "value");

    DeleteKVConfigRequestHeader header = new DeleteKVConfigRequestHeader();
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_KV_CONFIG,
        header);
    request.addExtField("namespace", "namespace");
    request.addExtField("key", "key");

    RemotingCommand response = defaultRequestProcessor.processRequest(null, request);

    assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
    assertThat(response.getRemark()).isNull();

    assertThat(namesrvController.getKvConfigManager().getKVConfig("namespace", "key"))
        .isNull();
}
 
Example #25
Source File: AbstractSendMessageProcessor.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
protected RemotingCommand msgContentCheck(final ChannelHandlerContext ctx,
    final SendMessageRequestHeader requestHeader, RemotingCommand request,
    final RemotingCommand response) {
    if (requestHeader.getTopic().length() > Byte.MAX_VALUE) {
        log.warn("putMessage message topic length too long {}", requestHeader.getTopic().length());
        response.setCode(ResponseCode.MESSAGE_ILLEGAL);
        return response;
    }
    if (requestHeader.getProperties() != null && requestHeader.getProperties().length() > Short.MAX_VALUE) {
        log.warn("putMessage message properties length too long {}", requestHeader.getProperties().length());
        response.setCode(ResponseCode.MESSAGE_ILLEGAL);
        return response;
    }
    if (request.getBody().length > DBMsgConstants.MAX_BODY_SIZE) {
        log.warn(" topic {}  msg body size {}  from {}", requestHeader.getTopic(),
            request.getBody().length, ChannelUtil.getRemoteIp(ctx.channel()));
        response.setRemark("msg body must be less 64KB");
        response.setCode(ResponseCode.MESSAGE_ILLEGAL);
        return response;
    }
    return response;
}
 
Example #26
Source File: MQClientAPIImpl.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
public void unlockBatchMQ(//
    final String addr, //
    final UnlockBatchRequestBody requestBody, //
    final long timeoutMillis, //
    final boolean oneway//
) throws RemotingException, MQBrokerException, InterruptedException {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNLOCK_BATCH_MQ, null);

    request.setBody(requestBody.encode());

    if (oneway) {
        this.remotingClient.invokeOneway(addr, request, timeoutMillis);
    } else {
        RemotingCommand response = this.remotingClient
            .invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
        switch (response.getCode()) {
            case ResponseCode.SUCCESS: {
                return;
            }
            default:
                break;
        }

        throw new MQBrokerException(response.getCode(), response.getRemark());
    }
}
 
Example #27
Source File: BrokerOuterAPITest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test
public void test_register_normal() throws Exception {
    init();
    brokerOuterAPI.start();

    final RemotingCommand response = RemotingCommand.createResponseCommand(RegisterBrokerResponseHeader.class);
    final RegisterBrokerResponseHeader responseHeader = (RegisterBrokerResponseHeader) response.readCustomHeader();
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);

    TopicConfigSerializeWrapper topicConfigSerializeWrapper = new TopicConfigSerializeWrapper();

    when(nettyRemotingClient.getNameServerAddressList()).thenReturn(Lists.asList(nameserver1, nameserver2, new String[] {nameserver3}));
    when(nettyRemotingClient.invokeSync(anyString(), any(RemotingCommand.class), anyLong())).thenReturn(response);
    List<RegisterBrokerResult> registerBrokerResultList = brokerOuterAPI.registerBrokerAll(clusterName, brokerAddr, brokerName, brokerId, "hasServerAddr", topicConfigSerializeWrapper, Lists.<String>newArrayList(), false, timeOut, true);

    assertTrue(registerBrokerResultList.size() > 0);
}
 
Example #28
Source File: TopicValidatorTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test
public void testTopicValidator_NotPass() {
    RemotingCommand response = RemotingCommand.createResponseCommand(-1, "");

    Boolean res = TopicValidator.validateTopic("", response);
    assertThat(res).isFalse();
    assertThat(response.getCode()).isEqualTo(ResponseCode.SYSTEM_ERROR);
    assertThat(response.getRemark()).contains("The specified topic is blank");

    clearResponse(response);
    res = TopicValidator.validateTopic("../TopicTest", response);
    assertThat(res).isFalse();
    assertThat(response.getCode()).isEqualTo(ResponseCode.SYSTEM_ERROR);
    assertThat(response.getRemark()).contains("The specified topic contains illegal characters");

    clearResponse(response);
    res = TopicValidator.validateTopic(generateString(128), response);
    assertThat(res).isFalse();
    assertThat(response.getCode()).isEqualTo(ResponseCode.SYSTEM_ERROR);
    assertThat(response.getRemark()).contains("The specified topic is longer than topic max length.");
}
 
Example #29
Source File: AdminBrokerProcessor.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
private RemotingCommand queryTopicConsumeByWho(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    QueryTopicConsumeByWhoRequestHeader requestHeader =
        (QueryTopicConsumeByWhoRequestHeader)request.decodeCommandCustomHeader(QueryTopicConsumeByWhoRequestHeader.class);

    HashSet<String> groups = this.brokerController.getConsumerManager().queryTopicConsumeByWho(requestHeader.getTopic());

    Set<String> groupInOffset = this.brokerController.getConsumerOffsetManager().whichGroupByTopic(requestHeader.getTopic());
    if (groupInOffset != null && !groupInOffset.isEmpty()) {
        groups.addAll(groupInOffset);
    }

    GroupList groupList = new GroupList();
    groupList.setGroupList(groups);
    byte[] body = groupList.encode();

    response.setBody(body);
    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example #30
Source File: EndTransactionProcessor.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
private RemotingCommand checkPrepareMessage(MessageExt msgExt, EndTransactionRequestHeader requestHeader) {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    if (msgExt != null) {
        final String pgroupRead = msgExt.getProperty(MessageConst.PROPERTY_PRODUCER_GROUP);
        if (!pgroupRead.equals(requestHeader.getProducerGroup())) {
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("The producer group wrong");
            return response;
        }

        if (msgExt.getQueueOffset() != requestHeader.getTranStateTableOffset()) {
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("The transaction state table offset wrong");
            return response;
        }

        if (msgExt.getCommitLogOffset() != requestHeader.getCommitLogOffset()) {
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("The commit log offset wrong");
            return response;
        }
    } else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("Find prepared transaction message failed");
        return response;
    }
    response.setCode(ResponseCode.SUCCESS);
    return response;
}