@Override public CompletionStage<NodeConnectionReport> closeConnectionAsync( SocketAddress connection, CloseType type) { Optional<Channel> channel = this.clientChannelGroup .stream() .filter(c -> c.remoteAddress().equals(connection)) .findFirst(); if (channel.isPresent()) { ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); channelGroup.add(channel.get()); ClusterConnectionReport clusterReport = new ClusterConnectionReport(getCluster().getId()); NodeConnectionReport report = clusterReport.addNode(this, Collections.singletonList(connection), getAddress()); return closeChannelGroup(channelGroup, type).thenApply(f -> report); } else { CompletableFuture<NodeConnectionReport> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new IllegalArgumentException("Not found")); return failedFuture; } }
@Deprecated public RedisClient(final Timer timer, ExecutorService executor, EventLoopGroup group, Class<? extends SocketChannel> socketChannelClass, String host, int port, int connectTimeout, int commandTimeout) { RedisClientConfig config = new RedisClientConfig(); config.setTimer(timer).setExecutor(executor).setGroup(group).setSocketChannelClass(socketChannelClass) .setAddress(host, port).setConnectTimeout(connectTimeout).setCommandTimeout(commandTimeout); this.config = config; this.executor = config.getExecutor(); this.timer = config.getTimer(); addr = new InetSocketAddress(config.getAddress().getHost(), config.getAddress().getPort()); channels = new DefaultChannelGroup(config.getGroup().next()); bootstrap = createBootstrap(config, Type.PLAIN); pubSubBootstrap = createBootstrap(config, Type.PUBSUB); this.commandTimeout = config.getCommandTimeout(); }
public void init() throws SyncException { cg = new DefaultChannelGroup("Cluster Bootstrap", GlobalEventExecutor.INSTANCE); workerExecutor = new NioEventLoopGroup(); timer = new HashedWheelTimer(); bootstrap = new Bootstrap() .group(workerExecutor) .channel(NioSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_SNDBUF, RPCService.SEND_BUFFER_SIZE) .option(ChannelOption.SO_RCVBUF, RPCService.SEND_BUFFER_SIZE) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, RPCService.CONNECT_TIMEOUT); pipelineFactory = new BootstrapChannelInitializer(timer, this); bootstrap.handler(pipelineFactory); }
public NettyIoAcceptor(NettyIoServiceFactory factory, IoHandler handler) { this.factory = factory; this.handler = handler; channelGroup = new DefaultChannelGroup("sshd-acceptor-channels", GlobalEventExecutor.INSTANCE);; bootstrap.group(factory.eventLoopGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new NettyIoSession(NettyIoAcceptor.this, handler).adapter); } }); }
/** * ReplicatorService creates and starts fibers; it must be stopped (or failed) in * order to dispose them. */ public ReplicatorService(EventLoopGroup bossGroup, EventLoopGroup workerGroup, long nodeId, int port, ModuleInformationProvider moduleInformationProvider, FiberSupplier fiberSupplier, QuorumFileReaderWriter quorumFileReaderWriter) { this.bossGroup = bossGroup; this.workerGroup = workerGroup; this.nodeId = nodeId; this.port = port; this.moduleInformationProvider = moduleInformationProvider; this.fiberSupplier = fiberSupplier; this.allChannels = new DefaultChannelGroup(workerGroup.next()); this.persister = new Persister(quorumFileReaderWriter); }
/** * Create a new instance with client resources. * * @param clientResources the client resources. If {@literal null}, the client will create a new dedicated instance of * client resources and keep track of them. */ protected AbstractRedisClient(ClientResources clientResources) { if (clientResources == null) { sharedResources = false; this.clientResources = DefaultClientResources.create(); } else { sharedResources = true; this.clientResources = clientResources; } unit = TimeUnit.SECONDS; genericWorkerPool = this.clientResources.eventExecutorGroup(); channels = new DefaultChannelGroup(genericWorkerPool.next()); timer = (HashedWheelTimer) this.clientResources.timer(); }
<T extends ServerSocketChannel> RpcServer(EventLoopGroup eventLoopGroup, EventExecutorGroup eventExecutor, Class<T> channel, SocketAddress address) { this.address = address; this.allChannels = new DefaultChannelGroup(eventLoopGroup.next()); this.handler = new ServerHandler(allChannels); this.bootstrap = new ServerBootstrap(); bootstrap.channel(channel); bootstrap.childHandler(new ServerInitializer(eventExecutor, handler)); bootstrap.group(eventLoopGroup); bootstrap.option(ChannelOption.TCP_NODELAY, true); }
private RedisClient(RedisClientConfig config) { this.config = config; this.executor = config.getExecutor(); this.timer = config.getTimer(); addr = new InetSocketAddress(config.getAddress().getHost(), config.getAddress().getPort()); channels = new DefaultChannelGroup(config.getGroup().next()); bootstrap = createBootstrap(config, Type.PLAIN); pubSubBootstrap = createBootstrap(config, Type.PUBSUB); this.commandTimeout = config.getCommandTimeout(); }
public WebSocketServerThread(Settings settings) { this.PORT = settings.httpPort; this.SSL = false; // TODO: support ssl? this.blockBridge = null; this.playersBridge = null; this.webPlayerBridge = null; this.allUsersGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); this.settings = settings; }
public WebImageViewer(InetSocketAddress address) { this.address = address; this.bossGroup = new NioEventLoopGroup(); this.workerGroup = new NioEventLoopGroup(); this.allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); this.bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class); }
@Override protected void startUp() throws Exception { channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); EventLoopGroup bossGroup = new NioEventLoopGroup(NUM_BOSS_THREADS, new ThreadFactoryBuilder() .setDaemon(true).setNameFormat("boss-thread").build()); EventLoopGroup workerGroup = new NioEventLoopGroup(NUM_WORKER_THREADS, new ThreadFactoryBuilder() .setDaemon(true).setNameFormat("worker-thread#%d").build()); bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { channelGroup.add(ch); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("codec", new HttpServerCodec()); pipeline.addLast("compressor", new HttpContentCompressor()); pipeline.addLast("aggregator", new HttpObjectAggregator(MAX_INPUT_SIZE)); pipeline.addLast("handler", new ReportHandler()); } }); Channel serverChannel = bootstrap.bind(new InetSocketAddress(host, 0)).sync().channel(); channelGroup.add(serverChannel); bindAddress = (InetSocketAddress) serverChannel.localAddress(); url = URI.create(String.format("http://%s:%d", host, bindAddress.getPort())).toURL(); LOG.info("Tracker service started at {}", url); }
/** * {@inheritDoc} * @see com.heliosapm.streams.tracing.AbstractMetricWriter#configure(java.util.Properties) */ @Override public void configure(final Properties config) { super.configure(config); remotes = ConfigurationHelper.getArraySystemThenEnvProperty(CONFIG_REMOTE_URIS, DEFAULT_REMOTE_URIS, config); Collections.addAll(remoteUris, remotes); channelGroupThreads = ConfigurationHelper.getIntSystemThenEnvProperty(CONFIG_EXEC_THREADS, DEFAULT_EXEC_THREADS, config); this.config.put("channelGroupThreads", channelGroupThreads); eventLoopThreads = ConfigurationHelper.getIntSystemThenEnvProperty(CONFIG_ELOOP_THREADS, DEFAULT_ELOOP_THREADS, config); this.config.put("eventLoopThreads", eventLoopThreads); eventExecutor = new UnorderedThreadPoolEventExecutor(channelGroupThreads, groupThreadFactory, this); channels = new DefaultChannelGroup(getClass().getSimpleName() + "Channels", eventExecutor); group = new NioEventLoopGroup(eventLoopThreads, eventLoopThreadFactory); bootstrap .group(group) .channel(channelType) .handler(getChannelInitializer()) ; bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); // FIXME: config bootstrap.option(ChannelOption.ALLOCATOR, BufferManager.getInstance()); this.config.put("connectTimeout", 5000); // FIXME: Tweaks for channel configuration }
/** * Scotty, start me up! * Initializes the netty data pipeline and starts the IO server * * @throws InterruptedException if interrupted while waiting for the startup * @throws IllegalStateException is the Server is already running */ private void startServer() throws InterruptedException { if (isChannelOpen()) { throw new IllegalStateException("Server already running"); } //Setup the Executor and Connection Pool final ExecutionServiceComponent eventLoop = requireComponent(ExecutionServiceComponent.KEY); connections = new DefaultChannelGroup(eventLoop.next()); ServerBootstrap b = new ServerBootstrap() .group(eventLoop) .channel(NioServerSocketChannel.class) .childHandler(getHandshakeHandler()) .childOption(ChannelOption.SO_KEEPALIVE, true); //Bind to ports and wait for the start of the server final int localPort = getLocalPort(); if (localPort < 0 || localPort > 65535) { throw new StartupException("Illegal localPort " + localPort); } localChannel = b.bind(localPort).sync(); final int publicPort = getPublicPort(); if (publicPort >= 0 && publicPort <= 65535 && localPort != publicPort) { publicChannel = b.bind(publicPort).sync(); } Log.i(getClass().getSimpleName(), "Server bound to port " + localChannel.channel() + (publicChannel != null ? " and " + publicChannel.channel() : "")); }
public void init(CamelContext camelContext, NettyServerBootstrapConfiguration configuration, ChannelInitializer<Channel> pipelineFactory) { this.camelContext = camelContext; this.configuration = configuration; this.pipelineFactory = pipelineFactory; this.allChannels = configuration.getChannelGroup() != null ? configuration.getChannelGroup() : new DefaultChannelGroup(SingleTCPNettyServerBootstrapFactory.class.getName(), ImmediateEventExecutor.INSTANCE); }
public void init(ThreadFactory threadFactory, NettyServerBootstrapConfiguration configuration, ChannelInitializer<Channel> pipelineFactory) { this.threadFactory = threadFactory; this.configuration = configuration; this.pipelineFactory = pipelineFactory; this.allChannels = configuration.getChannelGroup() != null ? configuration.getChannelGroup() : new DefaultChannelGroup(SingleTCPNettyServerBootstrapFactory.class.getName(), ImmediateEventExecutor.INSTANCE); }
private static void runTest(ThreadPerChannelEventLoopGroup loopGroup) throws InterruptedException { int taskCount = 100; EventExecutor testExecutor = new TestEventExecutor(); ChannelGroup channelGroup = new DefaultChannelGroup(testExecutor); while (taskCount-- > 0) { Channel channel = new EmbeddedChannel(NOOP_HANDLER); loopGroup.register(channel, new DefaultChannelPromise(channel, testExecutor)); channelGroup.add(channel); } channelGroup.close().sync(); loopGroup.shutdownGracefully(100, 200, TimeUnit.MILLISECONDS).sync(); assertTrue(loopGroup.isTerminated()); }
/** * Test try to reproduce issue #1335 */ @Test public void testBindMultiple() throws Exception { DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); NioEventLoopGroup group = new NioEventLoopGroup(); try { for (int i = 0; i < 100; i++) { Bootstrap udpBootstrap = new Bootstrap(); udpBootstrap.group(group).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // Discard ReferenceCountUtil.release(msg); } }); DatagramChannel datagramChannel = (DatagramChannel) udpBootstrap .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); channelGroup.add(datagramChannel); } Assert.assertEquals(100, channelGroup.size()); } finally { channelGroup.close().sync(); group.shutdownGracefully().sync(); } }
@Override protected void startServer(int port, final Action<ServerWebSocket> websocketAction) { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()) .addLast(new AsityServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals(TEST_URI); } }.onwebsocket(websocketAction)); } }); channels.add(bootstrap.bind(port).channel()); }
@Override protected void startServer(int port, final Action<ServerHttpExchange> requestAction) throws Exception { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()) .addLast(new AsityServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals(TEST_URI); } }.onhttp(requestAction)); } }); channels.add(bootstrap.bind(port).channel()); }
public ChannelGroup getGroup() { ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); if(!CollectionUtils.isEmpty(items)) { items.forEach((itemId, channel) -> channelGroup.add(channel)); } return channelGroup; }
public ChannelGroup getGroup(String... itemIds) { if(ArrayUtils.isEmpty(itemIds)) { return DEFAULT; } ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); if(!CollectionUtils.isEmpty(items)) { items.entrySet().stream().filter(entry -> ObjectCompare.isInList(entry.getKey(), itemIds)).forEach(entry -> channelGroup.add(entry.getValue())); } return channelGroup; }
/** * Creates a new Server */ private Server() { log.info("Configuring Netty Server...."); String serverLevel = ConfigurationHelper.getSystemThenEnvProperty(Constants.CONF_NETTY_SERVER_LOGLEVEL, Constants.DEFAULT_NETTY_SERVER_LOGLEVEL); loggingHandler = new LoggingHandler(getClass(), LogLevel.valueOf(serverLevel.trim().toUpperCase())); iface = ConfigurationHelper.getSystemThenEnvProperty(Constants.CONF_NETTY_IFACE, Constants.DEFAULT_NETTY_IFACE); port = ConfigurationHelper.getIntSystemThenEnvProperty(Constants.CONF_NETTY_PORT, Constants.DEFAULT_NETTY_PORT); int bossThreads = ConfigurationHelper.getIntSystemThenEnvProperty(Constants.CONF_NETTY_BOSS_THREADS, Constants.DEFAULT_NETTY_BOSS_THREADS); int workerThreads = ConfigurationHelper.getIntSystemThenEnvProperty(Constants.CONF_NETTY_WORKER_THREADS, Constants.DEFAULT_NETTY_WORKER_THREADS); int groupThreads = ConfigurationHelper.getIntSystemThenEnvProperty(Constants.CONF_NETTY_CGROUP_THREADS, Constants.DEFAULT_NETTY_CGROUP_THREADS); bossPool = new ManagedDefaultExecutorServiceFactory("bossPool").newExecutorService(bossThreads); // ForkJoinPoolManager.register(bossPool, BOSS_POOL_ON); workerPool = new ManagedDefaultExecutorServiceFactory("workerPool").newExecutorService(workerThreads); // ForkJoinPoolManager.register(workerPool, WORKER_POOL_ON); channelGroupPool = new ManagedDefaultExecutorServiceFactory("groupPool").newExecutorService(groupThreads); // ForkJoinPoolManager.register(channelGroupPool, CGROUP_POOL_ON); bossGroup = new NioEventLoopGroup(bossThreads, bossPool, selectorProvider); workerGroup = new NioEventLoopGroup(bossThreads, workerPool, selectorProvider); bootStrap = new ServerBootstrap(); groupExecutor = new DefaultEventExecutor(channelGroupPool); channelGroup = new DefaultChannelGroup("TSDBLite", groupExecutor); MetricCache.getInstance(); // fire up the metric cache before we start taking calls log.info("Selector: {}", selectorProvider.getClass().getName()); bootStrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(loggingHandler) .childHandler(this); try { serverChannel = (NioServerSocketChannel)bootStrap.bind(iface, port).sync().channel(); } catch (Exception ex) { stop(); log.error("Failed to bind Netty server on [{}:{}]", iface, port, ex); throw new RuntimeException("Failed to bind Netty server", ex); } JMXHelper.registerMBean(this, OBJECT_NAME); log.info("\n\t======================================\n\tNetty Server started on [{}:{}]\n\t======================================", iface, port); }
public HttpFileServer(final InetSocketAddress addr) { this.addr = addr; this.eventloopGroup = new NioEventLoopGroup(2, Executors.defaultThreadFactory()); // Configure the server. this.bootstrap = new ServerBootstrap(); this.bootstrap.childHandler(new HttpFileServerChannelInitializer()) .group(eventloopGroup) .option(ChannelOption.TCP_NODELAY, true) .channel(NioServerSocketChannel.class); this.channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); }
@Override protected void startServer() { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()) .addLast(new VibeServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals("/test"); } } .onwebsocket(performer.serverAction())); } }); channels.add(bootstrap.bind(port).channel()); }
@Override protected void startServer() { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()) .addLast(new VibeServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals("/test"); } } .onhttp(performer.serverAction())); } }); channels.add(bootstrap.bind(port).channel()); }
public final Server build() { final ChannelGroup activeChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); registerAllServices(); final StaticPathResolver staticResolver = new StaticPathResolver(contextPath, staticFolders, staticMappings, staticResources); final NettyServer server = new NettyServer(port, registry, staticResolver, activeChannels, contextPath, appName, acceptKeepAlive, idleTimeoutMs, supportZip, metricFactory, maxContentLength, requestTimeoutMs); server.addListeners(listeners); return server; }
public ServerStream(final String rawName, final String typeString) { this.name = Utils.trimSlashes(rawName).toLowerCase(); if(typeString != null) { this.publishType = PublishType.parse(typeString); // TODO record, append subscribers = new DefaultChannelGroup(name,null); configMessages = new ArrayList<RtmpMessage>(); } else { this.publishType = null; subscribers = null; configMessages = null; } logger.info("Created ServerStream {}", this); }
public HttpServer(IController ledController) { this.bossGroup = new NioEventLoopGroup(1); this.clientGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()); this.scheduler = Schedulers.from(bossGroup); this.connections = new DefaultChannelGroup(bossGroup.next()); this.wsConnections = new DefaultChannelGroup(bossGroup.next()); this.ledController = ledController; }
private static void runTest(ThreadPerChannelEventLoopGroup loopGroup) throws InterruptedException { int taskCount = 100; EventExecutor testExecutor = new TestEventExecutor(); ChannelGroup channelGroup = new DefaultChannelGroup(testExecutor); while (taskCount-- > 0) { Channel channel = new EmbeddedChannel(NOOP_HANDLER); channel.unsafe().register(new DefaultChannelPromise(channel, testExecutor)); channelGroup.add(channel); } channelGroup.close().sync(); loopGroup.shutdownGracefully(100, 200, TimeUnit.MILLISECONDS).sync(); assertTrue(loopGroup.isTerminated()); }
/** * Test try to reproduce issue #1335 */ @Test public void testBindMultiple() throws Exception { DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); NioEventLoopGroup group = new NioEventLoopGroup(); try { for (int i = 0; i < 100; i++) { Bootstrap udpBootstrap = new Bootstrap(); udpBootstrap.group(group).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChannelHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // Discard ReferenceCountUtil.release(msg); } }); DatagramChannel datagramChannel = (DatagramChannel) udpBootstrap .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); channelGroup.add(datagramChannel); } Assert.assertEquals(100, channelGroup.size()); } finally { channelGroup.close().sync(); group.shutdownGracefully().sync(); } }