Search in sources :

Example 6 with ConnectionObserver

use of reactor.netty.ConnectionObserver in project reactor-netty by reactor.

the class NewConnectionProvider method acquire.

@Override
public Mono<? extends Connection> acquire(TransportConfig config, ConnectionObserver observer, @Nullable Supplier<? extends SocketAddress> remoteAddress, @Nullable AddressResolverGroup<?> resolverGroup) {
    return Mono.create(sink -> {
        SocketAddress remote = null;
        if (remoteAddress != null) {
            remote = Objects.requireNonNull(remoteAddress.get(), "Remote Address supplier returned null");
        }
        ConnectionObserver connectionObserver = new NewConnectionObserver(sink, observer);
        DisposableConnect disposableConnect = new DisposableConnect(sink, config.bindAddress());
        if (remote != null && resolverGroup != null) {
            ChannelInitializer<Channel> channelInitializer = config.channelInitializer(connectionObserver, remote, false);
            TransportConnector.connect(config, remote, resolverGroup, channelInitializer).subscribe(disposableConnect);
        } else {
            Objects.requireNonNull(config.bindAddress(), "bindAddress");
            SocketAddress local = Objects.requireNonNull(config.bindAddress().get(), "Bind Address supplier returned null");
            if (local instanceof InetSocketAddress) {
                InetSocketAddress localInet = (InetSocketAddress) local;
                if (localInet.isUnresolved()) {
                    local = AddressUtils.createResolved(localInet.getHostName(), localInet.getPort());
                }
            }
            ChannelInitializer<Channel> channelInitializer = config.channelInitializer(connectionObserver, null, true);
            TransportConnector.bind(config, channelInitializer, local, local instanceof DomainSocketAddress).subscribe(disposableConnect);
        }
    });
}
Also used : ConnectionObserver(reactor.netty.ConnectionObserver) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) SocketAddress(java.net.SocketAddress) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 7 with ConnectionObserver

use of reactor.netty.ConnectionObserver in project reactor-netty by reactor.

the class PooledConnectionProvider method acquire.

@Override
public final Mono<? extends Connection> acquire(TransportConfig config, ConnectionObserver connectionObserver, @Nullable Supplier<? extends SocketAddress> remote, @Nullable AddressResolverGroup<?> resolverGroup) {
    Objects.requireNonNull(config, "config");
    Objects.requireNonNull(connectionObserver, "connectionObserver");
    Objects.requireNonNull(remote, "remoteAddress");
    Objects.requireNonNull(resolverGroup, "resolverGroup");
    return Mono.create(sink -> {
        SocketAddress remoteAddress = Objects.requireNonNull(remote.get(), "Remote Address supplier returned null");
        PoolKey holder = new PoolKey(remoteAddress, config.channelHash());
        PoolFactory<T> poolFactory = poolFactory(remoteAddress);
        InstrumentedPool<T> pool = MapUtils.computeIfAbsent(channelPools, holder, poolKey -> {
            if (log.isDebugEnabled()) {
                log.debug("Creating a new [{}] client pool [{}] for [{}]", name, poolFactory, remoteAddress);
            }
            InstrumentedPool<T> newPool = createPool(config, poolFactory, remoteAddress, resolverGroup);
            if (poolFactory.metricsEnabled || config.metricsRecorder() != null) {
                // registrar is null when metrics are enabled on HttpClient level or
                // with the `metrics(boolean metricsEnabled)` method on ConnectionProvider
                String id = poolKey.hashCode() + "";
                if (poolFactory.registrar != null) {
                    poolFactory.registrar.get().registerMetrics(name, id, remoteAddress, new DelegatingConnectionPoolMetrics(newPool.metrics()));
                } else if (Metrics.isInstrumentationAvailable()) {
                    // work directly with the pool otherwise a weak reference is needed to ConnectionPoolMetrics
                    // we don't want to keep another map with weak references
                    registerDefaultMetrics(id, remoteAddress, newPool.metrics());
                }
            }
            return newPool;
        });
        EventLoop eventLoop = config.loopResources().onClient(config.isPreferNative()).next();
        pool.acquire(Duration.ofMillis(poolFactory.pendingAcquireTimeout)).contextWrite(ctx -> ctx.put(CONTEXT_CALLER_EVENTLOOP, eventLoop)).subscribe(createDisposableAcquire(config, connectionObserver, poolFactory.pendingAcquireTimeout, pool, sink));
    });
}
Also used : ReactorNetty(reactor.netty.ReactorNetty) SamplingAllocationStrategy(reactor.pool.introspection.SamplingAllocationStrategy) Disposable(reactor.core.Disposable) SocketAddress(java.net.SocketAddress) ReactorNetty.format(reactor.netty.ReactorNetty.format) InstrumentedPool(reactor.pool.InstrumentedPool) MonoSink(reactor.core.publisher.MonoSink) HashMap(java.util.HashMap) Nullable(reactor.util.annotation.Nullable) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ConcurrentMap(java.util.concurrent.ConcurrentMap) InetAddress(java.net.InetAddress) ConnectionObserver(reactor.netty.ConnectionObserver) BiPredicate(java.util.function.BiPredicate) CoreSubscriber(reactor.core.CoreSubscriber) TransportConfig(reactor.netty.transport.TransportConfig) AllocationStrategy(reactor.pool.AllocationStrategy) Loggers(reactor.util.Loggers) Metrics(reactor.netty.internal.util.Metrics) Logger(reactor.util.Logger) Duration(java.time.Duration) Map(java.util.Map) Schedulers(reactor.core.scheduler.Schedulers) MapUtils(reactor.netty.internal.util.MapUtils) PoolConfig(reactor.pool.PoolConfig) PENDING_ACQUIRE_MAX_COUNT_NOT_SPECIFIED(reactor.netty.resources.ConnectionProvider.ConnectionPoolSpec.PENDING_ACQUIRE_MAX_COUNT_NOT_SPECIFIED) Connection(reactor.netty.Connection) PooledRef(reactor.pool.PooledRef) Publisher(org.reactivestreams.Publisher) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PoolBuilder(reactor.pool.PoolBuilder) Mono(reactor.core.publisher.Mono) Pool(reactor.pool.Pool) GracefulShutdownInstrumentedPool(reactor.pool.decorators.GracefulShutdownInstrumentedPool) EventLoop(io.netty.channel.EventLoop) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) List(java.util.List) Clock(java.time.Clock) PooledRefMetadata(reactor.pool.PooledRefMetadata) InstrumentedPoolDecorators(reactor.pool.decorators.InstrumentedPoolDecorators) EventLoop(io.netty.channel.EventLoop) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 8 with ConnectionObserver

use of reactor.netty.ConnectionObserver in project reactor-netty by reactor.

the class ContextAwareChannelMetricsHandler method recordException.

@Override
protected void recordException(ChannelHandlerContext ctx, SocketAddress address) {
    Connection connection = Connection.from(ctx.channel());
    ChannelOperations<?, ?> ops = connection.as(ChannelOperations.class);
    if (ops != null) {
        recorder().incrementErrorsCount(ops.currentContext(), address);
    } else if (connection instanceof ConnectionObserver) {
        recorder().incrementErrorsCount(((ConnectionObserver) connection).currentContext(), address);
    } else {
        super.recordException(ctx, address);
    }
}
Also used : ConnectionObserver(reactor.netty.ConnectionObserver) Connection(reactor.netty.Connection)

Example 9 with ConnectionObserver

use of reactor.netty.ConnectionObserver in project reactor-netty by reactor.

the class ClientTransport method connect.

/**
 * Connect the {@link ClientTransport} and return a {@link Mono} of {@link Connection}. If
 * {@link Mono} is cancelled, the underlying connection will be aborted. Once the
 * {@link Connection} has been emitted and is not necessary anymore, disposing must be
 * done by the user via {@link Connection#dispose()}.
 *
 * @return a {@link Mono} of {@link Connection}
 */
protected Mono<? extends Connection> connect() {
    CONF config = configuration();
    ConnectionObserver observer = config.defaultConnectionObserver().then(config.observer);
    AddressResolverGroup<?> resolver = config.resolverInternal();
    Mono<? extends Connection> mono = config.connectionProvider().acquire(config, observer, config.remoteAddress, resolver);
    if (config.doOnConnect != null) {
        mono = mono.doOnSubscribe(s -> config.doOnConnect.accept(config));
    }
    return mono;
}
Also used : ConnectionObserver(reactor.netty.ConnectionObserver) LoopResources(reactor.netty.resources.LoopResources) Properties(java.util.Properties) SocketAddress(java.net.SocketAddress) Mono(reactor.core.publisher.Mono) Supplier(java.util.function.Supplier) Objects(java.util.Objects) Consumer(java.util.function.Consumer) NoopAddressResolverGroup(io.netty.resolver.NoopAddressResolverGroup) ConnectionObserver(reactor.netty.ConnectionObserver) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) Duration(java.time.Duration) BiConsumer(java.util.function.BiConsumer) Connection(reactor.netty.Connection)

Example 10 with ConnectionObserver

use of reactor.netty.ConnectionObserver in project reactor-netty by reactor.

the class ServerTransport method bind.

/**
 * Binds the {@link ServerTransport} and returns a {@link Mono} of {@link DisposableServer}. If
 * {@link Mono} is cancelled, the underlying binding will be aborted. Once the {@link
 * DisposableServer} has been emitted and is not necessary anymore, disposing the main server
 * loop must be done by the user via {@link DisposableServer#dispose()}.
 *
 * @return a {@link Mono} of {@link DisposableServer}
 */
public Mono<? extends DisposableServer> bind() {
    CONF config = configuration();
    Objects.requireNonNull(config.bindAddress(), "bindAddress");
    Mono<? extends DisposableServer> mono = Mono.create(sink -> {
        SocketAddress local = Objects.requireNonNull(config.bindAddress().get(), "Bind Address supplier returned null");
        if (local instanceof InetSocketAddress) {
            InetSocketAddress localInet = (InetSocketAddress) local;
            if (localInet.isUnresolved()) {
                local = AddressUtils.createResolved(localInet.getHostName(), localInet.getPort());
            }
        }
        boolean isDomainSocket = false;
        DisposableBind disposableServer;
        if (local instanceof DomainSocketAddress) {
            isDomainSocket = true;
            disposableServer = new UdsDisposableBind(sink, config, local);
        } else {
            disposableServer = new InetDisposableBind(sink, config, local);
        }
        ConnectionObserver childObs = new ChildObserver(config.defaultChildObserver().then(config.childObserver()));
        Acceptor acceptor = new Acceptor(config.childEventLoopGroup(), config.channelInitializer(childObs, null, true), config.childOptions, config.childAttrs, isDomainSocket);
        TransportConnector.bind(config, new AcceptorInitializer(acceptor), local, isDomainSocket).subscribe(disposableServer);
    });
    if (config.doOnBind() != null) {
        mono = mono.doOnSubscribe(s -> config.doOnBind().accept(config));
    }
    return mono;
}
Also used : AttributeKey(io.netty.util.AttributeKey) SocketAddress(java.net.SocketAddress) ChannelOption(io.netty.channel.ChannelOption) AbortedException(reactor.netty.channel.AbortedException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) ReactorNetty.format(reactor.netty.ReactorNetty.format) MonoSink(reactor.core.publisher.MonoSink) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ConnectionObserver(reactor.netty.ConnectionObserver) CoreSubscriber(reactor.core.CoreSubscriber) Loggers(reactor.util.Loggers) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) Duration(java.time.Duration) Map(java.util.Map) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Logger(reactor.util.Logger) Connection(reactor.netty.Connection) LoopResources(reactor.netty.resources.LoopResources) DecoderException(io.netty.handler.codec.DecoderException) EventLoopGroup(io.netty.channel.EventLoopGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) Operators(reactor.core.publisher.Operators) ChannelOperations(reactor.netty.channel.ChannelOperations) Context(reactor.util.context.Context) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) InetSocketAddress(java.net.InetSocketAddress) ChannelBindException(reactor.netty.ChannelBindException) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Channel(io.netty.channel.Channel) List(java.util.List) ChannelConfig(io.netty.channel.ChannelConfig) Subscription(org.reactivestreams.Subscription) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelHandler(io.netty.channel.ChannelHandler) ConnectionProvider(reactor.netty.resources.ConnectionProvider) DisposableServer(reactor.netty.DisposableServer) InetSocketAddress(java.net.InetSocketAddress) ConnectionObserver(reactor.netty.ConnectionObserver) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) SocketAddress(java.net.SocketAddress) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

ConnectionObserver (reactor.netty.ConnectionObserver)16 Connection (reactor.netty.Connection)9 InetSocketAddress (java.net.InetSocketAddress)7 SocketAddress (java.net.SocketAddress)7 Duration (java.time.Duration)6 Mono (reactor.core.publisher.Mono)5 EventLoopGroup (io.netty.channel.EventLoopGroup)4 AddressResolverGroup (io.netty.resolver.AddressResolverGroup)4 Supplier (java.util.function.Supplier)4 ConnectionProvider (reactor.netty.resources.ConnectionProvider)4 LoopResources (reactor.netty.resources.LoopResources)4 Channel (io.netty.channel.Channel)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 List (java.util.List)3 Objects (java.util.Objects)3 TimeUnit (java.util.concurrent.TimeUnit)3 Test (org.junit.jupiter.api.Test)3 CoreSubscriber (reactor.core.CoreSubscriber)3 PooledConnection (reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection)3 TransportConfig (reactor.netty.transport.TransportConfig)3