Example usage for io.netty.channel ChannelFuture cause

List of usage examples for io.netty.channel ChannelFuture cause

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture cause.

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:org.apache.hive.spark.client.rpc.Rpc.java

License:Apache License

/**
 * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
 * operation./*  w  w w  .j av a  2 s . co  m*/
 *
 * @param msg RPC call to send.
 * @param retType Type of expected reply.
 * @return A future used to monitor the operation.
 */
public <T> Future<T> call(Object msg, Class<T> retType) {
    Preconditions.checkArgument(msg != null);
    Preconditions.checkState(channel.isActive(), "RPC channel is closed.");
    try {
        final long id = rpcId.getAndIncrement();
        final Promise<T> promise = createPromise();
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture cf) {
                if (!cf.isSuccess() && !promise.isDone()) {
                    LOG.warn("Failed to send RPC, closing connection.", cf.cause());
                    promise.setFailure(cf.cause());
                    dispatcher.discardRpc(id);
                    close();
                }
            }
        };

        dispatcher.registerRpc(id, promise, msg.getClass().getName());
        synchronized (channelLock) {
            channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener);
            channel.writeAndFlush(msg).addListener(listener);
        }
        return promise;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.client.FailedRequestListener.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isSuccess()) {
        promise.setFailure(future.cause());
        future.channel().close();//from   ww w .j a v a 2  s  .c o m
    } else {
        future.channel().read();
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.server.StandbyServer.java

License:Apache License

private void start(boolean wait) {
    if (running)// w ww  . j a  v  a 2 s .com
        return;

    this.handler.state = STATUS_STARTING;

    final Thread close = new Thread() {
        @Override
        public void run() {
            try {
                running = true;
                handler.state = STATUS_RUNNING;
                channelFuture.sync().channel().closeFuture().sync();
            } catch (InterruptedException e) {
                StandbyServer.this.stop();
            }
        }
    };
    final ChannelFutureListener bindListener = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                close.start();
            } else {
                log.error("Server failed to start on port " + port + ", will be canceled", future.cause());
                future.channel().close();
                new Thread() {
                    @Override
                    public void run() {
                        close();
                    }
                }.start();
            }
        }
    };
    Future<?> startup = bossGroup.submit(new Runnable() {
        @Override
        public void run() {
            //netty 4.0.20 has a race condition issue with
            //asynchronous channel registration. As a workaround
            //we bind asynchronously from the boss event group to make
            //the channel registration synchronous.
            //Note that now this method will return immediately.
            channelFuture = b.bind(port);
            channelFuture.addListener(bindListener);
        }
    });
    if (!startup.awaitUninterruptibly(10000)) {
        log.error("Server failed to start within 10 seconds and will be canceled");
        startup.cancel(true);
    } else if (wait) {
        try {
            close.join();
        } catch (InterruptedException ignored) {
        }
    }
}

From source file:org.apache.pulsar.client.impl.ConnectionPool.java

License:Apache License

private CompletableFuture<ClientCnx> createConnection(InetSocketAddress address, int connectionKey) {
    if (log.isDebugEnabled()) {
        log.debug("Connection for {} not found in cache", address);
    }/*  ww  w  .  j a  v a  2 s  .c o  m*/

    final CompletableFuture<ClientCnx> cnxFuture = new CompletableFuture<ClientCnx>();

    // Trigger async connect to broker
    bootstrap.connect(address).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            log.warn("Failed to open connection to {} : {}", address,
                    future.cause().getClass().getSimpleName());
            cnxFuture.completeExceptionally(new PulsarClientException(future.cause()));
            cleanupConnection(address, connectionKey, cnxFuture);
            return;
        }

        log.info("[{}] Connected to server", future.channel());

        future.channel().closeFuture().addListener(v -> {
            // Remove connection from pool when it gets closed
            if (log.isDebugEnabled()) {
                log.debug("Removing closed connection from pool: {}", v);
            }
            cleanupConnection(address, connectionKey, cnxFuture);
        });

        // We are connected to broker, but need to wait until the connect/connected handshake is
        // complete
        final ClientCnx cnx = (ClientCnx) future.channel().pipeline().get("handler");
        if (!future.channel().isActive() || cnx == null) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Connection was already closed by the time we got notified", future.channel());
            }
            cnxFuture.completeExceptionally(new ChannelException("Connection already closed"));
            return;
        }

        cnx.connectionFuture().thenRun(() -> {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Connection handshake completed", cnx.channel());
            }
            cnxFuture.complete(cnx);
        }).exceptionally(exception -> {
            log.warn("[{}] Connection handshake failed: {}", cnx.channel(), exception.getMessage());
            cnxFuture.completeExceptionally(exception);
            cleanupConnection(address, connectionKey, cnxFuture);
            cnx.ctx().close();
            return null;
        });
    });

    return cnxFuture;
}

From source file:org.apache.qpid.jms.transports.netty.NettyTcpTransport.java

License:Apache License

@Override
public void connect(SSLContext sslContextOverride) throws IOException {

    if (listener == null) {
        throw new IllegalStateException("A transport listener must be set before connection attempts.");
    }//w w  w.jav a2s.c o m

    final SslHandler sslHandler;
    if (isSecure()) {
        try {
            TransportSslOptions sslOptions = getSslOptions();
            sslOptions.setSslContextOverride(sslContextOverride);

            sslHandler = TransportSupport.createSslHandler(getRemoteLocation(), sslOptions);
        } catch (Exception ex) {
            // TODO: can we stop it throwing Exception?
            throw IOExceptionSupport.create(ex);
        }
    } else {
        sslHandler = null;
    }

    group = new NioEventLoopGroup(1);

    bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel connectedChannel) throws Exception {
            configureChannel(connectedChannel, sslHandler);
        }
    });

    configureNetty(bootstrap, getTransportOptions());

    ChannelFuture future = bootstrap.connect(getRemoteHost(), getRemotePort());
    future.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handleException(future.channel(), IOExceptionSupport.create(future.cause()));
            }
        }
    });

    try {
        connectLatch.await();
    } catch (InterruptedException ex) {
        LOG.debug("Transport connection was interrupted.");
        Thread.interrupted();
        failureCause = IOExceptionSupport.create(ex);
    }

    if (failureCause != null) {
        // Close out any Netty resources now as they are no longer needed.
        if (channel != null) {
            channel.close().syncUninterruptibly();
            channel = null;
        }
        if (group != null) {
            Future<?> fut = group.shutdownGracefully(0, SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS);
            if (!fut.awaitUninterruptibly(2 * SHUTDOWN_TIMEOUT)) {
                LOG.trace("Channel group shutdown failed to complete in allotted time");
            }
            group = null;
        }

        throw failureCause;
    } else {
        // Connected, allow any held async error to fire now and close the transport.
        channel.eventLoop().execute(new Runnable() {

            @Override
            public void run() {
                if (failureCause != null) {
                    channel.pipeline().fireExceptionCaught(failureCause);
                }
            }
        });
    }
}

From source file:org.apache.rocketmq.broker.client.net.Broker2Client.java

License:Apache License

public void checkProducerTransactionState(final Channel channel,
        final CheckTransactionStateRequestHeader requestHeader,
        final SelectMappedBufferResult selectMappedBufferResult) {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_TRANSACTION_STATE,
            requestHeader);/*from  w  w w  .  j a va2 s.c o m*/
    request.markOnewayRPC();

    try {
        FileRegion fileRegion = new OneMessageTransfer(request.encodeHeader(selectMappedBufferResult.getSize()),
                selectMappedBufferResult);
        channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                selectMappedBufferResult.release();
                if (!future.isSuccess()) {
                    log.error("invokeProducer failed,", future.cause());
                }
            }
        });
    } catch (Throwable e) {
        log.error("invokeProducer exception", e);
        selectMappedBufferResult.release();
    }
}

From source file:org.apache.rocketmq.broker.processor.PullMessageProcessor.java

License:Apache License

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());

    if (LOG.isDebugEnabled()) {
        LOG.debug("receive PullMessage request command, {}", request);
    }// ww  w. j ava2  s .c o  m

    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 illagal, 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;
    if (hasSubscriptionFlag) {
        try {
            subscriptionData = FilterAPI.buildSubscriptionData(requestHeader.getConsumerGroup(),
                    requestHeader.getTopic(), requestHeader.getSubscription());
        } 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;
        }
    }

    final GetMessageResult getMessageResult = this.brokerController.getMessageStore().getMessage(
            requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId(),
            requestHeader.getQueueOffset(), requestHeader.getMaxMsgNums(), subscriptionData);
    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());
            }
            // consume ok
            else {
                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 is 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("Fail to transfer messages from page cache to {}",
                                        channel.remoteAddress(), future.cause());
                            }
                        }
                    });
                } catch (Throwable e) {
                    LOG.error("Error occurred when transferring messages from page cache", 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);
                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;
}

From source file:org.apache.rocketmq.broker.processor.PullMessageProcessor.java

License:Apache License

public void executeRequestWhenWakeup(final Channel channel, final RemotingCommand request)
        throws RemotingCommandException {
    Runnable run = new Runnable() {
        @Override//w  ww.j a  va2  s  .c  o  m
        public void run() {
            try {
                final RemotingCommand response = PullMessageProcessor.this.processRequest(channel, request,
                        false);

                if (response != null) {
                    response.setOpaque(request.getOpaque());
                    response.markResponseType();
                    try {
                        channel.writeAndFlush(response).addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    LOG.error("ProcessRequestWrapper response to {} failed",
                                            future.channel().remoteAddress(), future.cause());
                                    LOG.error(request.toString());
                                    LOG.error(response.toString());
                                }
                            }
                        });
                    } catch (Throwable e) {
                        LOG.error("ProcessRequestWrapper process request over, but response failed", e);
                        LOG.error(request.toString());
                        LOG.error(response.toString());
                    }
                }
            } catch (RemotingCommandException e1) {
                LOG.error("ExecuteRequestWhenWakeup run", e1);
            }
        }
    };
    this.brokerController.getPullMessageExecutor().submit(new RequestTask(run, channel, request));
}

From source file:org.apache.rocketmq.broker.processor.QueryMessageProcessor.java

License:Apache License

public RemotingCommand queryMessage(ChannelHandlerContext ctx, RemotingCommand request)
        throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(QueryMessageResponseHeader.class);
    final QueryMessageResponseHeader responseHeader = (QueryMessageResponseHeader) response.readCustomHeader();
    final QueryMessageRequestHeader requestHeader = (QueryMessageRequestHeader) request
            .decodeCommandCustomHeader(QueryMessageRequestHeader.class);

    response.setOpaque(request.getOpaque());

    String isUniqueKey = request.getExtFields().get(MixAll.UNIQUE_MSG_QUERY_FLAG);
    if (isUniqueKey != null && isUniqueKey.equals("true")) {
        requestHeader.setMaxNum(this.brokerController.getMessageStoreConfig().getDefaultQueryMaxNum());
    }//from  w w  w .  ja v  a 2s  .  c  o m

    final QueryMessageResult queryMessageResult = this.brokerController.getMessageStore().queryMessage(
            requestHeader.getTopic(), requestHeader.getKey(), requestHeader.getMaxNum(),
            requestHeader.getBeginTimestamp(), requestHeader.getEndTimestamp());
    assert queryMessageResult != null;

    responseHeader.setIndexLastUpdatePhyoffset(queryMessageResult.getIndexLastUpdatePhyoffset());
    responseHeader.setIndexLastUpdateTimestamp(queryMessageResult.getIndexLastUpdateTimestamp());

    if (queryMessageResult.getBufferTotalSize() > 0) {
        response.setCode(ResponseCode.SUCCESS);
        response.setRemark(null);

        try {
            FileRegion fileRegion = new QueryMessageTransfer(
                    response.encodeHeader(queryMessageResult.getBufferTotalSize()), queryMessageResult);
            ctx.channel().writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    queryMessageResult.release();
                    if (!future.isSuccess()) {
                        log.error("transfer query message by page cache failed, ", future.cause());
                    }
                }
            });
        } catch (Throwable e) {
            log.error("", e);
            queryMessageResult.release();
        }

        return null;
    }

    response.setCode(ResponseCode.QUERY_NOT_FOUND);
    response.setRemark("can not find message, maybe time range not correct");
    return response;
}

From source file:org.apache.rocketmq.broker.processor.QueryMessageProcessor.java

License:Apache License

public RemotingCommand viewMessageById(ChannelHandlerContext ctx, RemotingCommand request)
        throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final ViewMessageRequestHeader requestHeader = (ViewMessageRequestHeader) request
            .decodeCommandCustomHeader(ViewMessageRequestHeader.class);

    response.setOpaque(request.getOpaque());

    final SelectMappedBufferResult selectMappedBufferResult = this.brokerController.getMessageStore()
            .selectOneMessageByOffset(requestHeader.getOffset());
    if (selectMappedBufferResult != null) {
        response.setCode(ResponseCode.SUCCESS);
        response.setRemark(null);//from  www. ja v  a2s.c  om

        try {
            FileRegion fileRegion = new OneMessageTransfer(
                    response.encodeHeader(selectMappedBufferResult.getSize()), selectMappedBufferResult);
            ctx.channel().writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    selectMappedBufferResult.release();
                    if (!future.isSuccess()) {
                        log.error("Transfer one message from page cache failed, ", future.cause());
                    }
                }
            });
        } catch (Throwable e) {
            log.error("", e);
            selectMappedBufferResult.release();
        }

        return null;
    } else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("can not find message by the offset, " + requestHeader.getOffset());
    }

    return response;
}