Search in sources :

Example 51 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project BRFS by zhangnianli.

the class NettyHttpServer method start.

@Override
public void start() throws InterruptedException {
    ServerBootstrap serverStart = new ServerBootstrap();
    serverStart.group(bossGroup, workerGroup);
    serverStart.channel(NioServerSocketChannel.class);
    serverStart.childHandler(handlerInitializer);
    // 积压数量
    serverStart.option(ChannelOption.SO_BACKLOG, baklog);
    // 连接超时时间(毫秒)
    serverStart.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conTimeout);
    // 保持连接
    serverStart.childOption(ChannelOption.SO_KEEPALIVE, true);
    InetSocketAddress address = (ip == null ? new InetSocketAddress(port) : new InetSocketAddress(ip, port));
    channelFuture = serverStart.bind(address).sync();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 52 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project swift by luastar.

the class RpcServer method start.

public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
                pipeline.addLast(new RpcDecoder(RpcRequest.class, rpcSerialize));
                pipeline.addLast(new RpcEncoder(RpcResponse.class, rpcSerialize));
                pipeline.addLast(new RpcServerChannelHandler(handlerMap));
            }
        });
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        Channel channel = bootstrap.bind(port).sync().channel();
        logger.info("SwiftRpcServer started on port {}", port);
        // 注册 RPC 服务地址
        String serviceAddress = RpcConstant.CURRENT_SERVER_ADDRESS + ":" + port;
        for (String interfaceName : handlerMap.keySet()) {
            serviceRegistry.register(interfaceName, serviceAddress);
        }
        channel.closeFuture().sync();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) RpcEncoder(com.luastar.swift.rpc.serialize.RpcEncoder) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) RpcDecoder(com.luastar.swift.rpc.serialize.RpcDecoder) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 53 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project CorfuDB by CorfuDB.

the class CorfuServer method main.

public static void main(String[] args) {
    serverRunning = true;
    // Parse the options given, using docopt.
    Map<String, Object> opts = new Docopt(USAGE).withVersion(GitRepositoryState.getRepositoryState().describe).parse(args);
    int port = Integer.parseInt((String) opts.get("<port>"));
    // Print a nice welcome message.
    AnsiConsole.systemInstall();
    printLogo();
    System.out.println(ansi().a("Welcome to ").fg(RED).a("CORFU ").fg(MAGENTA).a("SERVER").reset());
    System.out.println(ansi().a("Version ").a(Version.getVersionString()).a(" (").fg(BLUE).a(GitRepositoryState.getRepositoryState().commitIdAbbrev).reset().a(")"));
    System.out.println(ansi().a("Serving on port ").fg(WHITE).a(port).reset());
    System.out.println(ansi().a("Service directory: ").fg(WHITE).a((Boolean) opts.get("--memory") ? "MEMORY mode" : opts.get("--log-path")).reset());
    // Pick the correct logging level before outputting error messages.
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    switch((String) opts.get("--log-level")) {
        case "ERROR":
            root.setLevel(Level.ERROR);
            break;
        case "WARN":
            root.setLevel(Level.WARN);
            break;
        case "INFO":
            root.setLevel(Level.INFO);
            break;
        case "DEBUG":
            root.setLevel(Level.DEBUG);
            break;
        case "TRACE":
            root.setLevel(Level.TRACE);
            break;
        default:
            root.setLevel(Level.INFO);
            log.warn("Level {} not recognized, defaulting to level INFO", opts.get("--log-level"));
    }
    log.debug("Started with arguments: " + opts);
    // Create the service directory if it does not exist.
    if (!(Boolean) opts.get("--memory")) {
        File serviceDir = new File((String) opts.get("--log-path"));
        if (!serviceDir.exists()) {
            if (serviceDir.mkdirs()) {
                log.info("Created new service directory at {}.", serviceDir);
            }
        } else if (!serviceDir.isDirectory()) {
            log.error("Service directory {} does not point to a directory. Aborting.", serviceDir);
            throw new RuntimeException("Service directory must be a directory!");
        }
    }
    // Now, we start the Netty router, and have it route to the correct port.
    router = new NettyServerRouter(opts);
    // Create a common Server Context for all servers to access.
    serverContext = new ServerContext(opts, router);
    // Add each role to the router.
    addSequencer();
    addLayoutServer();
    addLogUnit();
    addManagementServer();
    router.baseServer.setOptionsMap(opts);
    // Setup SSL if needed
    Boolean tlsEnabled = (Boolean) opts.get("--enable-tls");
    Boolean tlsMutualAuthEnabled = (Boolean) opts.get("--enable-tls-mutual-auth");
    if (tlsEnabled) {
        // Get the TLS cipher suites to enable
        String ciphs = (String) opts.get("--tls-ciphers");
        if (ciphs != null) {
            List<String> ciphers = Pattern.compile(",").splitAsStream(ciphs).map(String::trim).collect(Collectors.toList());
            enabledTlsCipherSuites = ciphers.toArray(new String[ciphers.size()]);
        }
        // Get the TLS protocols to enable
        String protos = (String) opts.get("--tls-protocols");
        if (protos != null) {
            List<String> protocols = Pattern.compile(",").splitAsStream(protos).map(String::trim).collect(Collectors.toList());
            enabledTlsProtocols = protocols.toArray(new String[protocols.size()]);
        }
        try {
            sslContext = TlsUtils.enableTls(TlsUtils.SslContextType.SERVER_CONTEXT, (String) opts.get("--keystore"), e -> {
                log.error("Could not load keys from the key store.");
                System.exit(1);
            }, (String) opts.get("--keystore-password-file"), e -> {
                log.error("Could not read the key store password file.");
                System.exit(1);
            }, (String) opts.get("--truststore"), e -> {
                log.error("Could not load keys from the trust store.");
                System.exit(1);
            }, (String) opts.get("--truststore-password-file"), e -> {
                log.error("Could not read the trust store password file.");
                System.exit(1);
            });
        } catch (Exception ex) {
            log.error("Could not build the SSL context");
            System.exit(1);
        }
    }
    Boolean saslPlainTextAuth = (Boolean) opts.get("--enable-sasl-plain-text-auth");
    // Create the event loops responsible for servicing inbound messages.
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    EventExecutorGroup ee;
    bossGroup = new NioEventLoopGroup(1, new ThreadFactory() {

        final AtomicInteger threadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("accept-" + threadNum.getAndIncrement());
            return t;
        }
    });
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {

        final AtomicInteger threadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("io-" + threadNum.getAndIncrement());
            return t;
        }
    });
    ee = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {

        final AtomicInteger threadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("event-" + threadNum.getAndIncrement());
            return t;
        }
    });
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(io.netty.channel.socket.SocketChannel ch) throws Exception {
                if (tlsEnabled) {
                    SSLEngine engine = sslContext.newEngine(ch.alloc());
                    engine.setEnabledCipherSuites(enabledTlsCipherSuites);
                    engine.setEnabledProtocols(enabledTlsProtocols);
                    if (tlsMutualAuthEnabled) {
                        engine.setNeedClientAuth(true);
                    }
                    ch.pipeline().addLast("ssl", new SslHandler(engine));
                }
                ch.pipeline().addLast(new LengthFieldPrepender(4));
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                if (saslPlainTextAuth) {
                    ch.pipeline().addLast("sasl/plain-text", new PlainTextSaslNettyServer());
                }
                ch.pipeline().addLast(ee, new NettyCorfuMessageDecoder());
                ch.pipeline().addLast(ee, new NettyCorfuMessageEncoder());
                ch.pipeline().addLast(ee, router);
            }
        });
        ChannelFuture f = b.bind(port).sync();
        while (true) {
            try {
                f.channel().closeFuture().sync();
            } catch (InterruptedException ie) {
            }
        }
    } catch (InterruptedException ie) {
    } catch (Exception ex) {
        log.error("Corfu server shut down unexpectedly due to exception", ex);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) Getter(lombok.Getter) GitRepositoryState(org.corfudb.util.GitRepositoryState) LoggerFactory(org.slf4j.LoggerFactory) NettyCorfuMessageEncoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageEncoder) Docopt(org.docopt.Docopt) SSLEngine(javax.net.ssl.SSLEngine) PlainTextSaslNettyServer(org.corfudb.security.sasl.plaintext.PlainTextSaslNettyServer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) Map(java.util.Map) Color(org.fusesource.jansi.Ansi.Color) ThreadFactory(java.util.concurrent.ThreadFactory) SocketChannel(io.netty.channel.socket.SocketChannel) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) TlsUtils(org.corfudb.security.tls.TlsUtils) Ansi.ansi(org.fusesource.jansi.Ansi.ansi) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NettyCorfuMessageDecoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageDecoder) EventLoopGroup(io.netty.channel.EventLoopGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Level(ch.qos.logback.classic.Level) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) AnsiConsole(org.fusesource.jansi.AnsiConsole) Logger(ch.qos.logback.classic.Logger) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Pattern(java.util.regex.Pattern) Version(org.corfudb.util.Version) ThreadFactory(java.util.concurrent.ThreadFactory) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) SSLEngine(javax.net.ssl.SSLEngine) NettyCorfuMessageEncoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageEncoder) Logger(ch.qos.logback.classic.Logger) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) Docopt(org.docopt.Docopt) PlainTextSaslNettyServer(org.corfudb.security.sasl.plaintext.PlainTextSaslNettyServer) SocketChannel(io.netty.channel.socket.SocketChannel) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) ChannelFuture(io.netty.channel.ChannelFuture) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SslHandler(io.netty.handler.ssl.SslHandler) NettyCorfuMessageDecoder(org.corfudb.protocols.wireprotocol.NettyCorfuMessageDecoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) File(java.io.File)

Example 54 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project dubbo by alibaba.

the class NettyServer method doOpen.

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), new DefaultThreadFactory("NettyServerWorker", true));
    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE).childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
            // .addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
            ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder()).addLast("handler", nettyServerHandler);
        }
    });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();
}
Also used : DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelFuture(io.netty.channel.ChannelFuture) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) RemotingException(com.alibaba.dubbo.remoting.RemotingException)

Example 55 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project geode by apache.

the class GeodeRedisServer method startRedisServer.

/**
   * Helper method to start the server listening for connections. The server is bound to the port
   * specified by {@link GeodeRedisServer#serverPort}
   * 
   * @throws IOException
   * @throws InterruptedException
   */
private void startRedisServer() throws IOException, InterruptedException {
    ThreadFactory selectorThreadFactory = new ThreadFactory() {

        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GeodeRedisServer-SelectorThread-" + counter.incrementAndGet());
            t.setDaemon(true);
            return t;
        }
    };
    ThreadFactory workerThreadFactory = new ThreadFactory() {

        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GeodeRedisServer-WorkerThread-" + counter.incrementAndGet());
            return t;
        }
    };
    bossGroup = null;
    workerGroup = null;
    Class<? extends ServerChannel> socketClass = null;
    if (singleThreadPerConnection) {
        bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory);
        workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory);
        socketClass = OioServerSocketChannel.class;
    } else {
        bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory);
        workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory);
        socketClass = NioServerSocketChannel.class;
    }
    InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
    String pwd = system.getConfig().getRedisPassword();
    final byte[] pwdB = Coder.stringToBytes(pwd);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (logger.fineEnabled())
                logger.fine("GeodeRedisServer-Connection established with " + ch.remoteAddress());
            ChannelPipeline p = ch.pipeline();
            p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder());
            p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GeodeRedisServer.this, pwdB));
        }
    }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GeodeRedisServer.connectTimeoutMillis).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync();
    if (this.logger.infoEnabled()) {
        String logMessage = "GeodeRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads;
        if (this.singleThreadPerConnection)
            logMessage += ", One worker thread per connection";
        else
            logMessage += ", Worker threads: " + this.numWorkerThreads;
        this.logger.info(logMessage);
    }
    this.serverChannel = f.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ThreadFactory(java.util.concurrent.ThreadFactory) OioServerSocketChannel(io.netty.channel.socket.oio.OioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) OioEventLoopGroup(io.netty.channel.oio.OioEventLoopGroup) ByteToCommandDecoder(org.apache.geode.redis.internal.ByteToCommandDecoder) InetSocketAddress(java.net.InetSocketAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutionHandlerContext(org.apache.geode.redis.internal.ExecutionHandlerContext) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)448 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)246 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)239 Channel (io.netty.channel.Channel)187 ChannelFuture (io.netty.channel.ChannelFuture)183 EventLoopGroup (io.netty.channel.EventLoopGroup)168 Bootstrap (io.netty.bootstrap.Bootstrap)134 SocketChannel (io.netty.channel.socket.SocketChannel)126 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)115 InetSocketAddress (java.net.InetSocketAddress)113 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)98 ChannelPipeline (io.netty.channel.ChannelPipeline)88 LoggingHandler (io.netty.handler.logging.LoggingHandler)82 LocalServerChannel (io.netty.channel.local.LocalServerChannel)76 LocalChannel (io.netty.channel.local.LocalChannel)73 CountDownLatch (java.util.concurrent.CountDownLatch)66 Test (org.junit.jupiter.api.Test)66 LocalAddress (io.netty.channel.local.LocalAddress)61 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)60 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)57