Java Code Examples for io.netty.util.concurrent.Promise#setFailure()

The following examples show how to use io.netty.util.concurrent.Promise#setFailure() . 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: HttpOrHttp2ChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void protocolConfigInProgress_poolClosed_delegatePoolClosedOnAcquireFailure() throws InterruptedException {
    Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise();
    when(mockDelegatePool.acquire()).thenReturn(acquirePromise);

    // initiate the configuration
    httpOrHttp2ChannelPool.acquire();

    // close the pool before the config can complete (we haven't completed acquirePromise yet)
    httpOrHttp2ChannelPool.close();

    Thread.sleep(500);

    acquirePromise.setFailure(new RuntimeException("Some failure"));

    Thread.sleep(500);
    verify(mockDelegatePool).close();
}
 
Example 2
Source File: Http2MultiplexedChannelPool.java    From ambry with Apache License 2.0 6 votes vote down vote up
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
  http2ClientMetrics.http2NewStreamCount.inc();
  if (closed.get()) {
    return promise.setFailure(new IOException("Channel pool is closed!"));
  }

  // Only when number of connections reach http2MinConnectionPerPort, we reuse connections.
  if (parentConnections.size() >= http2ClientConfig.http2MinConnectionPerPort) {
    List<MultiplexedChannelRecord> multiplexedChannelRecords = new ArrayList<>(parentConnections);
    Collections.shuffle(multiplexedChannelRecords);
    // Attempt at most multiplexedChannelRecords.size(). No slip acquire expected.
    for (MultiplexedChannelRecord multiplexedChannelRecord : multiplexedChannelRecords) {
      if (acquireStreamOnInitializedConnection(multiplexedChannelRecord, promise)) {
        return promise;
      }
      log.warn("Stream slip acquire on {}", inetSocketAddress);
      http2ClientMetrics.http2StreamSlipAcquireCount.inc();
    }
  }

  // No connection or No available streams on existing connections, establish new connection and add it to set.
  acquireStreamOnNewConnection(promise);
  return promise;
}
 
Example 3
Source File: Http2MultiplexedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
    if (closed.get()) {
        return promise.setFailure(new IOException("Channel pool is closed!"));
    }

    for (MultiplexedChannelRecord multiplexedChannel : connections) {
        if (acquireStreamOnInitializedConnection(multiplexedChannel, promise)) {
            return promise;
        }
    }

    // No available streams on existing connections, establish new connection and add it to list
    acquireStreamOnNewConnection(promise);
    return promise;
}
 
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: NettyUtils.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link BiConsumer} that notifies the promise of any failures either via the throwable passed into the BiConsumer
 * or as a result of running the successConsumer. This assumes that the successConsumer will notify the promise when it
 * completes successfully.
 *
 * @param successConsumer BiConsumer to call if the result is successful. Promise is also passed and must be notified on
 * success.
 * @param promise Promise to notify.
 * @param <SuccessT> Success type.
 * @param <PromiseT> Type being fulfilled by the Promise.
 * @return BiConsumer that can be used in a {@link CompletableFuture#whenComplete(BiConsumer)} method.
 */
public static <SuccessT, PromiseT> BiConsumer<SuccessT, ? super Throwable> asyncPromiseNotifyingBiConsumer(
    BiConsumer<SuccessT, Promise<PromiseT>> successConsumer, Promise<PromiseT> promise) {
  return (success, fail) -> {
    if (fail != null) {
      promise.setFailure(fail);
    } else {
      try {
        successConsumer.accept(success, promise);
      } catch (Throwable e) {
        // If the successConsumer fails synchronously then we can notify the promise. If it fails asynchronously
        // it's up to the successConsumer to notify.
        promise.setFailure(e);
      }
    }
  };
}
 
Example 6
Source File: FixedChannelPool.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
    public Future<Channel> acquire(final Promise<Channel> promise) {
        try {
            if (executor.inEventLoop()) {
//                获取channel
                acquire0(promise);
            } else {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        acquire0(promise);
                    }
                });
            }
        } catch (Throwable cause) {
            promise.setFailure(cause);
        }
        return promise;
    }
 
Example 7
Source File: CompositeNameResolver.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private void doResolveRec(final String inetHost,
                          final Promise<T> promise,
                          final int resolverIndex,
                          Throwable lastFailure) throws Exception {
    if (resolverIndex >= resolvers.length) {
        promise.setFailure(lastFailure);
    } else {
        NameResolver<T> resolver = resolvers[resolverIndex];
        resolver.resolve(inetHost).addListener(new FutureListener<T>() {
            @Override
            public void operationComplete(Future<T> future) throws Exception {
                if (future.isSuccess()) {
                    promise.setSuccess(future.getNow());
                } else {
                    doResolveRec(inetHost, promise, resolverIndex + 1, future.cause());
                }
            }
        });
    }
}
 
Example 8
Source File: CancellableAcquireChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void promiseCancelledBeforeAcquireComplete_closesAndReleasesChannel() throws InterruptedException {
    Promise<Channel> acquireFuture = eventExecutor.newPromise();
    acquireFuture.setFailure(new RuntimeException("Changed my mind!"));

    when(mockDelegatePool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
        Promise p = invocationOnMock.getArgumentAt(0, Promise.class);
        p.setSuccess(channel);
        return p;
    });

    cancellableAcquireChannelPool.acquire(acquireFuture);

    Thread.sleep(500);
    verify(mockDelegatePool).release(eq(channel));
    assertThat(channel.closeFuture().isDone()).isTrue();
}
 
Example 9
Source File: SocketConnectionAttemptTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void testConnectRefused0(Bootstrap cb, boolean halfClosure) throws Throwable {
    final Promise<Error> errorPromise = GlobalEventExecutor.INSTANCE.newPromise();
    ChannelHandler handler = new ChannelInboundHandlerAdapter() {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            errorPromise.setFailure(new AssertionError("should have never been called"));
        }
    };

    cb.handler(handler);
    cb.option(ChannelOption.ALLOW_HALF_CLOSURE, halfClosure);
    ChannelFuture future = cb.connect(NetUtil.LOCALHOST, UNASSIGNED_PORT).awaitUninterruptibly();
    assertThat(future.cause(), is(instanceOf(ConnectException.class)));
    assertThat(errorPromise.cause(), is(nullValue()));
}
 
Example 10
Source File: NettyUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link BiConsumer} that notifies the promise of any failures either via the {@link Throwable} passed into the
 * BiConsumer of as a result of running the successFunction.
 *
 * @param successFunction Function called to process the successful result and map it into the result to notify the promise
 * with.
 * @param promise Promise to notify of success or failure.
 * @param <SuccessT> Success type.
 * @param <PromiseT> Type being fulfilled by the promise.
 * @return BiConsumer that can be used in a {@link CompletableFuture#whenComplete(BiConsumer)} method.
 */
public static <SuccessT, PromiseT> BiConsumer<SuccessT, ? super Throwable> promiseNotifyingBiConsumer(
    Function<SuccessT, PromiseT> successFunction, Promise<PromiseT> promise) {
    return (success, fail) -> {
        if (fail != null) {
            promise.setFailure(fail);
        } else {
            try {
                promise.setSuccess(successFunction.apply(success));
            } catch (Throwable e) {
                promise.setFailure(e);
            }
        }
    };
}
 
Example 11
Source File: NettyUtils.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link GenericFutureListener} that will notify the provided {@link Promise} on success and failure.
 *
 * @param channelPromise Promise to notify.
 * @return GenericFutureListener
 */
public static <T> GenericFutureListener<Future<T>> promiseNotifyingListener(Promise<T> channelPromise) {
  return future -> {
    if (future.isSuccess()) {
      channelPromise.setSuccess(future.getNow());
    } else {
      channelPromise.setFailure(future.cause());
    }
  };
}
 
Example 12
Source File: DefaultNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doResolveAll(String inetHost, Promise<List<InetAddress>> promise) throws Exception {
    try {
        promise.setSuccess(Arrays.asList(SocketUtils.allAddressesByName(inetHost)));
    } catch (UnknownHostException e) {
        promise.setFailure(e);
    }
}
 
Example 13
Source File: DefaultNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doResolve(String inetHost, Promise<InetAddress> promise) throws Exception {
    try {
        promise.setSuccess(SocketUtils.addressByName(inetHost));
    } catch (UnknownHostException e) {
        promise.setFailure(e);
    }
}
 
Example 14
Source File: SimpleNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public Future<T> resolve(String inetHost, Promise<T> promise) {
    checkNotNull(promise, "promise");

    try {
        doResolve(inetHost, promise);
        return promise;
    } catch (Exception e) {
        return promise.setFailure(e);
    }
}
 
Example 15
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void assertExecutor(ChannelHandlerContext ctx, Promise<Void> promise) {
    final boolean same;
    try {
        same = executor == ctx.executor();
    } catch (Throwable cause) {
        promise.setFailure(cause);
        return;
    }
    if (same) {
        promise.setSuccess(null);
    } else {
        promise.setFailure(new AssertionError("EventExecutor not the same"));
    }
}
 
Example 16
Source File: Http2MultiplexedChannelPool.java    From ambry with Apache License 2.0 5 votes vote down vote up
private Future<Void> closeAndReleaseParent(Channel parentChannel, Throwable cause, Promise<Void> resultPromise) {
  if (parentChannel.parent() != null) {
    // This isn't a parent channel. Notify it that something is wrong.
    Exception exception = new IOException(
        "Channel (" + parentChannel + ") is not a parent channel. It will be closed, "
            + "but cannot be released within this pool.");
    log.error(exception.getMessage());
    parentChannel.close();
    return resultPromise.setFailure(exception);
  }

  MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get();

  // We may not have a multiplexed channel if the parent channel hasn't been fully initialized.
  if (multiplexedChannel != null) {
    if (cause == null) {
      multiplexedChannel.closeChildChannels();
    } else {
      multiplexedChannel.closeChildChannels(cause);
    }
    parentConnections.remove(multiplexedChannel);
  }

  parentChannel.close();
  if (parentChannel.attr(PARENT_CHANNEL_RELEASED).getAndSet(Boolean.TRUE) == null) {
    return parentConnectionPool.release(parentChannel, resultPromise);
  }

  return resultPromise.setSuccess(null);
}
 
Example 17
Source File: SniHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public Future<SslContext> map(String input, Promise<SslContext> promise) {
    final SslContext context;
    try {
        context = mapping.map(input);
    } catch (Throwable cause) {
        return promise.setFailure(cause);
    }
    return promise.setSuccess(context);
}
 
Example 18
Source File: Http2MultiplexedChannelPool.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> release(Channel childChannel, Promise<Void> promise) {
  if (childChannel.parent() == null) {
    // This isn't a child channel. Oddly enough, this is "expected" and is handled properly by the
    // BetterFixedChannelPool AS LONG AS we return an IllegalArgumentException via the promise.
    closeAndReleaseParent(childChannel);
    return promise.setFailure(new IllegalArgumentException("Channel (" + childChannel + ") is not a child channel."));
  }

  Channel parentChannel = childChannel.parent();
  MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get();
  if (multiplexedChannel == null) {
    // This is a child channel, but there is no attached multiplexed channel, which there should be if it was from
    // this pool. Close it and log an error.
    Exception exception = new IOException(
        "Channel (" + childChannel + ") is not associated with any channel records. "
            + "It will be closed, but cannot be released within this pool.");
    log.error(exception.getMessage());
    childChannel.close();
    return promise.setFailure(exception);
  }

  multiplexedChannel.closeAndReleaseChild(childChannel);

  if (multiplexedChannel.canBeClosedAndReleased()) {
    log.debug("Parent channel closed: {}", parentChannel.remoteAddress());
    // We just closed the last stream in a connection that has reached the end of its life.
    return closeAndReleaseParent(parentChannel, null, promise);
  }

  return promise.setSuccess(null);
}
 
Example 19
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves the specified host name and port into a list of address.
 *
 * @param inetHost the name to resolve
 * @param additionals additional records ({@code OPT})
 * @param promise the {@link Promise} which will be fulfilled when the name resolution is finished
 *
 * @return the list of the address as the result of the resolution
 */
public final Future<List<InetAddress>> resolveAll(String inetHost, Iterable<DnsRecord> additionals,
                                            Promise<List<InetAddress>> promise) {
    checkNotNull(promise, "promise");
    DnsRecord[] additionalsArray = toArray(additionals, true);
    try {
        doResolveAll(inetHost, additionalsArray, promise, resolveCache);
        return promise;
    } catch (Exception e) {
        return promise.setFailure(e);
    }
}
 
Example 20
Source File: Http2MultiplexedChannelPool.java    From ambry with Apache License 2.0 4 votes vote down vote up
private Void failAndCloseParent(Promise<Channel> promise, Channel parentChannel, Throwable exception) {
  promise.setFailure(exception);
  closeAndReleaseParent(parentChannel);
  return null;
}