Search in sources :

Example 6 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project mule by mulesoft.

the class ExtensionNotificationsTestCase method sourceFiresNotificationsOnBackPressure.

@Test
public void sourceFiresNotificationsOnBackPressure() throws Exception {
    Latch latch = new Latch();
    String batchFailed = "BATCH_FAILED";
    setUpListener(notification -> {
        if (batchFailed.equals(notification.getAction().getIdentifier())) {
            latch.release();
        }
    });
    Flow flow = (Flow) getFlowConstruct("sourceNotificationsBackPressure");
    flow.start();
    latch.await(10000, MILLISECONDS);
    flow.stop();
    assertThat(listener.getNotifications(), hasSize(greaterThan(3)));
    // Find first BATCH_FAILED
    ExtensionNotification backPressureNotification = listener.getNotifications().stream().filter(n -> batchFailed.equals(n.getAction().getIdentifier())).findFirst().get();
    // Find matching event notifications
    List<ExtensionNotification> notifications = listener.getNotifications().stream().filter(n -> backPressureNotification.getEvent().getCorrelationId().equals(n.getEvent().getCorrelationId())).collect(toList());
    assertThat(notifications, hasSize(4));
    int batchNumber = (Integer) backPressureNotification.getData().getValue();
    ExtensionNotification notification1 = notifications.get(0);
    verifyNewBatch(notification1, batchNumber);
    ExtensionNotification notification2 = notifications.get(1);
    verifyNextBatch(notification2, 10L);
    ExtensionNotification notification3 = notifications.get(2);
    verifyNotificationAndValue(notification3, batchFailed, batchNumber);
    ExtensionNotification notification4 = notifications.get(3);
    verifyBatchTerminated(notification4, batchNumber);
}
Also used : PersonalInfo(org.mule.test.heisenberg.extension.model.PersonalInfo) AbstractExtensionFunctionalTestCase(org.mule.test.module.extension.AbstractExtensionFunctionalTestCase) Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ExtensionNotificationListener(org.mule.runtime.api.notification.ExtensionNotificationListener) ExtensionNotification(org.mule.runtime.api.notification.ExtensionNotification) Flow(org.mule.runtime.core.api.construct.Flow) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) Assert.assertThat(org.junit.Assert.assertThat) Consumer(java.util.function.Consumer) Inject(javax.inject.Inject) NotificationListenerRegistry(org.mule.runtime.api.notification.NotificationListenerRegistry) CountDownLatch(java.util.concurrent.CountDownLatch) Collectors.toList(java.util.stream.Collectors.toList) Latch(org.mule.runtime.api.util.concurrent.Latch) List(java.util.List) SimpleKnockeableDoor(org.mule.test.heisenberg.extension.model.SimpleKnockeableDoor) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) LinkedList(java.util.LinkedList) HeisenbergExtension(org.mule.test.heisenberg.extension.HeisenbergExtension) ExtensionNotification(org.mule.runtime.api.notification.ExtensionNotification) CountDownLatch(java.util.concurrent.CountDownLatch) Latch(org.mule.runtime.api.util.concurrent.Latch) Flow(org.mule.runtime.core.api.construct.Flow) Test(org.junit.Test)

Example 7 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project mule by mulesoft.

the class HeisenbergRouters method concurrentRouteExecutor.

public void concurrentRouteExecutor(WhenRoute when, RouterCompletionCallback callback) {
    Consumer<Chain> processor = (chain) -> {
        final Latch latch = new Latch();
        chain.process((result -> latch.release()), (error, result) -> latch.release());
        try {
            latch.await(10000, MILLISECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
    Thread first = new Thread(() -> processor.accept(when.getChain()));
    Thread second = new Thread(() -> processor.accept(when.getChain()));
    first.start();
    second.start();
    try {
        first.join();
        second.join();
    } catch (Exception e) {
        callback.error(e);
    }
    callback.success(Result.builder().output("SUCCESS").build());
}
Also used : Summary(org.mule.runtime.extension.api.annotation.param.display.Summary) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException) Attribute(org.mule.test.heisenberg.extension.model.Attribute) Preconditions.checkArgument(org.mule.runtime.api.util.Preconditions.checkArgument) OtherwiseRoute(org.mule.test.heisenberg.extension.route.OtherwiseRoute) RouterCompletionCallback(org.mule.runtime.extension.api.runtime.process.RouterCompletionCallback) DrugKillingRoute(org.mule.test.heisenberg.extension.route.DrugKillingRoute) AfterCall(org.mule.test.heisenberg.extension.route.AfterCall) Collectors.toMap(java.util.stream.Collectors.toMap) MuleException(org.mule.runtime.api.exception.MuleException) BeforeCall(org.mule.test.heisenberg.extension.route.BeforeCall) Map(java.util.Map) Chain(org.mule.runtime.extension.api.runtime.route.Chain) VoidCompletionCallback(org.mule.runtime.extension.api.runtime.process.VoidCompletionCallback) Optional(org.mule.runtime.extension.api.annotation.param.Optional) Parameter(org.mule.runtime.extension.api.annotation.param.Parameter) Disposable(org.mule.runtime.api.lifecycle.Disposable) Startable(org.mule.runtime.api.lifecycle.Startable) I18nMessageFactory.createStaticMessage(org.mule.runtime.api.i18n.I18nMessageFactory.createStaticMessage) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Initialisable(org.mule.runtime.api.lifecycle.Initialisable) Result(org.mule.runtime.extension.api.runtime.operation.Result) Consumer(java.util.function.Consumer) Latch(org.mule.runtime.api.util.concurrent.Latch) List(java.util.List) WhenRoute(org.mule.test.heisenberg.extension.route.WhenRoute) Stoppable(org.mule.runtime.api.lifecycle.Stoppable) NullSafe(org.mule.runtime.extension.api.annotation.param.NullSafe) KillingRoute(org.mule.test.heisenberg.extension.route.KillingRoute) NOT_SUPPORTED(org.mule.runtime.api.meta.ExpressionSupport.NOT_SUPPORTED) Expression(org.mule.runtime.extension.api.annotation.Expression) Chain(org.mule.runtime.extension.api.runtime.route.Chain) Latch(org.mule.runtime.api.util.concurrent.Latch) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException) MuleException(org.mule.runtime.api.exception.MuleException)

Example 8 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project presto by prestodb.

the class AbstractTestParquetReader method testCaching.

@Test
public void testCaching() throws Exception {
    Cache<ParquetDataSourceId, ParquetFileMetadata> parquetFileMetadataCache = CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, metadata) -> ((ParquetFileMetadata) metadata).getMetadataSize()).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build();
    ParquetMetadataSource parquetMetadataSource = new CachingParquetMetadataSource(parquetFileMetadataCache, new MetadataReader());
    try (ParquetTester.TempFile tempFile = new ParquetTester.TempFile("test", "parquet")) {
        Iterable<Integer> values = intsBetween(0, 10);
        Iterator<?>[] readValues = stream(new Iterable<?>[] { values }).map(Iterable::iterator).toArray(size -> new Iterator<?>[size]);
        List<String> columnNames = singletonList("column1");
        List<Type> columnTypes = singletonList(INTEGER);
        writeParquetFileFromPresto(tempFile.getFile(), columnTypes, columnNames, readValues, 10, CompressionCodecName.GZIP);
        testSingleRead(new Iterable<?>[] { values }, columnNames, columnTypes, parquetMetadataSource, tempFile.getFile());
        assertEquals(parquetFileMetadataCache.stats().missCount(), 1);
        assertEquals(parquetFileMetadataCache.stats().hitCount(), 0);
        testSingleRead(new Iterable<?>[] { values }, columnNames, columnTypes, parquetMetadataSource, tempFile.getFile());
        assertEquals(parquetFileMetadataCache.stats().missCount(), 1);
        assertEquals(parquetFileMetadataCache.stats().hitCount(), 1);
        testSingleRead(new Iterable<?>[] { values }, columnNames, columnTypes, parquetMetadataSource, tempFile.getFile());
        assertEquals(parquetFileMetadataCache.stats().missCount(), 1);
        assertEquals(parquetFileMetadataCache.stats().hitCount(), 2);
        parquetFileMetadataCache.invalidateAll();
        testSingleRead(new Iterable<?>[] { values }, columnNames, columnTypes, parquetMetadataSource, tempFile.getFile());
        assertEquals(parquetFileMetadataCache.stats().missCount(), 2);
        assertEquals(parquetFileMetadataCache.stats().hitCount(), 2);
        testSingleRead(new Iterable<?>[] { values }, columnNames, columnTypes, parquetMetadataSource, tempFile.getFile());
        assertEquals(parquetFileMetadataCache.stats().missCount(), 2);
        assertEquals(parquetFileMetadataCache.stats().hitCount(), 3);
    }
}
Also used : DateTimeZone(org.joda.time.DateTimeZone) Arrays(java.util.Arrays) JavaHiveDecimalObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaHiveDecimalObjectInspector) VarcharType.createUnboundedVarcharType(com.facebook.presto.common.type.VarcharType.createUnboundedVarcharType) PrimitiveObjectInspectorFactory.javaByteObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteObjectInspector) PrimitiveObjectInspectorFactory.javaLongObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaLongObjectInspector) Test(org.testng.annotations.Test) HIVE_STORAGE_TIME_ZONE(com.facebook.presto.hive.parquet.ParquetTester.HIVE_STORAGE_TIME_ZONE) PrimitiveObjectInspectorFactory.javaTimestampObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaTimestampObjectInspector) PrimitiveObjectInspectorFactory.javaDateObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDateObjectInspector) Collections.singletonList(java.util.Collections.singletonList) BigDecimal(java.math.BigDecimal) Iterables.cycle(com.google.common.collect.Iterables.cycle) Arrays.asList(java.util.Arrays.asList) MessageTypeParser(org.apache.parquet.schema.MessageTypeParser) Map(java.util.Map) BigInteger(java.math.BigInteger) ObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector) Functions.compose(com.google.common.base.Functions.compose) ParquetFileMetadata(com.facebook.presto.parquet.cache.ParquetFileMetadata) PrimitiveObjectInspectorFactory.javaByteArrayObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteArrayObjectInspector) PrimitiveObjectInspectorFactory.javaFloatObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaFloatObjectInspector) PrimitiveObjectInspectorFactory.javaDoubleObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDoubleObjectInspector) Range(com.google.common.collect.Range) ParquetMetadataSource(com.facebook.presto.parquet.cache.ParquetMetadataSource) Statistics(org.apache.parquet.format.Statistics) MAX_PRECISION(com.facebook.presto.common.type.Decimals.MAX_PRECISION) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Stream(java.util.stream.Stream) SqlTimestamp(com.facebook.presto.common.type.SqlTimestamp) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) CompressionCodecName(org.apache.parquet.hadoop.metadata.CompressionCodecName) StructuralTestUtil.mapType(com.facebook.presto.tests.StructuralTestUtil.mapType) PrimitiveObjectInspectorFactory.javaIntObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaIntObjectInspector) MetadataReader(com.facebook.presto.parquet.cache.MetadataReader) ContiguousSet(com.google.common.collect.ContiguousSet) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) MINUTES(java.util.concurrent.TimeUnit.MINUTES) DATE(com.facebook.presto.common.type.DateType.DATE) REAL(com.facebook.presto.common.type.RealType.REAL) ArrayList(java.util.ArrayList) SqlDate(com.facebook.presto.common.type.SqlDate) PrimitiveObjectInspectorFactory.javaShortObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaShortObjectInspector) SqlVarbinary(com.facebook.presto.common.type.SqlVarbinary) DiscreteDomain(com.google.common.collect.DiscreteDomain) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) ArrayType(com.facebook.presto.common.type.ArrayType) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) RowType.field(com.facebook.presto.common.type.RowType.field) ParquetTester.insertNullEvery(com.facebook.presto.hive.parquet.ParquetTester.insertNullEvery) AbstractIterator(com.google.common.collect.AbstractIterator) ObjectInspectorFactory.getStandardStructObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardStructObjectInspector) UTC_KEY(com.facebook.presto.common.type.TimeZoneKey.UTC_KEY) DecimalTypeInfo(org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo) SMALLINT(com.facebook.presto.common.type.SmallintType.SMALLINT) ParquetTester.testSingleRead(com.facebook.presto.hive.parquet.ParquetTester.testSingleRead) RowType(com.facebook.presto.common.type.RowType) PrimitiveType(org.apache.parquet.schema.PrimitiveType) Iterables.transform(com.google.common.collect.Iterables.transform) Random(java.util.Random) Duration(io.airlift.units.Duration) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) SESSION(com.facebook.presto.testing.TestingConnectorSession.SESSION) Iterables.concat(com.google.common.collect.Iterables.concat) SqlDecimal(com.facebook.presto.common.type.SqlDecimal) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) BINARY(org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.BINARY) BeforeClass(org.testng.annotations.BeforeClass) Timestamp(java.sql.Timestamp) ParquetTester.writeParquetFileFromPresto(com.facebook.presto.hive.parquet.ParquetTester.writeParquetFileFromPresto) UUID(java.util.UUID) Iterables.limit(com.google.common.collect.Iterables.limit) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) MessageType(org.apache.parquet.schema.MessageType) DataSize(io.airlift.units.DataSize) List(java.util.List) LocalDate(java.time.LocalDate) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) Arrays.stream(java.util.Arrays.stream) PrimitiveObjectInspectorFactory.javaBooleanObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaBooleanObjectInspector) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) DateTimeTestingUtils.sqlTimestampOf(com.facebook.presto.testing.DateTimeTestingUtils.sqlTimestampOf) Assert.assertEquals(org.testng.Assert.assertEquals) Shorts(com.google.common.primitives.Shorts) HashMap(java.util.HashMap) OPTIONAL(org.apache.parquet.schema.Type.Repetition.OPTIONAL) AbstractSequentialIterator(com.google.common.collect.AbstractSequentialIterator) Level(java.util.logging.Level) ImmutableList(com.google.common.collect.ImmutableList) ParquetDataSourceId(com.facebook.presto.parquet.ParquetDataSourceId) ObjectInspectorFactory.getStandardMapObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardMapObjectInspector) Type(com.facebook.presto.common.type.Type) MessageTypeParser.parseMessageType(org.apache.parquet.schema.MessageTypeParser.parseMessageType) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) ObjectInspectorFactory.getStandardListObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardListObjectInspector) Date(java.sql.Date) CachingParquetMetadataSource(com.facebook.presto.parquet.cache.CachingParquetMetadataSource) HiveDecimal(org.apache.hadoop.hive.common.type.HiveDecimal) PrimitiveObjectInspectorFactory.javaStringObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaStringObjectInspector) Cache(com.google.common.cache.Cache) Collections(java.util.Collections) DecimalType.createDecimalType(com.facebook.presto.common.type.DecimalType.createDecimalType) CachingParquetMetadataSource(com.facebook.presto.parquet.cache.CachingParquetMetadataSource) ParquetDataSourceId(com.facebook.presto.parquet.ParquetDataSourceId) ParquetFileMetadata(com.facebook.presto.parquet.cache.ParquetFileMetadata) MetadataReader(com.facebook.presto.parquet.cache.MetadataReader) Duration(io.airlift.units.Duration) BigInteger(java.math.BigInteger) VarcharType.createUnboundedVarcharType(com.facebook.presto.common.type.VarcharType.createUnboundedVarcharType) StructuralTestUtil.mapType(com.facebook.presto.tests.StructuralTestUtil.mapType) ArrayType(com.facebook.presto.common.type.ArrayType) RowType(com.facebook.presto.common.type.RowType) PrimitiveType(org.apache.parquet.schema.PrimitiveType) MessageType(org.apache.parquet.schema.MessageType) Type(com.facebook.presto.common.type.Type) MessageTypeParser.parseMessageType(org.apache.parquet.schema.MessageTypeParser.parseMessageType) DecimalType.createDecimalType(com.facebook.presto.common.type.DecimalType.createDecimalType) DataSize(io.airlift.units.DataSize) AbstractIterator(com.google.common.collect.AbstractIterator) AbstractSequentialIterator(com.google.common.collect.AbstractSequentialIterator) Iterator(java.util.Iterator) ParquetMetadataSource(com.facebook.presto.parquet.cache.ParquetMetadataSource) CachingParquetMetadataSource(com.facebook.presto.parquet.cache.CachingParquetMetadataSource) Test(org.testng.annotations.Test)

Example 9 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project presto by prestodb.

the class TestExchangeClient method testInitialRequestLimit.

@Test
public void testInitialRequestLimit() {
    DataSize bufferCapacity = new DataSize(16, MEGABYTE);
    DataSize maxResponseSize = new DataSize(DEFAULT_MAX_PAGE_SIZE_IN_BYTES, BYTE);
    CountDownLatch countDownLatch = new CountDownLatch(1);
    MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize) {

        @Override
        public Response handle(Request request) {
            if (!awaitUninterruptibly(countDownLatch, 10, SECONDS)) {
                throw new UncheckedTimeoutException();
            }
            return super.handle(request);
        }
    };
    List<URI> locations = new ArrayList<>();
    int numLocations = 16;
    List<DataSize> expectedMaxSizes = new ArrayList<>();
    // add pages
    for (int i = 0; i < numLocations; i++) {
        URI location = URI.create("http://localhost:" + (8080 + i));
        locations.add(location);
        processor.addPage(location, createPage(DEFAULT_MAX_PAGE_SIZE_IN_BYTES));
        processor.addPage(location, createPage(DEFAULT_MAX_PAGE_SIZE_IN_BYTES));
        processor.addPage(location, createPage(DEFAULT_MAX_PAGE_SIZE_IN_BYTES));
        processor.setComplete(location);
        expectedMaxSizes.add(maxResponseSize);
    }
    try (ExchangeClient exchangeClient = createExchangeClient(processor, bufferCapacity, maxResponseSize)) {
        for (int i = 0; i < numLocations; i++) {
            exchangeClient.addLocation(locations.get(i), TaskId.valueOf("taskid.0.0." + i));
        }
        exchangeClient.noMoreLocations();
        assertFalse(exchangeClient.isClosed());
        long start = System.nanoTime();
        countDownLatch.countDown();
        // wait for a page to be fetched
        do {
            // there is no thread coordination here, so sleep is the best we can do
            assertLessThan(Duration.nanosSince(start), new Duration(5, TimeUnit.SECONDS));
            sleepUninterruptibly(100, MILLISECONDS);
        } while (exchangeClient.getStatus().getBufferedPages() < 16);
        // Client should have sent 16 requests for a single page (0) and gotten them back
        // The memory limit should be hit immediately and then it doesn't fetch the third page from each
        assertEquals(exchangeClient.getStatus().getBufferedPages(), 16);
        assertTrue(exchangeClient.getStatus().getBufferedBytes() > 0);
        List<PageBufferClientStatus> pageBufferClientStatuses = exchangeClient.getStatus().getPageBufferClientStatuses();
        assertEquals(16, pageBufferClientStatuses.stream().filter(status -> status.getPagesReceived() == 1).mapToInt(PageBufferClientStatus::getPagesReceived).sum());
        assertEquals(processor.getRequestMaxSizes(), expectedMaxSizes);
        for (int i = 0; i < numLocations * 3; i++) {
            assertNotNull(getNextPage(exchangeClient));
        }
        do {
            // there is no thread coordination here, so sleep is the best we can do
            assertLessThan(Duration.nanosSince(start), new Duration(5, TimeUnit.SECONDS));
            sleepUninterruptibly(100, MILLISECONDS);
        } while (processor.getRequestMaxSizes().size() < 64);
        for (int i = 0; i < 48; i++) {
            expectedMaxSizes.add(maxResponseSize);
        }
        assertEquals(processor.getRequestMaxSizes(), expectedMaxSizes);
    }
}
Also used : TestingPagesSerdeFactory.testingPagesSerde(com.facebook.presto.execution.buffer.TestingPagesSerdeFactory.testingPagesSerde) Page(com.facebook.presto.common.Page) SerializedPage(com.facebook.presto.spi.page.SerializedPage) Test(org.testng.annotations.Test) Maps.uniqueIndex(com.google.common.collect.Maps.uniqueIndex) BlockAssertions(com.facebook.presto.block.BlockAssertions) Duration(io.airlift.units.Duration) Assertions.assertLessThan(com.facebook.airlift.testing.Assertions.assertLessThan) Uninterruptibles.awaitUninterruptibly(com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly) Executors.newScheduledThreadPool(java.util.concurrent.Executors.newScheduledThreadPool) TestingHttpClient(com.facebook.airlift.http.client.testing.TestingHttpClient) Response(com.facebook.airlift.http.client.Response) URI(java.net.URI) Assert.assertFalse(org.testng.Assert.assertFalse) DEFAULT_MAX_PAGE_SIZE_IN_BYTES(com.facebook.presto.common.block.PageBuilderStatus.DEFAULT_MAX_PAGE_SIZE_IN_BYTES) ImmutableMap(com.google.common.collect.ImmutableMap) BeforeClass(org.testng.annotations.BeforeClass) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Assert.assertNotNull(org.testng.Assert.assertNotNull) Uninterruptibles.sleepUninterruptibly(com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly) Executors(java.util.concurrent.Executors) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) Threads.daemonThreadsNamed(com.facebook.airlift.concurrent.Threads.daemonThreadsNamed) CountDownLatch(java.util.concurrent.CountDownLatch) DataSize(io.airlift.units.DataSize) List(java.util.List) MoreFutures.tryGetFutureValue(com.facebook.airlift.concurrent.MoreFutures.tryGetFutureValue) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assert.assertNull(org.testng.Assert.assertNull) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) Assert.assertEquals(org.testng.Assert.assertEquals) MINUTES(java.util.concurrent.TimeUnit.MINUTES) PrestoException(com.facebook.presto.spi.PrestoException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) SimpleLocalMemoryContext(com.facebook.presto.memory.context.SimpleLocalMemoryContext) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) AggregatedMemoryContext.newSimpleAggregatedMemoryContext(com.facebook.presto.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext) ExecutorService(java.util.concurrent.ExecutorService) AfterClass(org.testng.annotations.AfterClass) TimeUnit(java.util.concurrent.TimeUnit) Futures(com.google.common.util.concurrent.Futures) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) Request(com.facebook.airlift.http.client.Request) PagesSerde(com.facebook.presto.spi.page.PagesSerde) TaskId(com.facebook.presto.execution.TaskId) Assert.assertTrue(org.testng.Assert.assertTrue) BYTE(io.airlift.units.DataSize.Unit.BYTE) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Request(com.facebook.airlift.http.client.Request) ArrayList(java.util.ArrayList) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) Duration(io.airlift.units.Duration) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) DataSize(io.airlift.units.DataSize) Test(org.testng.annotations.Test)

Example 10 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project presto by prestodb.

the class AbstractTestOrcReader method testCaching.

@Test
public void testCaching() throws Exception {
    Cache<OrcDataSourceId, OrcFileTail> orcFileTailCache = CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, tail) -> ((OrcFileTail) tail).getFooterSize() + ((OrcFileTail) tail).getMetadataSize()).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build();
    OrcFileTailSource orcFileTailSource = new CachingOrcFileTailSource(new StorageOrcFileTailSource(), orcFileTailCache);
    Cache<StripeId, Slice> stripeFootercache = CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, footer) -> ((Slice) footer).length()).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build();
    Cache<StripeStreamId, Slice> stripeStreamCache = CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, stream) -> ((Slice) stream).length()).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build();
    Optional<Cache<StripeStreamId, List<RowGroupIndex>>> rowGroupIndexCache = Optional.of(CacheBuilder.newBuilder().maximumWeight(new DataSize(1, MEGABYTE).toBytes()).weigher((id, rowGroupIndices) -> toIntExact(((List<RowGroupIndex>) rowGroupIndices).stream().mapToLong(RowGroupIndex::getRetainedSizeInBytes).sum())).expireAfterAccess(new Duration(10, MINUTES).toMillis(), MILLISECONDS).recordStats().build());
    StripeMetadataSource stripeMetadataSource = new CachingStripeMetadataSource(new StorageStripeMetadataSource(), stripeFootercache, stripeStreamCache, rowGroupIndexCache);
    try (TempFile tempFile = createTempFile(10001)) {
        OrcBatchRecordReader storageReader = createCustomOrcRecordReader(tempFile, ORC, OrcPredicate.TRUE, ImmutableList.of(BIGINT), INITIAL_BATCH_SIZE, orcFileTailSource, stripeMetadataSource, true, ImmutableMap.of(), false);
        assertEquals(orcFileTailCache.stats().missCount(), 1);
        assertEquals(orcFileTailCache.stats().hitCount(), 0);
        OrcBatchRecordReader cacheReader = createCustomOrcRecordReader(tempFile, ORC, OrcPredicate.TRUE, ImmutableList.of(BIGINT), INITIAL_BATCH_SIZE, orcFileTailSource, stripeMetadataSource, true, ImmutableMap.of(), false);
        assertEquals(orcFileTailCache.stats().missCount(), 1);
        assertEquals(orcFileTailCache.stats().hitCount(), 1);
        assertEquals(storageReader.getRetainedSizeInBytes(), cacheReader.getRetainedSizeInBytes());
        assertEquals(storageReader.getFileRowCount(), cacheReader.getFileRowCount());
        assertEquals(storageReader.getSplitLength(), cacheReader.getSplitLength());
        storageReader.nextBatch();
        assertEquals(stripeFootercache.stats().missCount(), 1);
        assertEquals(stripeFootercache.stats().hitCount(), 0);
        assertEquals(stripeStreamCache.stats().missCount(), 2);
        assertEquals(stripeStreamCache.stats().hitCount(), 0);
        assertEquals(rowGroupIndexCache.get().stats().missCount(), 1);
        assertEquals(rowGroupIndexCache.get().stats().hitCount(), 0);
        cacheReader.nextBatch();
        assertEquals(stripeFootercache.stats().missCount(), 1);
        assertEquals(stripeFootercache.stats().hitCount(), 1);
        assertEquals(stripeStreamCache.stats().missCount(), 2);
        assertEquals(stripeStreamCache.stats().hitCount(), 2);
        assertEquals(rowGroupIndexCache.get().stats().missCount(), 1);
        assertEquals(rowGroupIndexCache.get().stats().hitCount(), 1);
        assertEquals(storageReader.readBlock(0).getInt(0), cacheReader.readBlock(0).getInt(0));
    }
}
Also used : RecordWriter(org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter) CharType.createCharType(com.facebook.presto.common.type.CharType.createCharType) DateTimeZone(org.joda.time.DateTimeZone) StripeId(com.facebook.presto.orc.StripeReader.StripeId) Writable(org.apache.hadoop.io.Writable) Test(org.testng.annotations.Test) Random(java.util.Random) ORC_12(com.facebook.presto.orc.OrcTester.Format.ORC_12) OrcSerde(org.apache.hadoop.hive.ql.io.orc.OrcSerde) Duration(io.airlift.units.Duration) SESSION(com.facebook.presto.testing.TestingConnectorSession.SESSION) Iterables.concat(com.google.common.collect.Iterables.concat) Iterables.cycle(com.google.common.collect.Iterables.cycle) RowGroupIndex(com.facebook.presto.orc.metadata.RowGroupIndex) HIVE_STORAGE_TIME_ZONE(com.facebook.presto.orc.OrcTester.HIVE_STORAGE_TIME_ZONE) CachingOrcFileTailSource(com.facebook.presto.orc.cache.CachingOrcFileTailSource) OrcTester.createOrcRecordWriter(com.facebook.presto.orc.OrcTester.createOrcRecordWriter) BigInteger(java.math.BigInteger) SqlDecimal(com.facebook.presto.common.type.SqlDecimal) ImmutableMap(com.google.common.collect.ImmutableMap) DOUBLE(com.facebook.presto.common.type.DoubleType.DOUBLE) Collections.nCopies(java.util.Collections.nCopies) BeforeClass(org.testng.annotations.BeforeClass) INITIAL_BATCH_SIZE(com.facebook.presto.orc.OrcReader.INITIAL_BATCH_SIZE) Range(com.google.common.collect.Range) StripeStreamId(com.facebook.presto.orc.StripeReader.StripeStreamId) Iterables.limit(com.google.common.collect.Iterables.limit) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Collectors(java.util.stream.Collectors) ORC(com.facebook.presto.orc.OrcEncoding.ORC) DataSize(io.airlift.units.DataSize) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) OrcTester.createCustomOrcRecordReader(com.facebook.presto.orc.OrcTester.createCustomOrcRecordReader) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) CompressionKind(com.facebook.presto.orc.metadata.CompressionKind) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) Builder(com.google.common.collect.ImmutableList.Builder) StructField(org.apache.hadoop.hive.serde2.objectinspector.StructField) DecimalType(com.facebook.presto.common.type.DecimalType) ContiguousSet(com.google.common.collect.ContiguousSet) Slice(io.airlift.slice.Slice) TINYINT(com.facebook.presto.common.type.TinyintType.TINYINT) VARCHAR(com.facebook.presto.common.type.VarcharType.VARCHAR) DateTimeTestingUtils.sqlTimestampOf(com.facebook.presto.testing.DateTimeTestingUtils.sqlTimestampOf) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) Assert.assertEquals(org.testng.Assert.assertEquals) TIMESTAMP(com.facebook.presto.common.type.TimestampType.TIMESTAMP) MINUTES(java.util.concurrent.TimeUnit.MINUTES) DATE(com.facebook.presto.common.type.DateType.DATE) REAL(com.facebook.presto.common.type.RealType.REAL) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) SqlDate(com.facebook.presto.common.type.SqlDate) ImmutableList(com.google.common.collect.ImmutableList) OrcFileTail(com.facebook.presto.orc.metadata.OrcFileTail) SqlVarbinary(com.facebook.presto.common.type.SqlVarbinary) DiscreteDomain(com.google.common.collect.DiscreteDomain) BOOLEAN(com.facebook.presto.common.type.BooleanType.BOOLEAN) CharType(com.facebook.presto.common.type.CharType) Math.toIntExact(java.lang.Math.toIntExact) OrcFileTailSource(com.facebook.presto.orc.cache.OrcFileTailSource) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) AbstractIterator(com.google.common.collect.AbstractIterator) IOException(java.io.IOException) VARBINARY(com.facebook.presto.common.type.VarbinaryType.VARBINARY) SettableStructObjectInspector(org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector) StorageOrcFileTailSource(com.facebook.presto.orc.cache.StorageOrcFileTailSource) Collectors.toList(java.util.stream.Collectors.toList) SMALLINT(com.facebook.presto.common.type.SmallintType.SMALLINT) Serializer(org.apache.hadoop.hive.serde2.Serializer) Cache(com.google.common.cache.Cache) SerDeException(org.apache.hadoop.hive.serde2.SerDeException) OrcTester.createSettableStructObjectInspector(com.facebook.presto.orc.OrcTester.createSettableStructObjectInspector) Collections(java.util.Collections) StripeStreamId(com.facebook.presto.orc.StripeReader.StripeStreamId) CachingOrcFileTailSource(com.facebook.presto.orc.cache.CachingOrcFileTailSource) OrcFileTailSource(com.facebook.presto.orc.cache.OrcFileTailSource) StorageOrcFileTailSource(com.facebook.presto.orc.cache.StorageOrcFileTailSource) StorageOrcFileTailSource(com.facebook.presto.orc.cache.StorageOrcFileTailSource) Duration(io.airlift.units.Duration) OrcFileTail(com.facebook.presto.orc.metadata.OrcFileTail) StripeId(com.facebook.presto.orc.StripeReader.StripeId) CachingOrcFileTailSource(com.facebook.presto.orc.cache.CachingOrcFileTailSource) RowGroupIndex(com.facebook.presto.orc.metadata.RowGroupIndex) Slice(io.airlift.slice.Slice) DataSize(io.airlift.units.DataSize) List(java.util.List) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toList(java.util.stream.Collectors.toList) Cache(com.google.common.cache.Cache) Test(org.testng.annotations.Test)

Aggregations

MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)55 List (java.util.List)34 Test (org.junit.Test)27 CountDownLatch (java.util.concurrent.CountDownLatch)22 ArrayList (java.util.ArrayList)20 Arrays (java.util.Arrays)14 Optional (java.util.Optional)14 Future (java.util.concurrent.Future)14 SECONDS (java.util.concurrent.TimeUnit.SECONDS)14 Before (org.junit.Before)13 Duration (io.airlift.units.Duration)11 Map (java.util.Map)10 ExecutorService (java.util.concurrent.ExecutorService)8 Context (android.content.Context)7 Math.toIntExact (java.lang.Math.toIntExact)7 Rule (org.junit.Rule)7 Threads.daemonThreadsNamed (com.facebook.airlift.concurrent.Threads.daemonThreadsNamed)6 Cache (com.google.common.cache.Cache)6 CacheBuilder (com.google.common.cache.CacheBuilder)6 IOException (java.io.IOException)6