Search in sources :

Example 1 with Supplier

use of com.google.common.base.Supplier in project hadoop by apache.

the class TestRPC method testClientBackOffByResponseTime.

/**
   *  Test RPC backoff by response time of each priority level.
   */
@Test(timeout = 30000)
public void testClientBackOffByResponseTime() throws Exception {
    final TestRpcService proxy;
    boolean succeeded = false;
    final int numClients = 1;
    GenericTestUtils.setLogLevel(DecayRpcScheduler.LOG, Level.DEBUG);
    GenericTestUtils.setLogLevel(RPC.LOG, Level.DEBUG);
    final List<Future<Void>> res = new ArrayList<Future<Void>>();
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);
    conf.setInt(CommonConfigurationKeys.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, 0);
    final String ns = CommonConfigurationKeys.IPC_NAMESPACE + ".0";
    Server server = setupDecayRpcSchedulerandTestServer(ns + ".");
    @SuppressWarnings("unchecked") CallQueueManager<Call> spy = spy((CallQueueManager<Call>) Whitebox.getInternalState(server, "callQueue"));
    Whitebox.setInternalState(server, "callQueue", spy);
    Exception lastException = null;
    proxy = getClient(addr, conf);
    MetricsRecordBuilder rb1 = getMetrics("DecayRpcSchedulerMetrics2." + ns);
    final long beginDecayedCallVolume = MetricsAsserts.getLongCounter("DecayedCallVolume", rb1);
    final long beginRawCallVolume = MetricsAsserts.getLongCounter("CallVolume", rb1);
    final int beginUniqueCaller = MetricsAsserts.getIntCounter("UniqueCallers", rb1);
    try {
        // start a sleep RPC call that sleeps 3s.
        for (int i = 0; i < numClients; i++) {
            res.add(executorService.submit(new Callable<Void>() {

                @Override
                public Void call() throws ServiceException, InterruptedException {
                    proxy.sleep(null, newSleepRequest(3000));
                    return null;
                }
            }));
            verify(spy, timeout(500).times(i + 1)).offer(Mockito.<Call>anyObject());
        }
        // avg response time(3s) exceeds threshold (2s).
        try {
            // wait for the 1st response time update
            Thread.sleep(5500);
            proxy.sleep(null, newSleepRequest(100));
        } catch (ServiceException e) {
            RemoteException re = (RemoteException) e.getCause();
            IOException unwrapExeption = re.unwrapRemoteException();
            if (unwrapExeption instanceof RetriableException) {
                succeeded = true;
            } else {
                lastException = unwrapExeption;
            }
            // Lets Metric system update latest metrics
            GenericTestUtils.waitFor(new Supplier<Boolean>() {

                @Override
                public Boolean get() {
                    MetricsRecordBuilder rb2 = getMetrics("DecayRpcSchedulerMetrics2." + ns);
                    long decayedCallVolume1 = MetricsAsserts.getLongCounter("DecayedCallVolume", rb2);
                    long rawCallVolume1 = MetricsAsserts.getLongCounter("CallVolume", rb2);
                    int uniqueCaller1 = MetricsAsserts.getIntCounter("UniqueCallers", rb2);
                    long callVolumePriority0 = MetricsAsserts.getLongGauge("Priority.0.CompletedCallVolume", rb2);
                    long callVolumePriority1 = MetricsAsserts.getLongGauge("Priority.1.CompletedCallVolume", rb2);
                    double avgRespTimePriority0 = MetricsAsserts.getDoubleGauge("Priority.0.AvgResponseTime", rb2);
                    double avgRespTimePriority1 = MetricsAsserts.getDoubleGauge("Priority.1.AvgResponseTime", rb2);
                    LOG.info("DecayedCallVolume: " + decayedCallVolume1);
                    LOG.info("CallVolume: " + rawCallVolume1);
                    LOG.info("UniqueCaller: " + uniqueCaller1);
                    LOG.info("Priority.0.CompletedCallVolume: " + callVolumePriority0);
                    LOG.info("Priority.1.CompletedCallVolume: " + callVolumePriority1);
                    LOG.info("Priority.0.AvgResponseTime: " + avgRespTimePriority0);
                    LOG.info("Priority.1.AvgResponseTime: " + avgRespTimePriority1);
                    return decayedCallVolume1 > beginDecayedCallVolume && rawCallVolume1 > beginRawCallVolume && uniqueCaller1 > beginUniqueCaller;
                }
            }, 30, 60000);
        }
    } finally {
        executorService.shutdown();
        stop(server, proxy);
    }
    if (lastException != null) {
        LOG.error("Last received non-RetriableException:", lastException);
    }
    assertTrue("RetriableException not received", succeeded);
}
Also used : Call(org.apache.hadoop.ipc.Server.Call) ArrayList(java.util.ArrayList) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ServiceException(com.google.protobuf.ServiceException) AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) HadoopIllegalArgumentException(org.apache.hadoop.HadoopIllegalArgumentException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) AccessControlException(org.apache.hadoop.security.AccessControlException) Callable(java.util.concurrent.Callable) ServiceException(com.google.protobuf.ServiceException) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Supplier(com.google.common.base.Supplier) MetricsRecordBuilder(org.apache.hadoop.metrics2.MetricsRecordBuilder) Test(org.junit.Test)

Example 2 with Supplier

use of com.google.common.base.Supplier in project hadoop by apache.

the class TestAMRMClientAsync method testAMRMClientAsyncShutDownWithWaitFor.

@Test(timeout = 10000)
public void testAMRMClientAsyncShutDownWithWaitFor() throws Exception {
    Configuration conf = new Configuration();
    final TestCallbackHandler callbackHandler = new TestCallbackHandler();
    @SuppressWarnings("unchecked") AMRMClient<ContainerRequest> client = mock(AMRMClientImpl.class);
    when(client.allocate(anyFloat())).thenThrow(new ApplicationAttemptNotFoundException("app not found, shut down"));
    AMRMClientAsync<ContainerRequest> asyncClient = AMRMClientAsync.createAMRMClientAsync(client, 10, callbackHandler);
    asyncClient.init(conf);
    asyncClient.start();
    Supplier<Boolean> checker = new Supplier<Boolean>() {

        @Override
        public Boolean get() {
            return callbackHandler.reboot;
        }
    };
    asyncClient.registerApplicationMaster("localhost", 1234, null);
    asyncClient.waitFor(checker);
    asyncClient.stop();
    // stopping should have joined all threads and completed all callbacks
    Assert.assertTrue(callbackHandler.callbackCount == 0);
    verify(client, times(1)).allocate(anyFloat());
    asyncClient.stop();
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) ContainerRequest(org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest) Supplier(com.google.common.base.Supplier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ApplicationAttemptNotFoundException(org.apache.hadoop.yarn.exceptions.ApplicationAttemptNotFoundException) Test(org.junit.Test)

Example 3 with Supplier

use of com.google.common.base.Supplier in project hadoop by apache.

the class TestAMRMClientAsync method testCallAMRMClientAsyncStopFromCallbackHandlerWithWaitFor.

@Test(timeout = 5000)
public void testCallAMRMClientAsyncStopFromCallbackHandlerWithWaitFor() throws YarnException, IOException, InterruptedException {
    Configuration conf = new Configuration();
    final TestCallbackHandler2 callbackHandler = new TestCallbackHandler2();
    @SuppressWarnings("unchecked") AMRMClient<ContainerRequest> client = mock(AMRMClientImpl.class);
    List<ContainerStatus> completed = Arrays.asList(ContainerStatus.newInstance(newContainerId(0, 0, 0, 0), ContainerState.COMPLETE, "", 0));
    final AllocateResponse response = createAllocateResponse(completed, new ArrayList<Container>(), null);
    when(client.allocate(anyFloat())).thenReturn(response);
    AMRMClientAsync<ContainerRequest> asyncClient = AMRMClientAsync.createAMRMClientAsync(client, 20, callbackHandler);
    callbackHandler.asynClient = asyncClient;
    asyncClient.init(conf);
    asyncClient.start();
    Supplier<Boolean> checker = new Supplier<Boolean>() {

        @Override
        public Boolean get() {
            return callbackHandler.notify;
        }
    };
    asyncClient.registerApplicationMaster("localhost", 1234, null);
    asyncClient.waitFor(checker);
    Assert.assertTrue(checker.get());
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) AllocateResponse(org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse) ContainerStatus(org.apache.hadoop.yarn.api.records.ContainerStatus) UpdatedContainer(org.apache.hadoop.yarn.api.records.UpdatedContainer) Container(org.apache.hadoop.yarn.api.records.Container) ContainerRequest(org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest) Supplier(com.google.common.base.Supplier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 4 with Supplier

use of com.google.common.base.Supplier in project hadoop by apache.

the class TestLogAggregationService method testInvalidThreadPoolSizeValue.

private void testInvalidThreadPoolSizeValue(final String threadPoolSize) throws IOException {
    Supplier<Boolean> isInputInvalid = new Supplier<Boolean>() {

        @Override
        public Boolean get() {
            try {
                int value = Integer.parseInt(threadPoolSize);
                return value <= 0;
            } catch (NumberFormatException ex) {
                return true;
            }
        }
    };
    assertTrue("The thread pool size must be invalid to use with this " + "method", isInputInvalid.get());
    // store configured thread pool size temporarily for restoration
    int initThreadPoolSize = conf.getInt(YarnConfiguration.NM_LOG_AGGREGATION_THREAD_POOL_SIZE, YarnConfiguration.DEFAULT_NM_LOG_AGGREGATION_THREAD_POOL_SIZE);
    conf.set(YarnConfiguration.NM_LOG_AGGREGATION_THREAD_POOL_SIZE, threadPoolSize);
    DeletionService delSrvc = mock(DeletionService.class);
    LocalDirsHandlerService dirSvc = mock(LocalDirsHandlerService.class);
    when(dirSvc.getLogDirs()).thenThrow(new RuntimeException());
    LogAggregationService logAggregationService = new LogAggregationService(dispatcher, this.context, delSrvc, dirSvc);
    logAggregationService.init(this.conf);
    logAggregationService.start();
    ThreadPoolExecutor executorService = (ThreadPoolExecutor) logAggregationService.threadPool;
    assertEquals("The thread pool size should be set to the value of YARN" + ".DEFAULT_NM_LOG_AGGREGATION_THREAD_POOL_SIZE because the configured " + " thread pool size is " + "invalid.", YarnConfiguration.DEFAULT_NM_LOG_AGGREGATION_THREAD_POOL_SIZE, executorService.getMaximumPoolSize());
    logAggregationService.stop();
    logAggregationService.close();
    // retore original configuration to aviod side effects
    conf.setInt(YarnConfiguration.NM_LOG_AGGREGATION_THREAD_POOL_SIZE, initThreadPoolSize);
}
Also used : YarnRuntimeException(org.apache.hadoop.yarn.exceptions.YarnRuntimeException) DeletionService(org.apache.hadoop.yarn.server.nodemanager.DeletionService) Supplier(com.google.common.base.Supplier) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) LocalDirsHandlerService(org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService)

Example 5 with Supplier

use of com.google.common.base.Supplier in project druid by druid-io.

the class IncrementalIndexStorageAdapterTest method testSingleValueTopN.

@Test
public void testSingleValueTopN() throws IOException {
    IncrementalIndex index = indexCreator.createIndex();
    DateTime t = DateTime.now();
    index.add(new MapBasedInputRow(t.minus(1).getMillis(), Lists.newArrayList("sally"), ImmutableMap.<String, Object>of("sally", "bo")));
    TopNQueryEngine engine = new TopNQueryEngine(new StupidPool<ByteBuffer>("TopNQueryEngine-bufferPool", new Supplier<ByteBuffer>() {

        @Override
        public ByteBuffer get() {
            return ByteBuffer.allocate(50000);
        }
    }));
    final Iterable<Result<TopNResultValue>> results = Sequences.toList(engine.query(new TopNQueryBuilder().dataSource("test").granularity(Granularities.ALL).intervals(Lists.newArrayList(new Interval(0, new DateTime().getMillis()))).dimension("sally").metric("cnt").threshold(10).aggregators(Lists.<AggregatorFactory>newArrayList(new LongSumAggregatorFactory("cnt", "cnt"))).build(), new IncrementalIndexStorageAdapter(index)), Lists.<Result<TopNResultValue>>newLinkedList());
    Assert.assertEquals(1, Iterables.size(results));
    Assert.assertEquals(1, results.iterator().next().getValue().getValue().size());
}
Also used : TopNQueryBuilder(io.druid.query.topn.TopNQueryBuilder) TopNResultValue(io.druid.query.topn.TopNResultValue) LongSumAggregatorFactory(io.druid.query.aggregation.LongSumAggregatorFactory) AggregatorFactory(io.druid.query.aggregation.AggregatorFactory) CountAggregatorFactory(io.druid.query.aggregation.CountAggregatorFactory) JavaScriptAggregatorFactory(io.druid.query.aggregation.JavaScriptAggregatorFactory) LongSumAggregatorFactory(io.druid.query.aggregation.LongSumAggregatorFactory) ByteBuffer(java.nio.ByteBuffer) DateTime(org.joda.time.DateTime) TopNQueryEngine(io.druid.query.topn.TopNQueryEngine) Result(io.druid.query.Result) Supplier(com.google.common.base.Supplier) MapBasedInputRow(io.druid.data.input.MapBasedInputRow) Interval(org.joda.time.Interval) Test(org.junit.Test)

Aggregations

Supplier (com.google.common.base.Supplier)51 IOException (java.io.IOException)14 Test (org.junit.Test)11 ImmutableMap (com.google.common.collect.ImmutableMap)8 Map (java.util.Map)8 Path (java.nio.file.Path)5 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Set (java.util.Set)5 VisibleForTesting (com.google.common.annotations.VisibleForTesting)4 ImmutableList (com.google.common.collect.ImmutableList)4 ImmutableSet (com.google.common.collect.ImmutableSet)4 Committer (io.druid.data.input.Committer)4 ByteBuffer (java.nio.ByteBuffer)4 Optional (java.util.Optional)4 SourcePath (com.facebook.buck.rules.SourcePath)3 InputRow (io.druid.data.input.InputRow)3 AggregatorFactory (io.druid.query.aggregation.AggregatorFactory)3 File (java.io.File)3 HashMap (java.util.HashMap)3