Search in sources :

Example 71 with Channel

use of io.netty.channel.Channel in project proxyee-down by monkeyWie.

the class HttpDownHandleInterceptFactory method create.

@Override
public HttpProxyIntercept create() {
    return new HttpProxyIntercept() {

        @Override
        public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception {
            HttpRequest httpRequest = pipeline.getHttpRequest();
            ProxyConfig proxyConfig = ContentManager.CONFIG.get().getSecProxyConfig();
            TaskInfo taskInfo = HttpDownUtil.getTaskInfo(httpRequest, httpResponse.headers(), proxyConfig, HttpDownConstant.clientSslContext, HttpDownConstant.clientLoopGroup);
            HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, httpRequest, proxyConfig);
            ContentManager.DOWN.putBoot(httpDownInfo);
            httpResponse.setStatus(HttpResponseStatus.OK);
            httpResponse.headers().clear();
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html");
            byte[] content;
            if (HttpUtil.checkHead(httpRequest, HttpHeaderNames.HOST, "^.*\\.baidupcs\\.com.*$")) {
                content = "<script>window.close();</script>".getBytes();
            } else {
                content = "<script>window.history.go(-1);</script>".getBytes();
            }
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length);
            clientChannel.writeAndFlush(httpResponse);
            HttpContent httpContent = new DefaultLastHttpContent();
            httpContent.content().writeBytes(content);
            clientChannel.writeAndFlush(httpContent);
            clientChannel.close();
            httpDownDispatch.dispatch(httpDownInfo);
        }
    };
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) TaskInfo(lee.study.down.model.TaskInfo) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpProxyIntercept(lee.study.proxyee.intercept.HttpProxyIntercept) ProxyConfig(lee.study.proxyee.proxy.ProxyConfig) HttpDownInfo(lee.study.down.model.HttpDownInfo) HttpProxyInterceptPipeline(lee.study.proxyee.intercept.HttpProxyInterceptPipeline) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent)

Example 72 with Channel

use of io.netty.channel.Channel in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class DefaultRequestProcessorTest method registerRouteInfoManager.

private void registerRouteInfoManager() {
    TopicConfigSerializeWrapper topicConfigSerializeWrapper = new TopicConfigSerializeWrapper();
    ConcurrentHashMap<String, TopicConfig> topicConfigConcurrentHashMap = new ConcurrentHashMap<>();
    TopicConfig topicConfig = new TopicConfig();
    topicConfig.setWriteQueueNums(8);
    topicConfig.setTopicName("unit-test");
    topicConfig.setPerm(6);
    topicConfig.setReadQueueNums(8);
    topicConfig.setOrder(false);
    topicConfigConcurrentHashMap.put("unit-test", topicConfig);
    topicConfigSerializeWrapper.setTopicConfigTable(topicConfigConcurrentHashMap);
    Channel channel = mock(Channel.class);
    RegisterBrokerResult registerBrokerResult = routeInfoManager.registerBroker("default-cluster", "127.0.0.1:10911", "default-broker", 1234, "127.0.0.1:1001", topicConfigSerializeWrapper, new ArrayList<String>(), channel);
}
Also used : RegisterBrokerResult(org.apache.rocketmq.common.namesrv.RegisterBrokerResult) TopicConfigSerializeWrapper(org.apache.rocketmq.common.protocol.body.TopicConfigSerializeWrapper) Channel(io.netty.channel.Channel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TopicConfig(org.apache.rocketmq.common.TopicConfig)

Example 73 with Channel

use of io.netty.channel.Channel in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class NettyRemotingClient method getAndCreateNameserverChannel.

// 就有取,没有就创建namessrv channel
private Channel getAndCreateNameserverChannel() throws InterruptedException {
    String addr = this.namesrvAddrChoosed.get();
    if (addr != null) {
        ChannelWrapper cw = this.channelTables.get(addr);
        if (cw != null && cw.isOK()) {
            return cw.getChannel();
        }
    }
    final List<String> addrList = this.namesrvAddrList.get();
    if (this.lockNamesrvChannel.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
        try {
            addr = this.namesrvAddrChoosed.get();
            if (addr != null) {
                ChannelWrapper cw = this.channelTables.get(addr);
                if (cw != null && cw.isOK()) {
                    return cw.getChannel();
                }
            }
            if (addrList != null && !addrList.isEmpty()) {
                for (int i = 0; i < addrList.size(); i++) {
                    int index = this.namesrvIndex.incrementAndGet();
                    index = Math.abs(index);
                    index = index % addrList.size();
                    String newAddr = addrList.get(index);
                    this.namesrvAddrChoosed.set(newAddr);
                    log.info("new name server is chosen. OLD: {} , NEW: {}. namesrvIndex = {}", addr, newAddr, namesrvIndex);
                    Channel channelNew = this.createChannel(newAddr);
                    if (channelNew != null)
                        return channelNew;
                }
            }
        } catch (Exception e) {
            log.error("getAndCreateNameserverChannel: create name server channel exception", e);
        } finally {
            this.lockNamesrvChannel.unlock();
        }
    } else {
        log.warn("getAndCreateNameserverChannel: try to lock name server, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
    }
    return null;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) RemotingTooMuchRequestException(org.apache.rocketmq.remoting.exception.RemotingTooMuchRequestException) RemotingConnectException(org.apache.rocketmq.remoting.exception.RemotingConnectException) RemotingSendRequestException(org.apache.rocketmq.remoting.exception.RemotingSendRequestException) RemotingTimeoutException(org.apache.rocketmq.remoting.exception.RemotingTimeoutException)

Example 74 with Channel

use of io.netty.channel.Channel in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class DefaultConsumerIdsChangeListener method handle.

@Override
public void handle(ConsumerGroupEvent event, String group, Object... args) {
    if (event == null) {
        return;
    }
    switch(event) {
        case CHANGE:
            if (args == null || args.length < 1) {
                return;
            }
            List<Channel> channels = (List<Channel>) args[0];
            if (channels != null && brokerController.getBrokerConfig().isNotifyConsumerIdsChangedEnable()) {
                for (Channel chl : channels) {
                    this.brokerController.getBroker2Client().notifyConsumerIdsChanged(chl, group);
                }
            }
            break;
        case UNREGISTER:
            this.brokerController.getConsumerFilterManager().unRegister(group);
            break;
        case REGISTER:
            if (args == null || args.length < 1) {
                return;
            }
            Collection<SubscriptionData> subscriptionDataList = (Collection<SubscriptionData>) args[0];
            this.brokerController.getConsumerFilterManager().register(group, subscriptionDataList);
            break;
        default:
            throw new RuntimeException("Unknown event " + event);
    }
}
Also used : Channel(io.netty.channel.Channel) SubscriptionData(org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData) Collection(java.util.Collection) List(java.util.List)

Example 75 with Channel

use of io.netty.channel.Channel in project rocketmq-rocketmq-all-4.1.0-incubating by lirenzuo.

the class Broker2Client method getConsumeStatus.

public RemotingCommand getConsumeStatus(String topic, String group, String originClientId) {
    final RemotingCommand result = RemotingCommand.createResponseCommand(null);
    GetConsumerStatusRequestHeader requestHeader = new GetConsumerStatusRequestHeader();
    requestHeader.setTopic(topic);
    requestHeader.setGroup(group);
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_STATUS_FROM_CLIENT, requestHeader);
    Map<String, Map<MessageQueue, Long>> consumerStatusTable = new HashMap<String, Map<MessageQueue, Long>>();
    ConcurrentMap<Channel, ClientChannelInfo> channelInfoTable = this.brokerController.getConsumerManager().getConsumerGroupInfo(group).getChannelInfoTable();
    if (null == channelInfoTable || channelInfoTable.isEmpty()) {
        result.setCode(ResponseCode.SYSTEM_ERROR);
        result.setRemark(String.format("No Any Consumer online in the consumer group: [%s]", group));
        return result;
    }
    for (Map.Entry<Channel, ClientChannelInfo> entry : channelInfoTable.entrySet()) {
        int version = entry.getValue().getVersion();
        String clientId = entry.getValue().getClientId();
        if (version < MQVersion.Version.V3_0_7_SNAPSHOT.ordinal()) {
            result.setCode(ResponseCode.SYSTEM_ERROR);
            result.setRemark("the client does not support this feature. version=" + MQVersion.getVersionDesc(version));
            log.warn("[get-consumer-status] the client does not support this feature. version={}", RemotingHelper.parseChannelRemoteAddr(entry.getKey()), MQVersion.getVersionDesc(version));
            return result;
        } else if (UtilAll.isBlank(originClientId) || originClientId.equals(clientId)) {
            try {
                RemotingCommand response = this.brokerController.getRemotingServer().invokeSync(entry.getKey(), request, 5000);
                assert response != null;
                switch(response.getCode()) {
                    case ResponseCode.SUCCESS:
                        {
                            if (response.getBody() != null) {
                                GetConsumerStatusBody body = GetConsumerStatusBody.decode(response.getBody(), GetConsumerStatusBody.class);
                                consumerStatusTable.put(clientId, body.getMessageQueueTable());
                                log.info("[get-consumer-status] get consumer status success. topic={}, group={}, channelRemoteAddr={}", topic, group, clientId);
                            }
                        }
                    default:
                        break;
                }
            } catch (Exception e) {
                log.error("[get-consumer-status] get consumer status exception. topic={}, group={}, offset={}", new Object[] { topic, group }, e);
            }
            if (!UtilAll.isBlank(originClientId) && originClientId.equals(clientId)) {
                break;
            }
        }
    }
    result.setCode(ResponseCode.SUCCESS);
    GetConsumerStatusBody resBody = new GetConsumerStatusBody();
    resBody.setConsumerTable(consumerStatusTable);
    result.setBody(resBody.encode());
    return result;
}
Also used : ClientChannelInfo(org.apache.rocketmq.broker.client.ClientChannelInfo) HashMap(java.util.HashMap) Channel(io.netty.channel.Channel) RemotingSendRequestException(org.apache.rocketmq.remoting.exception.RemotingSendRequestException) RemotingTimeoutException(org.apache.rocketmq.remoting.exception.RemotingTimeoutException) RemotingCommand(org.apache.rocketmq.remoting.protocol.RemotingCommand) MessageQueue(org.apache.rocketmq.common.message.MessageQueue) GetConsumerStatusBody(org.apache.rocketmq.common.protocol.body.GetConsumerStatusBody) GetConsumerStatusRequestHeader(org.apache.rocketmq.common.protocol.header.GetConsumerStatusRequestHeader) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Aggregations

Channel (io.netty.channel.Channel)884 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)226 ChannelFuture (io.netty.channel.ChannelFuture)204 Test (org.junit.Test)203 Bootstrap (io.netty.bootstrap.Bootstrap)199 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)191 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)177 InetSocketAddress (java.net.InetSocketAddress)165 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)151 EventLoopGroup (io.netty.channel.EventLoopGroup)142 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)138 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)132 IOException (java.io.IOException)126 ByteBuf (io.netty.buffer.ByteBuf)112 SocketChannel (io.netty.channel.socket.SocketChannel)106 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)99 ChannelPipeline (io.netty.channel.ChannelPipeline)98 CountDownLatch (java.util.concurrent.CountDownLatch)96 LocalChannel (io.netty.channel.local.LocalChannel)93 LocalServerChannel (io.netty.channel.local.LocalServerChannel)89