@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; } }
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); }
/** * Disconnect from the AudioConnect server and shutdown this client.<br> * If this client has already been or is being shutdown, this will do nothing.<br> * <b>Note:</b> This client instance will no longer be able to connect after this is called. * @return a Future for when this client has completely disconnected and been shutdown. */ public Future<?> shutdown() { if (bootstrap.group().isShuttingDown()) { return GlobalEventExecutor.INSTANCE.newSucceededFuture(null); } final Promise<Object> shutdownPromise = GlobalEventExecutor.INSTANCE.newPromise(); disconnect().addListener(new FutureListener<Object>() { @Override public void operationComplete(Future<Object> future) { bootstrap.group().shutdownGracefully().addListener(new PromiseNotifier<>(shutdownPromise)); } }); return shutdownPromise; }
@Inject public FibManagerImpl(final NexthopManager nexthopManager, final VrfEntryListener vrfEntryListener, final BundleContext bundleContext, final FibUtil fibUtil, final InterVpnLinkCache interVpnLinkCache) { this.nexthopManager = nexthopManager; this.vrfEntryListener = vrfEntryListener; this.fibUtil = fibUtil; this.interVpnLinkCache = interVpnLinkCache; GlobalEventExecutor.INSTANCE.execute(() -> { final WaitingServiceTracker<IVpnManager> tracker = WaitingServiceTracker.create( IVpnManager.class, bundleContext); vpnmanager = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); LOG.info("FibManagerImpl initialized. IVpnManager={}", vpnmanager); }); }
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); } }); }
@Test public void testTerminationFutureSuccessReflectively() throws Exception { Field terminationFutureField = ThreadPerChannelEventLoopGroup.class.getDeclaredField("terminationFuture"); terminationFutureField.setAccessible(true); final Exception[] exceptionHolder = new Exception[1]; for (int i = 0; i < 2; i++) { ThreadPerChannelEventLoopGroup loopGroup = new ThreadPerChannelEventLoopGroup(64); Promise<?> promise = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE) { @Override public Promise<Void> setSuccess(Void result) { try { return super.setSuccess(result); } catch (IllegalStateException e) { exceptionHolder[0] = e; throw e; } } }; terminationFutureField.set(loopGroup, promise); runTest(loopGroup); } // The global event executor will not terminate, but this will give the test a chance to fail. GlobalEventExecutor.INSTANCE.awaitTermination(100, TimeUnit.MILLISECONDS); assertNull(exceptionHolder[0]); }
/** * Schedules the specified object to be released when the caller thread terminates. Note that this operation is * intended to simplify reference counting of ephemeral objects during unit tests. Do not use it beyond the * intended use case. */ public static <T> T releaseLater(T msg, int decrement) { if (msg instanceof ReferenceCounted) { synchronized (pendingReleases) { Thread thread = Thread.currentThread(); List<Entry> entries = pendingReleases.get(thread); if (entries == null) { // Start the periodic releasing task (if not started yet.) if (pendingReleases.isEmpty()) { ReleasingTask task = new ReleasingTask(); task.future = GlobalEventExecutor.INSTANCE.scheduleWithFixedDelay(task, 1, 1, TimeUnit.SECONDS); } // Create a new entry. entries = new ArrayList<Entry>(); pendingReleases.put(thread, entries); } entries.add(new Entry((ReferenceCounted) msg, decrement)); } } return msg; }
/** * Establish PCEPS TLS connection with peer */ @Test public void testEstablishTLS() { final DefaultPCEPSessionNegotiator negotiator = new DefaultPCEPSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE), this.channel, this.listener, (short) 1, 20, new OpenBuilder().setKeepalive((short) 1).build(), SslContextFactoryTest.createTlsConfig()); negotiator.channelActive(null); assertEquals(1, this.msgsSend.size()); assertTrue(this.msgsSend.get(0) instanceof Starttls); assertEquals(DefaultPCEPSessionNegotiator.State.START_TLS_WAIT, negotiator.getState()); negotiator.handleMessage(this.startTlsMsg); assertEquals(DefaultPCEPSessionNegotiator.State.OPEN_WAIT, negotiator.getState()); assertEquals(2, this.msgsSend.size()); assertTrue(this.msgsSend.get(1) instanceof Open); negotiator.handleMessage(this.openMsg); assertEquals(DefaultPCEPSessionNegotiator.State.KEEP_WAIT, negotiator.getState()); }
public synchronized void init() { this.transactionChain = this.dataBroker.createTransactionChain(this); final TimerTask task = new TimerTask() { @Override @SuppressWarnings("checkstyle:IllegalCatch") public void run() { synchronized (StateProviderImpl.this) { final WriteTransaction wTx = StateProviderImpl.this.transactionChain.newWriteOnlyTransaction(); try { updateBGPStats(wTx); } catch (final Exception e) { LOG.warn("Failed to update BGP Stats", e); } finally { wTx.submit(); } } } }; this.scheduleTask = GlobalEventExecutor.INSTANCE.scheduleAtFixedRate(task, 0, this.timeout, TimeUnit.SECONDS); }
@Before public void setUp() throws Exception { super.setup(); MockitoAnnotations.initMocks(this); final String hexMessages = "/bgp_hex.txt"; final List<byte[]> bgpMessages = HexDumpBGPFileParser.parseMessages(ParserToSalTest.class.getResourceAsStream(hexMessages)); this.mock = new BGPMock(new EventBus("test"), ServiceLoaderBGPExtensionProviderContext .getSingletonInstance().getMessageRegistry(), Lists.newArrayList(fixMessages(bgpMessages))); Mockito.doReturn(GlobalEventExecutor.INSTANCE.newSucceededFuture(null)).when(this.dispatcher) .createReconnectingClient(Mockito.any(InetSocketAddress.class), Mockito.anyInt(), Mockito.any(KeyMapping.class)); this.ext1 = new SimpleRIBExtensionProviderContext(); this.ext2 = new SimpleRIBExtensionProviderContext(); this.baseact = new RIBActivator(); this.lsact = new org.opendaylight.protocol.bgp.linkstate.impl.RIBActivator(); this.baseact.startRIBExtensionProvider(this.ext1); this.lsact.startRIBExtensionProvider(this.ext2); }
public <T extends MessageLite> Future<T> sendRequestMsg(ApplicationIdentifier applicationId, MessageLite appSpecificRequestMsg, final Class<T> appSpecificResponseClass) { ByteBuf appSpecificProtobufBytes=ProtobufByteBufCodec.encodeNoLengthPrefix(appSpecificRequestMsg); Future<ByteBuf> responseBytesFuture = sendRequestBytes(applicationId, appSpecificProtobufBytes); //FIXME should we release() something? //FIXME Hum, is that the proper thread to do the decoding? final DefaultPromise<T> responseFuture = new DefaultPromise<T>(GlobalEventExecutor.INSTANCE); responseBytesFuture.addListener(new GenericFutureListener<Future<? super ByteBuf>>() { @Override public void operationComplete(Future<? super ByteBuf> future) throws Exception { if(future.isSuccess()==false){ responseFuture.setFailure(future.cause()); return; } T decodedAppSpecificResponse=(T) ProtobufByteBufCodec.decodeNoLengthPrefix((ByteBuf) future.get(), appSpecificResponseClass); responseFuture.setSuccess(decodedAppSpecificResponse); } }); return responseFuture; }
@Test public void regularUse() { final DefaultPromise<Boolean> target = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); Futures.PromiseAggregator<Boolean, Promise<Boolean>> sut = new Futures.PromiseAggregator<>( target); sut.expectMore(1); sut.arm(); DefaultPromise<Boolean> part = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); sut.add(part); assertThat(target.isDone()).isFalse(); part.setSuccess(true); Wait.untilTrue(target::isDone).waitOrTimeout(); assertThat(target.isDone()).isTrue(); }
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 public void execute(Runnable task) { if(preferGlobalEventExecutor){ GlobalEventExecutor.INSTANCE.execute(task); return; } synchronized (tasks) { tasks.add(task); if (!this.isRunning) { this.isRunning = true; newThread().start(); } } }
@Override public void publish(E message) { final Date now = new Date(); GlobalEventExecutor.INSTANCE.execute(() -> { Message<E> msg = new Message<E>(name, message, now.getTime(), null); messageListeners.values().forEach(c -> c.onMessage(msg)); }); }
@Inject public BgpConfigurationManager(final DataBroker dataBroker, final EntityOwnershipService entityOwnershipService, final FibDSWriter fibDSWriter, final IVpnLinkService vpnLinkSrvce, final BundleContext bundleContext, final BgpUtil bgpUtil) throws InterruptedException, ExecutionException, TimeoutException { this.dataBroker = dataBroker; this.fibDSWriter = fibDSWriter; this.vpnLinkService = vpnLinkSrvce; this.bundleContext = bundleContext; this.bgpUtil = bgpUtil; String updatePort = getProperty(UPDATE_PORT, DEF_UPORT); hostStartup = getProperty(CONFIG_HOST, DEF_CHOST); portStartup = getProperty(CONFIG_PORT, DEF_CPORT); LOG.info("UpdateServer at localhost:" + updatePort + " ConfigServer at " + hostStartup + ":" + portStartup); VtyshCli.setHostAddr(hostStartup); ClearBgpCli.setHostAddr(hostStartup); bgpRouter = BgpRouter.newInstance(this::getConfig, this::isBGPEntityOwner); registerCallbacks(); entityOwnershipUtils = new EntityOwnershipUtils(entityOwnershipService); candidateRegistration = registerEntityCandidate(entityOwnershipService); entityListenerRegistration = registerEntityListener(entityOwnershipService); LOG.info("BGP Configuration manager initialized"); initer.countDown(); GlobalEventExecutor.INSTANCE.execute(() -> { final WaitingServiceTracker<IBgpManager> tracker = WaitingServiceTracker.create( IBgpManager.class, bundleContext); bgpManager = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); updateServer = new BgpThriftService(Integer.parseInt(updatePort), bgpManager, this); updateServer.start(); LOG.info("BgpConfigurationManager initialized. IBgpManager={}", bgpManager); }); }
public void testSerialRoundTrip() throws InterruptedException, ExecutionException { final BlockingQueue<Object> serverQueue = new LinkedBlockingQueue<>(); final BlockingQueue<Object> clientQueue = new LinkedBlockingQueue<>(); final Promise<SocketChannel> serverChannel = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); final Promise<SocketChannel> clientChannel = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); SimpleContainer serverContainer = new SimpleContainer(); addContext(serverContainer); Server server = new TestServer(serverQueue, serverChannel); serverContainer.register(UDPDiscoveryServer.KEY, new UDPDiscoveryServer()); serverContainer.register(Server.KEY, server); try { SimpleContainer clientContainer = new SimpleContainer(); addContext(clientContainer); Client client = new TestClient(clientQueue, clientChannel); clientContainer.register(UDPDiscoveryClient.KEY, new UDPDiscoveryClient()); clientContainer.register(Client.KEY, client); try { serverChannel.await(1000); clientChannel.await(1000); runRoundTripTests(serverQueue, clientQueue, serverChannel, clientChannel); } finally { clientContainer.unregister(Client.KEY); client.awaitShutdown(); } } finally { shutdownServer(serverContainer); } assertTrue(serverQueue.isEmpty()); assertTrue(clientQueue.isEmpty()); }
@Override protected Executor closeExecutor() { if (javaChannel().isOpen() && config().getSoLinger() > 0) { return GlobalEventExecutor.INSTANCE; } return null; }
@Override public ChannelFuture register(Channel channel) { if (channel == null) { throw new NullPointerException("channel"); } try { EventLoop l = nextChild(); return l.register(channel, new DefaultChannelPromise(channel, l)); } catch (Throwable t) { return new FailedChannelFuture(channel, GlobalEventExecutor.INSTANCE, t); } }
final ChannelFuture initAndRegister() { final Channel channel = channelFactory().newChannel(); try { init(channel); } catch (Throwable t) { channel.unsafe().closeForcibly(); // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t); } ChannelFuture regFuture = group().register(channel); if (regFuture.cause() != null) { if (channel.isRegistered()) { channel.close(); } else { channel.unsafe().closeForcibly(); } } // If we are here and the promise is not failed, it's one of the following cases: // 1) If we attempted registration from the event loop, the registration has been completed at this point. // i.e. It's safe to attempt bind() or connect() now because the channel has been registered. // 2) If we attempted registration from the other thread, the registration request has been successfully // added to the event loop's task queue for later execution. // i.e. It's safe to attempt bind() or connect() now: // because bind() or connect() will be executed *after* the scheduled registration task is executed // because register(), bind(), and connect() are all bound to the same thread. return regFuture; }
@Test public void testNotThrowBlockingOperationException() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.childHandler(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) { allChannels.add(ctx.channel()); } }); b.channel(NioServerSocketChannel.class); ChannelFuture f = b.bind(0).syncUninterruptibly(); if (f.isSuccess()) { allChannels.add(f.channel()); allChannels.close().awaitUninterruptibly(); } bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); bossGroup.terminationFuture().sync(); workerGroup.terminationFuture().sync(); }
/** * 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 Executor closeExecutor() { if (config().getSoLinger() > 0) { return GlobalEventExecutor.INSTANCE; } return null; }
@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()); }
private static void completeFuture(CompletableFuture<Void> future) { if (GlobalEventExecutor.INSTANCE.inEventLoop()) { future.complete(null); } else { GlobalEventExecutor.INSTANCE.execute(() -> future.complete(null)); } }
private static void completeFutureExceptionally(CompletableFuture<Void> future, Throwable cause) { if (GlobalEventExecutor.INSTANCE.inEventLoop()) { future.completeExceptionally(cause); } else { GlobalEventExecutor.INSTANCE.execute(() -> future.completeExceptionally(cause)); } }
private void runStreamingResponseTest(boolean slowClient) throws InterruptedException, ExecutionException { // Disable timeouts and length limits so that test does not fail due to slow transfer. clientWriteTimeoutMillis = 0; clientResponseTimeoutMillis = 0; clientMaxResponseLength = 0; serverRequestTimeoutMillis = 0; final HttpResponse res = client().get("/zeroes/" + STREAMING_CONTENT_LENGTH); final AtomicReference<HttpStatus> status = new AtomicReference<>(); final StreamConsumer consumer = new StreamConsumer(GlobalEventExecutor.INSTANCE, slowClient) { @Override public void onNext(HttpObject obj) { if (obj instanceof HttpHeaders) { status.compareAndSet(null, ((HttpHeaders) obj).status()); } super.onNext(obj); } @Override public void onError(Throwable cause) { // Will be notified via the 'awaitClose().get()' below. } @Override public void onComplete() {} }; res.subscribe(consumer); res.completionFuture().get(); assertThat(status.get(), is(HttpStatus.OK)); assertThat(consumer.numReceivedBytes(), is(STREAMING_CONTENT_LENGTH)); }
public ChannelGroup getGroup() { ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); if(!CollectionUtils.isEmpty(items)) { items.forEach((itemId, channel) -> channelGroup.add(channel)); } return channelGroup; }