Search in sources :

Example 96 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project vert.x by eclipse.

the class TCPServerBase method listen.

private synchronized io.netty.util.concurrent.Future<Channel> listen(SocketAddress localAddress, ContextInternal context) {
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    this.listenContext = context;
    this.listening = true;
    this.eventLoop = context.nettyEventLoop();
    SocketAddress bindAddress;
    Map<ServerID, TCPServerBase> sharedNetServers = vertx.sharedTCPServers((Class<TCPServerBase>) getClass());
    synchronized (sharedNetServers) {
        actualPort = localAddress.port();
        String hostOrPath = localAddress.isInetSocket() ? localAddress.host() : localAddress.path();
        TCPServerBase main;
        boolean shared;
        ServerID id;
        if (actualPort > 0 || localAddress.isDomainSocket()) {
            id = new ServerID(actualPort, hostOrPath);
            main = sharedNetServers.get(id);
            shared = true;
            bindAddress = localAddress;
        } else {
            if (actualPort < 0) {
                id = new ServerID(actualPort, hostOrPath + "/" + -actualPort);
                main = sharedNetServers.get(id);
                shared = true;
                bindAddress = SocketAddress.inetSocketAddress(0, localAddress.host());
            } else {
                id = new ServerID(actualPort, hostOrPath);
                main = null;
                shared = false;
                bindAddress = localAddress;
            }
        }
        if (main == null) {
            try {
                sslHelper = createSSLHelper();
                sslHelper.validate(vertx);
                worker = childHandler(listenContext, localAddress, sslHelper);
                servers = new HashSet<>();
                servers.add(this);
                channelBalancer = new ServerChannelLoadBalancer(vertx.getAcceptorEventLoopGroup().next());
                channelBalancer.addWorker(eventLoop, worker);
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(vertx.getAcceptorEventLoopGroup(), channelBalancer.workers());
                if (sslHelper.isSSL()) {
                    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
                } else {
                    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
                }
                bootstrap.childHandler(channelBalancer);
                applyConnectionOptions(localAddress.isDomainSocket(), bootstrap);
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, bindAddress, bootstrap);
                bindFuture.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) res -> {
                    if (res.isSuccess()) {
                        Channel ch = res.getNow();
                        log.trace("Net server listening on " + hostOrPath + ":" + ch.localAddress());
                        if (shared) {
                            ch.closeFuture().addListener((ChannelFutureListener) channelFuture -> {
                                synchronized (sharedNetServers) {
                                    sharedNetServers.remove(id);
                                }
                            });
                        }
                        if (bindAddress.isInetSocket()) {
                            actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
                        }
                        listenContext.addCloseHook(this);
                        metrics = createMetrics(localAddress);
                    } else {
                        if (shared) {
                            synchronized (sharedNetServers) {
                                sharedNetServers.remove(id);
                            }
                        }
                        listening = false;
                    }
                });
            } catch (Throwable t) {
                listening = false;
                return vertx.getAcceptorEventLoopGroup().next().newFailedFuture(t);
            }
            if (shared) {
                sharedNetServers.put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = main;
            metrics = main.metrics;
            sslHelper = main.sslHelper;
            worker = childHandler(listenContext, localAddress, sslHelper);
            actualServer.servers.add(this);
            actualServer.channelBalancer.addWorker(eventLoop, worker);
            listenContext.addCloseHook(this);
        }
    }
    return actualServer.bindFuture;
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) Context(io.vertx.core.Context) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Set(java.util.Set) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) NetServerOptions(io.vertx.core.net.NetServerOptions) List(java.util.List) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Handler(io.vertx.core.Handler) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) CompositeFuture(io.vertx.core.CompositeFuture) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) SocketAddress(io.vertx.core.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 97 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project crate by crate.

the class Messages method sendCommandComplete.

/**
 * | 'C' | int32 len | str commandTag
 * @param query    :the query
 * @param rowCount : number of rows in the result set or number of rows affected by the DML statement
 */
static ChannelFuture sendCommandComplete(Channel channel, String query, long rowCount) {
    query = query.trim().split(" ", 2)[0].toUpperCase(Locale.ENGLISH);
    String commandTag;
    /*
         * from https://www.postgresql.org/docs/current/static/protocol-message-formats.html:
         *
         * For an INSERT command, the tag is INSERT oid rows, where rows is the number of rows inserted.
         * oid is the object ID of the inserted row if rows is 1 and the target table has OIDs; otherwise oid is 0.
         */
    if ("BEGIN".equals(query)) {
        commandTag = "BEGIN";
    } else if ("INSERT".equals(query)) {
        commandTag = "INSERT 0 " + rowCount;
    } else {
        commandTag = query + " " + rowCount;
    }
    byte[] commandTagBytes = commandTag.getBytes(StandardCharsets.UTF_8);
    int length = 4 + commandTagBytes.length + 1;
    ByteBuf buffer = channel.alloc().buffer(length + 1);
    buffer.writeByte('C');
    buffer.writeInt(length);
    writeCString(buffer, commandTagBytes);
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentCommandComplete"));
    }
    return channelFuture;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SortedSet(java.util.SortedSet) RelationInfo(io.crate.metadata.RelationInfo) AccessControl(io.crate.auth.AccessControl) PGType(io.crate.protocols.postgres.types.PGType) PGTypes(io.crate.protocols.postgres.types.PGTypes) Collection(java.util.Collection) Reference(io.crate.metadata.Reference) DataType(io.crate.types.DataType) StandardCharsets(java.nio.charset.StandardCharsets) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) OidHash(io.crate.metadata.pgcatalog.OidHash) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Row(io.crate.data.Row) ByteBuf(io.netty.buffer.ByteBuf) Symbol(io.crate.expression.symbol.Symbol) Symbols(io.crate.expression.symbol.Symbols) Locale(java.util.Locale) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) Nullable(javax.annotation.Nullable) ByteBuf(io.netty.buffer.ByteBuf)

Example 98 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project crate by crate.

the class Messages method sendReadyForQuery.

/**
 * ReadyForQuery (B)
 * <p>
 * Byte1('Z')
 * Identifies the message type. ReadyForQuery is sent whenever the
 * backend is ready for a new query cycle.
 * <p>
 * Int32(5)
 * Length of message contents in bytes, including self.
 * <p>
 * Byte1
 * Current backend transaction status indicator. Possible values are
 * 'I' if idle (not in a transaction block); 'T' if in a transaction
 * block; or 'E' if in a failed transaction block (queries will be
 * rejected until block is ended).
 */
static ChannelFuture sendReadyForQuery(Channel channel, TransactionState transactionState) {
    ByteBuf buffer = channel.alloc().buffer(6);
    buffer.writeByte('Z');
    buffer.writeInt(5);
    buffer.writeByte(transactionState.code());
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentReadyForQuery"));
    }
    return channelFuture;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SortedSet(java.util.SortedSet) RelationInfo(io.crate.metadata.RelationInfo) AccessControl(io.crate.auth.AccessControl) PGType(io.crate.protocols.postgres.types.PGType) PGTypes(io.crate.protocols.postgres.types.PGTypes) Collection(java.util.Collection) Reference(io.crate.metadata.Reference) DataType(io.crate.types.DataType) StandardCharsets(java.nio.charset.StandardCharsets) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) OidHash(io.crate.metadata.pgcatalog.OidHash) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Row(io.crate.data.Row) ByteBuf(io.netty.buffer.ByteBuf) Symbol(io.crate.expression.symbol.Symbol) Symbols(io.crate.expression.symbol.Symbols) Locale(java.util.Locale) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) Nullable(javax.annotation.Nullable) ByteBuf(io.netty.buffer.ByteBuf)

Example 99 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project crate by crate.

the class Messages method sendRowDescription.

/**
 * RowDescription (B)
 * <p>
 * | 'T' | int32 len | int16 numCols
 * <p>
 * For each field:
 * <p>
 * | string name | int32 table_oid | int16 attr_num | int32 oid | int16 typlen | int32 type_modifier | int16 format_code
 * <p>
 * See https://www.postgresql.org/docs/current/static/protocol-message-formats.html
 */
static void sendRowDescription(Channel channel, Collection<Symbol> columns, @Nullable FormatCodes.FormatCode[] formatCodes, @Nullable RelationInfo relation) {
    int length = 4 + 2;
    int columnSize = 4 + 2 + 4 + 2 + 4 + 2;
    ByteBuf buffer = channel.alloc().buffer(// use 10 as an estimate for columnName length
    length + (columns.size() * (10 + columnSize)));
    buffer.writeByte('T');
    // will be set at the end
    buffer.writeInt(0);
    buffer.writeShort(columns.size());
    int tableOid = 0;
    if (relation != null && columns.stream().allMatch(Messages::isRefWithPosition)) {
        tableOid = OidHash.relationOid(relation);
    }
    int idx = 0;
    for (Symbol column : columns) {
        byte[] nameBytes = Symbols.pathFromSymbol(column).sqlFqn().getBytes(StandardCharsets.UTF_8);
        length += nameBytes.length + 1;
        length += columnSize;
        writeCString(buffer, nameBytes);
        buffer.writeInt(tableOid);
        // attr_num
        if (column instanceof Reference) {
            Integer position = ((Reference) column).position();
            buffer.writeShort(position == null ? 0 : position);
        } else {
            buffer.writeShort(0);
        }
        PGType<?> pgType = PGTypes.get(column.valueType());
        buffer.writeInt(pgType.oid());
        buffer.writeShort(pgType.typeLen());
        buffer.writeInt(pgType.typeMod());
        buffer.writeShort(FormatCodes.getFormatCode(formatCodes, idx).ordinal());
        idx++;
    }
    buffer.setInt(1, length);
    ChannelFuture channelFuture = channel.write(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentRowDescription"));
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SortedSet(java.util.SortedSet) RelationInfo(io.crate.metadata.RelationInfo) AccessControl(io.crate.auth.AccessControl) PGType(io.crate.protocols.postgres.types.PGType) PGTypes(io.crate.protocols.postgres.types.PGTypes) Collection(java.util.Collection) Reference(io.crate.metadata.Reference) DataType(io.crate.types.DataType) StandardCharsets(java.nio.charset.StandardCharsets) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) OidHash(io.crate.metadata.pgcatalog.OidHash) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Row(io.crate.data.Row) ByteBuf(io.netty.buffer.ByteBuf) Symbol(io.crate.expression.symbol.Symbol) Symbols(io.crate.expression.symbol.Symbols) Locale(java.util.Locale) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) Nullable(javax.annotation.Nullable) Symbol(io.crate.expression.symbol.Symbol) Reference(io.crate.metadata.Reference) ByteBuf(io.netty.buffer.ByteBuf)

Example 100 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project crate by crate.

the class Messages method sendAuthenticationCleartextPassword.

/**
 * AuthenticationCleartextPassword (B)
 *
 * Byte1('R')
 * Identifies the message as an authentication request.
 *
 * Int32(8)
 * Length of message contents in bytes, including self.
 *
 * Int32(3)
 * Specifies that a clear-text password is required.
 *
 * @param channel The channel to write to.
 */
static void sendAuthenticationCleartextPassword(Channel channel) {
    ByteBuf buffer = channel.alloc().buffer(9);
    buffer.writeByte('R');
    buffer.writeInt(8);
    buffer.writeInt(3);
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentAuthenticationCleartextPassword"));
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SortedSet(java.util.SortedSet) RelationInfo(io.crate.metadata.RelationInfo) AccessControl(io.crate.auth.AccessControl) PGType(io.crate.protocols.postgres.types.PGType) PGTypes(io.crate.protocols.postgres.types.PGTypes) Collection(java.util.Collection) Reference(io.crate.metadata.Reference) DataType(io.crate.types.DataType) StandardCharsets(java.nio.charset.StandardCharsets) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) OidHash(io.crate.metadata.pgcatalog.OidHash) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Row(io.crate.data.Row) ByteBuf(io.netty.buffer.ByteBuf) Symbol(io.crate.expression.symbol.Symbol) Symbols(io.crate.expression.symbol.Symbols) Locale(java.util.Locale) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) Nullable(javax.annotation.Nullable) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

ChannelFutureListener (io.netty.channel.ChannelFutureListener)223 ChannelFuture (io.netty.channel.ChannelFuture)208 Channel (io.netty.channel.Channel)70 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)57 ByteBuf (io.netty.buffer.ByteBuf)49 Bootstrap (io.netty.bootstrap.Bootstrap)43 Test (org.junit.jupiter.api.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)36 IOException (java.io.IOException)35 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)33 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)31 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)31 InetSocketAddress (java.net.InetSocketAddress)27 ClosedChannelException (java.nio.channels.ClosedChannelException)25 ChannelPromise (io.netty.channel.ChannelPromise)21 Logger (org.slf4j.Logger)21 LoggerFactory (org.slf4j.LoggerFactory)21 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)20 EventLoopGroup (io.netty.channel.EventLoopGroup)18 List (java.util.List)17