Example usage for io.netty.channel ChannelHandlerContext fireChannelActive

List of usage examples for io.netty.channel ChannelHandlerContext fireChannelActive

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext fireChannelActive.

Prototype

@Override
    ChannelHandlerContext fireChannelActive();

Source Link

Usage

From source file:network.thunder.core.communication.layer.low.ping.PingHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    this.ctx = ctx;
    ctx.fireChannelActive();

    new Thread(() -> {
        while (true) {
            if (connectionClosed) {
                return;
            } else {
                if (lastPing - lastPong > TIMEOUT) {
                    ctx.disconnect();/*  www. j  a  v a  2  s. c  o  m*/
                } else if (System.currentTimeMillis() - lastPing > PING_INTERVAL) {
                    sendPing();
                }
            }

            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                return;
            }
        }
    }).start();
}

From source file:network.thunder.core.communication.nio.handler.low.NodeConnectionHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    System.out.println("CHANNEL ACTIVE NODE_CONNECTION_HANDLER");
    context.activeNodes.add(node);//from w  w w.j av  a  2 s.co  m
    node.setNettyContext(ctx);
    ctx.fireChannelActive();
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.ActiveMQChannelHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    group.add(ctx.channel());/*from  w w  w  .  ja v a2  s  .c  o m*/
    ctx.fireChannelActive();
}

From source file:org.apache.cassandra.transport.ConnectionLimitHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final long count = counter.incrementAndGet();
    long limit = DatabaseDescriptor.getNativeTransportMaxConcurrentConnections();
    // Setting the limit to -1 disables it.
    if (limit < 0) {
        limit = Long.MAX_VALUE;//ww w . j  a  v  a2s  . c om
    }
    if (count > limit) {
        // The decrement will be done in channelClosed(...)
        logger.warn("Exceeded maximum native connection limit of {} by using {} connections", limit, count);
        ctx.close();
    } else {
        long perIpLimit = DatabaseDescriptor.getNativeTransportMaxConcurrentConnectionsPerIp();
        if (perIpLimit > 0) {
            InetAddress address = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress();

            AtomicLong perIpCount = connectionsPerClient.get(address);
            if (perIpCount == null) {
                perIpCount = new AtomicLong(0);

                AtomicLong old = connectionsPerClient.putIfAbsent(address, perIpCount);
                if (old != null) {
                    perIpCount = old;
                }
            }
            if (perIpCount.incrementAndGet() > perIpLimit) {
                // The decrement will be done in channelClosed(...)
                logger.warn("Exceeded maximum native connection limit per ip of {} by using {} connections",
                        perIpLimit, perIpCount);
                ctx.close();
                return;
            }
        }
        ctx.fireChannelActive();
    }
}

From source file:org.apache.giraph.comm.netty.handler.RequestServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("channelActive: Connected the channel on " + ctx.channel().remoteAddress());
    }// w  ww .  ja  v  a  2s.c om
    ctx.fireChannelActive();
}

From source file:org.apache.giraph.comm.netty.NettyServer.java

License:Apache License

/**
 * Start the server with the appropriate port
 *///from  www  .j  a  v  a2s.c o m
public void start() {
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, tcpBacklog)
            .option(ChannelOption.ALLOCATOR, conf.getNettyAllocator())
            .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_SNDBUF, sendBufferSize)
            .childOption(ChannelOption.SO_RCVBUF, receiveBufferSize)
            .childOption(ChannelOption.ALLOCATOR, conf.getNettyAllocator())
            .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(receiveBufferSize / 4,
                    receiveBufferSize, receiveBufferSize));

    /**
     * Pipeline setup: depends on whether configured to use authentication
     * or not.
     */
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            /*if_not[HADOOP_NON_SECURE]*/
            if (conf.authenticate()) {
                LOG.info("start: Will use Netty pipeline with "
                        + "authentication and authorization of clients.");
                // After a client authenticates, the two authentication-specific
                // pipeline components SaslServerHandler and ResponseEncoder are
                // removed, leaving the pipeline the same as in the non-authenticated
                // configuration except for the presence of the Authorize component.
                PipelineUtils.addLastWithExecutorCheck("serverInboundByteCounter", inByteCounter,
                        handlerToUseExecutionGroup, executionGroup, ch);
                if (conf.doCompression()) {
                    PipelineUtils.addLastWithExecutorCheck("compressionDecoder",
                            conf.getNettyCompressionDecoder(), handlerToUseExecutionGroup, executionGroup, ch);
                }
                PipelineUtils.addLastWithExecutorCheck("serverOutboundByteCounter", outByteCounter,
                        handlerToUseExecutionGroup, executionGroup, ch);
                if (conf.doCompression()) {
                    PipelineUtils.addLastWithExecutorCheck("compressionEncoder",
                            conf.getNettyCompressionEncoder(), handlerToUseExecutionGroup, executionGroup, ch);
                }
                PipelineUtils.addLastWithExecutorCheck("requestFrameDecoder",
                        new LengthFieldBasedFrameDecoder(1024 * 1024 * 1024, 0, 4, 0, 4),
                        handlerToUseExecutionGroup, executionGroup, ch);
                PipelineUtils.addLastWithExecutorCheck("requestDecoder",
                        new RequestDecoder(conf, inByteCounter), handlerToUseExecutionGroup, executionGroup,
                        ch);
                // Removed after authentication completes:
                PipelineUtils.addLastWithExecutorCheck("saslServerHandler",
                        saslServerHandlerFactory.newHandler(conf), handlerToUseExecutionGroup, executionGroup,
                        ch);
                PipelineUtils.addLastWithExecutorCheck("authorizeServerHandler", new AuthorizeServerHandler(),
                        handlerToUseExecutionGroup, executionGroup, ch);
                PipelineUtils.addLastWithExecutorCheck(
                        "requestServerHandler", requestServerHandlerFactory.newHandler(workerRequestReservedMap,
                                conf, myTaskInfo, exceptionHandler),
                        handlerToUseExecutionGroup, executionGroup, ch);
                // Removed after authentication completes:
                PipelineUtils.addLastWithExecutorCheck("responseEncoder", new ResponseEncoder(),
                        handlerToUseExecutionGroup, executionGroup, ch);
            } else {
                LOG.info("start: Using Netty without authentication.");
                /*end[HADOOP_NON_SECURE]*/
                // Store all connected channels in order to ensure that we can close
                // them on stop(), or else stop() may hang waiting for the
                // connections to close on their own
                ch.pipeline().addLast("connectedChannels", new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        accepted.add(ctx.channel());
                        ctx.fireChannelActive();
                    }
                });
                PipelineUtils.addLastWithExecutorCheck("serverInboundByteCounter", inByteCounter,
                        handlerToUseExecutionGroup, executionGroup, ch);
                if (conf.doCompression()) {
                    PipelineUtils.addLastWithExecutorCheck("compressionDecoder",
                            conf.getNettyCompressionDecoder(), handlerToUseExecutionGroup, executionGroup, ch);
                }
                PipelineUtils.addLastWithExecutorCheck("serverOutboundByteCounter", outByteCounter,
                        handlerToUseExecutionGroup, executionGroup, ch);
                if (conf.doCompression()) {
                    PipelineUtils.addLastWithExecutorCheck("compressionEncoder",
                            conf.getNettyCompressionEncoder(), handlerToUseExecutionGroup, executionGroup, ch);
                }
                PipelineUtils.addLastWithExecutorCheck("requestFrameDecoder",
                        new LengthFieldBasedFrameDecoder(1024 * 1024 * 1024, 0, 4, 0, 4),
                        handlerToUseExecutionGroup, executionGroup, ch);
                PipelineUtils.addLastWithExecutorCheck("requestDecoder",
                        new RequestDecoder(conf, inByteCounter), handlerToUseExecutionGroup, executionGroup,
                        ch);
                PipelineUtils.addLastWithExecutorCheck(
                        "requestServerHandler", requestServerHandlerFactory.newHandler(workerRequestReservedMap,
                                conf, myTaskInfo, exceptionHandler),
                        handlerToUseExecutionGroup, executionGroup, ch);
                /*if_not[HADOOP_NON_SECURE]*/
            }
            /*end[HADOOP_NON_SECURE]*/
        }
    });

    int taskId = conf.getTaskPartition();
    int numTasks = conf.getInt("mapred.map.tasks", 1);
    // Number of workers + 1 for master
    int numServers = conf.getInt(GiraphConstants.MAX_WORKERS, numTasks) + 1;
    int portIncrementConstant = (int) Math.pow(10, Math.ceil(Math.log10(numServers)));
    int bindPort = GiraphConstants.IPC_INITIAL_PORT.get(conf) + taskId;
    int bindAttempts = 0;
    final int maxIpcPortBindAttempts = MAX_IPC_PORT_BIND_ATTEMPTS.get(conf);
    final boolean failFirstPortBindingAttempt = GiraphConstants.FAIL_FIRST_IPC_PORT_BIND_ATTEMPT.get(conf);

    // Simple handling of port collisions on the same machine while
    // preserving debugability from the port number alone.
    // Round up the max number of workers to the next power of 10 and use
    // it as a constant to increase the port number with.
    while (bindAttempts < maxIpcPortBindAttempts) {
        this.myAddress = new InetSocketAddress(localHostname, bindPort);
        if (failFirstPortBindingAttempt && bindAttempts == 0) {
            if (LOG.isInfoEnabled()) {
                LOG.info("start: Intentionally fail first "
                        + "binding attempt as giraph.failFirstIpcPortBindAttempt " + "is true, port "
                        + bindPort);
            }
            ++bindAttempts;
            bindPort += portIncrementConstant;
            continue;
        }

        try {
            ChannelFuture f = bootstrap.bind(myAddress).sync();
            accepted.add(f.channel());
            break;
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
            // CHECKSTYLE: stop IllegalCatchCheck
        } catch (Exception e) {
            // CHECKSTYLE: resume IllegalCatchCheck
            LOG.warn("start: Likely failed to bind on attempt " + bindAttempts + " to port " + bindPort,
                    e.getCause());
            ++bindAttempts;
            bindPort += portIncrementConstant;
        }
    }
    if (bindAttempts == maxIpcPortBindAttempts || myAddress == null) {
        throw new IllegalStateException(
                "start: Failed to start NettyServer with " + bindAttempts + " attempts");
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("start: Started server " + "communication server: " + myAddress + " with up to " + maxPoolSize
                + " threads on bind attempt " + bindAttempts + " with sendBufferSize = " + sendBufferSize
                + " receiveBufferSize = " + receiveBufferSize);
    }
}

From source file:org.dcache.xrootd.plugins.AccessLogHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    NetLoggerBuilder log = new NetLoggerBuilder(INFO, "org.dcache.xrootd.connection.start").omitNullValues();
    log.add("session", CDC.getSession());
    log.add("socket.remote", (InetSocketAddress) ctx.channel().remoteAddress());
    log.add("socket.local", (InetSocketAddress) ctx.channel().localAddress());
    log.toLogger(logger);/* w  w  w  .  ja  v  a  2  s .c  om*/
    ctx.fireChannelActive();
}

From source file:org.eclipse.scada.protocol.relp.RelpHandler.java

License:Open Source License

protected void handleOpen(final ChannelHandlerContext ctx, final OpenRequest msg) {
    if (this.opened) {
        logger.warn("Duplicate open request. Closing channel.");
        ctx.close();// www.ja va2 s  .c  om
        return;
    }

    this.opened = true;

    logger.debug("Removing timeout");
    if (this.timeoutTask != null) {
        this.timeoutTask.cancel(false);
    }

    logger.debug("Process open command: {}", msg);

    final String cs = msg.getOffers().get(Constants.OFFER_COMMANDS);
    if (cs == null) {
        ctx.write(ServerCloseMessage.INSTANCE);
        throw new IllegalStateException("Offer 'commands' not found in open command");
    }

    final Set<String> commands = new HashSet<>(Arrays.asList(cs.split(",")));

    logger.debug("Supported commands: {}", commands);

    if (!commands.contains("syslog")) {
        ctx.write(ServerCloseMessage.INSTANCE);
        throw new IllegalStateException("Command 'syslog' not supported");
    }

    final Map<String, String> result = new HashMap<>(1);
    result.put(Constants.OFFER_COMMANDS, "syslog");
    result.put(Constants.OFFER_PROTOCOL_VERSION, "0");

    ctx.writeAndFlush(msg.replyOk(result));
    ctx.fireChannelActive();
}

From source file:org.iotivity.cloud.base.protocols.coap.CoapLogHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Log.v(ctx.channel().id().asLongText().substring(26) + " Connected, Address: "
            + ctx.channel().remoteAddress().toString());

    ctx.fireChannelActive();
}

From source file:org.iotivity.cloud.base.protocols.coap.websocket.WebSocketFrameHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Log.v(ctx.channel().id().asLongText().substring(26) + " WebSocket Connected, Address: "
            + ctx.channel().remoteAddress().toString());

    ctx.fireChannelActive();
}