Search in sources :

Example 6 with RamAccounting

use of io.crate.breaker.RamAccounting in project crate by crate.

the class TransportFetchOperationTest method test_no_ram_accounting_on_empty_fetch_ids_and_close.

@Test
public void test_no_ram_accounting_on_empty_fetch_ids_and_close() {
    RamAccounting ramAccounting = TransportFetchOperation.ramAccountingForIncomingResponse(RamAccounting.NO_ACCOUNTING, new IntObjectHashMap<>(), true);
    assertThat(ramAccounting, is(RamAccounting.NO_ACCOUNTING));
}
Also used : BlockBasedRamAccounting(io.crate.breaker.BlockBasedRamAccounting) RamAccounting(io.crate.breaker.RamAccounting) Test(org.junit.Test)

Example 7 with RamAccounting

use of io.crate.breaker.RamAccounting in project crate by crate.

the class PercentileAggregationTest method testSingleItemFractionsArgumentResultsInArrayResult.

@Test
public void testSingleItemFractionsArgumentResultsInArrayResult() {
    AggregationFunction impl = (AggregationFunction<?, ?>) nodeCtx.functions().getQualified(Signature.aggregate(PercentileAggregation.NAME, DataTypes.LONG.getTypeSignature(), DataTypes.DOUBLE_ARRAY.getTypeSignature(), DataTypes.DOUBLE_ARRAY.getTypeSignature()), List.of(DataTypes.LONG, DataTypes.DOUBLE_ARRAY), DataTypes.DOUBLE_ARRAY);
    RamAccounting ramAccounting = RamAccounting.NO_ACCOUNTING;
    Object state = impl.newState(ramAccounting, Version.CURRENT, Version.CURRENT, memoryManager);
    Literal<List<Double>> fractions = Literal.of(Collections.singletonList(0.95D), DataTypes.DOUBLE_ARRAY);
    impl.iterate(ramAccounting, memoryManager, state, Literal.of(10L), fractions);
    impl.iterate(ramAccounting, memoryManager, state, Literal.of(20L), fractions);
    Object result = impl.terminatePartial(ramAccounting, state);
    assertThat("result must be an array", result, instanceOf(List.class));
}
Also used : AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) RamAccounting(io.crate.breaker.RamAccounting) List(java.util.List) Test(org.junit.Test)

Example 8 with RamAccounting

use of io.crate.breaker.RamAccounting in project crate by crate.

the class CollectTaskTest method setUp.

@Before
public void setUp() throws Exception {
    super.setUp();
    localNodeId = "dummyLocalNodeId";
    collectPhase = Mockito.mock(RoutedCollectPhase.class);
    Routing routing = Mockito.mock(Routing.class);
    when(routing.containsShards(localNodeId)).thenReturn(true);
    when(collectPhase.routing()).thenReturn(routing);
    when(collectPhase.maxRowGranularity()).thenReturn(RowGranularity.DOC);
    collectOperation = mock(MapSideDataCollectOperation.class);
    Mockito.doAnswer(new Answer<>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Runnable runnable = invocation.getArgument(0);
            runnable.run();
            return null;
        }
    }).when(collectOperation).launch(Mockito.any(), Mockito.anyString());
    consumer = new TestingRowConsumer();
    collectTask = new CollectTask(collectPhase, CoordinatorTxnCtx.systemTransactionContext(), collectOperation, RamAccounting.NO_ACCOUNTING, ramAccounting -> new OnHeapMemoryManager(ramAccounting::addBytes), consumer, mock(SharedShardContexts.class), Version.CURRENT, 4096);
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) BatchIterator(io.crate.data.BatchIterator) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Routing(io.crate.metadata.Routing) SharedShardContexts(io.crate.execution.jobs.SharedShardContexts) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ESTestCase(org.elasticsearch.test.ESTestCase) Before(org.junit.Before) JobKilledException(io.crate.exceptions.JobKilledException) InMemoryBatchIterator(io.crate.data.InMemoryBatchIterator) RoutedCollectPhase(io.crate.execution.dsl.phases.RoutedCollectPhase) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) RamAccounting(io.crate.breaker.RamAccounting) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito(org.mockito.Mockito) Exceptions(io.crate.exceptions.Exceptions) Version(org.elasticsearch.Version) RowGranularity(io.crate.metadata.RowGranularity) Row(io.crate.data.Row) Matchers.is(org.hamcrest.Matchers.is) OnHeapMemoryManager(io.crate.memory.OnHeapMemoryManager) RefCountedItem(io.crate.common.collections.RefCountedItem) TestingRowConsumer(io.crate.testing.TestingRowConsumer) SentinelRow(io.crate.data.SentinelRow) Mockito.mock(org.mockito.Mockito.mock) IndexSearcher(org.apache.lucene.search.IndexSearcher) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) OnHeapMemoryManager(io.crate.memory.OnHeapMemoryManager) Routing(io.crate.metadata.Routing) InvocationOnMock(org.mockito.invocation.InvocationOnMock) RoutedCollectPhase(io.crate.execution.dsl.phases.RoutedCollectPhase) TestingRowConsumer(io.crate.testing.TestingRowConsumer) Before(org.junit.Before)

Example 9 with RamAccounting

use of io.crate.breaker.RamAccounting in project crate by crate.

the class ShardingUpsertExecutor method apply.

@Override
public CompletableFuture<? extends Iterable<Row>> apply(BatchIterator<Row> batchIterator) {
    final ConcurrencyLimit nodeLimit = nodeLimits.get(localNode);
    long startTime = nodeLimit.startSample();
    var isUsedBytesOverThreshold = new IsUsedBytesOverThreshold(queryCircuitBreaker, nodeLimit);
    var reqBatchIterator = BatchIterators.partition(batchIterator, bulkSize, () -> new ShardedRequests<>(requestFactory, ramAccounting), grouper, bulkShardCreationLimiter.or(isUsedBytesOverThreshold));
    // If IO is involved the source iterator should pause when the target node reaches a concurrent job counter limit.
    // Without IO, we assume that the source iterates over in-memory structures which should be processed as
    // fast as possible to free resources.
    Predicate<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>> shouldPause = this::shouldPauseOnPartitionCreation;
    if (batchIterator.hasLazyResultSet()) {
        shouldPause = shouldPause.or(this::shouldPauseOnTargetNodeJobsCounter).or(isUsedBytesOverThreshold);
    }
    BatchIteratorBackpressureExecutor<ShardedRequests<ShardUpsertRequest, ShardUpsertRequest.Item>, UpsertResults> executor = new BatchIteratorBackpressureExecutor<>(jobId, scheduler, this.executor, reqBatchIterator, this::execute, resultCollector.combiner(), resultCollector.supplier().get(), shouldPause, earlyTerminationCondition, earlyTerminationExceptionGenerator, this::getMaxLastRttInMs);
    return executor.consumeIteratorAndExecute().thenApply(upsertResults -> resultCollector.finisher().apply(upsertResults)).whenComplete((res, err) -> {
        nodeLimit.onSample(startTime, err != null);
    });
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Item(io.crate.execution.dml.upsert.ShardUpsertRequest.Item) ClusterService(org.elasticsearch.cluster.service.ClusterService) CollectExpression(io.crate.execution.engine.collect.CollectExpression) CompletableFuture(java.util.concurrent.CompletableFuture) BatchIterator(io.crate.data.BatchIterator) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) NodeLimits(io.crate.execution.jobs.NodeLimits) BackoffPolicy(org.elasticsearch.action.bulk.BackoffPolicy) TransportCreatePartitionsAction(org.elasticsearch.action.admin.indices.create.TransportCreatePartitionsAction) RetryListener(io.crate.execution.support.RetryListener) BlockBasedRamAccounting(io.crate.breaker.BlockBasedRamAccounting) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) TypeGuessEstimateRowSize(io.crate.breaker.TypeGuessEstimateRowSize) ConcurrencyLimit(io.crate.concurrent.limits.ConcurrencyLimit) BulkRequestExecutor(org.elasticsearch.action.bulk.BulkRequestExecutor) ToLongFunction(java.util.function.ToLongFunction) Nullable(javax.annotation.Nullable) FutureActionListener(io.crate.action.FutureActionListener) Iterator(java.util.Iterator) Setting(org.elasticsearch.common.settings.Setting) Executor(java.util.concurrent.Executor) Predicate(java.util.function.Predicate) UUID(java.util.UUID) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) RamAccounting(io.crate.breaker.RamAccounting) TimeUnit(java.util.concurrent.TimeUnit) ShardResponse(io.crate.execution.dml.ShardResponse) ShardUpsertRequest(io.crate.execution.dml.upsert.ShardUpsertRequest) List(java.util.List) Logger(org.apache.logging.log4j.Logger) BatchIterators(io.crate.data.BatchIterators) Row(io.crate.data.Row) TimeValue(io.crate.common.unit.TimeValue) RowShardResolver(io.crate.execution.engine.collect.RowShardResolver) LogManager(org.apache.logging.log4j.LogManager) CreatePartitionsRequest(org.elasticsearch.action.admin.indices.create.CreatePartitionsRequest) ActionListener(org.elasticsearch.action.ActionListener) ConcurrencyLimit(io.crate.concurrent.limits.ConcurrencyLimit) ShardUpsertRequest(io.crate.execution.dml.upsert.ShardUpsertRequest)

Example 10 with RamAccounting

use of io.crate.breaker.RamAccounting in project crate by crate.

the class NodeFetchOperation method doFetch.

private CompletableFuture<? extends IntObjectMap<StreamBucket>> doFetch(FetchTask fetchTask, IntObjectMap<IntArrayList> toFetch) throws Exception {
    HashMap<RelationName, TableFetchInfo> tableFetchInfos = getTableFetchInfos(fetchTask);
    // RamAccounting is per doFetch call instead of per FetchTask/fetchPhase
    // To be able to free up the memory count when the operation is complete
    final var ramAccounting = ConcurrentRamAccounting.forCircuitBreaker("fetch-" + fetchTask.id(), circuitBreaker);
    ArrayList<Supplier<StreamBucket>> collectors = new ArrayList<>(toFetch.size());
    for (IntObjectCursor<IntArrayList> toFetchCursor : toFetch) {
        final int readerId = toFetchCursor.key;
        final IntArrayList docIds = toFetchCursor.value;
        RelationName ident = fetchTask.tableIdent(readerId);
        final TableFetchInfo tfi = tableFetchInfos.get(ident);
        assert tfi != null : "tfi must not be null";
        var collector = tfi.createCollector(readerId, new BlockBasedRamAccounting(ramAccounting::addBytes, BlockBasedRamAccounting.MAX_BLOCK_SIZE_IN_BYTES));
        collectors.add(() -> collector.collect(docIds));
    }
    return ThreadPools.runWithAvailableThreads(executor, ThreadPools.numIdleThreads(executor, numProcessors), collectors).thenApply(buckets -> {
        var toFetchIt = toFetch.iterator();
        assert toFetch.size() == buckets.size() : "Must have a bucket per reader and they must be in the same order";
        IntObjectHashMap<StreamBucket> bucketByReader = new IntObjectHashMap<>(toFetch.size());
        for (var bucket : buckets) {
            assert toFetchIt.hasNext() : "toFetchIt must have an element if there is one in buckets";
            int readerId = toFetchIt.next().key;
            bucketByReader.put(readerId, bucket);
        }
        return bucketByReader;
    }).whenComplete((result, err) -> ramAccounting.close());
}
Also used : IntObjectCursor(com.carrotsearch.hppc.cursors.IntObjectCursor) StreamBucket(io.crate.execution.engine.distribution.StreamBucket) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) RelationName(io.crate.metadata.RelationName) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) RootTask(io.crate.execution.jobs.RootTask) Supplier(java.util.function.Supplier) JobsLogs(io.crate.execution.engine.collect.stats.JobsLogs) ArrayList(java.util.ArrayList) BlockBasedRamAccounting(io.crate.breaker.BlockBasedRamAccounting) IntArrayList(com.carrotsearch.hppc.IntArrayList) Symbols(io.crate.expression.symbol.Symbols) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) Nullable(javax.annotation.Nullable) LuceneReferenceResolver(io.crate.expression.reference.doc.lucene.LuceneReferenceResolver) Streamer(io.crate.Streamer) Collection(java.util.Collection) IndexService(org.elasticsearch.index.IndexService) Reference(io.crate.metadata.Reference) UUID(java.util.UUID) RamAccounting(io.crate.breaker.RamAccounting) LuceneCollectorExpression(io.crate.expression.reference.doc.lucene.LuceneCollectorExpression) TasksService(io.crate.execution.jobs.TasksService) IntObjectMap(com.carrotsearch.hppc.IntObjectMap) ConcurrentRamAccounting(io.crate.breaker.ConcurrentRamAccounting) IntObjectHashMap(com.carrotsearch.hppc.IntObjectHashMap) SQLExceptions(io.crate.exceptions.SQLExceptions) ThreadPools(io.crate.execution.support.ThreadPools) IntObjectHashMap(com.carrotsearch.hppc.IntObjectHashMap) ArrayList(java.util.ArrayList) IntArrayList(com.carrotsearch.hppc.IntArrayList) BlockBasedRamAccounting(io.crate.breaker.BlockBasedRamAccounting) RelationName(io.crate.metadata.RelationName) Supplier(java.util.function.Supplier) IntArrayList(com.carrotsearch.hppc.IntArrayList)

Aggregations

RamAccounting (io.crate.breaker.RamAccounting)14 BlockBasedRamAccounting (io.crate.breaker.BlockBasedRamAccounting)7 Row (io.crate.data.Row)6 Nullable (javax.annotation.Nullable)6 CircuitBreaker (org.elasticsearch.common.breaker.CircuitBreaker)6 RowAccountingWithEstimators (io.crate.breaker.RowAccountingWithEstimators)4 ArrayList (java.util.ArrayList)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 Test (org.junit.Test)4 IntArrayList (com.carrotsearch.hppc.IntArrayList)3 IntObjectHashMap (com.carrotsearch.hppc.IntObjectHashMap)3 Streamer (io.crate.Streamer)3 ConcurrentRamAccounting (io.crate.breaker.ConcurrentRamAccounting)3 BatchIterator (io.crate.data.BatchIterator)3 NodeContext (io.crate.metadata.NodeContext)3 TransactionContext (io.crate.metadata.TransactionContext)3 List (java.util.List)3 IntObjectMap (com.carrotsearch.hppc.IntObjectMap)2 IntObjectCursor (com.carrotsearch.hppc.cursors.IntObjectCursor)2 Projector (io.crate.data.Projector)2