Search in sources :

Example 96 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project arthas by alibaba.

the class TunnelSocketFrameHandler method agentRegister.

private void agentRegister(ChannelHandlerContext ctx, HandshakeComplete handshake, String requestUri) throws URISyntaxException {
    QueryStringDecoder queryDecoder = new QueryStringDecoder(requestUri);
    Map<String, List<String>> parameters = queryDecoder.parameters();
    String appName = null;
    List<String> appNameList = parameters.get(URIConstans.APP_NAME);
    if (appNameList != null && !appNameList.isEmpty()) {
        appName = appNameList.get(0);
    }
    // generate a random agent id
    String id = null;
    if (appName != null) {
        // 如果有传 app name,则生成带 app name前缀的id,方便管理
        id = appName + "_" + RandomStringUtils.random(20, true, true).toUpperCase();
    } else {
        id = RandomStringUtils.random(20, true, true).toUpperCase();
    }
    // agent传过来,则优先用 agent的
    List<String> idList = parameters.get(URIConstans.ID);
    if (idList != null && !idList.isEmpty()) {
        id = idList.get(0);
    }
    String arthasVersion = null;
    List<String> arthasVersionList = parameters.get(URIConstans.ARTHAS_VERSION);
    if (arthasVersionList != null && !arthasVersionList.isEmpty()) {
        arthasVersion = arthasVersionList.get(0);
    }
    final String finalId = id;
    // URI responseUri = new URI("response", null, "/", "method=" + MethodConstants.AGENT_REGISTER + "&id=" + id, null);
    URI responseUri = UriComponentsBuilder.newInstance().scheme(URIConstans.RESPONSE).path("/").queryParam(URIConstans.METHOD, MethodConstants.AGENT_REGISTER).queryParam(URIConstans.ID, id).build().encode().toUri();
    AgentInfo info = new AgentInfo();
    // 前面可能有nginx代理
    HttpHeaders headers = handshake.requestHeaders();
    String host = HttpUtils.findClientIP(headers);
    if (host == null) {
        SocketAddress remoteAddress = ctx.channel().remoteAddress();
        if (remoteAddress instanceof InetSocketAddress) {
            InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
            info.setHost(inetSocketAddress.getHostString());
            info.setPort(inetSocketAddress.getPort());
        }
    } else {
        info.setHost(host);
        Integer port = HttpUtils.findClientPort(headers);
        if (port != null) {
            info.setPort(port);
        }
    }
    info.setChannelHandlerContext(ctx);
    if (arthasVersion != null) {
        info.setArthasVersion(arthasVersion);
    }
    tunnelServer.addAgent(id, info);
    ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            tunnelServer.removeAgent(finalId);
        }
    });
    ctx.channel().writeAndFlush(new TextWebSocketFrame(responseUri.toString()));
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) Future(io.netty.util.concurrent.Future) List(java.util.List) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 97 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project PaperDev by Kamillaova.

the class ServerConnection method c.

public void c() {
    List list = this.h;
    synchronized (this.h) {
        // Spigot Start
        // Paper
        addPending();
        // This prevents players from 'gaming' the server, and strategically relogging to increase their position in the tick order
        if (org.spigotmc.SpigotConfig.playerShuffle > 0 && MinecraftServer.currentTick % org.spigotmc.SpigotConfig.playerShuffle == 0) {
            Collections.shuffle(this.h);
        }
        // Spigot End
        Iterator iterator = this.h.iterator();
        while (iterator.hasNext()) {
            final NetworkManager networkmanager = (NetworkManager) iterator.next();
            if (!networkmanager.h()) {
                if (networkmanager.isConnected()) {
                    try {
                        networkmanager.a();
                    } catch (Exception exception) {
                        if (networkmanager.isLocal()) {
                            CrashReport crashreport = CrashReport.a(exception, "Ticking memory connection");
                            CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Ticking connection");
                            crashreportsystemdetails.a("Connection", new CrashReportCallable() {

                                public String a() throws Exception {
                                    return networkmanager.toString();
                                }

                                public Object call() throws Exception {
                                    return this.a();
                                }
                            });
                            throw new ReportedException(crashreport);
                        }
                        ServerConnection.e.warn("Failed to handle packet for {}", networkmanager.getSocketAddress(), exception);
                        final ChatComponentText chatcomponenttext = new ChatComponentText("Internal server error");
                        networkmanager.sendPacket(new PacketPlayOutKickDisconnect(chatcomponenttext), new GenericFutureListener() {

                            public void operationComplete(Future future) throws Exception {
                                networkmanager.close(chatcomponenttext);
                            }
                        }, new GenericFutureListener[0]);
                        networkmanager.stopReading();
                    }
                } else {
                    // Fix a race condition where a NetworkManager could be unregistered just before connection.
                    if (networkmanager.preparing)
                        continue;
                    // Spigot End
                    iterator.remove();
                    networkmanager.handleDisconnection();
                }
            }
        }
    }
}
Also used : Iterator(java.util.Iterator) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) IOException(java.io.IOException) ChannelException(io.netty.channel.ChannelException)

Example 98 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project zookeeper by apache.

the class NettyServerCnxn method close.

public void close() {
    closingChannel = true;
    LOG.debug("close called for session id: 0x{}", Long.toHexString(sessionId));
    setStale();
    // ZOOKEEPER-2743:
    // Always unregister connection upon close to prevent
    // connection bean leak under certain race conditions.
    factory.unregisterConnection(this);
    // if this is not in cnxns then it's already closed
    if (!factory.cnxns.remove(this)) {
        LOG.debug("cnxns size:{}", factory.cnxns.size());
        if (channel.isOpen()) {
            channel.close();
        }
        return;
    }
    LOG.debug("close in progress for session id: 0x{}", Long.toHexString(sessionId));
    factory.removeCnxnFromSessionMap(this);
    factory.removeCnxnFromIpMap(this, ((InetSocketAddress) channel.remoteAddress()).getAddress());
    if (zkServer != null) {
        zkServer.removeCnxn(this);
    }
    if (channel.isOpen()) {
        // Since we don't check on the futures created by write calls to the channel complete we need to make sure
        // that all writes have been completed before closing the channel or we risk data loss
        // See: http://lists.jboss.org/pipermail/netty-users/2009-August/001122.html
        channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) {
                future.channel().close().addListener(f -> releaseQueuedBuffer());
            }
        });
    } else {
        ServerMetrics.getMetrics().CONNECTION_DROP_COUNT.add(1);
        channel.eventLoop().execute(this::releaseQueuedBuffer);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) SetTraceMaskCommand(org.apache.zookeeper.server.command.SetTraceMaskCommand) ClientCnxn(org.apache.zookeeper.ClientCnxn) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Stat(org.apache.zookeeper.data.Stat) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) InetAddress(java.net.InetAddress) FourLetterCommands(org.apache.zookeeper.server.command.FourLetterCommands) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) PrintWriter(java.io.PrintWriter) NopCommand(org.apache.zookeeper.server.command.NopCommand) Logger(org.slf4j.Logger) UTF_8(java.nio.charset.StandardCharsets.UTF_8) BufferedWriter(java.io.BufferedWriter) SelectionKey(java.nio.channels.SelectionKey) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) IOException(java.io.IOException) Record(org.apache.jute.Record) WatchedEvent(org.apache.zookeeper.WatchedEvent) InetSocketAddress(java.net.InetSocketAddress) WatcherEvent(org.apache.zookeeper.proto.WatcherEvent) BinaryInputArchive(org.apache.jute.BinaryInputArchive) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBufUtil(io.netty.buffer.ByteBufUtil) Certificate(java.security.cert.Certificate) Id(org.apache.zookeeper.data.Id) Writer(java.io.Writer) ReplyHeader(org.apache.zookeeper.proto.ReplyHeader) Future(io.netty.util.concurrent.Future) CommandExecutor(org.apache.zookeeper.server.command.CommandExecutor) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 99 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project vert.x by eclipse.

the class HttpServerWorker method handle.

@Override
public void handle(Channel ch) {
    if (HAProxyMessageCompletionHandler.canUseProxyProtocol(options.isUseProxyProtocol())) {
        IdleStateHandler idle;
        io.netty.util.concurrent.Promise<Channel> p = ch.eventLoop().newPromise();
        ch.pipeline().addLast(new HAProxyMessageDecoder());
        if (options.getProxyProtocolTimeout() > 0) {
            ch.pipeline().addLast("idle", idle = new IdleStateHandler(0, 0, options.getProxyProtocolTimeout(), options.getProxyProtocolTimeoutUnit()));
        } else {
            idle = null;
        }
        ch.pipeline().addLast(new HAProxyMessageCompletionHandler(p));
        p.addListener((GenericFutureListener<Future<Channel>>) future -> {
            if (future.isSuccess()) {
                if (idle != null) {
                    ch.pipeline().remove(idle);
                }
                configurePipeline(future.getNow());
            } else {
                handleException(future.cause());
            }
        });
    } else {
        configurePipeline(ch);
    }
}
Also used : HAProxyMessageCompletionHandler(io.vertx.core.net.impl.HAProxyMessageCompletionHandler) SniHandler(io.netty.handler.ssl.SniHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) FlashPolicyHandler(io.vertx.core.http.impl.cgbystrom.FlashPolicyHandler) ContextInternal(io.vertx.core.impl.ContextInternal) SslHandshakeCompletionHandler(io.vertx.core.net.impl.SslHandshakeCompletionHandler) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) IdleState(io.netty.handler.timeout.IdleState) io.netty.channel(io.netty.channel) VertxHandler(io.vertx.core.net.impl.VertxHandler) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) VertxInternal(io.vertx.core.impl.VertxInternal) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) SSLHelper(io.vertx.core.net.impl.SSLHelper) StandardCharsets(java.nio.charset.StandardCharsets) HAProxyMessageDecoder(io.netty.handler.codec.haproxy.HAProxyMessageDecoder) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) EventLoopContext(io.vertx.core.impl.EventLoopContext) SslHandler(io.netty.handler.ssl.SslHandler) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Future(io.netty.util.concurrent.Future) Handler(io.vertx.core.Handler) HAProxyMessageCompletionHandler(io.vertx.core.net.impl.HAProxyMessageCompletionHandler) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HAProxyMessageDecoder(io.netty.handler.codec.haproxy.HAProxyMessageDecoder) Future(io.netty.util.concurrent.Future)

Example 100 with Future

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future in project grpc-java by grpc.

the class NettyServerTest method testBindScheduleFailure.

@Test
@SuppressWarnings("unchecked")
public void testBindScheduleFailure() throws Exception {
    when(bindFuture.awaitUninterruptibly()).thenReturn(bindFuture);
    when(bindFuture.isSuccess()).thenReturn(false);
    when(bindFuture.getNow()).thenReturn(null);
    Throwable mockCause = mock(Throwable.class);
    when(bindFuture.cause()).thenReturn(mockCause);
    Future<Void> mockFuture = (Future<Void>) mock(Future.class);
    doReturn(mockFuture).when(mockEventLoopGroup).submit(any(Runnable.class));
    SocketAddress addr = new InetSocketAddress(0);
    verifyServerNotStart(Collections.singletonList(addr), mockEventLoopGroup, IOException.class, "Failed to bind to addresses " + Arrays.asList(addr));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SettableFuture(com.google.common.util.concurrent.SettableFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.Test)

Aggregations

Future (io.netty.util.concurrent.Future)177 Channel (io.netty.channel.Channel)61 ChannelFuture (io.netty.channel.ChannelFuture)58 InetSocketAddress (java.net.InetSocketAddress)45 ArrayList (java.util.ArrayList)45 IOException (java.io.IOException)44 GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)42 CompletableFuture (java.util.concurrent.CompletableFuture)40 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)35 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)34 List (java.util.List)34 ChannelFutureListener (io.netty.channel.ChannelFutureListener)31 EventLoopGroup (io.netty.channel.EventLoopGroup)30 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)30 FutureListener (io.netty.util.concurrent.FutureListener)28 Logger (org.slf4j.Logger)28 LoggerFactory (org.slf4j.LoggerFactory)28 TimeUnit (java.util.concurrent.TimeUnit)27 Bootstrap (io.netty.bootstrap.Bootstrap)25 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)25