Java Code Examples for org.apache.rocketmq.remoting.protocol.RemotingCommand#getBody()

The following examples show how to use org.apache.rocketmq.remoting.protocol.RemotingCommand#getBody() . 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: NettyEncoder.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out)
    throws Exception {
    try {
        ByteBuffer header = remotingCommand.encodeHeader();
        out.writeBytes(header);
        byte[] body = remotingCommand.getBody();
        if (body != null) {
            out.writeBytes(body);
        }
    } catch (Exception e) {
        log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        if (remotingCommand != null) {
            log.error(remotingCommand.toString());
        }
        RemotingUtil.closeChannel(ctx.channel());
    }
}
 
Example 2
Source File: AbstractSendMessageProcessor.java    From rocketmq 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 3
Source File: AbstractSendMessageProcessor.java    From DDMQ 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 4
Source File: AbstractSendMessageProcessor.java    From rocketmq 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 5
Source File: NettyEncoder.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out)
    throws Exception {
    try {
        ByteBuffer header = remotingCommand.encodeHeader();
        out.writeBytes(header);
        byte[] body = remotingCommand.getBody();
        if (body != null) {
            out.writeBytes(body);
        }
    } catch (Exception e) {
        log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        if (remotingCommand != null) {
            log.error(remotingCommand.toString());
        }
        RemotingUtil.closeChannel(ctx.channel());
    }
}
 
Example 6
Source File: NettyEncoder.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out)
    throws Exception {
    try {
        //写入header
        ByteBuffer header = remotingCommand.encodeHeader();
        out.writeBytes(header);
        //写入body
        byte[] body = remotingCommand.getBody();
        if (body != null) {
            out.writeBytes(body);
        }
    } catch (Exception e) {
        log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        if (remotingCommand != null) {
            log.error(remotingCommand.toString());
        }
        RemotingUtil.closeChannel(ctx.channel());
    }
}
 
Example 7
Source File: NettyEncoder.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Override
    public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out)
        throws Exception {
        try {
//            对消息头进行编码,rocketmq只对消息头进行了编码
            ByteBuffer header = remotingCommand.encodeHeader();
//            往buf中写消息头
            out.writeBytes(header);
//            获取消息体
            byte[] body = remotingCommand.getBody();
            if (body != null) {
//                写消息体
                out.writeBytes(body);
            }
        } catch (Exception e) {
            log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
            if (remotingCommand != null) {
                log.error(remotingCommand.toString());
            }
//            出现异常关闭channel
            RemotingUtil.closeChannel(ctx.channel());
        }
    }
 
Example 8
Source File: ClientRemotingProcessor.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
public RemotingCommand resetOffset(ChannelHandlerContext ctx,
        RemotingCommand request) throws RemotingCommandException {
        final ResetOffsetRequestHeader requestHeader =
            (ResetOffsetRequestHeader) request.decodeCommandCustomHeader(ResetOffsetRequestHeader.class);
        log.info("invoke reset offset operation from broker. brokerAddr={}, topic={}, group={}, timestamp={}",
            RemotingHelper.parseChannelRemoteAddr(ctx.channel()), requestHeader.getTopic(), requestHeader.getGroup(),
            requestHeader.getTimestamp());
        Map<MessageQueue, Long> offsetTable = new HashMap<MessageQueue, Long>();
        if (request.getBody() != null) {
            ResetOffsetBody body = ResetOffsetBody.decode(request.getBody(), ResetOffsetBody.class);
            offsetTable = body.getOffsetTable();
        }
//        重置offset=》
        this.mqClientFactory.resetOffset(requestHeader.getTopic(), requestHeader.getGroup(), offsetTable);
        return null;
    }
 
Example 9
Source File: NettyEncoder.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out)
    throws Exception {
    try {
        ByteBuffer header = remotingCommand.encodeHeader();
        out.writeBytes(header);
        byte[] body = remotingCommand.getBody();
        if (body != null) {
            out.writeBytes(body);
        }
    } catch (Exception e) {
        log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        if (remotingCommand != null) {
            log.error(remotingCommand.toString());
        }
        RemotingUtil.closeChannel(ctx.channel());
    }
}
 
Example 10
Source File: DefaultRequestProcessor.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private RemotingCommand updateConfig(ChannelHandlerContext ctx, RemotingCommand request) {
    log.info("updateConfig called by {}", RemotingHelper.parseChannelRemoteAddr(ctx.channel()));

    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    byte[] body = request.getBody();
    if (body != null) {
        String bodyStr;
        try {
            bodyStr = new String(body, MixAll.DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            log.error("updateConfig byte array to string error: ", e);
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("UnsupportedEncodingException " + e);
            return response;
        }

        if (bodyStr == null) {
            log.error("updateConfig get null body!");
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("string2Properties error");
            return response;
        }

        Properties properties = MixAll.string2Properties(bodyStr);
        if (properties == null) {
            log.error("updateConfig MixAll.string2Properties error {}", bodyStr);
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("string2Properties error");
            return response;
        }

        this.namesrvController.getConfiguration().update(properties);
    }

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example 11
Source File: MQClientAPIImpl.java    From DDMQ with Apache License 2.0 5 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 12
Source File: DefaultRequestProcessor.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
private RemotingCommand updateConfig(ChannelHandlerContext ctx, RemotingCommand request) {
    log.info("updateConfig called by {}", RemotingHelper.parseChannelRemoteAddr(ctx.channel()));

    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    byte[] body = request.getBody();
    if (body != null) {
        String bodyStr;
        try {
            bodyStr = new String(body, MixAll.DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            log.error("updateConfig byte array to string error: ", e);
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("UnsupportedEncodingException " + e);
            return response;
        }

        if (bodyStr == null) {
            log.error("updateConfig get null body!");
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("string2Properties error");
            return response;
        }

        Properties properties = MixAll.string2Properties(bodyStr);
        if (properties == null) {
            log.error("updateConfig MixAll.string2Properties error {}", bodyStr);
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("string2Properties error");
            return response;
        }

        this.namesrvController.getConfiguration().update(properties);
    }

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example 13
Source File: ClientRemotingProcessor.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
public RemotingCommand resetOffset(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final ResetOffsetRequestHeader requestHeader =
        (ResetOffsetRequestHeader) request.decodeCommandCustomHeader(ResetOffsetRequestHeader.class);
    log.info("invoke reset offset operation from broker. brokerAddr={}, topic={}, group={}, timestamp={}",
            RemotingHelper.parseChannelRemoteAddr(ctx.channel()), requestHeader.getTopic(), requestHeader.getGroup(),
            requestHeader.getTimestamp());
    Map<MessageQueue, Long> offsetTable = new HashMap<MessageQueue, Long>();
    if (request.getBody() != null) {
        ResetOffsetBody body = ResetOffsetBody.decode(request.getBody(), ResetOffsetBody.class);
        offsetTable = body.getOffsetTable();
    }
    this.mqClientFactory.resetOffset(requestHeader.getTopic(), requestHeader.getGroup(), offsetTable);
    return null;
}
 
Example 14
Source File: AdminBrokerProcessor.java    From rocketmq-4.3.0 with Apache License 2.0 5 votes vote down vote up
private synchronized RemotingCommand updateBrokerConfig(ChannelHandlerContext ctx, RemotingCommand request) {
        final RemotingCommand response = RemotingCommand.createResponseCommand(null);

        log.info("updateBrokerConfig called by {}", RemotingHelper.parseChannelRemoteAddr(ctx.channel()));

        byte[] body = request.getBody();
        if (body != null) {
            try {
                String bodyStr = new String(body, MixAll.DEFAULT_CHARSET);
                Properties properties = MixAll.string2Properties(bodyStr);
                if (properties != null) {
                    log.info("updateBrokerConfig, new config: [{}] client: {} ", properties, ctx.channel().remoteAddress());
//                    更新持久存储 =》
                    this.brokerController.getConfiguration().update(properties);
//                    如果有权限设置强制更新
                    if (properties.containsKey("brokerPermission")) {
//                        更新数据的版本号
                        this.brokerController.getTopicConfigManager().getDataVersion().nextVersion();
//                        注册所有的broker =》
                        this.brokerController.registerBrokerAll(false, false, true);
                    }
                } else {
                    log.error("string2Properties error");
                    response.setCode(ResponseCode.SYSTEM_ERROR);
                    response.setRemark("string2Properties error");
                    return response;
                }
            } catch (UnsupportedEncodingException e) {
                log.error("", e);
                response.setCode(ResponseCode.SYSTEM_ERROR);
                response.setRemark("UnsupportedEncodingException " + e);
                return response;
            }
        }

        response.setCode(ResponseCode.SUCCESS);
        response.setRemark(null);
        return response;
    }
 
Example 15
Source File: MQClientAPIImpl.java    From DDMQ with Apache License 2.0 5 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 16
Source File: SendMessageProcessor.java    From rocketmq-4.3.0 with Apache License 2.0 4 votes vote down vote up
private RemotingCommand sendMessage(final ChannelHandlerContext ctx,
                                        final RemotingCommand request,
                                        final SendMessageContext sendMessageContext,
                                        final SendMessageRequestHeader requestHeader) throws RemotingCommandException {

        final RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
        final SendMessageResponseHeader responseHeader = (SendMessageResponseHeader)response.readCustomHeader();

        response.setOpaque(request.getOpaque());

        response.addExtField(MessageConst.PROPERTY_MSG_REGION, this.brokerController.getBrokerConfig().getRegionId());
        response.addExtField(MessageConst.PROPERTY_TRACE_SWITCH, String.valueOf(this.brokerController.getBrokerConfig().isTraceOn()));

        log.debug("receive SendMessage request command, {}", request);

//        查询开始接受发送消息请求的时间,默认是立即
        final long startTimstamp = this.brokerController.getBrokerConfig().getStartAcceptSendRequestTimeStamp();
        if (this.brokerController.getMessageStore().now() < startTimstamp) {
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark(String.format("broker unable to service, until %s", UtilAll.timeMillisToHumanString2(startTimstamp)));
            return response;
        }

        response.setCode(-1);
//        消息检查=》
        super.msgCheck(ctx, requestHeader, response);
        if (response.getCode() != -1) {
            return response;
        }

        final byte[] body = request.getBody();

        int queueIdInt = requestHeader.getQueueId();
//        按topic查询topic配置
        TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic());

        if (queueIdInt < 0) {
            queueIdInt = Math.abs(this.random.nextInt() % 99999999) % topicConfig.getWriteQueueNums();
        }

        MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
        msgInner.setTopic(requestHeader.getTopic());
        msgInner.setQueueId(queueIdInt);

//        不重试和延迟发送=》
        if (!handleRetryAndDLQ(requestHeader, response, request, msgInner, topicConfig)) {
            return response;
        }

        msgInner.setBody(body);
        msgInner.setFlag(requestHeader.getFlag());
        MessageAccessor.setProperties(msgInner, MessageDecoder.string2messageProperties(requestHeader.getProperties()));
        msgInner.setPropertiesString(requestHeader.getProperties());
        msgInner.setBornTimestamp(requestHeader.getBornTimestamp());
        msgInner.setBornHost(ctx.channel().remoteAddress());
        msgInner.setStoreHost(this.getStoreHost());
        msgInner.setReconsumeTimes(requestHeader.getReconsumeTimes() == null ? 0 : requestHeader.getReconsumeTimes());
        PutMessageResult putMessageResult = null;
        Map<String, String> oriProps = MessageDecoder.string2messageProperties(requestHeader.getProperties());
//        事务消息flag
        String traFlag = oriProps.get(MessageConst.PROPERTY_TRANSACTION_PREPARED);
        if (traFlag != null && Boolean.parseBoolean(traFlag)) {
            if (this.brokerController.getBrokerConfig().isRejectTransactionMessage()) {
                response.setCode(ResponseCode.NO_PERMISSION);
                response.setRemark(
                    "the broker[" + this.brokerController.getBrokerConfig().getBrokerIP1()
                        + "] sending transaction message is forbidden");
                return response;
            }
//            准备消息=》
            putMessageResult = this.brokerController.getTransactionalMessageService().prepareMessage(msgInner);
        } else {
//            存储消息=》
            putMessageResult = this.brokerController.getMessageStore().putMessage(msgInner);
        }

//        组装存储消息结果=》
        return handlePutMessageResult(putMessageResult, response, request, msgInner, responseHeader, sendMessageContext, ctx, queueIdInt);

    }
 
Example 17
Source File: SendMessageProcessor.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
private CompletableFuture<RemotingCommand> asyncSendMessage(ChannelHandlerContext ctx, RemotingCommand request,
                                                            SendMessageContext mqtraceContext,
                                                            SendMessageRequestHeader requestHeader) {
    final RemotingCommand response = preSend(ctx, request, requestHeader);
    final SendMessageResponseHeader responseHeader = (SendMessageResponseHeader)response.readCustomHeader();

    if (response.getCode() != -1) {
        return CompletableFuture.completedFuture(response);
    }

    final byte[] body = request.getBody();

    int queueIdInt = requestHeader.getQueueId();
    TopicConfig topicConfig = this.brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic());

    if (queueIdInt < 0) {
        queueIdInt = randomQueueId(topicConfig.getWriteQueueNums());
    }

    MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
    msgInner.setTopic(requestHeader.getTopic());
    msgInner.setQueueId(queueIdInt);

    if (!handleRetryAndDLQ(requestHeader, response, request, msgInner, topicConfig)) {
        return CompletableFuture.completedFuture(response);
    }

    msgInner.setBody(body);
    msgInner.setFlag(requestHeader.getFlag());
    MessageAccessor.setProperties(msgInner, MessageDecoder.string2messageProperties(requestHeader.getProperties()));
    msgInner.setPropertiesString(requestHeader.getProperties());
    msgInner.setBornTimestamp(requestHeader.getBornTimestamp());
    msgInner.setBornHost(ctx.channel().remoteAddress());
    msgInner.setStoreHost(this.getStoreHost());
    msgInner.setReconsumeTimes(requestHeader.getReconsumeTimes() == null ? 0 : requestHeader.getReconsumeTimes());
    String clusterName = this.brokerController.getBrokerConfig().getBrokerClusterName();
    MessageAccessor.putProperty(msgInner, MessageConst.PROPERTY_CLUSTER, clusterName);
    msgInner.setPropertiesString(MessageDecoder.messageProperties2String(msgInner.getProperties()));

    CompletableFuture<PutMessageResult> putMessageResult = null;
    Map<String, String> origProps = MessageDecoder.string2messageProperties(requestHeader.getProperties());
    String transFlag = origProps.get(MessageConst.PROPERTY_TRANSACTION_PREPARED);
    if (transFlag != null && Boolean.parseBoolean(transFlag)) {
        if (this.brokerController.getBrokerConfig().isRejectTransactionMessage()) {
            response.setCode(ResponseCode.NO_PERMISSION);
            response.setRemark(
                    "the broker[" + this.brokerController.getBrokerConfig().getBrokerIP1()
                            + "] sending transaction message is forbidden");
            return CompletableFuture.completedFuture(response);
        }
        putMessageResult = this.brokerController.getTransactionalMessageService().asyncPrepareMessage(msgInner);
    } else {
        putMessageResult = this.brokerController.getMessageStore().asyncPutMessage(msgInner);
    }
    return handlePutMessageResultFuture(putMessageResult, response, request, msgInner, responseHeader, mqtraceContext, ctx, queueIdInt);
}
 
Example 18
Source File: DefaultRequestProcessor.java    From rocketmq-read with Apache License 2.0 4 votes vote down vote up
/**
 * 新版本的注册请求
 * @param ctx ctx
 * @param request request
 * @return ;
 * @throws RemotingCommandException ;
 */
public RemotingCommand registerBrokerWithFilterServer(ChannelHandlerContext ctx, RemotingCommand request)
    throws RemotingCommandException {

    final RemotingCommand response = RemotingCommand.createResponseCommand(RegisterBrokerResponseHeader.class);
    final RegisterBrokerResponseHeader responseHeader = (RegisterBrokerResponseHeader) response.readCustomHeader();
    final RegisterBrokerRequestHeader requestHeader =
        (RegisterBrokerRequestHeader) request.decodeCommandCustomHeader(RegisterBrokerRequestHeader.class);

    //校验crc32
    if (!checksum(ctx, request, requestHeader)) {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("crc32 not match");
        return response;
    }

    RegisterBrokerBody registerBrokerBody = new RegisterBrokerBody();

    if (request.getBody() != null) {
        try {
            registerBrokerBody = RegisterBrokerBody.decode(request.getBody(), requestHeader.isCompressed());
        } catch (Exception e) {
            throw new RemotingCommandException("Failed to decode RegisterBrokerBody", e);
        }
    } else {
        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setCounter(new AtomicLong(0));
        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setTimestamp(0);
    }

    /*
     * 注册Broker,存在filerServerList
     */
    RegisterBrokerResult result = this.namesrvController.getRouteInfoManager().registerBroker(
        requestHeader.getClusterName(),
        requestHeader.getBrokerAddr(),
        requestHeader.getBackUpBrokerAddr(),
        requestHeader.getBrokerName(),
        requestHeader.getBrokerId(),
        requestHeader.getHaServerAddr(),
        registerBrokerBody.getTopicConfigSerializeWrapper(),
        registerBrokerBody.getFilterServerList(),
        ctx.channel());

    //返回结果
    responseHeader.setHaServerAddr(result.getHaServerAddr());
    responseHeader.setMasterAddr(result.getMasterAddr());

    byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
    response.setBody(jsonValue);

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    return response;
}
 
Example 19
Source File: DefaultRequestProcessor.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public RemotingCommand registerBrokerWithFilterServer(ChannelHandlerContext ctx, RemotingCommand request)
    throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(RegisterBrokerResponseHeader.class);
    final RegisterBrokerResponseHeader responseHeader = (RegisterBrokerResponseHeader) response.readCustomHeader();

    long start = System.currentTimeMillis();
    final RegisterBrokerRequestHeader requestHeader =
        (RegisterBrokerRequestHeader) request.decodeCommandCustomHeader(RegisterBrokerRequestHeader.class);
    long decodeCost = System.currentTimeMillis() - start;

    RegisterBrokerBody registerBrokerBody = new RegisterBrokerBody();

    long decodeBodyCost = 0;
    if (request.getBody() != null) {
        long startDecodeBody = System.currentTimeMillis();
        registerBrokerBody = RegisterBrokerBody.decode(request.getBody(), RegisterBrokerBody.class);
        decodeBodyCost = System.currentTimeMillis() - startDecodeBody;
    } else {
        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setCounter(new AtomicLong(0));
        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setTimestamp(0);
    }

    long startRegister = System.currentTimeMillis();
    RegisterBrokerResult result = this.namesrvController.getRouteInfoManager().registerBroker(
        requestHeader.getClusterName(),
        requestHeader.getBrokerAddr(),
        requestHeader.getBrokerName(),
        requestHeader.getBrokerId(),
        requestHeader.getHaServerAddr(),
        requestHeader.getMaxPhyOffset(),
        requestHeader.getTerm(),
        registerBrokerBody.getTopicConfigSerializeWrapper(),
        registerBrokerBody.getFilterServerList(),
        ctx.channel());
    long registerCost = System.currentTimeMillis() - startRegister;

    responseHeader.setHaServerAddr(result.getHaServerAddr());
    responseHeader.setMasterAddr(result.getMasterAddr());

    byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
    response.setBody(jsonValue);

    response.setCode(ResponseCode.SUCCESS);
    response.setRemark(null);
    log.info("registerBrokerWithFilterServer cost:{},decodeRequest:{},decodeBody:{},registerCost:{}",
        System.currentTimeMillis() - start,
        decodeCost,
        decodeBodyCost,
        registerCost);
    return response;
}
 
Example 20
Source File: AdminBrokerProcessor.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
private RemotingCommand updateBrokerConfig(ChannelHandlerContext ctx, RemotingCommand request) {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);

    log.info("updateBrokerConfig called by {}", RemotingHelper.parseChannelRemoteAddr(ctx.channel()));

    byte[] body = request.getBody();
    if (body != null) {
        try {
            String bodyStr = new String(body, MixAll.DEFAULT_CHARSET);
            Properties properties = MixAll.string2Properties(bodyStr);

            if (properties != null) {
                //not for ASYNC_MASTER to SYNC_MASTER or SYNC_MASTER to ASYNC_MASTER
                if (properties.containsKey(ConfigName.BROKER_ROLE) && properties.containsKey(ConfigName.BROKER_ID)) {
                    if (!brokerController.onRoleChangePre(properties)) {
                        response.setCode(ResponseCode.SYSTEM_ERROR);
                        response.setRemark("check status failed before change role");
                        return response;
                    }
                }

                BrokerRole oldBrokerRole = brokerController.getMessageStoreConfig().getBrokerRole();
                long oldBrokerId = brokerController.getBrokerConfig().getBrokerId();

                log.info("updateBrokerConfig, new config: [{}] client: {} ", properties, ctx.channel().remoteAddress());
                this.brokerController.getConfiguration().update(properties);

                if (properties.containsKey(ConfigName.BROKER_PERMISSION)) {
                    this.brokerController.registerBrokerAll(false, false);
                    this.brokerController.getTopicConfigManager().getDataVersion().nextVersion();
                }
                if (properties.containsKey(ConfigName.BROKER_ROLE) && properties.containsKey(ConfigName.BROKER_ID)) {
                    if (!brokerController.onRoleChange(oldBrokerRole, oldBrokerId)) {
                        response.setCode(ResponseCode.SYSTEM_ERROR);
                        response.setRemark("change role failed");
                        return response;
                    }
                }
            } else {
                log.error("string2Properties error");
                response.setCode(ResponseCode.SYSTEM_ERROR);
                response.setRemark("string2Properties error");
                return response;
            }
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
            response.setCode(ResponseCode.SYSTEM_ERROR);
            response.setRemark("UnsupportedEncodingException " + e);
            return response;
        }
    }

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