Search in sources :

Example 11 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestAsyncPool method testCreationTimeout.

@Test(dataProvider = "creationTimeoutDataProvider")
public void testCreationTimeout(int poolSize, int concurrency) throws Exception {
    // this object creation life cycle simulate the creation limbo state
    ObjectCreatorThatNeverCreates objectCreatorThatNeverCreates = new ObjectCreatorThatNeverCreates();
    ClockedExecutor clockedExecutor = new ClockedExecutor();
    ExponentialBackOffRateLimiter rateLimiter = new ExponentialBackOffRateLimiter(0, 5000, 10, clockedExecutor, concurrency);
    final AsyncPool<Object> pool = new AsyncPoolImpl<>("object pool", objectCreatorThatNeverCreates, poolSize, Integer.MAX_VALUE, Integer.MAX_VALUE, clockedExecutor, Integer.MAX_VALUE, AsyncPoolImpl.Strategy.MRU, 0, rateLimiter, clockedExecutor, new LongTracking());
    pool.start();
    List<FutureCallback<Object>> checkoutCallbacks = new ArrayList<>();
    // Lets try to checkout more than the max Pool Size times when the object creator is in limbo state
    for (int i = 0; i < poolSize * 2; i++) {
        FutureCallback<Object> cb = new FutureCallback<>();
        checkoutCallbacks.add(cb);
        // Reset the exponential back off due to creation timeout error
        rateLimiter.setPeriod(0);
        pool.get(cb);
        // run for the duration of default creation timeout
        // TODO: parameterize the creation duration when the default creation gets parameterized
        clockedExecutor.runFor(AsyncPoolImpl.DEFAULT_OBJECT_CREATION_TIMEOUT);
    }
    // drain all the pending tasks
    clockedExecutor.runFor(AsyncPoolImpl.DEFAULT_OBJECT_CREATION_TIMEOUT);
    // since the object creator went to limbo state
    for (FutureCallback<Object> cb : checkoutCallbacks) {
        try {
            cb.get(100, TimeUnit.MILLISECONDS);
        } catch (Exception ex) {
            Assert.assertTrue(ex.getCause() instanceof ObjectCreationTimeoutException);
        }
    }
    // Lets make sure the channel pool stats are at expected state
    PoolStats stats = pool.getStats();
    // Lets make sure all the limbo creations are timed out as expected
    Assert.assertEquals(stats.getTotalCreateErrors(), poolSize * 2);
    // No checkout should have happened due to object creator in limbo
    Assert.assertEquals(stats.getCheckedOut(), 0);
    // No Idle objects in the pool
    Assert.assertEquals(stats.getIdleCount(), 0);
    // Lets make sure that all the slots in the pool are reclaimed even if the object creation is in limbo
    Assert.assertEquals(stats.getPoolSize(), 0);
    // Since the max pending creation request reached the max pool size,
    // we should have reached the maPool Size at least once
    Assert.assertEquals(stats.getMaxPoolSize(), poolSize);
    // Since no object is successfully created, expecting idle objects to be zero
    Assert.assertEquals(stats.getIdleCount(), 0);
}
Also used : LongTracking(com.linkedin.common.stats.LongTracking) ArrayList(java.util.ArrayList) ClockedExecutor(com.linkedin.test.util.ClockedExecutor) ObjectCreationTimeoutException(com.linkedin.r2.transport.http.client.ObjectCreationTimeoutException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) PoolStats(com.linkedin.r2.transport.http.client.PoolStats) AsyncPoolImpl(com.linkedin.r2.transport.http.client.AsyncPoolImpl) ExponentialBackOffRateLimiter(com.linkedin.r2.transport.http.client.ExponentialBackOffRateLimiter) FutureCallback(com.linkedin.common.callback.FutureCallback) ObjectCreationTimeoutException(com.linkedin.r2.transport.http.client.ObjectCreationTimeoutException) Test(org.testng.annotations.Test)

Example 12 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestAsyncPool method testWaiterTimeout.

/**
 * This test case verifies that the correct number of waiters are timed out while waiting for object from the pool
 *
 *     Assumption: the channel pool max size is always bigger than the requested checkout size
 *
 *|----------A------------|---------------B---------------|---------------C--------------|-------------D--------------
 *   A = In Phase A , N number of object checkout request to the pool when there are no tasks pending in the rate
 *       limiter. A's Expected result = channel pool will create N number of new objects and check them out
 *   B = In Phase B, O number of object checkout request again sent to the channel pool when the pool has already
 *       checkout N number of objects, In this phase, the object creation inside the pool is blocked
 *       and the rate limiter will Queue the creation requests once it reached its maximum concurrency configured.
 *   C = Ih Phase C, P number of objects are returned to the pool which are created in Phase A, this will make
 *       the number of waiter queue size to be O-P
 *   D = In Phase D, A delay will be introduced to timeout the waiters and all the O-P waiters should be timed out.
 *       After the delay the object creation will be unblocked and it should create aleast the concurrency number of
 *       objects even though the waiters are timedout.
 *
 * @param numberOfCheckoutsInPhaseA the N number of checkout operations that will be performed in phase A
 * @param numberOfCheckoutsInPhaseB the O number of checkout operations that will be performed in Phase B
 * @param numbOfObjectsToBeReturnedInPhaseC the numeber of objects returned in Phase C
 * @param poolSize size of the pool,
 * @param concurrency concurrency of the rate limiter
 */
@Test(dataProvider = "waiterTimeoutDataProvider")
public void testWaiterTimeout(int numberOfCheckoutsInPhaseA, int numberOfCheckoutsInPhaseB, int numbOfObjectsToBeReturnedInPhaseC, int poolSize, int concurrency, int waiterTimeout) throws Exception {
    CreationBlockableSynchronousLifecycle blockableObjectCreator = new CreationBlockableSynchronousLifecycle(numberOfCheckoutsInPhaseB, concurrency);
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(500);
    ExponentialBackOffRateLimiter rateLimiter = new ExponentialBackOffRateLimiter(0, 5000, 10, executor, concurrency);
    ClockedExecutor clockedExecutor = new ClockedExecutor();
    final AsyncPool<Object> pool = new AsyncPoolImpl<>("object pool", blockableObjectCreator, poolSize, Integer.MAX_VALUE, waiterTimeout, clockedExecutor, Integer.MAX_VALUE, AsyncPoolImpl.Strategy.MRU, 0, rateLimiter, clockedExecutor, new LongTracking());
    pool.start();
    // Phase A : Checking out object 'numberOfCheckoutsInPhaseA' times !
    List<Object> checkedOutObjects = performCheckout(numberOfCheckoutsInPhaseA, pool);
    // Phase B : Blocking object creation and performing the checkout 'numberOfCheckoutsInPhaseB' times again
    blockableObjectCreator.blockCreation();
    Future<None> future = performUnblockingCheckout(numberOfCheckoutsInPhaseB, 0, pool);
    blockableObjectCreator.waitUntilAllBlocked();
    // Phase C : Returning the checkedOut objects from Phase A back to the object pool
    for (int i = 0; i < numbOfObjectsToBeReturnedInPhaseC; i++) {
        pool.put(checkedOutObjects.remove(0));
    }
    clockedExecutor.runFor(waiterTimeout);
    // Phase D : All the object creation in phase B gets unblocked now
    blockableObjectCreator.unblockCreation();
    try {
        future.get(5, TimeUnit.SECONDS);
    } catch (Exception e) {
        Assert.fail("Did not complete unblocked object creations on time, Unexpected interruption", e);
    }
    // Making sure the rate limiter pending tasks are submitted to the executor
    AssertionMethods.assertWithTimeout(5000, () -> Assert.assertEquals(rateLimiter.numberOfPendingTasks(), 0, "Number of tasks has to drop to 0"));
    executor.shutdown();
    try {
        if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
            Assert.fail("Executor took too long to shutdown");
        }
    } catch (Exception ex) {
        Assert.fail("Unexpected interruption while shutting down executor", ex);
    }
    PoolStats stats = pool.getStats();
    Assert.assertEquals(stats.getTotalCreationIgnored(), numberOfCheckoutsInPhaseB - concurrency);
    Assert.assertEquals(stats.getCheckedOut(), numberOfCheckoutsInPhaseA);
    Assert.assertEquals(stats.getIdleCount(), concurrency);
    Assert.assertEquals(stats.getTotalCreated(), numberOfCheckoutsInPhaseA + concurrency);
    Assert.assertEquals(stats.getPoolSize(), numberOfCheckoutsInPhaseA + concurrency);
    Assert.assertEquals(stats.getTotalWaiterTimedOut(), numberOfCheckoutsInPhaseB - numbOfObjectsToBeReturnedInPhaseC);
}
Also used : LongTracking(com.linkedin.common.stats.LongTracking) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ClockedExecutor(com.linkedin.test.util.ClockedExecutor) ObjectCreationTimeoutException(com.linkedin.r2.transport.http.client.ObjectCreationTimeoutException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) PoolStats(com.linkedin.r2.transport.http.client.PoolStats) AsyncPoolImpl(com.linkedin.r2.transport.http.client.AsyncPoolImpl) ExponentialBackOffRateLimiter(com.linkedin.r2.transport.http.client.ExponentialBackOffRateLimiter) None(com.linkedin.common.util.None) Test(org.testng.annotations.Test)

Example 13 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestAsyncSharedPoolImpl method testShutdownWithMultiplePendingDispose.

@Test
public void testShutdownWithMultiplePendingDispose() throws Exception {
    final AsyncSharedPoolImpl<Object> pool = new AsyncSharedPoolImpl<>(POOL_NAME, LIFECYCLE, SCHEDULER, LIMITER, NO_POOL_TIMEOUT, MAX_WAITERS);
    pool.start();
    final CountDownLatch latch = new CountDownLatch(GET_COUNT);
    final Collection<FutureCallback<Object>> getCallbacks = new ConcurrentLinkedQueue<>();
    IntStream.range(0, GET_COUNT).forEach(i -> SCHEDULER.execute(() -> {
        FutureCallback<Object> getCallback = new FutureCallback<>();
        pool.get(getCallback);
        getCallbacks.add(getCallback);
        latch.countDown();
    }));
    if (!latch.await(OPERATION_TIMEOUT, TIME_UNIT)) {
        Assert.fail("Timeout waiting for get calls");
    }
    final Collection<Object> items = new ConcurrentLinkedQueue<>();
    getCallbacks.stream().forEach(callback -> {
        try {
            items.add(callback.get(GET_TIMEOUT, TIME_UNIT));
        } catch (Exception e) {
        }
    });
    Assert.assertEquals(items.size(), GET_COUNT);
    verifyStats(pool.getStats(), 1, GET_COUNT, 0, 0, 0, 0, 1, 0, 0);
    FutureCallback<None> shutdownCallback = new FutureCallback<>();
    pool.shutdown(shutdownCallback);
    // Put items back to the pool
    items.stream().forEach(item -> SCHEDULER.execute(() -> pool.dispose(item)));
    shutdownCallback.get(SHUTDOWN_TIMEOUT, TIME_UNIT);
}
Also used : AsyncSharedPoolImpl(com.linkedin.r2.transport.http.client.AsyncSharedPoolImpl) CountDownLatch(java.util.concurrent.CountDownLatch) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) None(com.linkedin.common.util.None) FutureCallback(com.linkedin.common.callback.FutureCallback) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 14 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class TestAsyncSharedPoolImpl method testShutdownWithMultiplePendingPut.

@Test
public void testShutdownWithMultiplePendingPut() throws Exception {
    final AsyncSharedPoolImpl<Object> pool = new AsyncSharedPoolImpl<>(POOL_NAME, LIFECYCLE, SCHEDULER, LIMITER, NO_POOL_TIMEOUT, MAX_WAITERS);
    pool.start();
    final CountDownLatch latch = new CountDownLatch(GET_COUNT);
    final Collection<FutureCallback<Object>> getCallbacks = new ConcurrentLinkedQueue<>();
    IntStream.range(0, GET_COUNT).forEach(i -> SCHEDULER.execute(() -> {
        FutureCallback<Object> getCallback = new FutureCallback<>();
        pool.get(getCallback);
        getCallbacks.add(getCallback);
        latch.countDown();
    }));
    if (!latch.await(OPERATION_TIMEOUT, TIME_UNIT)) {
        Assert.fail("Timeout waiting for get calls");
    }
    final Collection<Object> items = new ConcurrentLinkedQueue<>();
    getCallbacks.stream().forEach(callback -> {
        try {
            items.add(callback.get(GET_TIMEOUT, TIME_UNIT));
        } catch (Exception e) {
        }
    });
    Assert.assertEquals(items.size(), GET_COUNT);
    verifyStats(pool.getStats(), 1, GET_COUNT, 0, 0, 0, 0, 1, 0, 0);
    FutureCallback<None> shutdownCallback = new FutureCallback<>();
    pool.shutdown(shutdownCallback);
    // Put items back to the pool
    items.stream().forEach(item -> SCHEDULER.execute(() -> pool.put(item)));
    shutdownCallback.get(SHUTDOWN_TIMEOUT, TIME_UNIT);
}
Also used : AsyncSharedPoolImpl(com.linkedin.r2.transport.http.client.AsyncSharedPoolImpl) CountDownLatch(java.util.concurrent.CountDownLatch) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) None(com.linkedin.common.util.None) FutureCallback(com.linkedin.common.callback.FutureCallback) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 15 with Timeout

use of com.linkedin.r2.util.Timeout in project rest.li by linkedin.

the class BaseTestSmoothRateLimiter method testSubmitExceedsPermits.

@Test(timeOut = TEST_TIMEOUT)
public void testSubmitExceedsPermits() throws Exception {
    ClockedExecutor clockedExecutor = new ClockedExecutor();
    AsyncRateLimiter rateLimiter = getRateLimiter(clockedExecutor, clockedExecutor, clockedExecutor);
    rateLimiter.setRate(ONE_PERMIT_PER_PERIOD, ONE_MILLISECOND_PERIOD, UNLIMITED_BURST);
    List<FutureCallback<None>> callbacks = new ArrayList<>();
    IntStream.range(0, 5).forEach(i -> {
        FutureCallback<None> callback = new FutureCallback<>();
        rateLimiter.submit(callback);
        callbacks.add(callback);
    });
    Assert.assertEquals(rateLimiter.getPendingTasksCount(), 5);
    // trigger task to run them until current time
    clockedExecutor.runFor(0);
    // We have one permit to begin with so the first task should run immediate and left with 4 pending
    callbacks.get(0).get();
    Assert.assertEquals(rateLimiter.getPendingTasksCount(), 4);
    IntStream.range(0, 1).forEach(i -> assertTrue(callbacks.get(i).isDone()));
    IntStream.range(1, 5).forEach(i -> assertFalse(callbacks.get(i).isDone()));
    // We increment the clock by one period and one more permit should have been issued
    clockedExecutor.runFor(ONE_MILLISECOND_PERIOD);
    callbacks.get(1).get();
    Assert.assertEquals(rateLimiter.getPendingTasksCount(), 3);
    IntStream.range(0, 2).forEach(i -> assertTrue(callbacks.get(i).isDone()));
    IntStream.range(2, 5).forEach(i -> assertFalse(callbacks.get(i).isDone()));
    clockedExecutor.runFor(ONE_MILLISECOND_PERIOD);
    callbacks.get(2).get();
    Assert.assertEquals(rateLimiter.getPendingTasksCount(), 2);
    IntStream.range(0, 3).forEach(i -> assertTrue(callbacks.get(i).isDone()));
    IntStream.range(3, 5).forEach(i -> assertFalse(callbacks.get(i).isDone()));
    clockedExecutor.runFor(ONE_MILLISECOND_PERIOD);
    callbacks.get(3).get();
    Assert.assertEquals(rateLimiter.getPendingTasksCount(), 1);
    IntStream.range(0, 4).forEach(i -> assertTrue(callbacks.get(i).isDone()));
    IntStream.range(4, 5).forEach(i -> assertFalse(callbacks.get(i).isDone()));
    clockedExecutor.runFor(ONE_MILLISECOND_PERIOD);
    callbacks.get(4).get();
    Assert.assertEquals(rateLimiter.getPendingTasksCount(), 0);
    IntStream.range(0, 5).forEach(i -> assertTrue(callbacks.get(i).isDone()));
}
Also used : AsyncRateLimiter(com.linkedin.r2.transport.http.client.AsyncRateLimiter) ArrayList(java.util.ArrayList) ClockedExecutor(com.linkedin.test.util.ClockedExecutor) None(com.linkedin.common.util.None) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)78 RequestContext (com.linkedin.r2.message.RequestContext)46 CountDownLatch (java.util.concurrent.CountDownLatch)40 TimeoutException (java.util.concurrent.TimeoutException)40 None (com.linkedin.common.util.None)33 FutureCallback (com.linkedin.common.callback.FutureCallback)32 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)26 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)25 URI (java.net.URI)25 RestRequest (com.linkedin.r2.message.rest.RestRequest)21 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)21 ByteString (com.linkedin.data.ByteString)19 HashMap (java.util.HashMap)19 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 RestResponse (com.linkedin.r2.message.rest.RestResponse)18 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)17 ExecutionException (java.util.concurrent.ExecutionException)17 TransportClient (com.linkedin.r2.transport.common.bridge.client.TransportClient)15 IOException (java.io.IOException)15 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)13