io.netty.channel.pool.ChannelPool Java Examples

The following examples show how to use io.netty.channel.pool.ChannelPool. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NettyNioAsyncHttpClientWireMockTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void closeClient_shouldCloseUnderlyingResources() {
    SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.builder().build();
    ChannelPool channelPool = mock(ChannelPool.class);
    SdkChannelPoolMap<URI, ChannelPool> sdkChannelPoolMap = new SdkChannelPoolMap<URI, ChannelPool>() {
        @Override
        protected ChannelPool newPool(URI key) {
            return channelPool;
        }
    };

    sdkChannelPoolMap.get(URI.create("http://blah"));
    NettyConfiguration nettyConfiguration = new NettyConfiguration(AttributeMap.empty());

    SdkAsyncHttpClient customerClient =
        new NettyNioAsyncHttpClient(eventLoopGroup, sdkChannelPoolMap, nettyConfiguration);

    customerClient.close();
    assertThat(eventLoopGroup.eventLoopGroup().isShuttingDown()).isTrue();
    assertThat(eventLoopGroup.eventLoopGroup().isTerminated()).isTrue();
    assertThat(sdkChannelPoolMap).isEmpty();
    Mockito.verify(channelPool).close();
}
 
Example #2
Source File: HttpOrHttp2ChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void close0() {
    if (closed) {
        return;
    }

    closed = true;
    if (protocolImpl != null) {
        protocolImpl.close();
    } else if (protocolImplPromise != null) {
        protocolImplPromise.addListener((Future<ChannelPool> f) -> {
            if (f.isSuccess()) {
                f.getNow().close();
            } else {
                delegatePool.close();
            }
        });
    } else {
        delegatePool.close();
    }
}
 
Example #3
Source File: StreamingAsyncHttpClient.java    From riposte with Apache License 2.0 6 votes vote down vote up
StreamingChannel(
    Channel channel,
    ChannelPool pool,
    ObjectHolder<Boolean> callActiveHolder,
    ObjectHolder<Boolean> downstreamLastChunkSentHolder,
    Deque<Span> distributedTracingSpanStack,
    Map<String, String> distributedTracingMdcInfo,
    Span spanForDownstreamCall,
    ProxyRouterSpanNamingAndTaggingStrategy<Span> proxySpanTaggingStrategy
) {
    this.channel = channel;
    this.pool = pool;
    this.callActiveHolder = callActiveHolder;
    this.downstreamLastChunkSentHolder = downstreamLastChunkSentHolder;
    this.distributedTracingSpanStack = distributedTracingSpanStack;
    this.distributedTracingMdcInfo = distributedTracingMdcInfo;
    this.spanForDownstreamCall = spanForDownstreamCall;
    this.proxySpanTaggingStrategy = proxySpanTaggingStrategy;
}
 
Example #4
Source File: HttpOrHttp2ChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void acquire0(Promise<Channel> promise) {
    if (closed) {
        promise.setFailure(new IllegalStateException("Channel pool is closed!"));
        return;
    }

    if (protocolImpl != null) {
        protocolImpl.acquire(promise);
        return;
    }
    if (protocolImplPromise == null) {
        initializeProtocol();
    }
    protocolImplPromise.addListener((GenericFutureListener<Future<ChannelPool>>) future -> {
        if (future.isSuccess()) {
            future.getNow().acquire(promise);
        } else {
            // Couldn't negotiate protocol, fail this acquire.
            promise.setFailure(future.cause());
        }
    });
}
 
Example #5
Source File: StreamingAsyncHttpClient.java    From riposte with Apache License 2.0 6 votes vote down vote up
protected static void releaseChannelBackToPoolIfCallIsActive(Channel ch, ChannelPool pool,
                                                             ObjectHolder<Boolean> callActiveHolder,
                                                             String contextReason,
                                                             Deque<Span> distributedTracingStack,
                                                             Map<String, String> distributedTracingMdcInfo) {
    if (callActiveHolder.heldObject) {
        if (logger.isDebugEnabled()) {
            runnableWithTracingAndMdc(
                () -> logger.debug(
                    "Marking call as inactive and releasing channel back to pool. "
                    + "channel_release_reason=\"{}\"", contextReason
                ),
                distributedTracingStack, distributedTracingMdcInfo
            ).run();
        }

        callActiveHolder.heldObject = false;
        pool.release(ch);
    }
}
 
Example #6
Source File: ChannelPipelineInitializer.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public ChannelPipelineInitializer(Protocol protocol,
                                  SslContext sslCtx,
                                  SslProvider sslProvider,
                                  long clientMaxStreams,
                                  int clientInitialWindowSize,
                                  Duration healthCheckPingPeriod,
                                  AtomicReference<ChannelPool> channelPoolRef,
                                  NettyConfiguration configuration,
                                  URI poolKey) {
    this.protocol = protocol;
    this.sslCtx = sslCtx;
    this.sslProvider = sslProvider;
    this.clientMaxStreams = clientMaxStreams;
    this.clientInitialWindowSize = clientInitialWindowSize;
    this.healthCheckPingPeriod = healthCheckPingPeriod;
    this.channelPoolRef = channelPoolRef;
    this.configuration = configuration;
    this.poolKey = poolKey;
}
 
Example #7
Source File: Http2MultiplexedChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void acquire_shouldAcquireAgainIfExistingNotReusable() throws Exception {
    Channel channel = new EmbeddedChannel();

    try {
        ChannelPool connectionPool = Mockito.mock(ChannelPool.class);

        loopGroup.register(channel).awaitUninterruptibly();
        Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
        channelPromise.setSuccess(channel);

        Mockito.when(connectionPool.acquire()).thenReturn(channelPromise);

        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
                                                                             Collections.emptySet(), null);

        h2Pool.acquire().awaitUninterruptibly();
        h2Pool.acquire().awaitUninterruptibly();

        Mockito.verify(connectionPool, Mockito.times(2)).acquire();
    } finally {
        channel.close();
    }
}
 
Example #8
Source File: AwaitCloseChannelPoolMapTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void usesProvidedKeyManagersProvider() {
    TlsKeyManagersProvider provider = mock(TlsKeyManagersProvider.class);

    AttributeMap config = AttributeMap.builder()
            .put(TLS_KEY_MANAGERS_PROVIDER, provider)
            .build();

    channelPoolMap = AwaitCloseChannelPoolMap.builder()
            .sdkChannelOptions(new SdkChannelOptions())
            .sdkEventLoopGroup(SdkEventLoopGroup.builder().build())
            .configuration(new NettyConfiguration(config.merge(GLOBAL_HTTP_DEFAULTS)))
            .build();

    ChannelPool channelPool = channelPoolMap.newPool(URI.create("https://localhost:" + mockProxy.port()));
    channelPool.acquire().awaitUninterruptibly();
    verify(provider).keyManagers();
}
 
Example #9
Source File: NettyPooledTransport.java    From async-gamequery-lib with MIT License 6 votes vote down vote up
/**
 * <p>Acquires a {@link Channel} from the {@link ChannelPool}</p>
 *
 * @param message
 *         An {@link AbstractRequest} that will be used as the lookup reference for the {@link
 *         io.netty.channel.pool.ChannelPoolMap} key
 *
 * @return A {@link CompletableFuture} containing the acquired {@link Channel}
 */
@Override
public CompletableFuture<Channel> getChannel(M message) {
    final CompletableFuture<Channel> channelFuture = new CompletableFuture<>();
    //Retrieve our channel pool based on the message
    final ChannelPool pool = poolMap.get(message);

    log.debug("Acquiring channel from pool '{}' for message : {}", pool, message);

    //Acquire a channel from the pool and listen for completion
    pool.acquire().addListener((Future<Channel> future) -> {
        if (future.isSuccess()) {
            log.debug("Successfully acquired Channel from pool");
            Channel channel = future.get();
            channel.attr(ChannelAttributes.CHANNEL_POOL).set(pool);
            channelFuture.complete(channel);
        } else {
            log.debug("Failed to acquire Channel from Pool");
            channelFuture.completeExceptionally(new ConnectException(future.cause()));
        }
    });
    return channelFuture;
}
 
Example #10
Source File: Http2MultiplexedChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5_000)
public void interruptDuringClosePreservesFlag() throws InterruptedException {
    SocketChannel channel = new NioSocketChannel();
    try {
        loopGroup.register(channel).awaitUninterruptibly();
        Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
        channelPromise.setSuccess(channel);

        ChannelPool connectionPool = mock(ChannelPool.class);
        Promise<Void> releasePromise = Mockito.spy(new DefaultPromise<>(loopGroup.next()));

        when(connectionPool.release(eq(channel))).thenReturn(releasePromise);

        MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null);
        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
                                                                             Collections.singleton(record), null);

        CompletableFuture<Boolean> interrupteFlagPreserved = new CompletableFuture<>();

        Thread t = new Thread(() -> {
            try {
                h2Pool.close();
            } catch (Exception e) {
                if (e.getCause() instanceof InterruptedException && Thread.currentThread().isInterrupted()) {
                    interrupteFlagPreserved.complete(true);
                }
            }
        });

        t.start();
        t.interrupt();
        t.join();
        assertThat(interrupteFlagPreserved.join()).isTrue();
    } finally {
        channel.close().awaitUninterruptibly();
    }
}
 
Example #11
Source File: NettyRequestExecutorTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    mockChannelPool = mock(ChannelPool.class);

    eventLoopGroup = new NioEventLoopGroup();

    requestContext = new RequestContext(mockChannelPool,
                                        eventLoopGroup,
                                        AsyncExecuteRequest.builder().build(),
                                        new NettyConfiguration(AttributeMap.empty()));
    nettyRequestExecutor = new NettyRequestExecutor(requestContext);
}
 
Example #12
Source File: HonorCloseOnReleaseChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void releaseClosesIfFlagged() throws Exception {
    ChannelPool channelPool = Mockito.mock(ChannelPool.class);

    MockChannel channel = new MockChannel();
    channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(true);

    new HonorCloseOnReleaseChannelPool(channelPool).release(channel);
    channel.runAllPendingTasks();

    assertThat(channel.isOpen()).isFalse();
    Mockito.verify(channelPool, new Times(0)).release(any());
    Mockito.verify(channelPool, new Times(1)).release(any(), any());
}
 
Example #13
Source File: Http2MultiplexedChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void closeWaitsForConnectionToBeReleasedBeforeClosingConnectionPool() {
    SocketChannel channel = new NioSocketChannel();
    try {
        loopGroup.register(channel).awaitUninterruptibly();

        ChannelPool connectionPool = mock(ChannelPool.class);
        ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
        when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
            Promise<?> promise = releasePromise.getValue();
            promise.setSuccess(null);
            return promise;
        });

        MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null);
        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
                                                                             Collections.singleton(record), null);

        h2Pool.close();

        InOrder inOrder = Mockito.inOrder(connectionPool);
        inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
        inOrder.verify(connectionPool).close();
    } finally {
        channel.close().awaitUninterruptibly();
    }
}
 
Example #14
Source File: Http2MultiplexedChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void acquireAfterCloseFails() throws InterruptedException {
    ChannelPool connectionPool = mock(ChannelPool.class);
    Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null);

    h2Pool.close();

    Future<Channel> acquireResult = h2Pool.acquire().await();
    assertThat(acquireResult.isSuccess()).isFalse();
    assertThat(acquireResult.cause()).isInstanceOf(IOException.class);
}
 
Example #15
Source File: NettyNioAsyncHttpClient.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@SdkTestInternalApi
NettyNioAsyncHttpClient(SdkEventLoopGroup sdkEventLoopGroup,
                        SdkChannelPoolMap<URI, ? extends ChannelPool> pools,
                        NettyConfiguration configuration) {
    this.sdkEventLoopGroup = sdkEventLoopGroup;
    this.pools = pools;
    this.configuration = configuration;
}
 
Example #16
Source File: Http2MultiplexedChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void failedConnectionAcquireNotifiesPromise() throws InterruptedException {
    IOException exception = new IOException();
    ChannelPool connectionPool = mock(ChannelPool.class);
    when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception));

    ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null);

    Future<Channel> acquirePromise = pool.acquire().await();
    assertThat(acquirePromise.isSuccess()).isFalse();
    assertThat(acquirePromise.cause()).isEqualTo(exception);
}
 
Example #17
Source File: Http2MultiplexedChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void releaseParentChannelIfReleasingLastChildChannelOnGoAwayChannel() {
    SocketChannel channel = new NioSocketChannel();
    try {
        loopGroup.register(channel).awaitUninterruptibly();

        ChannelPool connectionPool = mock(ChannelPool.class);
        ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
        when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
            Promise<?> promise = releasePromise.getValue();
            promise.setSuccess(null);
            return promise;
        });

        MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null);
        Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup,
                                                                             Collections.singleton(record), null);

        h2Pool.close();

        InOrder inOrder = Mockito.inOrder(connectionPool);
        inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
        inOrder.verify(connectionPool).close();
    } finally {
        channel.close().awaitUninterruptibly();
    }
}
 
Example #18
Source File: StreamingAsyncHttpClientTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    channelMock = mock(Channel.class);
    channelPoolMock = mock(ChannelPool.class);
    eventLoopMock = mock(EventLoop.class);

    contentChunkMock = mock(HttpContent.class);

    callActiveHolder = new ObjectHolder<>();
    callActiveHolder.heldObject = true;

    downstreamLastChunkSentHolder = new ObjectHolder<>();
    downstreamLastChunkSentHolder.heldObject = false;

    spanForDownstreamCallMock = mock(Span.class);
    proxySpanTaggingStrategyMock = mock(ProxyRouterSpanNamingAndTaggingStrategy.class);

    streamingChannelSpy = spy(new StreamingChannel(
        channelMock, channelPoolMock, callActiveHolder, downstreamLastChunkSentHolder, null, null,
        spanForDownstreamCallMock, proxySpanTaggingStrategyMock
    ));

    writeAndFlushChannelFutureMock = mock(ChannelFuture.class);

    doReturn(eventLoopMock).when(channelMock).eventLoop();

    doReturn(writeAndFlushChannelFutureMock).when(channelMock).writeAndFlush(contentChunkMock);

    channelIsBrokenAttrMock = mock(Attribute.class);
    doReturn(channelIsBrokenAttrMock).when(channelMock).attr(CHANNEL_IS_BROKEN_ATTR);

    streamChunkChannelPromiseMock = mock(ChannelPromise.class);
    doReturn(streamChunkChannelPromiseMock).when(channelMock).newPromise();

    failedFutureMock = mock(ChannelFuture.class);
    doReturn(failedFutureMock).when(channelMock).newFailedFuture(any(Throwable.class));

    resetTracing();
}
 
Example #19
Source File: Http2MultiplexedChannelPool.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * @param connectionPool The {@link ChannelPool} to acquire parent channel.
 * @param eventLoopGroup The event loop group.
 * @param inetSocketAddress Remote Socket Address (IP address + port number).
 * @param http2ClientConfig Http2 client configs.
 * @param http2ClientMetrics Http2 client metrics.
 * @param streamChannelInitializer {@link ChannelInitializer} to initilize a stream channel pipeline
 */
Http2MultiplexedChannelPool(ChannelPool connectionPool, EventLoopGroup eventLoopGroup,
    Set<MultiplexedChannelRecord> connections, InetSocketAddress inetSocketAddress,
    Http2ClientConfig http2ClientConfig, Http2ClientMetrics http2ClientMetrics,
    ChannelInitializer streamChannelInitializer) {
  this.parentConnectionPool = connectionPool;
  this.eventLoopGroup = eventLoopGroup;
  this.parentConnections = connections;
  this.inetSocketAddress = inetSocketAddress;
  this.http2ClientConfig = http2ClientConfig;
  this.http2ClientMetrics = http2ClientMetrics;
  this.streamChannelInitializer = streamChannelInitializer;
}
 
Example #20
Source File: Http2ChannelPoolMap.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelPool newPool(InetSocketAddress inetSocketAddress) {
  log.trace("New pool created for {}", inetSocketAddress);
  http2ClientMetrics.http2NewPoolCount.inc();
  return new Http2MultiplexedChannelPool(inetSocketAddress, sslFactory, eventLoopGroup, http2ClientConfig,
      http2ClientMetrics, streamChannelInitializer);
}
 
Example #21
Source File: Http2MultiplexedChannelPoolTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Channel acquire and release test.
 */
@Test
public void streamChannelAcquireReleaseTest() throws Exception {
  Channel channel = newHttp2Channel();

  try {
    ChannelPool connectionPool = Mockito.mock(ChannelPool.class);

    loopGroup.register(channel).awaitUninterruptibly();
    Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
    channelPromise.setSuccess(channel);

    Mockito.when(connectionPool.acquire()).thenReturn(channelPromise);

    Http2MultiplexedChannelPool h2Pool =
        new Http2MultiplexedChannelPool(connectionPool, loopGroup, new HashSet<>(), null,
            http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()),
            streamChannelInitializer);

    Channel streamChannel1 = h2Pool.acquire().awaitUninterruptibly().getNow();
    assertTrue(streamChannel1 instanceof Http2StreamChannel);
    Mockito.verify(connectionPool, Mockito.times(1)).acquire();

    Channel streamChannel2 = h2Pool.acquire().awaitUninterruptibly().getNow();
    assertTrue(streamChannel2 instanceof Http2StreamChannel);
    Mockito.verify(connectionPool, Mockito.times(1)).acquire();

    // Verify number of numOfAvailableStreams
    MultiplexedChannelRecord multiplexedChannelRecord =
        streamChannel2.parent().attr(Http2MultiplexedChannelPool.MULTIPLEXED_CHANNEL).get();
    assertEquals(maxConcurrentStreamsPerConnection - 2, multiplexedChannelRecord.getNumOfAvailableStreams().get());
    h2Pool.release(streamChannel1).getNow();
    h2Pool.release(streamChannel2).getNow();
    assertEquals(maxConcurrentStreamsPerConnection, multiplexedChannelRecord.getNumOfAvailableStreams().get());
  } finally {
    channel.close();
  }
}
 
Example #22
Source File: Http2MultiplexedChannelPoolTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Channel acquire should fail if parent channel pool acquire fails.
 */
@Test
public void failedConnectionAcquireNotifiesPromise() throws InterruptedException {
  IOException exception = new IOException();
  ChannelPool connectionPool = mock(ChannelPool.class);
  when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception));

  ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), new HashSet<>(), null,
      http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()), streamChannelInitializer);

  Future<Channel> acquirePromise = pool.acquire().await();
  assertFalse(acquirePromise.isSuccess());
  assertEquals(acquirePromise.cause(), exception);
}
 
Example #23
Source File: Http2MultiplexedChannelPoolTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Channel acquire should fail if pool is closed.
 */
@Test
public void releaseParentChannelsIfPoolIsClosed() {
  SocketChannel channel = new NioSocketChannel();
  try {
    loopGroup.register(channel).awaitUninterruptibly();

    ChannelPool connectionPool = mock(ChannelPool.class);
    ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
    when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
      Promise<?> promise = releasePromise.getValue();
      promise.setSuccess(null);
      return promise;
    });

    MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null, streamChannelInitializer);
    Http2MultiplexedChannelPool h2Pool =
        new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null,
            http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()),
            streamChannelInitializer);

    h2Pool.close();

    InOrder inOrder = Mockito.inOrder(connectionPool);
    inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
    inOrder.verify(connectionPool).close();
  } finally {
    channel.close().awaitUninterruptibly();
  }
}
 
Example #24
Source File: Http2MultiplexedChannelPoolTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Acquire should fail if pool is closed.
 */
@Test
public void acquireAfterCloseFails() throws InterruptedException {
  ChannelPool connectionPool = mock(ChannelPool.class);
  Http2MultiplexedChannelPool h2Pool =
      new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), new HashSet<>(), null,
          http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()), streamChannelInitializer);

  h2Pool.close();

  Future<Channel> acquireResult = h2Pool.acquire().await();
  assertFalse(acquireResult.isSuccess());
  assertTrue(acquireResult.cause() instanceof IOException);
}
 
Example #25
Source File: Http2MultiplexedChannelPoolTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Connection pool is released first and then close upon h2 pool close.
 */
@Test
public void closeWaitsForConnectionToBeReleasedBeforeClosingConnectionPool() {
  SocketChannel channel = new NioSocketChannel();
  try {
    loopGroup.register(channel).awaitUninterruptibly();

    ChannelPool connectionPool = mock(ChannelPool.class);
    ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class);
    when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> {
      Promise<?> promise = releasePromise.getValue();
      promise.setSuccess(null);
      return promise;
    });

    MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null, streamChannelInitializer);
    Http2MultiplexedChannelPool h2Pool =
        new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null,
            http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()),
            streamChannelInitializer);

    h2Pool.close();

    InOrder inOrder = Mockito.inOrder(connectionPool);
    inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class));
    inOrder.verify(connectionPool).close();
  } finally {
    channel.close().awaitUninterruptibly();
  }
}
 
Example #26
Source File: Http2MultiplexedChannelPoolTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5_000)
public void interruptDuringClosePreservesFlag() throws InterruptedException {
  SocketChannel channel = new NioSocketChannel();
  try {
    loopGroup.register(channel).awaitUninterruptibly();
    Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next());
    channelPromise.setSuccess(channel);

    ChannelPool connectionPool = mock(ChannelPool.class);
    Promise<Void> releasePromise = Mockito.spy(new DefaultPromise<>(loopGroup.next()));

    when(connectionPool.release(eq(channel))).thenReturn(releasePromise);

    MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null, streamChannelInitializer);
    Http2MultiplexedChannelPool h2Pool =
        new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null,
            http2ClientConfigForOneConnection, new Http2ClientMetrics(new MetricRegistry()),
            streamChannelInitializer);

    CompletableFuture<Boolean> interrupteFlagPreserved = new CompletableFuture<>();

    Thread t = new Thread(() -> {
      try {
        h2Pool.close();
      } catch (Exception e) {
        if (e.getCause() instanceof InterruptedException && Thread.currentThread().isInterrupted()) {
          interrupteFlagPreserved.complete(true);
        }
      }
    });

    t.start();
    t.interrupt();
    t.join();
    assertTrue(interrupteFlagPreserved.join());
  } finally {
    channel.close().awaitUninterruptibly();
  }
}
 
Example #27
Source File: ChannelPipelineInitializerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void channelConfigOptionCheck() throws SSLException {
    targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080");

    SslContext sslContext = SslContextBuilder.forClient()
                                             .sslProvider(SslProvider.JDK)
                                             .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                                             .build();

    AtomicReference<ChannelPool> channelPoolRef = new AtomicReference<>();

    NettyConfiguration nettyConfiguration = new NettyConfiguration(GLOBAL_HTTP_DEFAULTS);

    pipelineInitializer = new ChannelPipelineInitializer(Protocol.HTTP1_1,
                                                         sslContext,
                                                         SslProvider.JDK,
                                                         100,
                                                         1024,
                                                         Duration.ZERO,
                                                         channelPoolRef,
                                                         nettyConfiguration,
                                                         targetUri);

    Channel channel = new EmbeddedChannel();

    pipelineInitializer.channelCreated(channel);

    assertThat(channel.config().getOption(ChannelOption.ALLOCATOR), is(UnpooledByteBufAllocator.DEFAULT));

}
 
Example #28
Source File: Http2MultiplexedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@SdkTestInternalApi
Http2MultiplexedChannelPool(ChannelPool connectionPool,
                            EventLoopGroup eventLoopGroup,
                            Set<MultiplexedChannelRecord> connections,
                            Duration idleConnectionTimeout) {
    this(connectionPool, eventLoopGroup, idleConnectionTimeout);
    this.connections.addAll(connections);
}
 
Example #29
Source File: Http2MultiplexedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * @param connectionPool Connection pool for parent channels (i.e. the socket channel).
 */
Http2MultiplexedChannelPool(ChannelPool connectionPool, EventLoopGroup eventLoopGroup, Duration idleConnectionTimeout) {
    this.connectionPool = connectionPool;
    this.eventLoopGroup = eventLoopGroup;
    this.connections = ConcurrentHashMap.newKeySet();
    this.idleConnectionTimeout = idleConnectionTimeout;
}
 
Example #30
Source File: HttpOrHttp2ChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public HttpOrHttp2ChannelPool(ChannelPool delegatePool,
                              EventLoopGroup group,
                              int maxConcurrency,
                              NettyConfiguration configuration) {
    this.delegatePool = delegatePool;
    this.maxConcurrency = maxConcurrency;
    this.eventLoopGroup = group;
    this.eventLoop = group.next();
    this.configuration = configuration;
}