You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by cw...@apache.org on 2025/09/04 00:26:34 UTC
(druid) branch master updated: experimental virtual storage fabric mode for historicals (#18176)
This is an automated email from the ASF dual-hosted git repository.
cwylie pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/druid.git
The following commit(s) were added to refs/heads/master by this push:
new 7f784db4fa8 experimental virtual storage fabric mode for historicals (#18176)
7f784db4fa8 is described below
commit 7f784db4fa8aafa03cb6c54230b9e83d6ab928f2
Author: Clint Wylie <cw...@apache.org>
AuthorDate: Wed Sep 3 17:26:27 2025 -0700
experimental virtual storage fabric mode for historicals (#18176)
changes:
* Added new `CacheEntry` abstraction to segment storage layer management, with methods to identify an entry, track byte size, as well as 'mount' and 'unmount' the cache entry when it is assigned to or removed from a storage location.
* rewrote `StorageLocation` and `SegmentLocalCacheManager` to work with the new `CacheEntry` abstraction
* `StorageLocation` can now store 'weak' references, which may be unmounted to reclaim space if new static or weak entries need to be added to the storage location. Eviction is handled using an algorithm based on SIEVE so that one hit wonders are less likely to evict popular entries
* added new config `druid.segmentCache.virtualStorage` to enable a 'virtual storage fabric' mode for historical servers. When ``druid.segmentCache.virtualStorage` is set to true, `SegmentLocalCacheManager` performs all segment loads as 'weak' loads. These segments are visible in the timeline, but are not downloaded until query processing. `druid.server.maxSize` can be set to a value much greater than the total of the individual storage locations, making the segment cache behave as an [...]
* added supporting config `druid.segmentCache.virtualStorageLoadThreads` to control behavior of the on demand download pool used to retrieve weak reference segments from deep storage, mainly to help tune ideal default value for this setting.
---
.../benchmark/IndexedTableJoinCursorBenchmark.java | 2 +-
.../druid/benchmark/JoinAndLookupBenchmark.java | 8 +-
.../embedded/query/QueryVirtualStorageTest.java | 239 ++++
.../druid/indexing/common/task/CompactionTask.java | 32 +-
.../indexing/input/DruidSegmentInputEntity.java | 5 +-
.../shuffle/LocalIntermediaryDataManager.java | 92 +-
.../common/task/CompactionTaskRunTest.java | 4 +
.../indexing/common/task/CompactionTaskTest.java | 20 +-
.../druid/indexing/common/task/IndexTaskTest.java | 2 +
.../AbstractMultiPhaseParallelIndexingTest.java | 3 +-
.../indexing/input/DruidSegmentReaderTest.java | 12 +
.../tools/ServerManagerForQueryErrorTest.java | 8 +-
.../ServerManagerForQueryErrorTest.java | 7 +-
.../msq/dart/worker/DartDataSegmentProvider.java | 10 +-
.../druid/msq/exec/TaskDataSegmentProvider.java | 28 +-
.../druid/msq/indexing/IndexerWorkerContext.java | 2 +-
.../druid/msq/querykit/BaseLeafFrameProcessor.java | 4 +-
.../msq/exec/TaskDataSegmentProviderTest.java | 196 +---
.../druid/msq/test/CalciteMSQTestsHelper.java | 3 +-
.../org/apache/druid/msq/test/MSQTestBase.java | 7 +-
.../druid/msq/test/MSQTestSegmentManager.java | 2 +-
.../druid/query/DataSegmentAndDescriptor.java | 48 +
.../query/expression/NestedDataExpressions.java | 2 +
.../segment/ReferenceCountedSegmentProvider.java | 143 +--
.../segment/ReferenceCountingCloseableObject.java | 8 +-
.../apache/druid/segment/SegmentMapFunction.java | 16 +-
.../org/apache/druid/segment/SegmentReference.java | 74 ++
.../segment/loading/AcquireSegmentAction.java | 91 ++
.../apache/druid/query/QueryRunnerTestHelper.java | 13 +-
.../RestrictAllTablesPolicyEnforcerTest.java | 5 +-
.../timeboundary/TimeBoundaryQueryRunnerTest.java | 18 +-
.../segment/ReferenceCountingSegmentTest.java | 2 +-
.../java/org/apache/druid/segment/TestHelper.java | 10 +
.../java/org/apache/druid/segment/TestIndex.java | 15 +-
.../join/BaseHashJoinSegmentCursorFactoryTest.java | 2 +-
.../join/HashJoinSegmentCursorFactoryTest.java | 12 +-
.../druid/segment/join/HashJoinSegmentTest.java | 4 +-
.../druid/segment/join/PostJoinCursorTest.java | 2 +-
.../apache/druid/client/cache/CachePopulator.java | 3 +-
.../apache/druid/segment/loading/CacheEntry.java | 52 +
.../segment/loading/CacheEntryIdentifier.java | 30 +
...stBytesUsedStorageLocationSelectorStrategy.java | 2 +-
.../loading/SegmentCacheEntryIdentifier.java | 59 +
.../druid/segment/loading/SegmentCacheManager.java | 143 ++-
.../druid/segment/loading/SegmentLoaderConfig.java | 34 +-
.../segment/loading/SegmentLocalCacheManager.java | 1115 ++++++++++++-------
.../druid/segment/loading/StorageLocation.java | 907 +++++++++++++--
.../segment/loading/VirtualPlaceholderSegment.java | 130 +++
.../apache/druid/segment/realtime/FireHydrant.java | 10 +-
.../appenderator/AppenderatorsManager.java | 6 +-
.../druid/server/LocalQuerySegmentWalker.java | 6 +-
.../org/apache/druid/server/SegmentManager.java | 201 ++--
.../server/{coordination => }/ServerManager.java | 321 ++++--
...strapper.java => SegmentCacheBootstrapper.java} | 13 +-
.../server/coordinator/duty/CompactSegments.java | 1 +
.../druid/server/http/HistoricalResource.java | 12 +-
.../segment/loading/NoopSegmentCacheManager.java | 23 +-
.../SegmentLocalCacheManagerConcurrencyTest.java | 796 +++++++++++++-
.../loading/SegmentLocalCacheManagerTest.java | 1154 +++++++++-----------
.../StorageLocationSelectorStrategyTest.java | 44 +-
.../druid/segment/loading/StorageLocationTest.java | 511 +++++++--
.../druid/server/ClientQuerySegmentWalkerTest.java | 61 +-
.../org/apache/druid/server/QueryStackTests.java | 6 +-
.../apache/druid/server/SegmentManagerTest.java | 17 +-
.../server/SpecificSegmentsQuerySegmentWalker.java | 29 +-
.../server/TestClusterQuerySegmentWalker.java | 48 +-
...java => SegmentCacheBootstrapperCacheTest.java} | 25 +-
...Test.java => SegmentCacheBootstrapperTest.java} | 22 +-
.../coordination/SegmentLoadDropHandlerTest.java | 6 -
...egmentManagerBroadcastJoinIndexedTableTest.java | 3 +-
.../SegmentManagerThreadSafetyTest.java | 3 +-
.../server/coordination/ServerManagerTest.java | 17 +-
.../druid/test/utils/TestSegmentCacheManager.java | 86 +-
.../main/java/org/apache/druid/cli/CliBroker.java | 4 +-
.../java/org/apache/druid/cli/CliHistorical.java | 6 +-
.../main/java/org/apache/druid/cli/CliIndexer.java | 4 +-
.../main/java/org/apache/druid/cli/CliPeon.java | 4 +-
.../testing/embedded/EmbeddedDruidServer.java | 2 +-
.../druid/sql/calcite/util/SqlTestFramework.java | 1 +
79 files changed, 4936 insertions(+), 2132 deletions(-)
diff --git a/benchmarks/src/test/java/org/apache/druid/benchmark/IndexedTableJoinCursorBenchmark.java b/benchmarks/src/test/java/org/apache/druid/benchmark/IndexedTableJoinCursorBenchmark.java
index 7cd6c660fe1..a2a24373b63 100644
--- a/benchmarks/src/test/java/org/apache/druid/benchmark/IndexedTableJoinCursorBenchmark.java
+++ b/benchmarks/src/test/java/org/apache/druid/benchmark/IndexedTableJoinCursorBenchmark.java
@@ -194,7 +194,7 @@ public class IndexedTableJoinCursorBenchmark
hashJoinSegment = closer.register(
new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(baseSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(baseSegment).orElseThrow(),
null,
clauses,
preAnalysis,
diff --git a/benchmarks/src/test/java/org/apache/druid/benchmark/JoinAndLookupBenchmark.java b/benchmarks/src/test/java/org/apache/druid/benchmark/JoinAndLookupBenchmark.java
index bb098502992..03278c453e9 100644
--- a/benchmarks/src/test/java/org/apache/druid/benchmark/JoinAndLookupBenchmark.java
+++ b/benchmarks/src/test/java/org/apache/druid/benchmark/JoinAndLookupBenchmark.java
@@ -152,7 +152,7 @@ public class JoinAndLookupBenchmark
);
hashJoinLookupStringKeySegment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(baseSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(baseSegment).orElseThrow(),
null,
joinableClausesLookupStringKey,
preAnalysisLookupStringKey,
@@ -189,7 +189,7 @@ public class JoinAndLookupBenchmark
);
hashJoinLookupLongKeySegment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(baseSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(baseSegment).orElseThrow(),
null,
joinableClausesLookupLongKey,
preAnalysisLookupLongKey,
@@ -226,7 +226,7 @@ public class JoinAndLookupBenchmark
);
hashJoinIndexedTableStringKeySegment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(baseSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(baseSegment).orElseThrow(),
null,
joinableClausesIndexedTableStringKey,
preAnalysisIndexedStringKey,
@@ -263,7 +263,7 @@ public class JoinAndLookupBenchmark
);
hashJoinIndexedTableLongKeySegment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(baseSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(baseSegment).orElseThrow(),
null,
joinableClausesIndexedTableLongKey,
preAnalysisIndexedLongKey,
diff --git a/embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/QueryVirtualStorageTest.java b/embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/QueryVirtualStorageTest.java
new file mode 100644
index 00000000000..18599cd990c
--- /dev/null
+++ b/embedded-tests/src/test/java/org/apache/druid/testing/embedded/query/QueryVirtualStorageTest.java
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.testing.embedded.query;
+
+import org.apache.druid.common.utils.IdUtils;
+import org.apache.druid.data.input.impl.LocalInputSource;
+import org.apache.druid.indexer.TaskState;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.msq.dart.guice.DartControllerMemoryManagementModule;
+import org.apache.druid.msq.dart.guice.DartControllerModule;
+import org.apache.druid.msq.dart.guice.DartWorkerMemoryManagementModule;
+import org.apache.druid.msq.dart.guice.DartWorkerModule;
+import org.apache.druid.msq.guice.IndexerMemoryManagementModule;
+import org.apache.druid.msq.guice.MSQDurableStorageModule;
+import org.apache.druid.msq.guice.MSQExternalDataSourceModule;
+import org.apache.druid.msq.guice.MSQIndexingModule;
+import org.apache.druid.msq.guice.MSQSqlModule;
+import org.apache.druid.msq.guice.SqlTaskModule;
+import org.apache.druid.msq.indexing.report.MSQTaskReportPayload;
+import org.apache.druid.query.DruidProcessingConfigTest;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.testing.embedded.EmbeddedBroker;
+import org.apache.druid.testing.embedded.EmbeddedCoordinator;
+import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
+import org.apache.druid.testing.embedded.EmbeddedHistorical;
+import org.apache.druid.testing.embedded.EmbeddedIndexer;
+import org.apache.druid.testing.embedded.EmbeddedOverlord;
+import org.apache.druid.testing.embedded.EmbeddedRouter;
+import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
+import org.apache.druid.testing.embedded.minio.MinIOStorageResource;
+import org.apache.druid.testing.embedded.msq.EmbeddedDurableShuffleStorageTest;
+import org.apache.druid.testing.embedded.msq.EmbeddedMSQApis;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.testcontainers.shaded.com.google.common.io.ByteStreams;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.util.Collections;
+import java.util.concurrent.ThreadLocalRandom;
+
+/**
+ * Virtual storage mode tests for classic native JSON queries
+ */
+class QueryVirtualStorageTest extends EmbeddedClusterTestBase
+{
+ private final EmbeddedBroker broker = new EmbeddedBroker();
+ private final EmbeddedIndexer indexer = new EmbeddedIndexer();
+ private final EmbeddedOverlord overlord = new EmbeddedOverlord();
+ private final EmbeddedHistorical historical = new EmbeddedHistorical();
+ private final EmbeddedCoordinator coordinator = new EmbeddedCoordinator();
+ private final EmbeddedRouter router = new EmbeddedRouter();
+ private final MinIOStorageResource storageResource = new MinIOStorageResource();
+
+ private EmbeddedMSQApis msqApis;
+
+ @Override
+ public EmbeddedDruidCluster createCluster()
+ {
+ historical.addProperty("druid.segmentCache.virtualStorage", "true")
+ .addProperty("druid.segmentCache.virtualStorageLoadThreads", String.valueOf(Runtime.getRuntime().availableProcessors()))
+ .addBeforeStartHook(
+ (cluster, self) -> self.addProperty(
+ "druid.segmentCache.locations",
+ StringUtils.format(
+ "[{\"path\":\"%s\",\"maxSize\":\"%s\"}]",
+ cluster.getTestFolder().newFolder().getAbsolutePath(),
+ HumanReadableBytes.parse("1MiB")
+ )
+ )
+ )
+ .addProperty("druid.server.maxSize", String.valueOf(HumanReadableBytes.parse("100MiB")));
+
+ coordinator.addProperty("druid.manager.segments.useIncrementalCache", "always");
+
+ overlord.addProperty("druid.manager.segments.useIncrementalCache", "always")
+ .addProperty("druid.manager.segments.pollDuration", "PT0.1s");
+
+ indexer.setServerMemory(400_000_000)
+ .addProperty("druid.worker.capacity", "4")
+ .addProperty("druid.processing.numThreads", "3")
+ .addProperty("druid.segment.handoff.pollDuration", "PT0.1s");
+
+ return EmbeddedDruidCluster
+ .withEmbeddedDerbyAndZookeeper()
+ .useLatchableEmitter()
+ .addExtensions(
+ DartControllerModule.class,
+ DartWorkerModule.class,
+ DartControllerMemoryManagementModule.class,
+ DartWorkerMemoryManagementModule.class,
+ IndexerMemoryManagementModule.class,
+ MSQDurableStorageModule.class,
+ MSQIndexingModule.class,
+ MSQSqlModule.class,
+ SqlTaskModule.class,
+ MSQExternalDataSourceModule.class
+ )
+ .addResource(storageResource)
+ .addServer(coordinator)
+ .addServer(overlord)
+ .addServer(indexer)
+ .addServer(historical)
+ .addServer(broker)
+ .addServer(router);
+ }
+
+ @BeforeAll
+ void loadData() throws IOException
+ {
+ msqApis = new EmbeddedMSQApis(cluster, overlord);
+ dataSource = createTestDatasourceName();
+ loadWikiData();
+ }
+
+ @Override
+ protected void refreshDatasourceName()
+ {
+ // don't change the datasource name for each run because we set things up before all tests
+ }
+
+ @Test
+ void testQueryTooMuchData()
+ {
+ Throwable t = Assertions.assertThrows(
+ RuntimeException.class,
+ () -> cluster.runSql("select * from \"%s\"", dataSource)
+ );
+ Assertions.assertTrue(t.getMessage().contains("Unable to load segment"));
+ Assertions.assertTrue(t.getMessage().contains("] on demand, ensure enough disk space has been allocated to load all segments involved in the query"));
+ }
+
+ @Test
+ void testQueryPartials()
+ {
+ // at the time this test was written, we can divide the segments up into these intervals and fit the required
+ // segments in the cache, this is kind of brittle, but not quite sure what better to do and still expect exact
+ // results..
+ // "2015-09-12T00:00:00Z/2025-09-12T08:00:00Z"
+ // "2015-09-12T08:00:00Z/2025-09-12T14:00:00Z"
+ // "2015-09-12T14:00:00Z/2025-09-12T19:00:00Z"
+ // "2015-09-12T19:00:00Z/2025-09-13T00:00:00Z"
+ final String[] queries = new String[]{
+ "select count(*) from \"%s\" WHERE __time >= TIMESTAMP '2015-09-12 00:00:00' and __time < TIMESTAMP '2015-09-12 08:00:00'",
+ "select count(*) from \"%s\" WHERE __time >= TIMESTAMP '2015-09-12 08:00:00' and __time < TIMESTAMP '2015-09-12 14:00:00'",
+ "select count(*) from \"%s\" WHERE __time >= TIMESTAMP '2015-09-12 14:00:00' and __time < TIMESTAMP '2015-09-12 19:00:00'",
+ "select count(*) from \"%s\" WHERE __time >= TIMESTAMP '2015-09-12 19:00:00' and __time < TIMESTAMP '2015-09-13 00:00:00'"
+ };
+ final long[] expectedResults = new long[] {
+ 9770,
+ 10524,
+ 10267,
+ 8683
+ };
+
+ Assertions.assertEquals(expectedResults[0], Long.parseLong(cluster.runSql(queries[0], dataSource)));
+ Assertions.assertEquals(expectedResults[1], Long.parseLong(cluster.runSql(queries[1], dataSource)));
+ Assertions.assertEquals(expectedResults[2], Long.parseLong(cluster.runSql(queries[2], dataSource)));
+ Assertions.assertEquals(expectedResults[3], Long.parseLong(cluster.runSql(queries[3], dataSource)));
+
+ for (int i = 0; i < 1000; i++) {
+ int nextQuery = ThreadLocalRandom.current().nextInt(queries.length);
+ Assertions.assertEquals(expectedResults[nextQuery], Long.parseLong(cluster.runSql(queries[nextQuery], dataSource)));
+ }
+ }
+
+ private String createTestDatasourceName()
+ {
+ return "wiki-" + IdUtils.getRandomId();
+ }
+
+ /**
+ * Stolen from {@link EmbeddedDurableShuffleStorageTest#loadWikipediaTable()} but with hourly granularity and no
+ * durable shuffle location
+ */
+ private void loadWikiData() throws IOException
+ {
+ final File tmpDir = cluster.getTestFolder().newFolder();
+ final File wikiFile = new File(tmpDir, "wiki.gz");
+
+ ByteStreams.copy(
+ DruidProcessingConfigTest.class.getResourceAsStream("/wikipedia/wikiticker-2015-09-12-sampled.json.gz"),
+ Files.newOutputStream(wikiFile.toPath())
+ );
+ final String sql = StringUtils.format(
+ "SET waitUntilSegmentsLoad = TRUE;\n"
+ + "REPLACE INTO \"%s\" OVERWRITE ALL\n"
+ + "SELECT\n"
+ + " TIME_PARSE(\"time\") AS __time,\n"
+ + " channel,\n"
+ + " countryName,\n"
+ + " page,\n"
+ + " \"user\",\n"
+ + " added,\n"
+ + " deleted,\n"
+ + " delta\n"
+ + "FROM TABLE(\n"
+ + " EXTERN(\n"
+ + " %s,\n"
+ + " '{\"type\":\"json\"}',\n"
+ + " '[{\"name\":\"isRobot\",\"type\":\"string\"},{\"name\":\"channel\",\"type\":\"string\"},{\"name\":\"time\",\"type\":\"string\"},{\"name\":\"flags\",\"type\":\"string\"},{\"name\":\"isUnpatrolled\",\"type\":\"string\"},{\"name\":\"page\",\"type\":\"string\"},{\"name\":\"diffUrl\",\"type\":\"string\"},{\"name\":\"added\",\"type\":\"long\"},{\"name\":\"comment\",\"type\":\"string\"},{\"name\":\"commentLength\",\"type\":\"long\"},{\"name\":\"isNew\",\"type\":\"string\"},{\"n [...]
+ + " )\n"
+ + " )\n"
+ + "PARTITIONED BY HOUR\n"
+ + "CLUSTERED BY channel",
+ dataSource,
+ Calcites.escapeStringLiteral(
+ broker.bindings()
+ .jsonMapper()
+ .writeValueAsString(new LocalInputSource(null, null, Collections.singletonList(wikiFile), null))
+ )
+ );
+
+ final MSQTaskReportPayload payload = msqApis.runTaskSqlAndGetReport(sql);
+ Assertions.assertEquals(TaskState.SUCCESS, payload.getStatus().getStatus());
+ Assertions.assertEquals(24, payload.getStatus().getSegmentLoadWaiterStatus().getTotalSegments());
+ Assertions.assertNull(payload.getStatus().getErrorReport());
+ }
+}
diff --git a/indexing-service/src/main/java/org/apache/druid/indexing/common/task/CompactionTask.java b/indexing-service/src/main/java/org/apache/druid/indexing/common/task/CompactionTask.java
index 2a6457e3634..1c65264f6b6 100644
--- a/indexing-service/src/main/java/org/apache/druid/indexing/common/task/CompactionTask.java
+++ b/indexing-service/src/main/java/org/apache/druid/indexing/common/task/CompactionTask.java
@@ -79,10 +79,10 @@ import org.apache.druid.query.Order;
import org.apache.druid.query.OrderBy;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.segment.AggregateProjectionMetadata;
-import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.Metadata;
import org.apache.druid.segment.QueryableIndex;
+import org.apache.druid.segment.Segment;
import org.apache.druid.segment.column.ColumnCapabilities;
import org.apache.druid.segment.column.ColumnHolder;
import org.apache.druid.segment.column.ColumnType;
@@ -103,12 +103,12 @@ import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentTimeline;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.VersionedIntervalTimeline;
+import org.apache.druid.utils.CloseableUtils;
import org.joda.time.Duration;
import org.joda.time.Interval;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
-import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -615,7 +615,7 @@ public class CompactionTask extends AbstractBatchIndexTask implements PendingSeg
metricBuilder,
segmentProvider.dataSource,
interval,
- lazyFetchSegments(segmentsToCompact, toolbox.getSegmentCacheManager(), toolbox.getIndexIO()),
+ lazyFetchSegments(segmentsToCompact, toolbox.getSegmentCacheManager()),
dimensionsSpec,
transformSpec,
metricsSpec,
@@ -642,8 +642,7 @@ public class CompactionTask extends AbstractBatchIndexTask implements PendingSeg
),
lazyFetchSegments(
timelineSegments,
- toolbox.getSegmentCacheManager(),
- toolbox.getIndexIO()
+ toolbox.getSegmentCacheManager()
),
dimensionsSpec,
transformSpec,
@@ -768,13 +767,12 @@ public class CompactionTask extends AbstractBatchIndexTask implements PendingSeg
*/
private static Iterable<Pair<DataSegment, Supplier<ResourceHolder<QueryableIndex>>>> lazyFetchSegments(
Iterable<DataSegment> dataSegments,
- SegmentCacheManager segmentCacheManager,
- IndexIO indexIO
+ SegmentCacheManager segmentCacheManager
)
{
return Iterables.transform(
Iterables.filter(dataSegments, dataSegment -> !dataSegment.isTombstone()),
- dataSegment -> fetchSegment(dataSegment, segmentCacheManager, indexIO)
+ dataSegment -> fetchSegment(dataSegment, segmentCacheManager)
);
}
@@ -783,8 +781,7 @@ public class CompactionTask extends AbstractBatchIndexTask implements PendingSeg
// an error. Creating a function keeps everyone happy.
private static Pair<DataSegment, Supplier<ResourceHolder<QueryableIndex>>> fetchSegment(
DataSegment dataSegment,
- SegmentCacheManager segmentCacheManager,
- IndexIO indexIO
+ SegmentCacheManager segmentCacheManager
)
{
return Pair.of(
@@ -792,26 +789,21 @@ public class CompactionTask extends AbstractBatchIndexTask implements PendingSeg
() -> {
try {
final Closer closer = Closer.create();
- final File file = segmentCacheManager.getSegmentFiles(dataSegment);
- closer.register(() -> segmentCacheManager.cleanup(dataSegment));
- final QueryableIndex queryableIndex = closer.register(indexIO.loadIndex(file));
+ segmentCacheManager.load(dataSegment);
+ closer.register(() -> segmentCacheManager.drop(dataSegment));
+ final Segment segment = closer.register(segmentCacheManager.acquireCachedSegment(dataSegment).orElseThrow());
return new ResourceHolder<QueryableIndex>()
{
@Override
public QueryableIndex get()
{
- return queryableIndex;
+ return segment.as(QueryableIndex.class);
}
@Override
public void close()
{
- try {
- closer.close();
- }
- catch (IOException e) {
- throw new RuntimeException(e);
- }
+ CloseableUtils.closeAndWrapExceptions(closer);
}
};
}
diff --git a/indexing-service/src/main/java/org/apache/druid/indexing/input/DruidSegmentInputEntity.java b/indexing-service/src/main/java/org/apache/druid/indexing/input/DruidSegmentInputEntity.java
index 3396195a216..0f7f5a6b941 100644
--- a/indexing-service/src/main/java/org/apache/druid/indexing/input/DruidSegmentInputEntity.java
+++ b/indexing-service/src/main/java/org/apache/druid/indexing/input/DruidSegmentInputEntity.java
@@ -69,6 +69,7 @@ public class DruidSegmentInputEntity implements InputEntity
{
final File segmentFile;
try {
+ segmentCacheManager.load(segment);
segmentFile = segmentCacheManager.getSegmentFiles(segment);
}
catch (SegmentLoadingException e) {
@@ -85,9 +86,7 @@ public class DruidSegmentInputEntity implements InputEntity
@Override
public void close()
{
- if (!segmentFile.delete()) {
- log.warn("Could not clean temporary segment file: " + segmentFile);
- }
+ segmentCacheManager.drop(segment);
}
};
}
diff --git a/indexing-service/src/main/java/org/apache/druid/indexing/worker/shuffle/LocalIntermediaryDataManager.java b/indexing-service/src/main/java/org/apache/druid/indexing/worker/shuffle/LocalIntermediaryDataManager.java
index d94516f9cae..c510cd14b4d 100644
--- a/indexing-service/src/main/java/org/apache/druid/indexing/worker/shuffle/LocalIntermediaryDataManager.java
+++ b/indexing-service/src/main/java/org/apache/druid/indexing/worker/shuffle/LocalIntermediaryDataManager.java
@@ -45,6 +45,8 @@ import org.apache.druid.java.util.common.lifecycle.LifecycleStop;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.rpc.indexing.OverlordClient;
import org.apache.druid.segment.SegmentUtils;
+import org.apache.druid.segment.loading.CacheEntry;
+import org.apache.druid.segment.loading.CacheEntryIdentifier;
import org.apache.druid.segment.loading.StorageLocation;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.partition.BucketNumberedShardSpec;
@@ -63,6 +65,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -201,12 +204,7 @@ public class LocalIntermediaryDataManager implements IntermediaryDataManager
.toString();
// StorageLocation keeps track of how much storage capacity is being used.
// Newly found files should be known to the StorageLocation to keep it up to date.
- final File reservedFile = location.reserve(
- relativeSegmentPath,
- eachFile.getName(),
- eachFile.length()
- );
- if (reservedFile == null) {
+ if (!location.reserve(new FileNameCacheEntry(relativeSegmentPath, eachFile.length()))) {
LOG.warn("Can't add a discovered partition[%s]", eachFile.getAbsolutePath());
}
}
@@ -335,9 +333,10 @@ public class LocalIntermediaryDataManager implements IntermediaryDataManager
segment.getInterval(),
bucketNumberedShardSpec.getBucketId() // we must use the bucket ID instead of partition ID
);
- final File destFile = location.reserve(partitionFilePath, segment.getId().toString(), tempZippedFile.length());
- if (destFile != null) {
+ File destFile = null;
+ if (location.reserve(new FileNameCacheEntry(partitionFilePath, tempZippedFile.length()))) {
try {
+ destFile = new File(location.getPath(), partitionFilePath);
FileUtils.mkdirp(destFile.getParentFile());
FileUtils.writeAtomically(
destFile,
@@ -352,7 +351,7 @@ public class LocalIntermediaryDataManager implements IntermediaryDataManager
return segment.withSize(unzippedSizeBytes).withBinaryVersion(SegmentUtils.getVersionFromDir(segmentDir));
}
catch (Exception e) {
- location.release(partitionFilePath, tempZippedFile.length());
+ location.release(new FileNameCacheEntry(partitionFilePath, tempZippedFile.length()));
org.apache.commons.io.FileUtils.deleteQuietly(destFile);
LOG.warn(
e,
@@ -415,11 +414,84 @@ public class LocalIntermediaryDataManager implements IntermediaryDataManager
if (supervisorTaskPath.exists()) {
LOG.info("Cleaning up [%s]", supervisorTaskPath);
for (File eachFile : org.apache.commons.io.FileUtils.listFiles(supervisorTaskPath, null, true)) {
- location.removeFile(eachFile);
+ final String relativeSegmentPath = location.getPath()
+ .toPath()
+ .toAbsolutePath()
+ .relativize(eachFile.toPath().toAbsolutePath())
+ .toString();
+ location.release(new FileNameCacheEntry(relativeSegmentPath, eachFile.length()));
}
org.apache.commons.io.FileUtils.forceDelete(supervisorTaskPath);
}
}
supervisorTaskCheckTimes.remove(supervisorTaskId);
}
+
+ private static class FileNameCacheEntry implements CacheEntry
+ {
+ private final FileNameCacheEntryIdentifier name;
+ private final long size;
+
+ private FileNameCacheEntry(String file, long size)
+ {
+ this.name = new FileNameCacheEntryIdentifier(file);
+ this.size = size;
+ }
+
+ @Override
+ public FileNameCacheEntryIdentifier getId()
+ {
+ return name;
+ }
+
+ @Override
+ public long getSize()
+ {
+ return size;
+ }
+
+ @Override
+ public boolean isMounted()
+ {
+ return true;
+ }
+
+ @Override
+ public void mount(StorageLocation location)
+ {
+ // do nothing, since we are just using StorageLocation as an accountant
+ }
+
+ @Override
+ public void unmount()
+ {
+ // do nothing, since we are just using StorageLocation as an accountant
+ }
+ }
+
+ private static final class FileNameCacheEntryIdentifier implements CacheEntryIdentifier
+ {
+ private final String name;
+
+ private FileNameCacheEntryIdentifier(String name)
+ {
+ this.name = name;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ FileNameCacheEntryIdentifier that = (FileNameCacheEntryIdentifier) o;
+ return Objects.equals(name, that.name);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(name);
+ }
+ }
}
diff --git a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskRunTest.java b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskRunTest.java
index a4eddcb62f7..63111aa2088 100644
--- a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskRunTest.java
+++ b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskRunTest.java
@@ -1602,6 +1602,7 @@ public class CompactionTaskRunTest extends IngestionTestBase
List<String> rowsFromSegment = new ArrayList<>();
for (DataSegment segment : segments) {
+ segmentCacheManager.load(segment);
final File segmentFile = segmentCacheManager.getSegmentFiles(segment);
final WindowedCursorFactory windowed = new WindowedCursorFactory(
@@ -1722,6 +1723,7 @@ public class CompactionTaskRunTest extends IngestionTestBase
List<String> rowsFromSegment = new ArrayList<>();
for (DataSegment segment : segments) {
+ segmentCacheManager.load(segment);
final File segmentFile = segmentCacheManager.getSegmentFiles(segment);
final WindowedCursorFactory windowed = new WindowedCursorFactory(
@@ -1847,6 +1849,7 @@ public class CompactionTaskRunTest extends IngestionTestBase
final SegmentCacheManager segmentCacheManager = segmentCacheManagerFactory.manufacturate(cacheDir);
List<String> rowsFromSegment = new ArrayList<>();
+ segmentCacheManager.load(compactSegment);
final File segmentFile = segmentCacheManager.getSegmentFiles(compactSegment);
final QueryableIndex queryableIndex = testUtils.getTestIndexIO().loadIndex(segmentFile);
@@ -2103,6 +2106,7 @@ public class CompactionTaskRunTest extends IngestionTestBase
List<String> rowsFromSegment = new ArrayList<>();
for (DataSegment segment : segments) {
+ segmentCacheManager.load(segment);
final File segmentFile = segmentCacheManager.getSegmentFiles(segment);
final WindowedCursorFactory windowed = new WindowedCursorFactory(
diff --git a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskTest.java b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskTest.java
index b14ae4c09e8..3ae3715b978 100644
--- a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskTest.java
+++ b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/CompactionTaskTest.java
@@ -102,6 +102,8 @@ import org.apache.druid.segment.IndexMergerV9;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.Metadata;
import org.apache.druid.segment.QueryableIndex;
+import org.apache.druid.segment.QueryableIndexSegment;
+import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentUtils;
import org.apache.druid.segment.SimpleQueryableIndex;
import org.apache.druid.segment.TestIndex;
@@ -355,7 +357,7 @@ public class CompactionTaskTest
@Before
public void setup()
{
- final IndexIO testIndexIO = new TestIndexIO(OBJECT_MAPPER, SEGMENT_MAP);
+ final TestIndexIO testIndexIO = new TestIndexIO(OBJECT_MAPPER, SEGMENT_MAP);
emitter = new StubServiceEmitter();
toolbox = makeTaskToolbox(
new TestTaskActionClient(new ArrayList<>(SEGMENT_MAP.keySet())),
@@ -1925,20 +1927,28 @@ public class CompactionTaskTest
private TaskToolbox makeTaskToolbox(
TaskActionClient taskActionClient,
- IndexIO indexIO,
+ TestIndexIO indexIO,
Map<DataSegment, File> segments
)
{
final SegmentCacheManager segmentCacheManager = new NoopSegmentCacheManager()
{
@Override
- public File getSegmentFiles(DataSegment segment)
+ public void load(DataSegment segment)
{
- return Preconditions.checkNotNull(segments.get(segment));
+ // do nothing
}
@Override
- public void cleanup(DataSegment segment)
+ public Optional<Segment> acquireCachedSegment(DataSegment dataSegment)
+ {
+ return Optional.of(
+ new QueryableIndexSegment(indexIO.loadIndex(segments.get(dataSegment)), dataSegment.getId())
+ );
+ }
+
+ @Override
+ public void drop(DataSegment segment)
{
// Do nothing.
}
diff --git a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/IndexTaskTest.java b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/IndexTaskTest.java
index 9cb6860ee37..a27ba1327b1 100644
--- a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/IndexTaskTest.java
+++ b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/IndexTaskTest.java
@@ -503,6 +503,7 @@ public class IndexTaskTest extends IngestionTestBase
Assert.assertEquals(1, segments.size());
DataSegment segment = segments.get(0);
+ segmentCacheManager.load(segment);
final File segmentFile = segmentCacheManager.getSegmentFiles(segment);
final WindowedCursorFactory windowed = new WindowedCursorFactory(
@@ -732,6 +733,7 @@ public class IndexTaskTest extends IngestionTestBase
final HashBasedNumberedShardSpec hashBasedNumberedShardSpec = (HashBasedNumberedShardSpec) segment.getShardSpec();
Assert.assertEquals(HashPartitionFunction.MURMUR3_32_ABS, hashBasedNumberedShardSpec.getPartitionFunction());
+ segmentCacheManager.load(segment);
final File segmentFile = segmentCacheManager.getSegmentFiles(segment);
final WindowedCursorFactory windowed = new WindowedCursorFactory(
diff --git a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/batch/parallel/AbstractMultiPhaseParallelIndexingTest.java b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/batch/parallel/AbstractMultiPhaseParallelIndexingTest.java
index ccea9fbe3d8..a0eb6be6649 100644
--- a/indexing-service/src/test/java/org/apache/druid/indexing/common/task/batch/parallel/AbstractMultiPhaseParallelIndexingTest.java
+++ b/indexing-service/src/test/java/org/apache/druid/indexing/common/task/batch/parallel/AbstractMultiPhaseParallelIndexingTest.java
@@ -298,7 +298,8 @@ abstract class AbstractMultiPhaseParallelIndexingTest extends AbstractParallelIn
final SegmentCacheManager cacheManager = new SegmentCacheManagerFactory(TestIndex.INDEX_IO, getObjectMapper())
.manufacturate(tempSegmentDir);
try {
- return cacheManager.getSegment(dataSegment).acquireReference().orElseThrow();
+ cacheManager.load(dataSegment);
+ return cacheManager.acquireCachedSegment(dataSegment).orElseThrow();
}
catch (SegmentLoadingException e) {
throw new RuntimeException(e);
diff --git a/indexing-service/src/test/java/org/apache/druid/indexing/input/DruidSegmentReaderTest.java b/indexing-service/src/test/java/org/apache/druid/indexing/input/DruidSegmentReaderTest.java
index 0875cdde867..99f5f04ae49 100644
--- a/indexing-service/src/test/java/org/apache/druid/indexing/input/DruidSegmentReaderTest.java
+++ b/indexing-service/src/test/java/org/apache/druid/indexing/input/DruidSegmentReaderTest.java
@@ -931,11 +931,23 @@ public class DruidSegmentReaderTest extends InitializedNullHandlingTest
return new DruidSegmentInputEntity(
new NoopSegmentCacheManager()
{
+ @Override
+ public void load(DataSegment segment)
+ {
+ // do nothing
+ }
+
@Override
public File getSegmentFiles(DataSegment segment)
{
return segmentDirectory;
}
+
+ @Override
+ public void drop(DataSegment segment)
+ {
+ segmentDirectory.delete();
+ }
},
DataSegment.builder()
.dataSource("ds")
diff --git a/integration-tests-ex/tools/src/main/java/org/apache/druid/testing/tools/ServerManagerForQueryErrorTest.java b/integration-tests-ex/tools/src/main/java/org/apache/druid/testing/tools/ServerManagerForQueryErrorTest.java
index 2bb4d8097e9..8b358e4b11f 100644
--- a/integration-tests-ex/tools/src/main/java/org/apache/druid/testing/tools/ServerManagerForQueryErrorTest.java
+++ b/integration-tests-ex/tools/src/main/java/org/apache/druid/testing/tools/ServerManagerForQueryErrorTest.java
@@ -48,11 +48,11 @@ import org.apache.druid.query.ReportTimelineMissingSegmentQueryRunner;
import org.apache.druid.query.ResourceLimitExceededException;
import org.apache.druid.query.SegmentDescriptor;
import org.apache.druid.query.policy.NoopPolicyEnforcer;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.SegmentMapFunction;
import org.apache.druid.server.SegmentManager;
-import org.apache.druid.server.coordination.ServerManager;
+import org.apache.druid.server.ServerManager;
import org.apache.druid.server.initialization.ServerConfig;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import java.util.HashSet;
@@ -118,7 +118,7 @@ public class ServerManagerForQueryErrorTest extends ServerManager
@Override
protected <T> FunctionalIterable<QueryRunner<T>> getQueryRunnersForSegments(
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline,
+ final VersionedIntervalTimeline<String, DataSegment> timeline,
final Iterable<SegmentDescriptor> specs,
final Query<T> query,
final QueryRunnerFactory<T, Query<T>> factory,
@@ -130,7 +130,7 @@ public class ServerManagerForQueryErrorTest extends ServerManager
)
{
return FunctionalIterable
- .create(acquireAllSegments(timeline, specs, segmentMapFn, closer))
+ .create(getSegmentReferences(timeline, specs, segmentMapFn, query.context().getTimeout()))
.transform(
ref ->
ref.getSegmentReference()
diff --git a/integration-tests/src/main/java/org/apache/druid/server/coordination/ServerManagerForQueryErrorTest.java b/integration-tests/src/main/java/org/apache/druid/server/coordination/ServerManagerForQueryErrorTest.java
index aa838f5a727..62db7527ea8 100644
--- a/integration-tests/src/main/java/org/apache/druid/server/coordination/ServerManagerForQueryErrorTest.java
+++ b/integration-tests/src/main/java/org/apache/druid/server/coordination/ServerManagerForQueryErrorTest.java
@@ -48,10 +48,11 @@ import org.apache.druid.query.ReportTimelineMissingSegmentQueryRunner;
import org.apache.druid.query.ResourceLimitExceededException;
import org.apache.druid.query.SegmentDescriptor;
import org.apache.druid.query.policy.NoopPolicyEnforcer;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.SegmentMapFunction;
import org.apache.druid.server.SegmentManager;
+import org.apache.druid.server.ServerManager;
import org.apache.druid.server.initialization.ServerConfig;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import java.util.Optional;
@@ -133,7 +134,7 @@ public class ServerManagerForQueryErrorTest extends ServerManager
@Override
protected <T> FunctionalIterable<QueryRunner<T>> getQueryRunnersForSegments(
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline,
+ final VersionedIntervalTimeline<String, DataSegment> timeline,
final Iterable<SegmentDescriptor> specs,
final Query<T> query,
final QueryRunnerFactory<T, Query<T>> factory,
@@ -145,7 +146,7 @@ public class ServerManagerForQueryErrorTest extends ServerManager
)
{
return FunctionalIterable
- .create(acquireAllSegments(timeline, specs, segmentMapFn, closer))
+ .create(getSegmentReferences(timeline, specs, segmentMapFn, query.context().getTimeout()))
.transform(
ref ->
ref.getSegmentReference()
diff --git a/multi-stage-query/src/main/java/org/apache/druid/msq/dart/worker/DartDataSegmentProvider.java b/multi-stage-query/src/main/java/org/apache/druid/msq/dart/worker/DartDataSegmentProvider.java
index 281a63134b3..454b41b41ee 100644
--- a/multi-stage-query/src/main/java/org/apache/druid/msq/dart/worker/DartDataSegmentProvider.java
+++ b/multi-stage-query/src/main/java/org/apache/druid/msq/dart/worker/DartDataSegmentProvider.java
@@ -29,9 +29,9 @@ import org.apache.druid.msq.querykit.DataSegmentProvider;
import org.apache.druid.query.TableDataSource;
import org.apache.druid.segment.CompleteSegment;
import org.apache.druid.segment.PhysicalSegmentInspector;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.Segment;
import org.apache.druid.server.SegmentManager;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.PartitionChunk;
@@ -64,14 +64,14 @@ public class DartDataSegmentProvider implements DataSegmentProvider
}
return () -> {
- final Optional<VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timeline =
+ final Optional<VersionedIntervalTimeline<String, DataSegment>> timeline =
segmentManager.getTimeline(new TableDataSource(segmentId.getDataSource()));
if (!timeline.isPresent()) {
throw segmentNotFound(segmentId);
}
- final PartitionChunk<ReferenceCountedSegmentProvider> chunk =
+ final PartitionChunk<DataSegment> chunk =
timeline.get().findChunk(
segmentId.getInterval(),
segmentId.getVersion(),
@@ -82,8 +82,8 @@ public class DartDataSegmentProvider implements DataSegmentProvider
throw segmentNotFound(segmentId);
}
- final ReferenceCountedSegmentProvider segmentReference = chunk.getObject();
- final Optional<Segment> maybeSegment = segmentReference.acquireReference();
+ final DataSegment dataSegment = chunk.getObject();
+ final Optional<Segment> maybeSegment = segmentManager.acquireCachedSegment(dataSegment);
if (!maybeSegment.isPresent()) {
// Segment has disappeared before we could acquire a reference to it.
throw segmentNotFound(segmentId);
diff --git a/multi-stage-query/src/main/java/org/apache/druid/msq/exec/TaskDataSegmentProvider.java b/multi-stage-query/src/main/java/org/apache/druid/msq/exec/TaskDataSegmentProvider.java
index 04b08f9346a..89aa63e943a 100644
--- a/multi-stage-query/src/main/java/org/apache/druid/msq/exec/TaskDataSegmentProvider.java
+++ b/multi-stage-query/src/main/java/org/apache/druid/msq/exec/TaskDataSegmentProvider.java
@@ -24,15 +24,13 @@ import org.apache.druid.client.coordinator.CoordinatorClient;
import org.apache.druid.collections.ReferenceCountingResourceHolder;
import org.apache.druid.collections.ResourceHolder;
import org.apache.druid.common.guava.FutureUtils;
-import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.RE;
import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.msq.counters.ChannelCounters;
import org.apache.druid.msq.querykit.DataSegmentProvider;
import org.apache.druid.segment.CompleteSegment;
-import org.apache.druid.segment.IndexIO;
-import org.apache.druid.segment.QueryableIndex;
-import org.apache.druid.segment.QueryableIndexSegment;
+import org.apache.druid.segment.PhysicalSegmentInspector;
+import org.apache.druid.segment.Segment;
import org.apache.druid.segment.loading.SegmentCacheManager;
import org.apache.druid.segment.loading.SegmentLoadingException;
import org.apache.druid.timeline.DataSegment;
@@ -41,8 +39,6 @@ import org.apache.druid.utils.CloseableUtils;
import javax.annotation.Nullable;
import java.io.Closeable;
-import java.io.File;
-import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
@@ -54,18 +50,15 @@ public class TaskDataSegmentProvider implements DataSegmentProvider
{
private final CoordinatorClient coordinatorClient;
private final SegmentCacheManager segmentCacheManager;
- private final IndexIO indexIO;
private final ConcurrentHashMap<SegmentId, SegmentHolder> holders;
public TaskDataSegmentProvider(
CoordinatorClient coordinatorClient,
- SegmentCacheManager segmentCacheManager,
- IndexIO indexIO
+ SegmentCacheManager segmentCacheManager
)
{
this.coordinatorClient = coordinatorClient;
this.segmentCacheManager = segmentCacheManager;
- this.indexIO = indexIO;
this.holders = new ConcurrentHashMap<>();
}
@@ -122,20 +115,17 @@ public class TaskDataSegmentProvider implements DataSegmentProvider
final Closer closer = Closer.create();
try {
- if (!segmentCacheManager.reserve(dataSegment)) {
- throw new ISE("Could not reserve location for segment [%s]", segmentId);
- }
- closer.register(() -> segmentCacheManager.cleanup(dataSegment));
- final File segmentDir = segmentCacheManager.getSegmentFiles(dataSegment);
+ segmentCacheManager.load(dataSegment);
+ final Segment segment = closer.register(segmentCacheManager.acquireCachedSegment(dataSegment).orElseThrow());
+ closer.register(() -> segmentCacheManager.drop(dataSegment));
- final QueryableIndex index = closer.register(indexIO.loadIndex(segmentDir));
- final QueryableIndexSegment segment = new QueryableIndexSegment(index, dataSegment.getId());
- final int numRows = index.getNumRows();
+ final PhysicalSegmentInspector inspector = segment.as(PhysicalSegmentInspector.class);
+ final int numRows = inspector == null ? 0 : inspector.getNumRows();
final long size = dataSegment.getSize();
closer.register(() -> channelCounters.addFile(numRows, size));
return new ReferenceCountingResourceHolder<>(new CompleteSegment(dataSegment, segment), closer);
}
- catch (IOException | SegmentLoadingException e) {
+ catch (SegmentLoadingException e) {
throw CloseableUtils.closeInCatch(
new RE(e, "Failed to download segment [%s]", segmentId),
closer
diff --git a/multi-stage-query/src/main/java/org/apache/druid/msq/indexing/IndexerWorkerContext.java b/multi-stage-query/src/main/java/org/apache/druid/msq/indexing/IndexerWorkerContext.java
index 6c55a6add95..c48df4bdea5 100644
--- a/multi-stage-query/src/main/java/org/apache/druid/msq/indexing/IndexerWorkerContext.java
+++ b/multi-stage-query/src/main/java/org/apache/druid/msq/indexing/IndexerWorkerContext.java
@@ -154,7 +154,7 @@ public class IndexerWorkerContext implements WorkerContext
overlordClient,
new SpecificTaskServiceLocator(task.getControllerTaskId(), overlordClient),
indexIO,
- new TaskDataSegmentProvider(toolbox.getCoordinatorClient(), segmentCacheManager, indexIO),
+ new TaskDataSegmentProvider(toolbox.getCoordinatorClient(), segmentCacheManager),
serviceClientFactory,
memoryIntrospector,
processingBuffersProvider,
diff --git a/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/BaseLeafFrameProcessor.java b/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/BaseLeafFrameProcessor.java
index a0c82001c46..248b99b7cdb 100644
--- a/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/BaseLeafFrameProcessor.java
+++ b/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/BaseLeafFrameProcessor.java
@@ -141,8 +141,8 @@ public abstract class BaseLeafFrameProcessor implements FrameProcessor<Object>
*/
protected Optional<Segment> mapSegment(final Segment segment)
{
- // we use wrapUnmanaged here because segment reference tracking and lifecycle management happens elsewhere, so all
+ // we use a new reference counted segment because segment reference tracking and lifecycle management happens elsewhere, so all
// we need to be able to do here is apply a segment map function since we don't care about the provider
- return segmentMapFn.apply(ReferenceCountedSegmentProvider.wrapUnmanaged(segment));
+ return segmentMapFn.apply(ReferenceCountedSegmentProvider.unmanaged(segment));
}
}
diff --git a/multi-stage-query/src/test/java/org/apache/druid/msq/exec/TaskDataSegmentProviderTest.java b/multi-stage-query/src/test/java/org/apache/druid/msq/exec/TaskDataSegmentProviderTest.java
index a9bf5e91bb4..ca881efe99e 100644
--- a/multi-stage-query/src/test/java/org/apache/druid/msq/exec/TaskDataSegmentProviderTest.java
+++ b/multi-stage-query/src/test/java/org/apache/druid/msq/exec/TaskDataSegmentProviderTest.java
@@ -22,38 +22,33 @@ package org.apache.druid.msq.exec;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
+import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
-import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.druid.client.coordinator.NoopCoordinatorClient;
import org.apache.druid.collections.ResourceHolder;
-import org.apache.druid.collections.bitmap.BitmapFactory;
-import org.apache.druid.collections.bitmap.RoaringBitmapFactory;
import org.apache.druid.common.guava.FutureUtils;
+import org.apache.druid.jackson.SegmentizerModule;
import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.FileUtils;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Intervals;
-import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.jackson.JacksonUtils;
import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.math.expr.ExprMacroTable;
import org.apache.druid.msq.counters.ChannelCounters;
-import org.apache.druid.query.OrderBy;
+import org.apache.druid.query.expression.TestExprMacroTable;
import org.apache.druid.segment.CompleteSegment;
-import org.apache.druid.segment.DimensionHandler;
import org.apache.druid.segment.IndexIO;
-import org.apache.druid.segment.Metadata;
-import org.apache.druid.segment.QueryableIndex;
+import org.apache.druid.segment.IndexSpec;
+import org.apache.druid.segment.PhysicalSegmentInspector;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.TestIndex;
-import org.apache.druid.segment.column.ColumnHolder;
-import org.apache.druid.segment.data.Indexed;
-import org.apache.druid.segment.data.ListIndexed;
-import org.apache.druid.segment.loading.DataSegmentPusher;
import org.apache.druid.segment.loading.LeastBytesUsedStorageLocationSelectorStrategy;
import org.apache.druid.segment.loading.LoadSpec;
import org.apache.druid.segment.loading.SegmentLoaderConfig;
@@ -62,57 +57,69 @@ import org.apache.druid.segment.loading.SegmentLocalCacheManager;
import org.apache.druid.segment.loading.StorageLocation;
import org.apache.druid.segment.loading.StorageLocationConfig;
import org.apache.druid.server.metrics.NoopServiceEmitter;
+import org.apache.druid.testing.InitializedNullHandlingTest;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.partition.NumberedShardSpec;
-import org.easymock.EasyMock;
+import org.apache.druid.utils.CompressionUtils;
import org.joda.time.DateTime;
-import org.joda.time.Interval;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
-import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
-import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
-import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
-public class TaskDataSegmentProviderTest
+class TaskDataSegmentProviderTest extends InitializedNullHandlingTest
{
private static final String DATASOURCE = "foo";
private static final int NUM_SEGMENTS = 10;
private static final int THREADS = 8;
- private static final String LOAD_SPEC_FILE_NAME = "data";
private List<DataSegment> segments;
private File cacheDir;
private SegmentLocalCacheManager cacheManager;
private TaskDataSegmentProvider provider;
private ListeningExecutorService exec;
- private IndexIO indexIO = EasyMock.mock(IndexIO.class);
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ private static File SEGMENT_ZIP_FILE;
- @Before
+ @TempDir
+ public Path tempDir;
+
+ @BeforeAll
+ public static void setupStatic(@TempDir Path tempDir) throws IOException
+ {
+ File segDir = tempDir.resolve("segment").toFile();
+ File segmentFile = TestIndex.persist(TestIndex.getIncrementalTestIndex(), IndexSpec.DEFAULT, segDir);
+ File zipPath = tempDir.resolve("zip").toFile();
+ FileUtils.mkdirp(zipPath);
+ SEGMENT_ZIP_FILE = new File(zipPath, "index.zip");
+ CompressionUtils.zip(segmentFile, SEGMENT_ZIP_FILE);
+ }
+
+ @BeforeEach
public void setUp() throws Exception
{
EmittingLogger.registerEmitter(new NoopServiceEmitter());
- EasyMock.reset(indexIO);
- EasyMock.expect(indexIO.loadIndex(EasyMock.anyObject())).andReturn(new TestQueryableIndex()).anyTimes();
- EasyMock.replay(indexIO);
-
final ObjectMapper jsonMapper = TestHelper.JSON_MAPPER;
jsonMapper.registerSubtypes(TestLoadSpec.class);
+ jsonMapper.registerModule(new SegmentizerModule());
+ jsonMapper.setInjectableValues(
+ new InjectableValues.Std()
+ .addValue(ExprMacroTable.class.getName(), TestExprMacroTable.INSTANCE)
+ .addValue(ObjectMapper.class.getName(), jsonMapper)
+ .addValue(DataSegment.PruneSpecsHolder.class, DataSegment.PruneSpecsHolder.DEFAULT)
+ .addValue(IndexIO.class, TestIndex.INDEX_IO)
+ );
segments = new ArrayList<>();
@@ -143,7 +150,7 @@ public class TaskDataSegmentProviderTest
);
}
- cacheDir = temporaryFolder.newFolder();
+ cacheDir = tempDir.resolve("cache").toFile();
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(
ImmutableList.of(new StorageLocationConfig(cacheDir, 10_000_000_000L, null))
);
@@ -158,20 +165,15 @@ public class TaskDataSegmentProviderTest
provider = new TaskDataSegmentProvider(
new TestCoordinatorClientImpl(),
- cacheManager,
- indexIO
+ cacheManager
);
exec = MoreExecutors.listeningDecorator(Execs.multiThreaded(THREADS, getClass().getSimpleName() + "-%s"));
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
- if (indexIO != null) {
- EasyMock.verify(indexIO);
- }
-
if (exec != null) {
exec.shutdownNow();
exec.awaitTermination(1, TimeUnit.MINUTES);
@@ -194,47 +196,27 @@ public class TaskDataSegmentProviderTest
FutureUtils.transform(
f,
holderSupplier -> {
- try {
- final ResourceHolder<CompleteSegment> holder = holderSupplier.get();
- Assert.assertEquals(segment.getId(), holder.get().getSegment().getId());
-
- final String expectedStorageDir = DataSegmentPusher.getDefaultStorageDir(segment, false);
- final File expectedFile = new File(
- StringUtils.format(
- "%s/%s/%s",
- cacheDir,
- expectedStorageDir,
- LOAD_SPEC_FILE_NAME
- )
- );
-
- Assert.assertTrue(expectedFile.exists());
- Assert.assertArrayEquals(
- Ints.toByteArray(expectedSegmentNumber),
- Files.readAllBytes(expectedFile.toPath())
- );
-
- holder.close();
-
- return true;
- }
- catch (IOException e) {
- throw new RuntimeException(e);
- }
+ final ResourceHolder<CompleteSegment> holder = holderSupplier.get();
+ Assertions.assertEquals(segment.getId(), holder.get().getSegment().getId());
+ PhysicalSegmentInspector gadget = holder.get().getSegment().as(PhysicalSegmentInspector.class);
+ Assertions.assertNotNull(gadget);
+ Assertions.assertEquals(1209, gadget.getNumRows());
+ holder.close();
+ return true;
}
)
);
}
- Assert.assertEquals(iterations, testFutures.size());
+ Assertions.assertEquals(iterations, testFutures.size());
for (int i = 0; i < iterations; i++) {
ListenableFuture<Boolean> testFuture = testFutures.get(i);
- Assert.assertTrue("Test iteration #" + i, FutureUtils.getUnchecked(testFuture, false));
+ Assertions.assertTrue(FutureUtils.getUnchecked(testFuture, false), "Test iteration #" + i);
}
// Cache dir should exist, but be empty, since we've closed all holders.
- Assert.assertTrue(cacheDir.exists());
- Assert.assertArrayEquals(new String[]{}, cacheDir.list());
+ Assertions.assertTrue(cacheDir.exists());
+ Assertions.assertEquals(List.of(), List.of(cacheDir.list()));
}
private class TestCoordinatorClientImpl extends NoopCoordinatorClient
@@ -273,8 +255,7 @@ public class TaskDataSegmentProviderTest
public LoadSpecResult loadSegment(File destDir) throws SegmentLoadingException
{
try {
- Files.write(new File(destDir, LOAD_SPEC_FILE_NAME).toPath(), Ints.toByteArray(uniqueId));
- Files.write(new File(destDir, "version.bin").toPath(), Ints.toByteArray(1));
+ CompressionUtils.unzip(SEGMENT_ZIP_FILE, destDir);
return new LoadSpecResult(1);
}
catch (IOException e) {
@@ -282,69 +263,4 @@ public class TaskDataSegmentProviderTest
}
}
}
-
- private static class TestQueryableIndex implements QueryableIndex
- {
- @Override
- public Interval getDataInterval()
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getNumRows()
- {
- return 0;
- }
-
- @Override
- public Indexed<String> getAvailableDimensions()
- {
- return new ListIndexed<>();
- }
-
- @Override
- public BitmapFactory getBitmapFactoryForDimensions()
- {
- return RoaringBitmapFactory.INSTANCE;
- }
-
- @Nullable
- @Override
- public Metadata getMetadata()
- {
- return null;
- }
-
- @Override
- public Map<String, DimensionHandler> getDimensionHandlers()
- {
- return Collections.emptyMap();
- }
-
- @Override
- public List<String> getColumnNames()
- {
- return Collections.emptyList();
- }
-
- @Nullable
- @Override
- public ColumnHolder getColumnHolder(String columnName)
- {
- return null;
- }
-
- @Override
- public List<OrderBy> getOrdering()
- {
- return Collections.emptyList();
- }
-
- @Override
- public void close()
- {
-
- }
- }
}
diff --git a/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteMSQTestsHelper.java b/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteMSQTestsHelper.java
index 1d3242b114f..53cd229fb4e 100644
--- a/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteMSQTestsHelper.java
+++ b/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteMSQTestsHelper.java
@@ -154,7 +154,8 @@ public class CalciteMSQTestsHelper
public Supplier<ResourceHolder<CompleteSegment>> fetchSegment(
SegmentId segmentId,
ChannelCounters channelCounters,
- boolean isReindex)
+ boolean isReindex
+ )
{
CompleteSegment a = walker.getSegment(segmentId);
return () -> new ReferenceCountingResourceHolder<>(a, Closer.create());
diff --git a/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestBase.java b/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestBase.java
index 4c143025718..4254250b500 100644
--- a/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestBase.java
+++ b/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestBase.java
@@ -54,6 +54,7 @@ import org.apache.druid.guice.ExpressionModule;
import org.apache.druid.guice.IndexingServiceTuningConfigModule;
import org.apache.druid.guice.JoinableFactoryModule;
import org.apache.druid.guice.JsonConfigProvider;
+import org.apache.druid.guice.LazySingleton;
import org.apache.druid.guice.SegmentWranglerModule;
import org.apache.druid.guice.StartupInjectorBuilder;
import org.apache.druid.guice.annotations.EscalatedGlobal;
@@ -370,7 +371,10 @@ public class MSQTestBase extends BaseCalciteQueryTest
new HllSketchModule(),
new LocalMsqSqlModule(),
new ExpressionModule(),
- binder -> binder.bind(DataSegment.PruneSpecsHolder.class).toInstance(DataSegment.PruneSpecsHolder.DEFAULT)
+ binder -> {
+ binder.bind(DataSegment.PruneSpecsHolder.class).toInstance(DataSegment.PruneSpecsHolder.DEFAULT);
+ binder.bind(ColumnConfig.class).to(DruidProcessingConfig.class).in(LazySingleton.class);
+ }
);
}
@@ -1388,6 +1392,7 @@ public class MSQTestBase extends BaseCalciteQueryTest
dataSegment.getDataSource()
);
}
+ segmentCacheManager.load(dataSegment);
final QueryableIndex queryableIndex = indexIO.loadIndex(segmentCacheManager.getSegmentFiles(dataSegment));
final CursorFactory cursorFactory = new QueryableIndexCursorFactory(queryableIndex);
diff --git a/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestSegmentManager.java b/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestSegmentManager.java
index 2c0fdac3a69..08e82f69c6b 100644
--- a/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestSegmentManager.java
+++ b/multi-stage-query/src/test/java/org/apache/druid/msq/test/MSQTestSegmentManager.java
@@ -58,7 +58,7 @@ public class MSQTestSegmentManager
testGeneratedDataSegments.put(dataSegment.getId(), dataSegment);
try {
- segmentCacheManager.getSegmentFiles(dataSegment);
+ segmentCacheManager.load(dataSegment);
}
catch (SegmentLoadingException e) {
throw new ISE(e, "Unable to load segment [%s]", dataSegment.getId());
diff --git a/processing/src/main/java/org/apache/druid/query/DataSegmentAndDescriptor.java b/processing/src/main/java/org/apache/druid/query/DataSegmentAndDescriptor.java
new file mode 100644
index 00000000000..30e346d3301
--- /dev/null
+++ b/processing/src/main/java/org/apache/druid/query/DataSegmentAndDescriptor.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.query;
+
+import org.apache.druid.timeline.DataSegment;
+
+import javax.annotation.Nullable;
+
+public class DataSegmentAndDescriptor
+{
+ @Nullable
+ private final DataSegment dataSegment;
+ private final SegmentDescriptor descriptor;
+
+ public DataSegmentAndDescriptor(@Nullable DataSegment dataSegment, SegmentDescriptor descriptor)
+ {
+ this.dataSegment = dataSegment;
+ this.descriptor = descriptor;
+ }
+
+ @Nullable
+ public DataSegment getDataSegment()
+ {
+ return dataSegment;
+ }
+
+ public SegmentDescriptor getDescriptor()
+ {
+ return descriptor;
+ }
+}
diff --git a/processing/src/main/java/org/apache/druid/query/expression/NestedDataExpressions.java b/processing/src/main/java/org/apache/druid/query/expression/NestedDataExpressions.java
index 5a384994f69..3939dd8c39e 100644
--- a/processing/src/main/java/org/apache/druid/query/expression/NestedDataExpressions.java
+++ b/processing/src/main/java/org/apache/druid/query/expression/NestedDataExpressions.java
@@ -170,6 +170,8 @@ public class NestedDataExpressions
return ExprEval.ofComplex(ExpressionType.NESTED_DATA, obj);
}
+
+
@Nullable
@Override
public ExpressionType getOutputType(InputBindingInspector inspector)
diff --git a/processing/src/main/java/org/apache/druid/segment/ReferenceCountedSegmentProvider.java b/processing/src/main/java/org/apache/druid/segment/ReferenceCountedSegmentProvider.java
index 9395a3f26c3..f41912b32aa 100644
--- a/processing/src/main/java/org/apache/druid/segment/ReferenceCountedSegmentProvider.java
+++ b/processing/src/main/java/org/apache/druid/segment/ReferenceCountedSegmentProvider.java
@@ -20,12 +20,10 @@
package org.apache.druid.segment;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
import org.apache.druid.error.DruidException;
import org.apache.druid.query.policy.PolicyEnforcer;
-import org.apache.druid.timeline.Overshadowable;
import org.apache.druid.timeline.SegmentId;
-import org.apache.druid.timeline.partition.ShardSpec;
+import org.apache.druid.utils.CloseableUtils;
import org.joda.time.Interval;
import javax.annotation.Nonnull;
@@ -40,63 +38,29 @@ import java.util.concurrent.atomic.AtomicBoolean;
* with reference counting, releasing the reference on close. Closing this provider closes the underlying
* {@link Segment} once all references are returned, ensuring that a segment cannot be dropped while it is actively
* being used.
- * <p>
- * This also implements {@link Overshadowable}, so the providers can be arranged in a
- * {@link org.apache.druid.timeline.TimelineLookup}.
*/
public class ReferenceCountedSegmentProvider extends ReferenceCountingCloseableObject<Segment>
- implements Overshadowable<ReferenceCountedSegmentProvider>, ReferenceCountedObjectProvider<Segment>
+ implements ReferenceCountedObjectProvider<Segment>
{
- public static ReferenceCountedSegmentProvider wrapRootGenerationSegment(Segment baseSegment)
+ public static ReferenceCountedSegmentProvider of(Segment segment)
{
- int partitionNum = baseSegment.getId() == null ? 0 : baseSegment.getId().getPartitionNum();
- return new ReferenceCountedSegmentProvider(
- Preconditions.checkNotNull(baseSegment, "baseSegment"),
- partitionNum,
- partitionNum + 1,
- (short) 0,
- (short) 1
- );
- }
-
-
- public static ReferenceCountedSegmentProvider wrapSegment(
- Segment baseSegment,
- ShardSpec shardSpec
- )
- {
- return new ReferenceCountedSegmentProvider(
- baseSegment,
- shardSpec.getStartRootPartitionId(),
- shardSpec.getEndRootPartitionId(),
- shardSpec.getMinorVersion(),
- shardSpec.getAtomicUpdateGroupSize()
- );
+ return new ReferenceCountedSegmentProvider(segment);
}
/**
- * Returns a {@link ReferenceCountedObjectProvider<Segment>} that simply returns a wrapper around the supplied
- * {@link Segment} that prevents closing the segment, and does not provide any reference tracking functionality.
- * Useful for participating in places that require the interface (such as {@link SegmentMapFunction}) in cases where
- * the lifecycle of the segment is managed externally.
+ * Make a wrapper for a {@link Segment} that does not close the underlying segment on close
*/
- public static ReferenceCountedObjectProvider<Segment> wrapUnmanaged(Segment segment)
+ public static Optional<Segment> unmanaged(Segment segment)
{
- return () -> Optional.of(new UnmanagedReference(segment));
+ return Optional.of(new UnmanagedReference(segment));
}
- private final short startRootPartitionId;
- private final short endRootPartitionId;
- private final short minorVersion;
- private final short atomicUpdateGroupSize;
+ public static Optional<Segment> wrapCloseable(LeafReference segment, Closeable closeable)
+ {
+ return Optional.of(new CloseableWrappedReference(segment, closeable));
+ }
- private ReferenceCountedSegmentProvider(
- Segment baseSegment,
- int startRootPartitionId,
- int endRootPartitionId,
- short minorVersion,
- short atomicUpdateGroupSize
- )
+ public ReferenceCountedSegmentProvider(Segment baseSegment)
{
super(baseSegment);
// ReferenceCountingSegment should not wrap another reference, because the inner reference would effectively
@@ -107,10 +71,6 @@ public class ReferenceCountedSegmentProvider extends ReferenceCountingCloseableO
baseSegment.getDebugString()
);
}
- this.startRootPartitionId = (short) startRootPartitionId;
- this.endRootPartitionId = (short) endRootPartitionId;
- this.minorVersion = minorVersion;
- this.atomicUpdateGroupSize = atomicUpdateGroupSize;
}
@Nullable
@@ -119,51 +79,6 @@ public class ReferenceCountedSegmentProvider extends ReferenceCountingCloseableO
return !isClosed() ? baseObject : null;
}
- @Override
- public boolean overshadows(ReferenceCountedSegmentProvider other)
- {
- if (baseObject.getId().getDataSource().equals(other.baseObject.getId().getDataSource())
- && baseObject.getId().getInterval().overlaps(other.baseObject.getId().getInterval())) {
- final int majorVersionCompare = baseObject.getId().getVersion().compareTo(other.baseObject.getId().getVersion());
- if (majorVersionCompare > 0) {
- return true;
- } else if (majorVersionCompare == 0) {
- return includeRootPartitions(other) && getMinorVersion() > other.getMinorVersion();
- }
- }
- return false;
- }
-
- @Override
- public int getStartRootPartitionId()
- {
- return startRootPartitionId;
- }
-
- @Override
- public int getEndRootPartitionId()
- {
- return endRootPartitionId;
- }
-
- @Override
- public String getVersion()
- {
- return baseObject.getId().getVersion();
- }
-
- @Override
- public short getMinorVersion()
- {
- return minorVersion;
- }
-
- @Override
- public short getAtomicUpdateGroupSize()
- {
- return atomicUpdateGroupSize;
- }
-
@Override
public Optional<Segment> acquireReference()
{
@@ -171,11 +86,6 @@ public class ReferenceCountedSegmentProvider extends ReferenceCountingCloseableO
return reference.map(ReferenceClosingSegment::new);
}
- private boolean includeRootPartitions(ReferenceCountedSegmentProvider other)
- {
- return startRootPartitionId <= other.startRootPartitionId && endRootPartitionId >= other.endRootPartitionId;
- }
-
/**
* Base type to mark {@link Segment} returned by {@link ReferenceCountedObjectProvider<Segment>} as 'leaf' segments,
* to distinguish from other transformations which can be done on top of this segment, such as by
@@ -258,11 +168,6 @@ public class ReferenceCountedSegmentProvider extends ReferenceCountingCloseableO
{
if (isClosed.compareAndSet(false, true)) {
referenceCloseable.close();
- } else {
- throw DruidException.defensive(
- "Segment[%s] reference is already released, cannot close again",
- baseObject.getId()
- );
}
}
@@ -293,4 +198,28 @@ public class ReferenceCountedSegmentProvider extends ReferenceCountingCloseableO
// close nothing, the lifecycle of the wrapped segment isn't managed by a provider
}
}
+
+ public static final class CloseableWrappedReference extends LeafReference
+ {
+ private final Closeable closeable;
+
+ public CloseableWrappedReference(LeafReference delegate, Closeable closeable)
+ {
+ super(delegate);
+ this.closeable = closeable;
+ }
+
+ @Nullable
+ @Override
+ public <T> T as(@Nonnull Class<T> clazz)
+ {
+ return baseSegment.as(clazz);
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ CloseableUtils.closeAll(baseSegment, closeable);
+ }
+ }
}
diff --git a/processing/src/main/java/org/apache/druid/segment/ReferenceCountingCloseableObject.java b/processing/src/main/java/org/apache/druid/segment/ReferenceCountingCloseableObject.java
index a2ff617a82f..3bf7dd6e449 100644
--- a/processing/src/main/java/org/apache/druid/segment/ReferenceCountingCloseableObject.java
+++ b/processing/src/main/java/org/apache/druid/segment/ReferenceCountingCloseableObject.java
@@ -31,10 +31,10 @@ import java.util.concurrent.atomic.AtomicBoolean;
* ReferenceCountingCloseableObject implements something like automatic reference count-based resource management,
* backed by a {@link Phaser}.
* <p>
- * ReferenceCountingCloseableObject allows consumers to call {@link #close()} before some other "users", which called
- * {@link #increment()} or {@link #incrementReferenceAndDecrementOnceCloseable()}, but have not called
- * {@link #decrement()} yet or the closer for {@link #incrementReferenceAndDecrementOnceCloseable()}, and the wrapped
- * object won't be actually closed until that all references are released.
+ * ReferenceCountingCloseableObject allows consumers to call {@link #close()} before some other "users" which have
+ * checked out references via {@link #increment()} or {@link #incrementReferenceAndDecrementOnceCloseable()}, but have
+ * not called {@link #decrement()} yet or the closer for {@link #incrementReferenceAndDecrementOnceCloseable()}.
+ * The wrapped object won't be closed until all references are released.
*/
public abstract class ReferenceCountingCloseableObject<BaseObject extends Closeable> implements Closeable
{
diff --git a/processing/src/main/java/org/apache/druid/segment/SegmentMapFunction.java b/processing/src/main/java/org/apache/druid/segment/SegmentMapFunction.java
index 4ad06949fb3..5a88266e730 100644
--- a/processing/src/main/java/org/apache/druid/segment/SegmentMapFunction.java
+++ b/processing/src/main/java/org/apache/druid/segment/SegmentMapFunction.java
@@ -23,24 +23,22 @@ import java.util.Optional;
import java.util.function.Function;
/**
- * Functional interface that captures the process of acquiring a {@link Segment} from a
- * {@link ReferenceCountedObjectProvider<Segment>} and performing any transformations done on top of this leaf {@link Segment}
- * before it is available to query processing engines.
+ * Functional interface that captures the process of transforming a {@link Segment} to another {@link Segment} if
+ * possible.
* <p>
- * The {@link Segment} returned by this method, if present, must always be closed to return the reference to the base
- * {@link ReferenceCountedObjectProvider<Segment>} that it came from.
+ * The {@link Segment} returned by this method, if present, must always be closed by the caller.
*/
@FunctionalInterface
-public interface SegmentMapFunction extends Function<ReferenceCountedObjectProvider<Segment>, Optional<Segment>>
+public interface SegmentMapFunction extends Function<Optional<Segment>, Optional<Segment>>
{
/**
- * {@link SegmentMapFunction} that acquires a {@link Segment} from the {@link ReferenceCountedObjectProvider<Segment>}
+ * The identity function - returns the same segment
*/
- SegmentMapFunction IDENTITY = ReferenceCountedObjectProvider::acquireReference;
+ SegmentMapFunction IDENTITY = segment -> segment;
/**
* Returns a {@link SegmentMapFunction} which first applies this {@link SegmentMapFunction} and then applies
- * the function to the resulting {@link Segment}, if present
+ * the supplied transformation function to the resulting {@link Segment}, if present.
*/
default SegmentMapFunction thenMap(Function<Segment, Segment> mapFn)
{
diff --git a/processing/src/main/java/org/apache/druid/segment/SegmentReference.java b/processing/src/main/java/org/apache/druid/segment/SegmentReference.java
new file mode 100644
index 00000000000..58b6816fcc3
--- /dev/null
+++ b/processing/src/main/java/org/apache/druid/segment/SegmentReference.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.segment;
+
+import org.apache.druid.java.util.common.io.Closer;
+import org.apache.druid.query.SegmentDescriptor;
+import org.apache.druid.segment.loading.AcquireSegmentAction;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Optional;
+
+/**
+ * Wrapper for a {@link SegmentDescriptor} and {@link Optional<Segment>}, the latter being created by a
+ * {@link SegmentMapFunction} being applied to a {@link ReferenceCountedSegmentProvider}. Closing this object closes
+ * both the {@link #segmentReference} and any closeables attached from the process of creating this object, such as
+ * from {@link AcquireSegmentAction}
+ */
+public class SegmentReference implements Closeable
+{
+ public static SegmentReference missing(SegmentDescriptor segmentDescriptor)
+ {
+ return new SegmentReference(segmentDescriptor, Optional.empty(), null);
+ }
+
+ private final SegmentDescriptor segmentDescriptor;
+ private final Optional<Segment> segmentReference;
+ private final Closer closer = Closer.create();
+
+ public SegmentReference(
+ SegmentDescriptor segmentDescriptor,
+ Optional<Segment> segmentReference,
+ @Nullable Closeable cleanupHold
+ )
+ {
+ this.segmentDescriptor = segmentDescriptor;
+ closer.register(cleanupHold);
+ this.segmentReference = segmentReference.map(closer::register);
+ }
+
+ public SegmentDescriptor getSegmentDescriptor()
+ {
+ return segmentDescriptor;
+ }
+
+ public Optional<Segment> getSegmentReference()
+ {
+ return segmentReference;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ closer.close();
+ }
+}
diff --git a/processing/src/main/java/org/apache/druid/segment/loading/AcquireSegmentAction.java b/processing/src/main/java/org/apache/druid/segment/loading/AcquireSegmentAction.java
new file mode 100644
index 00000000000..5f02c1437c3
--- /dev/null
+++ b/processing/src/main/java/org/apache/druid/segment/loading/AcquireSegmentAction.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.segment.loading;
+
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.apache.druid.segment.ReferenceCountedObjectProvider;
+import org.apache.druid.segment.ReferenceCountedSegmentProvider;
+import org.apache.druid.segment.Segment;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Supplier;
+
+/**
+ * This class represents an intent to acquire a reference to a {@link Segment} and then use it to do stuff, and finally
+ * closing when done.
+ * <p>
+ * When an {@link AcquireSegmentAction} is created, segment cache implementations will create a
+ * 'hold' to ensure it cannot be removed from the cache until this action has been closed.
+ * <p>
+ * Calling {@link #getSegmentFuture()} is what actually initiates the 'action', and will return a segment reference
+ * provider if already cached, or attempt to download from deep storage to load into the cache if not. The
+ * {@link Segment} returned by acquiring a reference from the {@link ReferenceCountedObjectProvider} returned by the
+ * future places a separate hold on the cache until the segment itself is closed, and MUST be closed when the caller is
+ * finished doing segment things with it.
+ * <p>
+ * The caller must also call {@link #close()} on this object to clean up the hold that exists while possibly loading
+ * the segment, and may do so as soon as the {@link Segment} is acquired (or can do so earlier to abort the load and
+ * release the hold).
+ */
+public class AcquireSegmentAction implements Closeable
+{
+ public static AcquireSegmentAction missingSegment()
+ {
+ return new AcquireSegmentAction(() -> Futures.immediateFuture(Optional::empty), null);
+ }
+
+ private final Supplier<ListenableFuture<ReferenceCountedObjectProvider<Segment>>> segmentFutureSupplier;
+ @Nullable
+ private final Closeable loadCleanup;
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+
+ public AcquireSegmentAction(
+ Supplier<ListenableFuture<ReferenceCountedObjectProvider<Segment>>> segmentFutureSupplier,
+ @Nullable Closeable loadCleanup
+ )
+ {
+ this.segmentFutureSupplier = segmentFutureSupplier;
+ this.loadCleanup = loadCleanup;
+ }
+
+ /**
+ * Get a {@link ReferenceCountedObjectProvider<Segment>} to acquire a reference to an item that exists in the cache,
+ * or if necessary/possible, fetching it from deep storage. This is typically {@link ReferenceCountedSegmentProvider},
+ * either as an immediate future if the segment already exists in cache. The 'action' to fetch the segment and return
+ * the reference provider is not initiated until this method is called.
+ */
+ public ListenableFuture<ReferenceCountedObjectProvider<Segment>> getSegmentFuture()
+ {
+ return segmentFutureSupplier.get();
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ if (loadCleanup != null && closed.compareAndSet(false, true)) {
+ loadCleanup.close();
+ }
+ }
+}
diff --git a/processing/src/test/java/org/apache/druid/query/QueryRunnerTestHelper.java b/processing/src/test/java/org/apache/druid/query/QueryRunnerTestHelper.java
index 90c2888135e..2f17b310b67 100644
--- a/processing/src/test/java/org/apache/druid/query/QueryRunnerTestHelper.java
+++ b/processing/src/test/java/org/apache/druid/query/QueryRunnerTestHelper.java
@@ -68,6 +68,7 @@ import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.Segment;
import org.apache.druid.segment.TestIndex;
import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.VersionedIntervalTimeline;
@@ -562,13 +563,14 @@ public class QueryRunnerTestHelper
{
ExecutionVertex ev = ExecutionVertex.of(query);
final Optional<Segment> segmentReference = ev.createSegmentMapFunction(NoopPolicyEnforcer.instance())
- .apply(ReferenceCountedSegmentProvider.wrapRootGenerationSegment(adapter));
+ .apply(Optional.of(adapter));
return makeQueryRunner(factory, segmentReference.orElseThrow(), runnerName);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static <T> QueryRunner<T> makeFilteringQueryRunner(
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline,
+ final VersionedIntervalTimeline<String, DataSegment> timeline,
+ final Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders,
final QueryRunnerFactory<T, Query<T>> factory
)
{
@@ -584,7 +586,7 @@ public class QueryRunnerTestHelper
List<Sequence<T>> sequences = new ArrayList<>();
final Closer closer = Closer.create();
try {
- for (TimelineObjectHolder<String, ReferenceCountedSegmentProvider> holder : toolChest.filterSegments(
+ for (TimelineObjectHolder<String, DataSegment> holder : toolChest.filterSegments(
query,
segments
)) {
@@ -596,8 +598,11 @@ public class QueryRunnerTestHelper
final QueryPlus queryPlusRunning = queryPlus.withQuery(
queryPlus.getQuery().withQuerySegmentSpec(new SpecificSegmentSpec(descriptor))
);
+ final ReferenceCountedSegmentProvider referenceProvider = referenceProviders.get(
+ holder.getObject().getChunk(0).getObject()
+ );
final QueryRunner<?> runner = factory.createRunner(
- closer.register(holder.getObject().getChunk(0).getObject().acquireReference().orElseThrow())
+ closer.register(referenceProvider.acquireReference().orElseThrow())
);
sequences.add(runner.run(queryPlusRunning, responseContext));
}
diff --git a/processing/src/test/java/org/apache/druid/query/policy/RestrictAllTablesPolicyEnforcerTest.java b/processing/src/test/java/org/apache/druid/query/policy/RestrictAllTablesPolicyEnforcerTest.java
index ea9823481e8..d65e355ea80 100644
--- a/processing/src/test/java/org/apache/druid/query/policy/RestrictAllTablesPolicyEnforcerTest.java
+++ b/processing/src/test/java/org/apache/druid/query/policy/RestrictAllTablesPolicyEnforcerTest.java
@@ -28,7 +28,6 @@ import org.apache.druid.query.InlineDataSource;
import org.apache.druid.query.RestrictedDataSource;
import org.apache.druid.query.TableDataSource;
import org.apache.druid.query.filter.NullFilter;
-import org.apache.druid.segment.ReferenceCountedObjectProvider;
import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.RowBasedSegment;
import org.apache.druid.segment.Segment;
@@ -114,9 +113,7 @@ public class RestrictAllTablesPolicyEnforcerTest
inlineDataSource.rowAdapter(),
inlineDataSource.getRowSignature()
);
- ReferenceCountedObjectProvider<Segment> segment = ReferenceCountedSegmentProvider.wrapUnmanaged(inlineSegment);
-
- policyEnforcer.validateOrElseThrow(segment.acquireReference().orElseThrow(), null);
+ policyEnforcer.validateOrElseThrow(ReferenceCountedSegmentProvider.unmanaged(inlineSegment).orElseThrow(), null);
}
@Test
diff --git a/processing/src/test/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryRunnerTest.java b/processing/src/test/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryRunnerTest.java
index 41941462304..b388af0eb82 100644
--- a/processing/src/test/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryRunnerTest.java
+++ b/processing/src/test/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryRunnerTest.java
@@ -46,15 +46,18 @@ import org.apache.druid.segment.IncrementalIndexSegment;
import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.RowBasedSegment;
import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.TestIndex;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.incremental.OnheapIncrementalIndex;
import org.apache.druid.testing.InitializedNullHandlingTest;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.NoneShardSpec;
+import org.apache.druid.timeline.partition.NumberedShardSpec;
import org.apache.druid.timeline.partition.SingleElementPartitionChunk;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@@ -68,6 +71,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
/**
*
@@ -157,21 +161,27 @@ public class TimeBoundaryQueryRunnerTest extends InitializedNullHandlingTest
segment0 = new IncrementalIndexSegment(index0, makeIdentifier(index0, "v1"));
segment1 = new IncrementalIndexSegment(index1, makeIdentifier(index1, "v1"));
+ final DataSegment dataSegment0 = TestHelper.toSimpleDataSegment(segment0, new NumberedShardSpec(0, 1));
+ final DataSegment dataSegment1 = TestHelper.toSimpleDataSegment(segment1, new NumberedShardSpec(0, 1));
+ Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders = Map.of(
+ dataSegment0, ReferenceCountedSegmentProvider.of(segment0),
+ dataSegment1, ReferenceCountedSegmentProvider.of(segment1)
+ );
- VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline = new VersionedIntervalTimeline<>(
+ VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<>(
StringComparators.LEXICOGRAPHIC);
timeline.add(
index0.getInterval(),
"v1",
- new SingleElementPartitionChunk<>(ReferenceCountedSegmentProvider.wrapRootGenerationSegment(segment0))
+ new SingleElementPartitionChunk<>(dataSegment0)
);
timeline.add(
index1.getInterval(),
"v1",
- new SingleElementPartitionChunk<>(ReferenceCountedSegmentProvider.wrapRootGenerationSegment(segment1))
+ new SingleElementPartitionChunk<>(dataSegment1)
);
- return QueryRunnerTestHelper.makeFilteringQueryRunner(timeline, FACTORY);
+ return QueryRunnerTestHelper.makeFilteringQueryRunner(timeline, referenceProviders, FACTORY);
}
@Test
diff --git a/processing/src/test/java/org/apache/druid/segment/ReferenceCountingSegmentTest.java b/processing/src/test/java/org/apache/druid/segment/ReferenceCountingSegmentTest.java
index b50b5285441..9530dcb6d2e 100644
--- a/processing/src/test/java/org/apache/druid/segment/ReferenceCountingSegmentTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/ReferenceCountingSegmentTest.java
@@ -55,7 +55,7 @@ public class ReferenceCountingSegmentTest
cursorFactory = EasyMock.createNiceMock(CursorFactory.class);
indexedTable = EasyMock.createNiceMock(IndexedTable.class);
- segment = ReferenceCountedSegmentProvider.wrapRootGenerationSegment(
+ segment = ReferenceCountedSegmentProvider.of(
new Segment()
{
@Override
diff --git a/processing/src/test/java/org/apache/druid/segment/TestHelper.java b/processing/src/test/java/org/apache/druid/segment/TestHelper.java
index 737ce8abfbd..23af82a4804 100644
--- a/processing/src/test/java/org/apache/druid/segment/TestHelper.java
+++ b/processing/src/test/java/org/apache/druid/segment/TestHelper.java
@@ -43,7 +43,9 @@ import org.apache.druid.query.topn.TopNResultValue;
import org.apache.druid.segment.column.ColumnConfig;
import org.apache.druid.segment.join.JoinableFactoryWrapper;
import org.apache.druid.segment.writeout.SegmentWriteOutMediumFactory;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.DataSegment.PruneSpecsHolder;
+import org.apache.druid.timeline.partition.ShardSpec;
import org.junit.Assert;
import java.io.IOException;
@@ -513,4 +515,12 @@ public class TestHelper
throw new UncheckedIOException(e);
}
}
+
+ public static DataSegment toSimpleDataSegment(Segment segment, ShardSpec shardSpec)
+ {
+ return DataSegment.builder(segment.getId())
+ .shardSpec(shardSpec)
+ .size(0)
+ .build();
+ }
}
diff --git a/processing/src/test/java/org/apache/druid/segment/TestIndex.java b/processing/src/test/java/org/apache/druid/segment/TestIndex.java
index 3e84fc0a5b9..fb3f864c037 100644
--- a/processing/src/test/java/org/apache/druid/segment/TestIndex.java
+++ b/processing/src/test/java/org/apache/druid/segment/TestIndex.java
@@ -522,11 +522,7 @@ public class TestIndex
{
try {
File someTmpFile = File.createTempFile("billy", "yay");
- someTmpFile.delete();
- FileUtils.mkdirp(someTmpFile);
- someTmpFile.deleteOnExit();
-
- INDEX_MERGER.persist(index, someTmpFile, indexSpec, null);
+ someTmpFile = persist(index, indexSpec, someTmpFile);
return INDEX_IO.loadIndex(someTmpFile);
}
catch (IOException e) {
@@ -534,6 +530,15 @@ public class TestIndex
}
}
+ public static File persist(IncrementalIndex index, IndexSpec indexSpec, File path) throws IOException
+ {
+ path.delete();
+ FileUtils.mkdirp(path);
+ path.deleteOnExit();
+
+ return INDEX_MERGER.persist(index, path, indexSpec, null);
+ }
+
public static CharSource getResourceCharSource(final String resourceFilename)
{
diff --git a/processing/src/test/java/org/apache/druid/segment/join/BaseHashJoinSegmentCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/join/BaseHashJoinSegmentCursorFactoryTest.java
index f70203aaa6e..8076f6dc5f8 100644
--- a/processing/src/test/java/org/apache/druid/segment/join/BaseHashJoinSegmentCursorFactoryTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/join/BaseHashJoinSegmentCursorFactoryTest.java
@@ -232,7 +232,7 @@ public class BaseHashJoinSegmentCursorFactoryTest extends InitializedNullHandlin
protected HashJoinSegment makeFactToCountrySegment(JoinType joinType)
{
return new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(factSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(factSegment).orElseThrow(),
null,
ImmutableList.of(factToCountryOnIsoCode(joinType)),
null,
diff --git a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java
index 8d757484922..32acee4cd73 100644
--- a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java
@@ -1947,7 +1947,7 @@ public class HashJoinSegmentCursorFactoryTest extends BaseHashJoinSegmentCursorF
Assert.assertTrue(makeFactToCountrySegment(JoinType.FULL).as(TopNOptimizationInspector.class).areAllDictionaryIdsPresent());
// cross join
HashJoinSegment segment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(factSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(factSegment).orElseThrow(),
null,
ImmutableList.of(
new JoinableClause(
@@ -1972,7 +1972,7 @@ public class HashJoinSegmentCursorFactoryTest extends BaseHashJoinSegmentCursorF
public void test_hasBuiltInFiltersForConvertedJoin()
{
final HashJoinSegment segment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(factSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(factSegment).orElseThrow(),
new InDimFilter("dim", ImmutableSet.of("foo", "bar")),
ImmutableList.of(),
null,
@@ -1986,7 +1986,7 @@ public class HashJoinSegmentCursorFactoryTest extends BaseHashJoinSegmentCursorF
public void test_hasBuiltInFiltersForMultipleJoinableClausesWithVariousJoinTypes()
{
final HashJoinSegment segment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(factSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(factSegment).orElseThrow(),
null,
ImmutableList.of(
factToRegion(JoinType.INNER),
@@ -1998,7 +1998,7 @@ public class HashJoinSegmentCursorFactoryTest extends BaseHashJoinSegmentCursorF
Assert.assertFalse(segment.as(TopNOptimizationInspector.class).areAllDictionaryIdsPresent());
final HashJoinSegment segment2 = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(factSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(factSegment).orElseThrow(),
null,
ImmutableList.of(
factToRegion(JoinType.RIGHT),
@@ -2011,7 +2011,7 @@ public class HashJoinSegmentCursorFactoryTest extends BaseHashJoinSegmentCursorF
Assert.assertFalse(segment2.as(TopNOptimizationInspector.class).areAllDictionaryIdsPresent());
final HashJoinSegment segment3 = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(factSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(factSegment).orElseThrow(),
null,
ImmutableList.of(
factToRegion(JoinType.LEFT),
@@ -2023,7 +2023,7 @@ public class HashJoinSegmentCursorFactoryTest extends BaseHashJoinSegmentCursorF
Assert.assertTrue(segment3.as(TopNOptimizationInspector.class).areAllDictionaryIdsPresent());
final HashJoinSegment segment4 = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(factSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(factSegment).orElseThrow(),
null,
ImmutableList.of(
factToRegion(JoinType.LEFT),
diff --git a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentTest.java b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentTest.java
index be071b7f04b..bf4de04f7e0 100644
--- a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentTest.java
@@ -137,7 +137,7 @@ public class HashJoinSegmentTest extends InitializedNullHandlingTest
);
closer = Closer.create();
- baseSegmentRef = closer.register(ReferenceCountedSegmentProvider.wrapRootGenerationSegment(baseSegment));
+ baseSegmentRef = closer.register(ReferenceCountedSegmentProvider.of(baseSegment));
referencedSegment = () ->
baseSegmentRef.acquireReference()
.map(
@@ -179,7 +179,7 @@ public class HashJoinSegmentTest extends InitializedNullHandlingTest
preAnalysis,
SegmentMapFunction.IDENTITY
);
- return segmentMapFunction.apply(referencedSegment)
+ return segmentMapFunction.apply(referencedSegment.acquireReference())
.map(s -> {
final Closer closer = Closer.create();
allReferencesAcquireCount++;
diff --git a/processing/src/test/java/org/apache/druid/segment/join/PostJoinCursorTest.java b/processing/src/test/java/org/apache/druid/segment/join/PostJoinCursorTest.java
index e46eeb8b25c..10e398d1e2d 100644
--- a/processing/src/test/java/org/apache/druid/segment/join/PostJoinCursorTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/join/PostJoinCursorTest.java
@@ -265,7 +265,7 @@ public class PostJoinCursorTest extends BaseHashJoinSegmentCursorFactoryTest
);
HashJoinSegment hashJoinSegment = new HashJoinSegment(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(infiniteFactSegment).acquireReference().orElseThrow(),
+ ReferenceCountedSegmentProvider.unmanaged(infiniteFactSegment).orElseThrow(),
null,
joinableClauses,
joinFilterPreAnalysis,
diff --git a/server/src/main/java/org/apache/druid/client/cache/CachePopulator.java b/server/src/main/java/org/apache/druid/client/cache/CachePopulator.java
index dbbade1cf6a..bcfa37cf3eb 100644
--- a/server/src/main/java/org/apache/druid/client/cache/CachePopulator.java
+++ b/server/src/main/java/org/apache/druid/client/cache/CachePopulator.java
@@ -20,6 +20,7 @@
package org.apache.druid.client.cache;
import org.apache.druid.java.util.common.guava.Sequence;
+import org.apache.druid.server.ServerManager;
import java.util.function.Function;
@@ -31,7 +32,7 @@ import java.util.function.Function;
* Consumers of the {@link Sequence} will either be a processing thread (in the case of a historical or task), or
* an http thread in the case of a broker. See:
*
- * historicals: {@link org.apache.druid.server.coordination.ServerManager} and
+ * historicals: {@link ServerManager} and
* {@link org.apache.druid.client.CachingQueryRunner}
*
* realtime tasks: {@link org.apache.druid.segment.realtime.appenderator.SinkQuerySegmentWalker} and
diff --git a/server/src/main/java/org/apache/druid/segment/loading/CacheEntry.java b/server/src/main/java/org/apache/druid/segment/loading/CacheEntry.java
new file mode 100644
index 00000000000..36e699804f7
--- /dev/null
+++ b/server/src/main/java/org/apache/druid/segment/loading/CacheEntry.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.segment.loading;
+
+import java.io.IOException;
+
+/**
+ * Common interface for items stored in a {@link StorageLocation}
+ */
+public interface CacheEntry
+{
+ /**
+ * Unique identifier for the cache entry
+ */
+ CacheEntryIdentifier getId();
+
+ /**
+ * Size in bytes of the cache entry
+ */
+ long getSize();
+
+ boolean isMounted();
+
+ /**
+ * Materializes the cache entry into the assigned {@link StorageLocation}. If a cache entry is already mounted in the
+ * location, calling this method should be a no-op. It is an error condition to call this method if the cache entry
+ * is already mounted in a different location.
+ */
+ void mount(StorageLocation location) throws IOException, SegmentLoadingException;
+
+ /**
+ * Removes the physical artifacts of a cache entry from the location it is currently mounted
+ */
+ void unmount();
+}
diff --git a/server/src/main/java/org/apache/druid/segment/loading/CacheEntryIdentifier.java b/server/src/main/java/org/apache/druid/segment/loading/CacheEntryIdentifier.java
new file mode 100644
index 00000000000..bd172b28e7b
--- /dev/null
+++ b/server/src/main/java/org/apache/druid/segment/loading/CacheEntryIdentifier.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.segment.loading;
+
+import org.apache.druid.annotations.SubclassesMustOverrideEqualsAndHashCode;
+
+/**
+ * Common interface to specify a unique identifier of a {@link CacheEntry} for a {@link StorageLocation}
+ */
+@SubclassesMustOverrideEqualsAndHashCode
+public interface CacheEntryIdentifier
+{
+}
diff --git a/server/src/main/java/org/apache/druid/segment/loading/LeastBytesUsedStorageLocationSelectorStrategy.java b/server/src/main/java/org/apache/druid/segment/loading/LeastBytesUsedStorageLocationSelectorStrategy.java
index bcc37e3eed6..814a2493ca3 100644
--- a/server/src/main/java/org/apache/druid/segment/loading/LeastBytesUsedStorageLocationSelectorStrategy.java
+++ b/server/src/main/java/org/apache/druid/segment/loading/LeastBytesUsedStorageLocationSelectorStrategy.java
@@ -34,7 +34,7 @@ import java.util.List;
public class LeastBytesUsedStorageLocationSelectorStrategy implements StorageLocationSelectorStrategy
{
private static final Ordering<StorageLocation> ORDERING = Ordering.from(Comparator
- .comparingLong(StorageLocation::currSizeBytes));
+ .comparingLong(StorageLocation::currentSizeBytes));
private final List<StorageLocation> storageLocations;
diff --git a/server/src/main/java/org/apache/druid/segment/loading/SegmentCacheEntryIdentifier.java b/server/src/main/java/org/apache/druid/segment/loading/SegmentCacheEntryIdentifier.java
new file mode 100644
index 00000000000..c58e04a7030
--- /dev/null
+++ b/server/src/main/java/org/apache/druid/segment/loading/SegmentCacheEntryIdentifier.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.segment.loading;
+
+import org.apache.druid.timeline.SegmentId;
+
+import java.util.Objects;
+
+/**
+ * Use a {@link SegmentId} as a {@link CacheEntryIdentifier}
+ */
+public final class SegmentCacheEntryIdentifier implements CacheEntryIdentifier
+{
+ private final SegmentId segmentId;
+
+ public SegmentCacheEntryIdentifier(SegmentId segmentId)
+ {
+ this.segmentId = segmentId;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ SegmentCacheEntryIdentifier that = (SegmentCacheEntryIdentifier) o;
+ return Objects.equals(segmentId, that.segmentId);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return segmentId.hashCode();
+ }
+
+ @Override
+ public String toString()
+ {
+ return segmentId.toString();
+ }
+}
diff --git a/server/src/main/java/org/apache/druid/segment/loading/SegmentCacheManager.java b/server/src/main/java/org/apache/druid/segment/loading/SegmentCacheManager.java
index 54d474a76b3..135149c0960 100644
--- a/server/src/main/java/org/apache/druid/segment/loading/SegmentCacheManager.java
+++ b/server/src/main/java/org/apache/druid/segment/loading/SegmentCacheManager.java
@@ -19,17 +19,22 @@
package org.apache.druid.segment.loading;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
+import org.apache.druid.query.SegmentDescriptor;
+import org.apache.druid.segment.ReferenceCountedObjectProvider;
+import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentLazyLoadFailCallback;
+import org.apache.druid.segment.SegmentMapFunction;
import org.apache.druid.timeline.DataSegment;
+import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.List;
+import java.util.Optional;
/**
- * A class to fetch segment files to local disk and manage the local cache.
- * Implementations must be thread-safe.
+ * A class to fetch segment files from deep storage to local disk and manage the local cache. Implementations must be
+ * thread-safe.
*/
public interface SegmentCacheManager
{
@@ -39,116 +44,94 @@ public interface SegmentCacheManager
boolean canHandleSegments();
/**
- * Return a list of cached segments from local disk, if any. This should be called only
- * when {@link #canHandleSegments()} is true.
+ * Return a list of cached segments from local disk, if any. This should be called only when
+ * {@link #canHandleSegments()} is true.
*/
List<DataSegment> getCachedSegments() throws IOException;
/**
- * Store a segment info file for the supplied segment on disk. This operation is idempotent when called
- * multiple times for a given segment.
+ * Store a segment info file for the supplied segment on disk. This operation is idempotent when called multiple
+ * times for a given segment.
*/
void storeInfoFile(DataSegment segment) throws IOException;
/**
- * Remove the segment info file for the supplied segment from disk. If the file cannot be
- * deleted, do nothing.
+ * Remove the segment info file for the supplied segment from disk. If the file cannot be deleted, do nothing.
*
- * @see SegmentCacheManager#cleanup(DataSegment)
+ * @see SegmentCacheManager#drop(DataSegment)
*/
void removeInfoFile(DataSegment segment);
+
/**
- * Returns a {@link ReferenceCountedSegmentProvider} that will be added by the {@link org.apache.druid.server.SegmentManager}
- * to the {@link org.apache.druid.timeline.VersionedIntervalTimeline}. This method can be called multiple times
- * by the {@link org.apache.druid.server.SegmentManager} and implementation can either return same {@link ReferenceCountedSegmentProvider}
- * or a different {@link ReferenceCountedSegmentProvider}. Caller should not assume any particular behavior.
- * <p>
- * Returning a {@code ReferenceCountingSegment} will let custom implementations keep track of reference count for
- * segments that the custom implementations are creating. That way, custom implementations can know when the segment
- * is in use or not.
- * </p>
- * @param segment Segment to get on each download after service bootstrap
- * @throws SegmentLoadingException If there is an error in loading the segment
- * @see SegmentCacheManager#getBootstrapSegment(DataSegment, SegmentLazyLoadFailCallback)
+ * Given a {@link DataSegment}, which contains the instructions for where and how to fetch a {@link Segment} from
+ * deep storage, this method tries to load and subsequently serve it to callers via
+ * {@link #acquireCachedSegment(DataSegment)} or {@link #acquireSegment(DataSegment)}. If the segment
+ * cannot be loaded either due to error or insufficient storage space, this method throws a
+ * {@link SegmentLoadingException}.
+ *
+ * @param segment Segment to get on each download (after service bootstrap)
+ * @throws SegmentLoadingException If there is an error in loading the segment or insufficient storage space
+ * @see SegmentCacheManager#bootstrap(DataSegment, SegmentLazyLoadFailCallback)
*/
- ReferenceCountedSegmentProvider getSegment(DataSegment segment) throws SegmentLoadingException;
+ void load(DataSegment segment) throws SegmentLoadingException;
/**
- * Similar to {@link #getSegment(DataSegment)}, this method returns a {@link ReferenceCountedSegmentProvider} that will be
- * added by the {@link org.apache.druid.server.SegmentManager} to the {@link org.apache.druid.timeline.VersionedIntervalTimeline}
- * during startup on data nodes.
- * @param segment Segment to retrieve during service bootstrap
+ * Similar to {@link #load(DataSegment)}, this method loads segments during startup on data nodes. Implementations of
+ * this method may be configured to use a larger than normal work pool that only exists during startup and is shutdown
+ * after startup by calling {@link #shutdownBootstrap()}
+ *
+ * @param segment Segment to retrieve during service bootstrap
* @param loadFailed Callback to execute when segment lazy load failed. This applies only when
* {@code lazyLoadOnStart} is enabled
- * @throws SegmentLoadingException - If there is an error in loading the segment
- * @see SegmentCacheManager#getSegment(DataSegment)
- */
- ReferenceCountedSegmentProvider getBootstrapSegment(
- DataSegment segment,
- SegmentLazyLoadFailCallback loadFailed
- ) throws SegmentLoadingException;
-
- /**
- * This method fetches the files for the given segment if the segment is not downloaded already. It
- * is not required to {@link #reserve(DataSegment)} before calling this method. If caller has not reserved
- * the space explicitly via {@link #reserve(DataSegment)}, the implementation should reserve space on caller's
- * behalf.
- * If the space has been explicitly reserved already
- * - implementation should use only the reserved space to store segment files.
- * - implementation should not release the location in case of download erros and leave it to the caller.
- * @throws SegmentLoadingException if there is an error in downloading files
+ * @throws SegmentLoadingException - If there is an error in loading the segment or insufficient storage space
+ * @see SegmentCacheManager#load(DataSegment)
+ * @see SegmentCacheManager#shutdownBootstrap()
*/
- File getSegmentFiles(DataSegment segment) throws SegmentLoadingException;
+ void bootstrap(DataSegment segment, SegmentLazyLoadFailCallback loadFailed) throws SegmentLoadingException;
/**
- * Asynchronously load the supplied segment into the page cache on each download after the service finishes bootstrapping.
- * Equivalent to `cat segment_files > /dev/null` to force loading the segment index files into page cache so that
- * later when the segment is queried, they are already in page cache and only a minor page fault needs to be triggered
- * instead of a major page fault to make the query latency more consistent.
+ * Cleanup the segment files cache space used by the segment, releasing the {@link StorageLocation} reservation
*
- * @see SegmentCacheManager#loadSegmentIntoPageCacheOnBootstrap(DataSegment)
+ * @see SegmentCacheManager#removeInfoFile(DataSegment)
*/
- void loadSegmentIntoPageCache(DataSegment segment);
+ void drop(DataSegment segment);
/**
- * Similar to {@link #loadSegmentIntoPageCache(DataSegment)}, but asynchronously load the supplied segment into the
- * page cache during service bootstrap.
- *
- * @see SegmentCacheManager#loadSegmentIntoPageCache(DataSegment)
+ * Applies a {@link SegmentMapFunction} to a {@link Segment} if it is available in the cache. If not present in any
+ * storage location, this method will not attempt to download the {@link DataSegment} from deep storage. The
+ * {@link Segment} returned by this method is considered an open reference, cache implementations must not allow it
+ * to be dropped until it has been closed. As such, the returned {@link Segment} must be closed when the caller is
+ * finished doing segment things.
*/
- void loadSegmentIntoPageCacheOnBootstrap(DataSegment segment);
+ Optional<Segment> acquireCachedSegment(DataSegment dataSegment);
/**
- * Shutdown any previously set up bootstrap executor to save resources.
- * This should be called after loading bootstrap segments into the page cache.
+ * Returns a {@link AcquireSegmentAction} for a given {@link DataSegment} and {@link SegmentDescriptor}, which returns
+ * a reference provider for the {@link Segment} if already present in the cache, or tries to fetch from deep storage
+ * and map if not. The {@link Segment} returned by the provider returned by this method are considered an open
+ * reference, cache implementations must not allow the segment to be dropped until it has been closed. As such, the
+ * returned {@link Segment} from {@link ReferenceCountedObjectProvider#acquireReference()} must be closed when the
+ * caller is finished doing segment things.
*/
- void shutdownBootstrap();
-
- boolean reserve(DataSegment segment);
+ AcquireSegmentAction acquireSegment(DataSegment dataSegment) throws SegmentLoadingException;
/**
- * Reverts the effects of {@link #reserve(DataSegment)} by releasing the location reserved for this segment.
- * Callers that explicitly reserve the space via {@link #reserve(DataSegment)} should use this method to release the space.
- *
- * <p>
- * Implementation can throw error if the space is being released but there is data present. Callers
- * are supposed to ensure that any data is removed via {@link #cleanup(DataSegment)}. Only return a boolean instead
- * of a pointer to {@code StorageLocation} since we don't want callers to operate on {@code StorageLocation} directly
- * outside this interface.
- * </p>
- *
- * @param segment - Segment to release the location for.
- * @return - True if any location was reserved and released, false otherwise.
- *
+ * Alternative to {@link #acquireCachedSegment(DataSegment)}, to return the {@link File} location of the segment files
+ * stored in the cache, instead of a {@link Optional<Segment>}. Unlike {@link #acquireCachedSegment(DataSegment)} and
+ * {@link #acquireSegment(DataSegment)}, this method does not provide any protections for callers,
+ * and should only be used by callers that are in control of when {@link #drop(DataSegment)} is called. This method
+ * will not download the segment files from deep storage if they do not already exist in the cache, callers should use
+ * {@link #load(DataSegment)} before calling this method.
*/
- boolean release(DataSegment segment);
+ @Nullable
+ File getSegmentFiles(DataSegment segment) throws SegmentLoadingException;
/**
- * Cleanup the segment files cache space used by the segment. It will not release the space if the
- * space has been explicitly reserved via {@link #reserve(DataSegment)}.
- *
- * @see SegmentCacheManager#removeInfoFile(DataSegment)
+ * Shutdown any previously set-up bootstrap executor to save resources. This should be called after loading bootstrap
+ * segments.
*/
- void cleanup(DataSegment segment);
+ void shutdownBootstrap();
+
+ void shutdown();
}
diff --git a/server/src/main/java/org/apache/druid/segment/loading/SegmentLoaderConfig.java b/server/src/main/java/org/apache/druid/segment/loading/SegmentLoaderConfig.java
index 98ae16e4918..e4822f0661b 100644
--- a/server/src/main/java/org/apache/druid/segment/loading/SegmentLoaderConfig.java
+++ b/server/src/main/java/org/apache/druid/segment/loading/SegmentLoaderConfig.java
@@ -19,9 +19,10 @@
package org.apache.druid.segment.loading;
+import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Lists;
-import org.apache.druid.utils.JvmUtils;
+import org.apache.druid.utils.RuntimeInfo;
import java.io.File;
import java.util.Collections;
@@ -34,6 +35,9 @@ import java.util.stream.Collectors;
*/
public class SegmentLoaderConfig
{
+ @JacksonInject
+ private final RuntimeInfo runtimeInfo = new RuntimeInfo();
+
@JsonProperty
private List<StorageLocationConfig> locations = Collections.emptyList();
@@ -50,7 +54,7 @@ public class SegmentLoaderConfig
private int announceIntervalMillis = 0; // do not background announce
@JsonProperty("numLoadingThreads")
- private int numLoadingThreads = Math.max(1, JvmUtils.getRuntimeInfo().getAvailableProcessors() / 6);
+ private int numLoadingThreads = Math.max(1, runtimeInfo.getAvailableProcessors() / 6);
@JsonProperty("numBootstrapThreads")
private Integer numBootstrapThreads = null;
@@ -67,6 +71,12 @@ public class SegmentLoaderConfig
@JsonProperty
private int statusQueueMaxSize = 100;
+ @JsonProperty("virtualStorage")
+ private boolean virtualStorage = false;
+
+ @JsonProperty("virtualStorageLoadThreads")
+ private int virtualStorageLoadThreads = 2 * runtimeInfo.getAvailableProcessors();
+
private long combinedMaxSize = 0;
public List<StorageLocationConfig> getLocations()
@@ -134,6 +144,16 @@ public class SegmentLoaderConfig
return combinedMaxSize;
}
+ public boolean isVirtualStorage()
+ {
+ return virtualStorage;
+ }
+
+ public int getVirtualStorageLoadThreads()
+ {
+ return virtualStorageLoadThreads;
+ }
+
public SegmentLoaderConfig withLocations(List<StorageLocationConfig> locations)
{
SegmentLoaderConfig retVal = new SegmentLoaderConfig();
@@ -163,9 +183,19 @@ public class SegmentLoaderConfig
{
return "SegmentLoaderConfig{" +
"locations=" + locations +
+ ", lazyLoadOnStart=" + lazyLoadOnStart +
", deleteOnRemove=" + deleteOnRemove +
", dropSegmentDelayMillis=" + dropSegmentDelayMillis +
+ ", announceIntervalMillis=" + announceIntervalMillis +
+ ", numLoadingThreads=" + numLoadingThreads +
+ ", numBootstrapThreads=" + numBootstrapThreads +
+ ", numThreadsToLoadSegmentsIntoPageCacheOnDownload=" + numThreadsToLoadSegmentsIntoPageCacheOnDownload +
+ ", numThreadsToLoadSegmentsIntoPageCacheOnBootstrap=" + numThreadsToLoadSegmentsIntoPageCacheOnBootstrap +
", infoDir=" + infoDir +
+ ", statusQueueMaxSize=" + statusQueueMaxSize +
+ ", useVirtualStorageFabric=" + virtualStorage +
+ ", virtualStorageFabricLoadThreads=" + virtualStorageLoadThreads +
+ ", combinedMaxSize=" + combinedMaxSize +
'}';
}
}
diff --git a/server/src/main/java/org/apache/druid/segment/loading/SegmentLocalCacheManager.java b/server/src/main/java/org/apache/druid/segment/loading/SegmentLocalCacheManager.java
index 37c15cb9206..8ed033683aa 100644
--- a/server/src/main/java/org/apache/druid/segment/loading/SegmentLocalCacheManager.java
+++ b/server/src/main/java/org/apache/druid/segment/loading/SegmentLocalCacheManager.java
@@ -21,6 +21,12 @@ package org.apache.druid.segment.loading;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Suppliers;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.inject.Inject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
@@ -29,13 +35,16 @@ import org.apache.druid.guice.annotations.Json;
import org.apache.druid.java.util.common.FileUtils;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.concurrent.Execs;
+import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.segment.IndexIO;
+import org.apache.druid.segment.ReferenceCountedObjectProvider;
import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentLazyLoadFailCallback;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
+import org.apache.druid.utils.CloseableUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -43,12 +52,17 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.locks.Lock;
+import java.util.function.Supplier;
/**
*
@@ -65,35 +79,36 @@ public class SegmentLocalCacheManager implements SegmentCacheManager
private final List<StorageLocation> locations;
- // This directoryWriteRemoveLock is used when creating or removing a directory
- private final Object directoryWriteRemoveLock = new Object();
-
/**
* A map between segment and referenceCountingLocks.
- *
- * These locks should be acquired whenever getting or deleting files for a segment.
- * If different threads try to get or delete files simultaneously, one of them creates a lock first using
- * {@link #createOrGetLock}. And then, all threads compete with each other to get the lock.
- * Finally, the lock should be released using {@link #unlock}.
- *
+ * <p>
+ * These locks should be acquired whenever assigning a segment to a location. If different threads try to load
+ * segments simultaneously, one of them creates a lock first using {@link #lock(DataSegment)}. And then, all threads
+ * compete with each other to get the lock. Finally, the lock should be released using
+ * {@link #unlock(DataSegment, ReferenceCountingLock)}. A lock must be acquired any time a {@link SegmentCacheEntry}
+ * needs to be assigned to a {@link StorageLocation}.
+ * <p>
* An example usage is:
- *
- * final ReferenceCountingLock lock = createOrGetLock(segment);
+ * <p>
+ * final ReferenceCountingLock lock = lock(dataSegment);
* synchronized (lock) {
* try {
- * doSomething();
+ * // assign location
+ * ...
* }
* finally {
- * unlock(lock);
+ * unlock(dataSegment, lock);
* }
* }
*/
+
private final ConcurrentHashMap<DataSegment, ReferenceCountingLock> segmentLocks = new ConcurrentHashMap<>();
private final StorageLocationSelectorStrategy strategy;
private final IndexIO indexIO;
+ private final ListeningExecutorService virtualStorageLoadOnDemandExec;
private ExecutorService loadOnBootstrapExec = null;
private ExecutorService loadOnDownloadExec = null;
@@ -113,24 +128,47 @@ public class SegmentLocalCacheManager implements SegmentCacheManager
this.indexIO = indexIO;
log.info("Using storage location strategy[%s].", this.strategy.getClass().getSimpleName());
- log.info(
- "Number of threads to load segments into page cache - on bootstrap: [%d], on download: [%d].",
- config.getNumThreadsToLoadSegmentsIntoPageCacheOnBootstrap(),
- config.getNumThreadsToLoadSegmentsIntoPageCacheOnDownload()
- );
- if (config.getNumThreadsToLoadSegmentsIntoPageCacheOnBootstrap() > 0) {
- loadOnBootstrapExec = Execs.multiThreaded(
+ if (config.isVirtualStorage()) {
+ log.info(
+ "Using virtual storage mode - on demand load threads: [%d].",
+ config.getVirtualStorageLoadThreads()
+ );
+ if (config.getNumThreadsToLoadSegmentsIntoPageCacheOnDownload() > 0) {
+ throw DruidException.defensive("Invalid configuration: virtualStorage is incompatible with numThreadsToLoadSegmentsIntoPageCacheOnDownload");
+ }
+ if (config.getNumThreadsToLoadSegmentsIntoPageCacheOnBootstrap() > 0) {
+ throw DruidException.defensive("Invalid configuration: virtualStorage is incompatible with numThreadsToLoadSegmentsIntoPageCacheOnBootstrap");
+ }
+ virtualStorageLoadOnDemandExec =
+ MoreExecutors.listeningDecorator(
+ // probably replace this with virtual threads once minimum version is java 21
+ Executors.newFixedThreadPool(
+ config.getVirtualStorageLoadThreads(),
+ Execs.makeThreadFactory("VirtualStorageOnDemandLoadingThread-%s")
+ )
+ );
+ } else {
+ log.info(
+ "Number of threads to load segments into page cache - on bootstrap: [%d], on download: [%d].",
config.getNumThreadsToLoadSegmentsIntoPageCacheOnBootstrap(),
- "Load-SegmentsIntoPageCacheOnBootstrap-%s"
+ config.getNumThreadsToLoadSegmentsIntoPageCacheOnDownload()
);
- }
- if (config.getNumThreadsToLoadSegmentsIntoPageCacheOnDownload() > 0) {
- loadOnDownloadExec = Executors.newFixedThreadPool(
- config.getNumThreadsToLoadSegmentsIntoPageCacheOnDownload(),
- Execs.makeThreadFactory("LoadSegmentsIntoPageCacheOnDownload-%s")
- );
+ if (config.getNumThreadsToLoadSegmentsIntoPageCacheOnBootstrap() > 0) {
+ loadOnBootstrapExec = Execs.multiThreaded(
+ config.getNumThreadsToLoadSegmentsIntoPageCacheOnBootstrap(),
+ "Load-SegmentsIntoPageCacheOnBootstrap-%s"
+ );
+ }
+
+ if (config.getNumThreadsToLoadSegmentsIntoPageCacheOnDownload() > 0) {
+ loadOnDownloadExec = Executors.newFixedThreadPool(
+ config.getNumThreadsToLoadSegmentsIntoPageCacheOnDownload(),
+ Execs.makeThreadFactory("LoadSegmentsIntoPageCacheOnDownload-%s")
+ );
+ }
+ virtualStorageLoadOnDemandExec = null;
}
}
@@ -163,12 +201,46 @@ public class SegmentLocalCacheManager implements SegmentCacheManager
log.info("Loading segment cache file [%d/%d][%s].", i + 1, segmentsToLoad.length, file);
try {
final DataSegment segment = jsonMapper.readValue(file, DataSegment.class);
+ boolean removeInfo = false;
if (!segment.getId().toString().equals(file.getName())) {
log.warn("Ignoring cache file[%s] for segment[%s].", file.getPath(), segment.getId());
ignored++;
- } else if (isSegmentCached(segment)) {
- cachedSegments.add(segment);
} else {
+ removeInfo = true;
+ final SegmentCacheEntry cacheEntry = new SegmentCacheEntry(segment);
+ for (StorageLocation location : locations) {
+ // check for migrate from old nested local storage path format
+ final File legacyPath = new File(location.getPath(), DataSegmentPusher.getDefaultStorageDir(segment, false));
+ if (legacyPath.exists()) {
+ final File destination = cacheEntry.toPotentialLocation(location.getPath());
+ FileUtils.mkdirp(destination);
+ Files.move(legacyPath.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ cleanupLegacyCacheLocation(location.getPath(), legacyPath);
+ }
+
+ if (cacheEntry.checkExists(location.getPath())) {
+ removeInfo = false;
+ final boolean reserveResult;
+ if (config.isVirtualStorage()) {
+ reserveResult = location.reserveWeak(cacheEntry);
+ } else {
+ reserveResult = location.reserve(cacheEntry);
+ }
+ if (!reserveResult) {
+ log.makeAlert(
+ "storage[%s:%,d] has more segments than it is allowed. Currently loading Segment[%s:%,d]. Please increase druid.segmentCache.locations maxSize param",
+ location.getPath(),
+ location.availableSizeBytes(),
+ segment.getId(),
+ segment.getSize()
+ ).emit();
+ }
+ cachedSegments.add(segment);
+ }
+ }
+ }
+
+ if (removeInfo) {
final SegmentId segmentId = segment.getId();
log.warn("Unable to find cache file for segment[%s]. Deleting lookup entry.", segmentId);
removeInfoFile(segment);
@@ -191,7 +263,7 @@ public class SegmentLocalCacheManager implements SegmentCacheManager
}
@Override
- public void storeInfoFile(DataSegment segment) throws IOException
+ public void storeInfoFile(final DataSegment segment) throws IOException
{
final File segmentInfoCacheFile = new File(getEffectiveInfoDir(), segment.getId().toString());
if (!segmentInfoCacheFile.exists()) {
@@ -200,7 +272,7 @@ public class SegmentLocalCacheManager implements SegmentCacheManager
}
@Override
- public void removeInfoFile(DataSegment segment)
+ public void removeInfoFile(final DataSegment segment)
{
final File segmentInfoCacheFile = new File(getEffectiveInfoDir(), segment.getId().toString());
if (!segmentInfoCacheFile.delete()) {
@@ -209,44 +281,264 @@ public class SegmentLocalCacheManager implements SegmentCacheManager
}
@Override
- public ReferenceCountedSegmentProvider getSegment(final DataSegment dataSegment) throws SegmentLoadingException
+ public Optional<Segment> acquireCachedSegment(final DataSegment dataSegment)
{
- final File segmentFiles = getSegmentFiles(dataSegment);
- final SegmentizerFactory factory = getSegmentFactory(segmentFiles);
+ final SegmentCacheEntryIdentifier cacheEntryIdentifier = new SegmentCacheEntryIdentifier(dataSegment.getId());
+ for (StorageLocation location : locations) {
+ final SegmentCacheEntry cacheEntry = location.getStaticCacheEntry(cacheEntryIdentifier);
+ if (cacheEntry != null) {
+ return cacheEntry.acquireReference();
+ }
+ final StorageLocation.ReservationHold<SegmentCacheEntry> hold =
+ location.addWeakReservationHoldIfExists(cacheEntryIdentifier);
+ try {
+ if (hold != null) {
+
+ if (hold.getEntry().isMounted()) {
+ Optional<Segment> segment = hold.getEntry().acquireReference();
+ if (segment.isPresent()) {
+ return ReferenceCountedSegmentProvider.wrapCloseable(
+ (ReferenceCountedSegmentProvider.LeafReference) segment.get(),
+ hold
+ );
+ }
+ }
- final Segment segment = factory.factorize(dataSegment, segmentFiles, false, SegmentLazyLoadFailCallback.NOOP);
- return ReferenceCountedSegmentProvider.wrapSegment(segment, dataSegment.getShardSpec());
+ hold.close();
+ }
+ }
+ catch (Throwable e) {
+ hold.close();
+ throw e;
+ }
+ }
+ return Optional.empty();
}
@Override
- public ReferenceCountedSegmentProvider getBootstrapSegment(
+ public AcquireSegmentAction acquireSegment(final DataSegment dataSegment) throws SegmentLoadingException
+ {
+ final SegmentCacheEntryIdentifier identifier = new SegmentCacheEntryIdentifier(dataSegment.getId());
+ final AcquireSegmentAction acquireExisting = acquireExistingSegment(identifier);
+ if (acquireExisting != null) {
+ return acquireExisting;
+ }
+
+ final ReferenceCountingLock lock = lock(dataSegment);
+ synchronized (lock) {
+ try {
+ final AcquireSegmentAction retryAcquireExisting = acquireExistingSegment(identifier);
+ if (retryAcquireExisting != null) {
+ return retryAcquireExisting;
+ }
+ final Iterator<StorageLocation> iterator = strategy.getLocations();
+ while (iterator.hasNext()) {
+ final StorageLocation location = iterator.next();
+ final StorageLocation.ReservationHold<SegmentCacheEntry> hold = location.addWeakReservationHold(
+ identifier,
+ () -> new SegmentCacheEntry(dataSegment)
+ );
+ try {
+ if (hold != null) {
+ return new AcquireSegmentAction(
+ makeOnDemandLoadSupplier(hold.getEntry(), location),
+ hold
+ );
+ }
+ }
+ catch (Throwable t) {
+ throw CloseableUtils.closeAndWrapInCatch(t, hold);
+ }
+ }
+ throw DruidException.forPersona(DruidException.Persona.USER)
+ .ofCategory(DruidException.Category.CAPACITY_EXCEEDED)
+ .build(
+ "Unable to load segment[%s] on demand, ensure enough disk space has been allocated to load all segments involved in the query",
+ dataSegment.getId()
+ );
+ }
+ finally {
+ unlock(dataSegment, lock);
+ }
+ }
+ }
+
+ @Nullable
+ private AcquireSegmentAction acquireExistingSegment(SegmentCacheEntryIdentifier identifier)
+ {
+ final Closer safetyNet = Closer.create();
+ for (StorageLocation location : locations) {
+ try {
+ final StorageLocation.ReservationHold<SegmentCacheEntry> hold = safetyNet.register(
+ location.addWeakReservationHoldIfExists(identifier)
+ );
+ if (hold != null) {
+ if (hold.getEntry().isMounted()) {
+ return new AcquireSegmentAction(
+ () -> Futures.immediateFuture(hold.getEntry().referenceProvider),
+ hold
+ );
+ } else {
+ // go ahead and mount it, someone else is probably trying this as well, but mount is done under a segment
+ // lock and is a no-op if already mounted, and if we win we need it to be mounted
+ return new AcquireSegmentAction(
+ makeOnDemandLoadSupplier(hold.getEntry(), location),
+ hold
+ );
+ }
+ }
+ }
+ catch (Throwable t) {
+ throw CloseableUtils.closeAndWrapInCatch(t, safetyNet);
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public void load(final DataSegment dataSegment) throws SegmentLoadingException
+ {
+ if (config.isVirtualStorage()) {
+ // no-op, we'll do a load when someone asks for the segment
+ return;
+ }
+ final SegmentCacheEntry cacheEntry = new SegmentCacheEntry(dataSegment);
+ final ReferenceCountingLock lock = lock(dataSegment);
+ synchronized (lock) {
+ try {
+ final SegmentCacheEntry entry = assignLocationAndMount(cacheEntry, SegmentLazyLoadFailCallback.NOOP);
+ if (loadOnDownloadExec != null) {
+ loadOnDownloadExec.submit(entry::loadIntoPageCache);
+ }
+ }
+ finally {
+ unlock(dataSegment, lock);
+ }
+ }
+ }
+
+ @Override
+ public void bootstrap(
final DataSegment dataSegment,
final SegmentLazyLoadFailCallback loadFailed
) throws SegmentLoadingException
{
- final File segmentFiles = getSegmentFiles(dataSegment);
- final SegmentizerFactory factory = getSegmentFactory(segmentFiles);
-
- final Segment segment = factory.factorize(dataSegment, segmentFiles, config.isLazyLoadOnStart(), loadFailed);
- return ReferenceCountedSegmentProvider.wrapSegment(segment, dataSegment.getShardSpec());
+ if (config.isVirtualStorage()) {
+ // during bootstrap, check if the segment exists in a location and mount it, getCachedSegments already
+ // did the reserving for us
+ final SegmentCacheEntryIdentifier id = new SegmentCacheEntryIdentifier(dataSegment.getId());
+ final ReferenceCountingLock lock = lock(dataSegment);
+ synchronized (lock) {
+ try {
+ for (StorageLocation location : locations) {
+ final SegmentCacheEntry entry = location.getCacheEntry(id);
+ if (entry != null) {
+ entry.lazyLoadCallback = loadFailed;
+ entry.mount(location);
+ }
+ }
+ }
+ finally {
+ unlock(dataSegment, lock);
+ }
+ }
+ return;
+ }
+ final ReferenceCountingLock lock = lock(dataSegment);
+ synchronized (lock) {
+ try {
+ final SegmentCacheEntry entry = assignLocationAndMount(new SegmentCacheEntry(dataSegment), loadFailed);
+ if (loadOnBootstrapExec != null) {
+ loadOnBootstrapExec.submit(entry::loadIntoPageCache);
+ }
+ }
+ finally {
+ unlock(dataSegment, lock);
+ }
+ }
}
- private SegmentizerFactory getSegmentFactory(final File segmentFiles) throws SegmentLoadingException
+ @Nullable
+ @Override
+ public File getSegmentFiles(final DataSegment segment)
{
- final File factoryJson = new File(segmentFiles, "factory.json");
- final SegmentizerFactory factory;
-
- if (factoryJson.exists()) {
+ final SegmentCacheEntry cacheEntry = new SegmentCacheEntry(segment);
+ final ReferenceCountingLock lock = lock(segment);
+ synchronized (lock) {
try {
- factory = jsonMapper.readValue(factoryJson, SegmentizerFactory.class);
+ for (StorageLocation location : locations) {
+ final SegmentCacheEntry entry = location.getCacheEntry(cacheEntry.id);
+ if (entry != null) {
+ return entry.storageDir;
+ }
+ }
}
- catch (IOException e) {
- throw new SegmentLoadingException(e, "Failed to get segment facotry for %s", e.getMessage());
+ finally {
+ unlock(segment, lock);
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public void drop(final DataSegment segment)
+ {
+ final SegmentCacheEntryIdentifier id = new SegmentCacheEntryIdentifier(segment.getId());
+ for (StorageLocation location : locations) {
+ final SegmentCacheEntry entry = location.getCacheEntry(id);
+ if (entry != null) {
+ location.release(entry);
}
- } else {
- factory = new MMappedQueryableSegmentizerFactory(indexIO);
}
- return factory;
+ }
+
+ @Override
+ public void shutdownBootstrap()
+ {
+ if (loadOnBootstrapExec == null) {
+ return;
+ }
+ loadOnBootstrapExec.shutdown();
+ }
+
+ @Override
+ public void shutdown()
+ {
+ if (loadOnDownloadExec != null) {
+ loadOnDownloadExec.shutdown();
+ }
+ if (virtualStorageLoadOnDemandExec != null) {
+ virtualStorageLoadOnDemandExec.shutdown();
+ }
+ }
+
+ @VisibleForTesting
+ public ConcurrentHashMap<DataSegment, ReferenceCountingLock> getSegmentLocks()
+ {
+ return segmentLocks;
+ }
+
+ @VisibleForTesting
+ List<StorageLocation> getLocations()
+ {
+ return locations;
+ }
+
+ /**
+ * Checks whether a segment is already cached. This method does not confirm if the segment is actually mounted in
+ * the location, or even that the segment files in some location are valid, just that some files exist in the
+ * specified location
+ */
+ @VisibleForTesting
+ boolean isSegmentCached(final DataSegment segment)
+ {
+ final SegmentCacheEntry cacheEntry = new SegmentCacheEntry(segment);
+ for (StorageLocation location : locations) {
+ if (cacheEntry.checkExists(location.getPath())) {
+ return true;
+ }
+ }
+ return false;
}
/**
@@ -272,481 +564,456 @@ public class SegmentLocalCacheManager implements SegmentCacheManager
infoDir = new File(locations.get(0).getPath(), "info_dir");
} else {
throw DruidException.forPersona(DruidException.Persona.OPERATOR)
- .ofCategory(DruidException.Category.NOT_FOUND)
- .build("Could not determine infoDir. Make sure 'druid.segmentCache.infoDir' "
- + "or 'druid.segmentCache.locations' is set correctly.");
+ .ofCategory(DruidException.Category.NOT_FOUND)
+ .build("Could not determine infoDir. Make sure 'druid.segmentCache.infoDir' "
+ + "or 'druid.segmentCache.locations' is set correctly.");
}
return infoDir;
}
- private static String getSegmentDir(DataSegment segment)
+ private Supplier<ListenableFuture<ReferenceCountedObjectProvider<Segment>>> makeOnDemandLoadSupplier(
+ final SegmentCacheEntry entry,
+ final StorageLocation location
+ )
{
- return DataSegmentPusher.getDefaultStorageDir(segment, false);
+ return Suppliers.memoize(
+ () -> virtualStorageLoadOnDemandExec.submit(
+ () -> {
+ entry.mount(location);
+ return entry.referenceProvider;
+ }
+ )
+ );
}
- /**
- * Checks whether a segment is already cached. It can return false even if {@link #reserve(DataSegment)}
- * has been successful for a segment but is not downloaded yet.
- */
- boolean isSegmentCached(final DataSegment segment)
+ private ReferenceCountingLock lock(final DataSegment dataSegment)
{
- return findStoragePathIfCached(segment) != null;
+ return segmentLocks.compute(
+ dataSegment,
+ (segment, lock) -> {
+ final ReferenceCountingLock nonNullLock;
+ if (lock == null) {
+ nonNullLock = new ReferenceCountingLock();
+ } else {
+ nonNullLock = lock;
+ }
+ nonNullLock.increment();
+ return nonNullLock;
+ }
+ );
}
- /**
- * This method will try to find if the segment is already downloaded on any location. If so, the segment path
- * is returned. Along with that, location state is also updated with the segment location. Refer to
- * {@link StorageLocation#maybeReserve(String, DataSegment)} for more details.
- * If the segment files are damaged in any location, they are removed from the location.
- * @param segment - Segment to check
- * @return - Path corresponding to segment directory if found, null otherwise.
- */
- @Nullable
- private File findStoragePathIfCached(final DataSegment segment)
+ private void unlock(final DataSegment dataSegment, final ReferenceCountingLock lock)
{
- for (StorageLocation location : locations) {
- String storageDir = getSegmentDir(segment);
- File localStorageDir = location.segmentDirectoryAsFile(storageDir);
- if (localStorageDir.exists()) {
- if (checkSegmentFilesIntact(localStorageDir)) {
- log.warn(
- "[%s] may be damaged. Delete all the segment files and pull from DeepStorage again.",
- localStorageDir.getAbsolutePath()
- );
- cleanupCacheFiles(location.getPath(), localStorageDir);
- location.removeSegmentDir(localStorageDir, segment);
- break;
- } else {
- // Before returning, we also reserve the space. Refer to the StorageLocation#maybeReserve documentation for details.
- location.maybeReserve(storageDir, segment);
- return localStorageDir;
+ segmentLocks.compute(
+ dataSegment,
+ (segment, existingLock) -> {
+ if (existingLock == null) {
+ throw new ISE("Lock has already been removed");
+ } else if (existingLock != lock) {
+ throw new ISE("Different lock instance");
+ } else {
+ if (existingLock.numReferences == 1) {
+ return null;
+ } else {
+ existingLock.decrement();
+ return existingLock;
+ }
+ }
}
- }
- }
- return null;
+ );
}
- /**
- * check data intact.
- * @param dir segments cache dir
- * @return true means segment files may be damaged.
- */
- private boolean checkSegmentFilesIntact(File dir)
+ private SegmentCacheEntry assignLocationAndMount(
+ final SegmentCacheEntry cacheEntry,
+ final SegmentLazyLoadFailCallback segmentLoadFailCallback
+ ) throws SegmentLoadingException
{
- return checkSegmentFilesIntactWithStartMarker(dir);
+ try {
+ for (StorageLocation location : locations) {
+ if (cacheEntry.checkExists(location.getPath())) {
+ if (location.isReserved(cacheEntry.id) || location.reserve(cacheEntry)) {
+ final SegmentCacheEntry entry = location.getCacheEntry(cacheEntry.id);
+ entry.lazyLoadCallback = segmentLoadFailCallback;
+ entry.mount(location);
+ return entry;
+ } else {
+ // entry is not reserved, clean it up
+ deleteCacheEntryDirectory(cacheEntry.toPotentialLocation(location.getPath()));
+ }
+ }
+ }
+ }
+ catch (SegmentLoadingException e) {
+ log.warn(e, "Failed to load segment[%s] in existing location, trying new location", cacheEntry.id);
+ }
+ final Iterator<StorageLocation> locationsIterator = strategy.getLocations();
+ while (locationsIterator.hasNext()) {
+ final StorageLocation location = locationsIterator.next();
+ if (location.reserve(cacheEntry)) {
+ try {
+ final SegmentCacheEntry entry = location.getCacheEntry(cacheEntry.id);
+ entry.lazyLoadCallback = segmentLoadFailCallback;
+ entry.mount(location);
+ return entry;
+ }
+ catch (SegmentLoadingException e) {
+ log.warn(e, "Failed to load segment[%s] in location[%s], trying next location", cacheEntry.id, location.getPath());
+ }
+ }
+ }
+ throw new SegmentLoadingException("Failed to load segment[%s] in all locations.", cacheEntry.id);
}
/**
- * If there is 'downloadStartMarker' existed in localStorageDir, the segments files might be damaged.
- * Because each time, Druid will delete the 'downloadStartMarker' file after pulling and unzip the segments from DeepStorage.
- * downloadStartMarker existed here may mean something error during download segments and the segment files may be damaged.
+ * Deletes a directory and logs about it. This method should only be called under the lock of a {@link #segmentLocks}
*/
- private boolean checkSegmentFilesIntactWithStartMarker(File localStorageDir)
+ private static void deleteCacheEntryDirectory(final File path)
{
- final File downloadStartMarker = new File(localStorageDir.getPath(), DOWNLOAD_START_MARKER_FILE_NAME);
- return downloadStartMarker.exists();
+ log.info("Deleting directory[%s]", path);
+ try {
+ FileUtils.deleteDirectory(path);
+ }
+ catch (Exception e) {
+ log.error(e, "Unable to remove directory[%s]", path);
+ }
}
/**
- * Make sure segments files in loc is intact, otherwise function like loadSegments will failed because of segment files is damaged.
- * @param segment
- * @return
- * @throws SegmentLoadingException
+ * Calls {@link #deleteCacheEntryDirectory(File)} and then checks parent path if it is empty, and recursively
+ * continues until a non-empty directory or the base path is reached. This method is not thread-safe, and should only
+ * be used by a single caller.
*/
- @Override
- public File getSegmentFiles(DataSegment segment) throws SegmentLoadingException
+ private static void cleanupLegacyCacheLocation(final File baseFile, final File cacheFile)
{
- final ReferenceCountingLock lock = createOrGetLock(segment);
- synchronized (lock) {
- try {
- File segmentDir = findStoragePathIfCached(segment);
- if (segmentDir != null) {
- return segmentDir;
- }
+ if (cacheFile.equals(baseFile)) {
+ return;
+ }
- return loadSegmentWithRetry(segment);
- }
- finally {
- unlock(segment, lock);
+ deleteCacheEntryDirectory(cacheFile);
+
+ File parent = cacheFile.getParentFile();
+ if (parent != null) {
+ File[] children = parent.listFiles();
+ if (children == null || children.length == 0) {
+ cleanupLegacyCacheLocation(baseFile, parent);
}
}
}
/**
- * If we have already reserved a location before, probably via {@link #reserve(DataSegment)}, then only that location
- * should be tried. Otherwise, we would fetch locations using {@link StorageLocationSelectorStrategy} and try all
- * of them one by one till there is success.
- * Location may fail because of IO failure, most likely in two cases:<p>
- * 1. druid don't have the write access to this location, most likely the administrator doesn't config it correctly<p>
- * 2. disk failure, druid can't read/write to this disk anymore
- * <p>
- * Locations are fetched using {@link StorageLocationSelectorStrategy}.
+ * check if segment data is possibly corrupted.
+ * @param dir segments cache dir
+ * @return true means segment files may be damaged.
*/
- private File loadSegmentWithRetry(DataSegment segment) throws SegmentLoadingException
+ private static boolean isPossiblyCorrupted(final File dir)
{
- String segmentDir = getSegmentDir(segment);
-
- // Try the already reserved location. If location has been reserved outside, then we do not release the location
- // here and simply delete any downloaded files. That is, we revert anything we do in this function and nothing else.
- for (StorageLocation loc : locations) {
- if (loc.isReserved(segmentDir)) {
- File storageDir = loc.segmentDirectoryAsFile(segmentDir);
- boolean success = loadInLocationWithStartMarkerQuietly(loc, segment, storageDir, false);
- if (!success) {
- throw new SegmentLoadingException(
- "Failed to load segment[%s] in reserved location[%s]", segment.getId(), loc.getPath().getAbsolutePath()
- );
- }
- return storageDir;
- }
- }
-
- // No location was reserved so we try all the locations
- Iterator<StorageLocation> locationsIterator = strategy.getLocations();
- while (locationsIterator.hasNext()) {
-
- StorageLocation loc = locationsIterator.next();
-
- // storageDir is the file path corresponding to segment dir
- File storageDir = loc.reserve(segmentDir, segment);
- if (storageDir != null) {
- boolean success = loadInLocationWithStartMarkerQuietly(loc, segment, storageDir, true);
- if (success) {
- return storageDir;
- }
- }
- }
- throw new SegmentLoadingException("Failed to load segment[%s] in all locations.", segment.getId());
+ return hasStartMarker(dir);
}
/**
- * A helper method over {@link #loadInLocationWithStartMarker(DataSegment, File)} that catches the {@link SegmentLoadingException}
- * and emits alerts.
- * @param loc - {@link StorageLocation} where segment is to be downloaded in.
- * @param segment - {@link DataSegment} to download
- * @param storageDir - {@link File} pointing to segment directory
- * @param releaseLocation - Whether to release the location in case of failures
- * @return - True if segment was downloaded successfully, false otherwise.
+ * If {@link #DOWNLOAD_START_MARKER_FILE_NAME} exists in the path, the segment files might be damaged because this
+ * file is typically deleted after the segment is pulled from deep storage.
*/
- private boolean loadInLocationWithStartMarkerQuietly(StorageLocation loc, DataSegment segment, File storageDir, boolean releaseLocation)
+ private static boolean hasStartMarker(final File localStorageDir)
{
- try {
- loadInLocationWithStartMarker(segment, storageDir);
- return true;
- }
- catch (SegmentLoadingException e) {
- try {
- log.makeAlert(
- e,
- "Failed to load segment in current location [%s], try next location if any",
- loc.getPath().getAbsolutePath()
- ).addData("location", loc.getPath().getAbsolutePath()).emit();
- }
- finally {
- if (releaseLocation) {
- loc.removeSegmentDir(storageDir, segment);
- }
- cleanupCacheFiles(loc.getPath(), storageDir);
- }
- }
- return false;
+ final File downloadStartMarker = new File(localStorageDir.getPath(), DOWNLOAD_START_MARKER_FILE_NAME);
+ return downloadStartMarker.exists();
}
- private void loadInLocationWithStartMarker(DataSegment segment, File storageDir) throws SegmentLoadingException
+ private static final class ReferenceCountingLock
{
- // We use a marker to prevent the case where a segment is downloaded, but before the download completes,
- // the parent directories of the segment are removed
- final File downloadStartMarker = new File(storageDir, DOWNLOAD_START_MARKER_FILE_NAME);
- synchronized (directoryWriteRemoveLock) {
- try {
- FileUtils.mkdirp(storageDir);
-
- if (!downloadStartMarker.createNewFile()) {
- throw new SegmentLoadingException("Was not able to create new download marker for [%s]", storageDir);
- }
- }
- catch (IOException e) {
- throw new SegmentLoadingException(e, "Unable to create marker file for [%s]", storageDir);
- }
- }
- loadInLocation(segment, storageDir);
+ private int numReferences;
- if (!downloadStartMarker.delete()) {
- throw new SegmentLoadingException("Unable to remove marker file for [%s]", storageDir);
+ private void increment()
+ {
+ ++numReferences;
}
- }
- private void loadInLocation(DataSegment segment, File storageDir) throws SegmentLoadingException
- {
- // LoadSpec isn't materialized until here so that any system can interpret Segment without having to have all the
- // LoadSpec dependencies.
- final LoadSpec loadSpec = jsonMapper.convertValue(segment.getLoadSpec(), LoadSpec.class);
- final LoadSpec.LoadSpecResult result = loadSpec.loadSegment(storageDir);
- if (result.getSize() != segment.getSize()) {
- log.warn(
- "Segment [%s] is different than expected size. Expected [%d] found [%d]",
- segment.getId(),
- segment.getSize(),
- result.getSize()
- );
+ private void decrement()
+ {
+ --numReferences;
}
}
- @Override
- public boolean reserve(final DataSegment segment)
+ private final class SegmentCacheEntry implements CacheEntry
{
- final ReferenceCountingLock lock = createOrGetLock(segment);
- synchronized (lock) {
- try {
- // Maybe the segment was already loaded. This check is required to account for restart scenarios.
- if (null != findStoragePathIfCached(segment)) {
- return true;
- }
+ private final SegmentCacheEntryIdentifier id;
+ private final DataSegment dataSegment;
+ private final String relativePathString;
+ private SegmentLazyLoadFailCallback lazyLoadCallback = SegmentLazyLoadFailCallback.NOOP;
+ private StorageLocation location;
+ private File storageDir;
+ private ReferenceCountedSegmentProvider referenceProvider;
- String storageDirStr = getSegmentDir(segment);
+ private SegmentCacheEntry(final DataSegment dataSegment)
+ {
+ this.dataSegment = dataSegment;
+ this.id = new SegmentCacheEntryIdentifier(dataSegment.getId());
+ this.relativePathString = dataSegment.getId().toString();
+ }
- // check if we already reserved the segment
- for (StorageLocation location : locations) {
- if (location.isReserved(storageDirStr)) {
- return true;
- }
- }
+ @Override
+ public SegmentCacheEntryIdentifier getId()
+ {
+ return id;
+ }
- // Not found in any location, reserve now
- for (Iterator<StorageLocation> it = strategy.getLocations(); it.hasNext(); ) {
- StorageLocation location = it.next();
- if (null != location.reserve(storageDirStr, segment)) {
- return true;
- }
- }
- }
- finally {
- unlock(segment, lock);
- }
+ @Override
+ public long getSize()
+ {
+ return dataSegment.getSize();
}
- return false;
- }
+ @Override
+ public synchronized boolean isMounted()
+ {
+ return referenceProvider != null;
+ }
- @Override
- public boolean release(final DataSegment segment)
- {
- final ReferenceCountingLock lock = createOrGetLock(segment);
- synchronized (lock) {
+ @Override
+ public void mount(StorageLocation mountLocation) throws SegmentLoadingException
+ {
+ final Lock lock = mountLocation.getLock().readLock();
+ lock.lock();
try {
- String storageDir = getSegmentDir(segment);
- // Release the first location encountered
- for (StorageLocation location : locations) {
- if (location.isReserved(storageDir)) {
- File localStorageDir = location.segmentDirectoryAsFile(storageDir);
- if (localStorageDir.exists()) {
- throw new ISE(
- "Asking to release a location '%s' while the segment directory '%s' is present on disk. Any state on disk must be deleted before releasing",
- location.getPath().getAbsolutePath(),
- localStorageDir.getAbsolutePath()
+ if (!mountLocation.isReserved(this.id) && !mountLocation.isWeakReserved(this.id)) {
+ log.debug(
+ "aborting mount in location[%s] since entry[%s] is no longer reserved",
+ mountLocation.getPath(),
+ this.id
+ );
+ return;
+ }
+ synchronized (this) {
+ if (location != null) {
+ log.debug(
+ "already mounted [%s] in location[%s], but asked to load in [%s], unmounting old location",
+ id,
+ location.getPath(),
+ mountLocation.getPath()
+ );
+ if (!location.equals(mountLocation)) {
+ throw DruidException.defensive(
+ "already mounted[%s] in location[%s] which is different from requested[%s]",
+ id,
+ location.getPath(),
+ mountLocation.getPath()
+ );
+ } else {
+ log.debug("already mounted [%s] in location[%s]", id, mountLocation.getPath());
+ return;
+ }
+ }
+ location = mountLocation;
+ storageDir = new File(location.getPath(), relativePathString);
+ boolean needsLoad = true;
+ if (storageDir.exists()) {
+ if (isPossiblyCorrupted(storageDir)) {
+ log.warn(
+ "[%s] may be damaged. Delete all the segment files and pull from DeepStorage again.",
+ storageDir.getAbsolutePath()
);
+ deleteCacheEntryDirectory(storageDir);
+ } else {
+ needsLoad = false;
}
- return location.release(storageDir, segment.getSize());
}
+ if (needsLoad) {
+ loadInLocationWithStartMarker(dataSegment, storageDir);
+ }
+ final SegmentizerFactory factory = getSegmentFactory(storageDir);
+
+ final Segment segment = factory.factorize(dataSegment, storageDir, false, lazyLoadCallback);
+ // wipe load callback after calling
+ lazyLoadCallback = SegmentLazyLoadFailCallback.NOOP;
+ referenceProvider = ReferenceCountedSegmentProvider.of(segment);
+ }
+ }
+ catch (SegmentLoadingException e) {
+ try {
+ log.makeAlert(
+ e,
+ "Failed to load segment in current location [%s], try next location if any",
+ location.getPath().getAbsolutePath()
+ ).addData("location", location.getPath().getAbsolutePath()).emit();
+
+ throw new SegmentLoadingException(
+ "Failed to load segment[%s] in reserved location[%s]",
+ dataSegment.getId(),
+ location.getPath().getAbsolutePath()
+ );
+ }
+ finally {
+ unmount();
}
}
+ catch (Throwable t) {
+ unmount();
+ throw t;
+ }
finally {
- unlock(segment, lock);
+ lock.unlock();
}
}
- return false;
- }
-
- @Override
- public void cleanup(DataSegment segment)
- {
- if (!config.isDeleteOnRemove()) {
- return;
- }
-
- final ReferenceCountingLock lock = createOrGetLock(segment);
- synchronized (lock) {
- try {
- File loc = findStoragePathIfCached(segment);
-
- if (loc == null) {
- log.warn("Asked to cleanup something[%s] that didn't exist. Skipping.", segment.getId());
+ @Override
+ public void unmount()
+ {
+ final Lock lock;
+ synchronized (this) {
+ if (location == null) {
return;
}
- // If storageDir.mkdirs() success, but downloadStartMarker.createNewFile() failed,
- // in this case, findStorageLocationIfLoaded() will think segment is located in the failed storageDir which is actually not.
- // So we should always clean all possible locations here
- for (StorageLocation location : locations) {
- File localStorageDir = new File(location.getPath(), getSegmentDir(segment));
- if (localStorageDir.exists()) {
- // Druid creates folders of the form dataSource/interval/version/partitionNum.
- // We need to clean up all these directories if they are all empty.
- cleanupCacheFiles(location.getPath(), localStorageDir);
- location.removeSegmentDir(localStorageDir, segment);
+ lock = location.getLock().readLock();
+ }
+ lock.lock();
+ try {
+ synchronized (this) {
+ if (referenceProvider != null) {
+ referenceProvider.close();
+ referenceProvider = null;
+ }
+ if (!config.isDeleteOnRemove()) {
+ return;
+ }
+ if (storageDir != null) {
+ deleteCacheEntryDirectory(storageDir);
+ storageDir = null;
+ location = null;
}
}
}
finally {
- unlock(segment, lock);
+ lock.unlock();
}
}
- }
- @Override
- public void loadSegmentIntoPageCache(DataSegment segment)
- {
- if (loadOnDownloadExec == null) {
- return;
- }
-
- loadOnDownloadExec.submit(() -> loadSegmentIntoPageCacheInternal(segment));
- }
-
- @Override
- public void loadSegmentIntoPageCacheOnBootstrap(DataSegment segment)
- {
- if (loadOnBootstrapExec == null) {
- return;
+ public synchronized Optional<Segment> acquireReference()
+ {
+ if (referenceProvider == null) {
+ return Optional.empty();
+ }
+ return referenceProvider.acquireReference();
}
- loadOnBootstrapExec.submit(() -> loadSegmentIntoPageCacheInternal(segment));
- }
-
- void loadSegmentIntoPageCacheInternal(DataSegment segment)
- {
- final ReferenceCountingLock lock = createOrGetLock(segment);
- synchronized (lock) {
+ public void loadIntoPageCache()
+ {
+ if (!isMounted()) {
+ return;
+ }
+ final Lock lock;
+ synchronized (this) {
+ lock = location.getLock().readLock();
+ }
+ lock.lock();
try {
- for (StorageLocation location : locations) {
- File localStorageDir = new File(location.getPath(), DataSegmentPusher.getDefaultStorageDir(segment, false));
- if (localStorageDir.exists()) {
- File baseFile = location.getPath();
- if (localStorageDir.equals(baseFile)) {
- continue;
- }
-
- log.info("Loading directory[%s] into page cache.", localStorageDir);
-
- File[] children = localStorageDir.listFiles();
- if (children != null) {
- for (File child : children) {
- try (InputStream in = Files.newInputStream(child.toPath())) {
- IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM);
- log.info("Loaded [%s] into page cache.", child.getAbsolutePath());
- }
- catch (Exception e) {
- log.error(e, "Failed to load [%s] into page cache", child.getAbsolutePath());
- }
+ synchronized (this) {
+ final File[] children = storageDir.listFiles();
+ if (children != null) {
+ for (File child : children) {
+ try (InputStream in = Files.newInputStream(child.toPath())) {
+ IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM);
+ log.info("Loaded [%s] into page cache.", child.getAbsolutePath());
+ }
+ catch (Exception e) {
+ log.error(e, "Failed to load [%s] into page cache", child.getAbsolutePath());
}
}
}
}
}
finally {
- unlock(segment, lock);
+ lock.unlock();
}
}
- }
- @Override
- public void shutdownBootstrap()
- {
- if (loadOnBootstrapExec == null) {
- return;
+ public boolean checkExists(final File location)
+ {
+ return toPotentialLocation(location).exists();
}
- loadOnBootstrapExec.shutdown();
- }
- private void cleanupCacheFiles(File baseFile, File cacheFile)
- {
- if (cacheFile.equals(baseFile)) {
- return;
+ public File toPotentialLocation(final File location)
+ {
+ return new File(location, relativePathString);
}
- synchronized (directoryWriteRemoveLock) {
- log.info("Deleting directory[%s]", cacheFile);
+ @GuardedBy("this")
+ private void loadInLocationWithStartMarker(final DataSegment segment, final File storageDir)
+ throws SegmentLoadingException
+ {
+ // We use a marker to prevent the case where a segment is downloaded, but before the download completes,
+ // the parent directories of the segment are removed
+ final File downloadStartMarker = new File(storageDir, DOWNLOAD_START_MARKER_FILE_NAME);
try {
- FileUtils.deleteDirectory(cacheFile);
+ FileUtils.mkdirp(storageDir);
+
+ if (!downloadStartMarker.createNewFile()) {
+ throw new SegmentLoadingException("Was not able to create new download marker for [%s]", storageDir);
+ }
+ loadInLocation(segment, storageDir);
+
+ if (!downloadStartMarker.delete()) {
+ throw new SegmentLoadingException("Unable to remove marker file for [%s]", storageDir);
+ }
}
- catch (Exception e) {
- log.error(e, "Unable to remove directory[%s]", cacheFile);
+ catch (IOException e) {
+ throw new SegmentLoadingException(e, "Unable to create marker file for [%s]", storageDir);
}
+ }
- File parent = cacheFile.getParentFile();
- if (parent != null) {
- File[] children = parent.listFiles();
- if (children == null || children.length == 0) {
- cleanupCacheFiles(baseFile, parent);
- }
+ @GuardedBy("this")
+ private void loadInLocation(final DataSegment segment, final File storageDir)
+ throws SegmentLoadingException
+ {
+ // LoadSpec isn't materialized until here so that any system can interpret Segment without having to have all the
+ // LoadSpec dependencies.
+ final LoadSpec loadSpec = jsonMapper.convertValue(segment.getLoadSpec(), LoadSpec.class);
+ final LoadSpec.LoadSpecResult result = loadSpec.loadSegment(storageDir);
+ if (result.getSize() != segment.getSize()) {
+ log.warn(
+ "Segment [%s] is different than expected size. Expected [%d] found [%d]",
+ segment.getId(),
+ segment.getSize(),
+ result.getSize()
+ );
}
}
- }
- private ReferenceCountingLock createOrGetLock(DataSegment dataSegment)
- {
- return segmentLocks.compute(
- dataSegment,
- (segment, lock) -> {
- final ReferenceCountingLock nonNullLock;
- if (lock == null) {
- nonNullLock = new ReferenceCountingLock();
- } else {
- nonNullLock = lock;
- }
- nonNullLock.increment();
- return nonNullLock;
- }
- );
- }
+ @GuardedBy("this")
+ private SegmentizerFactory getSegmentFactory(final File segmentFiles) throws SegmentLoadingException
+ {
+ final File factoryJson = new File(segmentFiles, "factory.json");
+ final SegmentizerFactory factory;
- @SuppressWarnings("ObjectEquality")
- private void unlock(DataSegment dataSegment, ReferenceCountingLock lock)
- {
- segmentLocks.compute(
- dataSegment,
- (segment, existingLock) -> {
- if (existingLock == null) {
- throw new ISE("Lock has already been removed");
- } else if (existingLock != lock) {
- throw new ISE("Different lock instance");
- } else {
- if (existingLock.numReferences == 1) {
- return null;
- } else {
- existingLock.decrement();
- return existingLock;
- }
- }
+ if (factoryJson.exists()) {
+ try {
+ factory = jsonMapper.readValue(factoryJson, SegmentizerFactory.class);
}
- );
- }
-
- private static class ReferenceCountingLock
- {
- private int numReferences;
+ catch (IOException e) {
+ throw new SegmentLoadingException(e, "Failed to get segment factory for %s", e.getMessage());
+ }
+ } else {
+ factory = new MMappedQueryableSegmentizerFactory(indexIO);
+ }
+ return factory;
+ }
- private void increment()
+ @Override
+ public boolean equals(Object o)
{
- ++numReferences;
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ SegmentCacheEntry that = (SegmentCacheEntry) o;
+ return Objects.equals(dataSegment, that.dataSegment);
}
- private void decrement()
+ @Override
+ public int hashCode()
{
- --numReferences;
+ return Objects.hashCode(dataSegment);
}
}
-
- @VisibleForTesting
- public ConcurrentHashMap<DataSegment, ReferenceCountingLock> getSegmentLocks()
- {
- return segmentLocks;
- }
-
- @VisibleForTesting
- public List<StorageLocation> getLocations()
- {
- return locations;
- }
}
diff --git a/server/src/main/java/org/apache/druid/segment/loading/StorageLocation.java b/server/src/main/java/org/apache/druid/segment/loading/StorageLocation.java
index adbec82366a..f47c10e6cfe 100644
--- a/server/src/main/java/org/apache/druid/segment/loading/StorageLocation.java
+++ b/server/src/main/java/org/apache/druid/segment/loading/StorageLocation.java
@@ -20,25 +20,71 @@
package org.apache.druid.segment.loading;
import com.google.common.annotations.VisibleForTesting;
+import com.google.errorprone.annotations.ThreadSafe;
import com.google.errorprone.annotations.concurrent.GuardedBy;
-import org.apache.commons.io.FileUtils;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.emitter.EmittingLogger;
-import org.apache.druid.timeline.DataSegment;
import javax.annotation.Nullable;
+import java.io.Closeable;
import java.io.File;
-import java.util.HashSet;
-import java.util.Set;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Phaser;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Supplier;
/**
- * This class is a very simple logical representation of a local path. It keeps track of files stored under the
- * {@link #path} via {@link #reserve}, so that the total size of stored files doesn't exceed the {@link #maxSizeBytes}
- * and available space is always kept smaller than {@link #freeSpaceToKeep}.
- *
+ * Logical representation of a local disk path to store {@link CacheEntry}, controlling that the total size of stored
+ * files doesn't exceed the {@link #maxSizeBytes} and available space is always kept smaller than
+ * {@link #freeSpaceToKeep}.
+ * <p>
+ * {@link CacheEntry} can be stored in two manners in a storage location. The first is to store the entry indefinitely
+ * with {@link #reserve(CacheEntry)}, where the space of the entry is accounted for and the storage space will not be
+ * recovered until {@link #release(CacheEntry)} is called. These entries are stored in {@link #staticCacheEntries}.
+ * <p>
+ * The second way is to store as a transient cache item with one of {@link #reserveWeak(CacheEntry)},
+ * {@link #addWeakReservationHold(CacheEntryIdentifier, Supplier)}, or
+ * {@link #addWeakReservationHoldIfExists(CacheEntryIdentifier)}. {@link CacheEntry} stored in this manner will exist on
+ * disk in this location until the point that another new reservation needs more space than remains available in the
+ * location, at which point {@link #reclaim(long)} will be called to try to call {@link CacheEntry#unmount()} on any
+ * eligible entries until enough space is available to store the new item.
+ * <p>
+ * Items are chosen for eviction using an algorithm based on
+ * <a href="https://www.usenix.org/system/files/nsdi24spring_prepub_zhang-yazhuo.pdf">SIEVE</a> with additional
+ * mechanisms to place temporary holds on cache entries. The holds are required to support cases such as if a group of
+ * cache entries are taking part in a query and must all be loaded simultaneously before processing can continue.
+ * <p>
+ * Implementation-wise, {@link CacheEntry} are wrapped in {@link WeakCacheEntry} to form a doubly linked list
+ * functioning as a queue which can be interacted with via 3 fields, {@link #head}, {@link #tail}, and {@link #hand}.
+ * Head and tail expectedly mark the beginning and end of the queue, while the hand is the interesting bit and is used
+ * as the position of the current item to consider for eviction the next time {@link #reclaim(long)} needs to be called.
+ * Entries are also stored in a map, {@link #weakCacheEntries}, for fast retrieval. Using a weak cache entry sets
+ * {@link WeakCacheEntry#visited} to true, and {@link #addWeakReservationHold(CacheEntryIdentifier, Supplier)} and
+ * {@link #addWeakReservationHoldIfExists(CacheEntryIdentifier)} additionally will call
+ * {@link WeakCacheEntry#hold()} until {@link ReservationHold#close()} is called which will call
+ * {@link WeakCacheEntry#release()}.
+ * <p>
+ * When it is time to reclaim space, first the {@link #hand} is checked for holds - if any exist then the hand is moved
+ * to {@link WeakCacheEntry#prev} immediately and we try again. If no holds are present, then it is checked if it has
+ * been marked as {@link WeakCacheEntry#visited} - if so then it is unmarked as visited, and the hand moves to
+ * {@link WeakCacheEntry#prev} (allowing this entry to be reclaimed the next time we pass if it has not been visited
+ * again). Lastly, if neither under a hold or marked, the entry will be unlinked from the queue AND unmounted from the
+ * storage location (deleting the files from disk) with {@link #unlinkWeakEntry(WeakCacheEntry)}. This process
+ * is repeated until either a sufficient amount of space has been reclaimed, or no additional space is able to be
+ * reclaimed, in which case the new reservation fails.
+ * <p>
* This class is thread-safe, so that multiple threads can update its state at the same time.
- * One example usage is that a historical can use multiple threads to load different segments in parallel
+ * One example usage is that a historical server can use multiple threads to load different segments in parallel
* from deep storage.
-*/
+ */
+@ThreadSafe
public class StorageLocation
{
private static final EmittingLogger log = new EmittingLogger(StorageLocation.class);
@@ -47,17 +93,42 @@ public class StorageLocation
private final long maxSizeBytes;
private final long freeSpaceToKeep;
+ @GuardedBy("lock")
+ private final Map<CacheEntryIdentifier, CacheEntry> staticCacheEntries = new HashMap<>();
+
+ @GuardedBy("lock")
+ private final Map<CacheEntryIdentifier, WeakCacheEntry> weakCacheEntries = new HashMap<>();
+
+ @GuardedBy("lock")
+ private WeakCacheEntry head;
+ @GuardedBy("lock")
+ private WeakCacheEntry tail;
+ @GuardedBy("lock")
+ private WeakCacheEntry hand;
+
+ /**
+ * Current total size of files in bytes, including weak entries.
+ */
+
/**
- * Set of files stored under the {@link #path}.
+ * Current total size of files in bytes, including weak entries.
*/
- @GuardedBy("this")
- private final Set<File> files = new HashSet<>();
+ private final AtomicLong currSizeBytes = new AtomicLong(0);
+
+ private final AtomicLong currWeakSizeBytes = new AtomicLong(0);
+
+ private final AtomicReference<Stats> stats = new AtomicReference<>();
/**
- * Current total size of files in bytes.
+ * A {@link ReentrantReadWriteLock.ReadLock} may be used for any operations to access {@link #staticCacheEntries} or
+ * {@link #weakCacheEntries}, including visiting and placing holds on weak entries.
+ * <p>
+ * A {@link ReentrantReadWriteLock.WriteLock} must be acquired for all operations to insert or remove items, including
+ * any operations which traverse or modify the {@link WeakCacheEntry} double linked list such as
+ * {@link #linkNewWeakEntry(WeakCacheEntry)} or {@link #unlinkWeakEntry(WeakCacheEntry)}, including calling
+ * {@link #canHandle(CacheEntry)} which can unlink entries
*/
- @GuardedBy("this")
- private long currSizeBytes = 0;
+ private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public StorageLocation(File path, long maxSizeBytes, @Nullable Double freeSpacePercent)
{
@@ -76,167 +147,791 @@ public class StorageLocation
} else {
this.freeSpaceToKeep = 0;
}
+ resetStats();
}
+ /**
+ * Exposes the {@link #lock} used by the {@link StorageLocation} to allow {@link CacheEntry#mount(StorageLocation)}
+ * and {@link CacheEntry#unmount()} to synchronize operations with this location. Callers MUST pay attention to the
+ * type of lock they are using if planning to call any other methods of this class to ensure deadlocks are not
+ * possible.
+ */
+ public ReadWriteLock getLock()
+ {
+ return lock;
+ }
+
+ /**
+ * The place where the files are stored
+ */
public File getPath()
{
return path;
}
+ public <T extends CacheEntry> T getStaticCacheEntry(CacheEntryIdentifier entryId)
+ {
+ lock.readLock().lock();
+ try {
+ if (staticCacheEntries.containsKey(entryId)) {
+ return (T) staticCacheEntries.get(entryId);
+ }
+ return null;
+ }
+ finally {
+ lock.readLock().unlock();
+ }
+ }
+
/**
- * Remove a segment file from this location. The given file argument must be a file rather than directory.
+ * If a {@link CacheEntry} for a {@link CacheEntryIdentifier} exists in either {@link #staticCacheEntries} or
+ * {@link #weakCacheEntries}, this method will return it. Additionally, {@link WeakCacheEntry} will be marked as
+ * visited to reduce the chance that they are evicted during future calls to {@link #reclaim(long)}.
*/
- public synchronized void removeFile(File file)
+ @Nullable
+ public <T extends CacheEntry> T getCacheEntry(CacheEntryIdentifier entryId)
{
- if (files.remove(file)) {
- currSizeBytes -= FileUtils.sizeOf(file);
- } else {
- log.warn("File[%s] is not found under this location[%s]", file, path);
+ lock.readLock().lock();
+ try {
+ if (staticCacheEntries.containsKey(entryId)) {
+ return (T) staticCacheEntries.get(entryId);
+ }
+ if (weakCacheEntries.containsKey(entryId)) {
+ final WeakCacheEntry weakCacheEntry = weakCacheEntries.get(entryId);
+ weakCacheEntry.visited = true;
+ return (T) weakCacheEntry.cacheEntry;
+ }
+ return null;
+ }
+ finally {
+ lock.readLock().unlock();
}
}
/**
- * Remove a segment dir from this location. The segment size is subtracted from currSizeBytes.
+ * Returns true if a {@link CacheEntry} for a {@link CacheEntryIdentifier} exists in {@link #staticCacheEntries}
*/
- public synchronized void removeSegmentDir(File segmentDir, DataSegment segment)
+ public boolean isReserved(CacheEntryIdentifier identifier)
{
- if (files.remove(segmentDir)) {
- currSizeBytes -= segment.getSize();
- } else {
- log.warn("SegmentDir[%s] is not found under this location[%s]", segmentDir, path);
+ lock.readLock().lock();
+ try {
+ return staticCacheEntries.containsKey(identifier);
+ }
+ finally {
+ lock.readLock().unlock();
}
}
/**
- * Reserves space to store the given segment. The segment size is added to currSizeBytes.
- * If it succeeds, it returns a file for the given segmentDir in this storage location. Returns null otherwise.
+ * Returns true if a {@link CacheEntry} for a {@link CacheEntryIdentifier} exists in {@link #weakCacheEntries}
*/
- @Nullable
- public synchronized File reserve(String segmentDir, DataSegment segment)
+ public boolean isWeakReserved(CacheEntryIdentifier identifier)
{
- return reserve(segmentDir, segment.getId().toString(), segment.getSize());
+ lock.readLock().lock();
+ try {
+ return weakCacheEntries.containsKey(identifier);
+ }
+ finally {
+ lock.readLock().unlock();
+ }
}
- public synchronized boolean isReserved(String segmentDir)
+ /**
+ * Reserves space to store the given {@link CacheEntry}, returning true if sucessful and false if already reserved,
+ * or unable to be reserved.
+ */
+ public boolean reserve(CacheEntry entry)
{
- return files.contains(segmentDirectoryAsFile(segmentDir));
+ lock.readLock().lock();
+ try {
+ if (staticCacheEntries.containsKey(entry.getId())) {
+ return false;
+ }
+ }
+ finally {
+ lock.readLock().unlock();
+ }
+
+ lock.writeLock().lock();
+ try {
+ final ReclaimResult reclaimResult = canHandle(entry);
+ unmountReclaimed(reclaimResult);
+ if (reclaimResult.isSuccess()) {
+ staticCacheEntries.put(entry.getId(), entry);
+ currSizeBytes.getAndAdd(entry.getSize());
+ }
+ return reclaimResult.isSuccess();
+ }
+ finally {
+ lock.writeLock().unlock();
+ }
}
- public File segmentDirectoryAsFile(String segmentDir)
+ /**
+ * Reserves space to store a 'weak' reservation for a given {@link CacheEntry}. Returns true if already reserved or
+ * was able to be successfully reserved, or false if unable to be reserved. This method is intended for use during
+ * 'bootstrapping'. To use weak cache entries in a query engine use
+ * {@link #addWeakReservationHold(CacheEntryIdentifier, Supplier)} or
+ * {@link #addWeakReservationHoldIfExists(CacheEntryIdentifier)}, which places a hold on cache entries to prevent
+ * eviction until the hold is released.
+ */
+ public boolean reserveWeak(CacheEntry entry)
{
- return new File(path, segmentDir); //lgtm [java/path-injection]
+ lock.readLock().lock();
+ try {
+ if (staticCacheEntries.containsKey(entry.getId())) {
+ return true;
+ }
+ if (weakCacheEntries.containsKey(entry.getId())) {
+ weakCacheEntries.get(entry.getId()).visited = true;
+ return true;
+ }
+ }
+ finally {
+ lock.readLock().unlock();
+ }
+
+ lock.writeLock().lock();
+ try {
+ if (staticCacheEntries.containsKey(entry.getId())) {
+ return true;
+ }
+ if (weakCacheEntries.containsKey(entry.getId())) {
+ weakCacheEntries.get(entry.getId()).visited = true;
+ return true;
+ }
+ final ReclaimResult reclaimResult = canHandleWeak(entry);
+ unmountReclaimed(reclaimResult);
+ if (reclaimResult.isSuccess()) {
+ final WeakCacheEntry newEntry = new WeakCacheEntry(entry);
+ linkNewWeakEntry(newEntry);
+ weakCacheEntries.put(entry.getId(), newEntry);
+ stats.get().load();
+ }
+ return reclaimResult.isSuccess();
+ }
+ finally {
+ lock.writeLock().unlock();
+ }
}
/**
- * Reserves space to store the given segment, only if it has not been done already. This can be used
- * when segment is already downloaded on the disk. Unlike {@link #reserve(String, DataSegment)}, this function
- * skips the check on disk availability. We also account for segment usage even if available size dips below 0.
- * Such a situation indicates a configuration problem or a bug and we don't let segment loading fail because
- * of this.
+ * Returns a {@link ReservationHold} of a {@link CacheEntry} with a 'hold' placed on it, preventing it from being
+ * automatically removed by {@link #reclaim(long)} if the {@link CacheEntry} is one of {@link #weakCacheEntries} until
+ * the hold is released by {@link ReservationHold#close()}. Callers must call close on the returned object.
+ * <p>
+ * This method only returns already existing entries, if callers want to insert a new entry if it doesn't already
+ * exist, use {@link #addWeakReservationHold(CacheEntryIdentifier, Supplier)}
*/
- public synchronized void maybeReserve(String segmentFilePathToAdd, DataSegment segment)
+ @Nullable
+ public <T extends CacheEntry> ReservationHold<T> addWeakReservationHoldIfExists(CacheEntryIdentifier entryId)
{
- final File segmentFileToAdd = new File(path, segmentFilePathToAdd);
- if (files.contains(segmentFileToAdd)) {
- // Already reserved
- return;
+ lock.readLock().lock();
+ try {
+ if (staticCacheEntries.containsKey(entryId)) {
+ return new ReservationHold<>((T) staticCacheEntries.get(entryId), () -> {});
+ }
+
+ WeakCacheEntry existingEntry = weakCacheEntries.get(entryId);
+ if (existingEntry != null && existingEntry.hold()) {
+ existingEntry.visited = true;
+ stats.get().hit();
+ return new ReservationHold<>((T) existingEntry.cacheEntry, existingEntry::release);
+ }
+ return null;
}
- files.add(segmentFileToAdd);
- currSizeBytes += segment.getSize();
- if (availableSizeBytes() < 0) {
- log.makeAlert(
- "storage[%s:%,d] has more segments than it is allowed. Currently loading Segment[%s:%,d]. Please increase druid.segmentCache.locations maxSize param",
- getPath(),
- availableSizeBytes(),
- segment.getId(),
- segment.getSize()
- ).emit();
+ finally {
+ lock.readLock().unlock();
}
}
/**
- * Reserves space to store the given segment.
- * If it succeeds, it returns a file for the given segmentFilePathToAdd in this storage location.
- * Returns null otherwise.
+ * Returns a {@link ReservationHold} of a {@link CacheEntry} with a 'hold' placed on it, preventing it from being
+ * automatically removed by {@link #reclaim(long)} if the {@link CacheEntry} is one of {@link #weakCacheEntries} until
+ * the hold is released by {@link ReservationHold#close()}. Callers must call close on the returned object.
+ * <p>
+ * If the entry already exists, this method will return it, else it will create a new entry if there is space
+ * available.
*/
@Nullable
- public synchronized File reserve(String segmentFilePathToAdd, String segmentId, long segmentSize)
+ public <T extends CacheEntry> ReservationHold<T> addWeakReservationHold(
+ CacheEntryIdentifier entryId,
+ Supplier<? extends CacheEntry> entrySupplier
+ )
{
- final File segmentFileToAdd = new File(path, segmentFilePathToAdd);
- if (files.contains(segmentFileToAdd)) {
- return null;
+ final ReservationHold<T> existingEntry = addWeakReservationHoldIfExists(entryId);
+ if (existingEntry != null) {
+ return existingEntry;
+ }
+
+ lock.writeLock().lock();
+ try {
+ WeakCacheEntry retryExistingEntry = weakCacheEntries.get(entryId);
+ if (retryExistingEntry != null && retryExistingEntry.hold()) {
+ retryExistingEntry.visited = true;
+ stats.get().hit();
+ return new ReservationHold<>((T) retryExistingEntry.cacheEntry, retryExistingEntry::release);
+ }
+ final CacheEntry newEntry = entrySupplier.get();
+ final ReclaimResult reclaimResult = canHandleWeak(newEntry);
+ unmountReclaimed(reclaimResult);
+ final ReservationHold<T> hold;
+ if (reclaimResult.isSuccess()) {
+ final WeakCacheEntry newWeakEntry = new WeakCacheEntry(newEntry);
+ newWeakEntry.hold();
+ linkNewWeakEntry(newWeakEntry);
+ weakCacheEntries.put(newEntry.getId(), newWeakEntry);
+ stats.get().load();
+ hold = new ReservationHold<>(
+ (T) newEntry,
+ () -> {
+ newWeakEntry.release();
+ lock.writeLock().lock();
+ try {
+ weakCacheEntries.computeIfPresent(
+ newEntry.getId(),
+ (cacheEntryIdentifier, weakCacheEntry) -> {
+ if (!weakCacheEntry.cacheEntry.isMounted()) {
+ // if we never successfully mounted, go ahead and remove so we don't have a dead entry
+ unlinkWeakEntry(weakCacheEntry);
+ // we call unmount anyway to terminate the phaser
+ weakCacheEntry.unmount();
+ return null;
+ }
+ return weakCacheEntry;
+ }
+ );
+ }
+ finally {
+ lock.writeLock().unlock();
+ }
+ }
+ );
+ } else {
+ stats.get().reject();
+ hold = null;
+ }
+ return hold;
}
- if (canHandle(segmentId, segmentSize)) {
- files.add(segmentFileToAdd);
- currSizeBytes += segmentSize;
- return segmentFileToAdd;
+ finally {
+ lock.writeLock().unlock();
+ }
+ }
+
+ /**
+ * Removes an item from {@link #staticCacheEntries} or {@link #weakCacheEntries}, reducing {@link #currSizeBytes}
+ * by {@link CacheEntry#getSize()}
+ */
+ public void release(CacheEntry entry)
+ {
+ lock.writeLock().lock();
+ try {
+
+ if (staticCacheEntries.containsKey(entry.getId())) {
+ final CacheEntry toRemove = staticCacheEntries.remove(entry.getId());
+ toRemove.unmount();
+ currSizeBytes.getAndAdd(-entry.getSize());
+ } else if (weakCacheEntries.containsKey(entry.getId())) {
+ final WeakCacheEntry toRemove = weakCacheEntries.remove(entry.getId());
+ unlinkWeakEntry(toRemove);
+ toRemove.unmount();
+ stats.get().unmount();
+ }
+ }
+ finally {
+ lock.writeLock().unlock();
+ }
+ }
+
+ /**
+ * Inserts a new {@link WeakCacheEntry}, inserting it as {@link #head} (or both {@link #head} and {@link #tail} if it
+ * is the only entry), tracking size in {@link #currSizeBytes} and {@link #currWeakSizeBytes}
+ */
+ @GuardedBy("lock")
+ private void linkNewWeakEntry(WeakCacheEntry newWeakEntry)
+ {
+ if (head != null) {
+ newWeakEntry.next = head;
+ head.prev = newWeakEntry;
} else {
- return null;
+ // first item
+ tail = newWeakEntry;
+ hand = newWeakEntry;
}
+ head = newWeakEntry;
+ currWeakSizeBytes.getAndAdd(newWeakEntry.cacheEntry.getSize());
+ currSizeBytes.getAndAdd(newWeakEntry.cacheEntry.getSize());
}
- public synchronized boolean release(String segmentFilePath, long segmentSize)
+ /**
+ * Removes a {@link WeakCacheEntry} from the queue
+ */
+ @GuardedBy("lock")
+ private void unlinkWeakEntry(WeakCacheEntry toRemove)
{
- final File segmentFile = new File(path, segmentFilePath);
- if (files.remove(segmentFile)) {
- currSizeBytes -= segmentSize;
- return true;
+ if (head == toRemove) {
+ head = toRemove.next;
}
- return false;
+ if (tail == toRemove) {
+ tail = toRemove.prev;
+ }
+ if (hand == toRemove) {
+ hand = toRemove.prev != null ? toRemove.prev : tail;
+ }
+ if (toRemove.prev != null) {
+ toRemove.prev.next = toRemove.next;
+ }
+ if (toRemove.next != null) {
+ toRemove.next.prev = toRemove.prev;
+ }
+ toRemove.prev = null;
+ toRemove.next = null;
+ currSizeBytes.getAndAdd(-toRemove.cacheEntry.getSize());
+ currWeakSizeBytes.getAndAdd(-toRemove.cacheEntry.getSize());
}
/**
+ * Checks if this location can store a new {@link CacheEntry}, calling {@link #reclaim(long)} to drop
+ * {@link #weakCacheEntries} if possible.
+ * <p>
* This method is only package-private to use it in unit tests. Production code must not call this method directly.
* Use {@link #reserve} instead.
*/
@VisibleForTesting
- @GuardedBy("this")
- boolean canHandle(String segmentId, long segmentSize)
- {
- if (availableSizeBytes() < segmentSize) {
- log.warn(
- "Segment[%s:%,d] too large for storage[%s:%,d]. Check your druid.segmentCache.locations maxSize param",
- segmentId,
- segmentSize,
- getPath(),
- availableSizeBytes()
- );
- return false;
- }
+ @GuardedBy("lock")
+ ReclaimResult canHandle(CacheEntry entry)
+ {
+ return canHandle(entry, false);
+ }
- if (freeSpaceToKeep > 0) {
- long currFreeSpace = path.getFreeSpace();
- if ((freeSpaceToKeep + segmentSize) > currFreeSpace) {
- log.warn(
- "Segment[%s:%,d] too large for storage[%s:%,d] to maintain suggested freeSpace[%d], current freeSpace is [%d].",
- segmentId,
- segmentSize,
+
+ /**
+ * Checks if this location can store a new {@link WeakCacheEntry}, calling {@link #reclaim(long)} to drop
+ * {@link #weakCacheEntries} if possible.
+ */
+ @GuardedBy("lock")
+ private ReclaimResult canHandleWeak(CacheEntry entry)
+ {
+ return canHandle(entry, true);
+ }
+
+ @GuardedBy("lock")
+ private ReclaimResult canHandle(CacheEntry entry, boolean weak)
+ {
+ List<WeakCacheEntry> evicted = new ArrayList<>();
+ long bytesReclaimed = 0;
+ if (availableSizeBytes() < entry.getSize()) {
+ long sizeToReclaim = entry.getSize() - availableSizeBytes();
+ final ReclaimResult result = reclaim(sizeToReclaim);
+ if (!result.isSuccess()) {
+ final String msg = StringUtils.format(
+ "Cache entry[%s:%,d] too large for storage[%s:%,d/%,d]",
+ entry.getId(),
+ entry.getSize(),
getPath(),
availableSizeBytes(),
- freeSpaceToKeep,
- currFreeSpace
+ maxSizeBytes
);
- return false;
+ if (weak) {
+ log.debug(msg);
+ } else {
+ log.warn(msg);
+ }
+ return ReclaimResult.failed(sizeToReclaim);
+ }
+ bytesReclaimed += result.bytesReclaimed;
+ evicted.addAll(result.getEvictions());
+ }
+
+ if (freeSpaceToKeep > 0) {
+ long currFreeSpace = path.getFreeSpace();
+ if ((freeSpaceToKeep + entry.getSize()) > currFreeSpace) {
+ final ReclaimResult result = reclaim(freeSpaceToKeep + entry.getSize());
+ if (!result.isSuccess()) {
+ final String msg = StringUtils.format(
+ "Cache entry[%s:%,d] too large for storage[%s:%,d/%,d] to maintain suggested freeSpace[%d], current freeSpace is [%d].",
+ entry.getId(),
+ entry.getSize(),
+ getPath(),
+ availableSizeBytes(),
+ maxSizeBytes,
+ freeSpaceToKeep,
+ currFreeSpace
+ );
+ if (weak) {
+ log.debug(msg);
+ } else {
+ log.warn(msg);
+ }
+ return ReclaimResult.failed(freeSpaceToKeep + entry.getSize());
+ }
+ bytesReclaimed += result.bytesReclaimed;
+ evicted.addAll(result.getEvictions());
}
}
- return true;
+ return new ReclaimResult(true, entry.getSize(), bytesReclaimed, evicted);
}
- public synchronized long availableSizeBytes()
+ @GuardedBy("lock")
+ private void unmountReclaimed(ReclaimResult reclaimResult)
{
- return maxSizeBytes - currSizeBytes;
+ if (reclaimResult != null) {
+ for (WeakCacheEntry removed : reclaimResult.getEvictions()) {
+ weakCacheEntries.computeIfAbsent(
+ removed.cacheEntry.getId(),
+ cacheEntryIdentifier -> {
+ if (!staticCacheEntries.containsKey(cacheEntryIdentifier)) {
+ removed.unmount();
+ stats.get().unmount();
+ }
+ return null;
+ }
+ );
+ }
+ }
}
- public synchronized long currSizeBytes()
+ public int getWeakEntryCount()
{
- return currSizeBytes;
+ lock.readLock().lock();
+ try {
+ return weakCacheEntries.size();
+ }
+ finally {
+ lock.readLock().unlock();
+ }
}
@VisibleForTesting
- synchronized boolean contains(String relativePath)
+ public long getActiveWeakHolds()
+ {
+ lock.readLock().lock();
+ try {
+ return weakCacheEntries.values().stream().filter(WeakCacheEntry::isHeld).count();
+ }
+ finally {
+ lock.readLock().unlock();
+ }
+ }
+
+ public Stats getStats()
{
- final File segmentFileToAdd = new File(path, relativePath);
- return files.contains(segmentFileToAdd);
+ return stats.get();
+ }
+
+ public void resetStats()
+ {
+ stats.set(new Stats());
+ }
+
+ /**
+ * Tries to reclaim the specified number of bytes by removing {@link WeakCacheEntry}, starting from {@link #hand}.
+ * <p>
+ * If {@link WeakCacheEntry#visited} is set, the entry is skipped moving {@link #hand} to {@link WeakCacheEntry#prev}
+ * and setting {@link WeakCacheEntry#visited} to false so we can consider it for removal the next time it is the
+ * {@link #hand}.
+ * <p>
+ * If {@link WeakCacheEntry#isHeld()}, it is also skipped, moving {@link #hand} to {@link WeakCacheEntry#prev}.
+ *
+ * Otherwise, this method will remove entries until either it frees up enough space or runs out of entries to remove
+ * (either because there are no more entries or all remaining entries are under a hold).
+ */
+ @GuardedBy("lock")
+ private ReclaimResult reclaim(long sizeToReclaim)
+ {
+ return reclaimHelper(sizeToReclaim, new ArrayList<>());
+ }
+
+ @GuardedBy("lock")
+ private ReclaimResult reclaimHelper(long sizeToReclaim, List<WeakCacheEntry> droppedEntries)
+ {
+ if (head == null) {
+ return ReclaimResult.failed(sizeToReclaim);
+ }
+ long sizeFreed = 0;
+ // keep track of where we start so if we get back to the same entry we know when to stop
+ WeakCacheEntry startEntry = null;
+ // keep track of if we unset visited from any entries, allowing us to try again if we reach startEntry but didn't
+ // reclaim enough space yet and know there will likely still be candidates if we check again
+ boolean unmarked = false;
+ // run until we reclaim enough space, end up where we started, or remove everything
+ while (hand != null && sizeFreed < sizeToReclaim && startEntry != hand) {
+ if (startEntry == null) {
+ startEntry = hand;
+ }
+ if (hand.isHeld()) {
+ // item has one or more holds - move along
+ hand = hand.prev;
+ } else if (hand.visited) {
+ // item is visited, unmark so we can consider it the next time it is hand
+ unmarked = true;
+ hand.visited = false;
+ hand = hand.prev;
+ } else {
+ // item is valid to remove
+ final WeakCacheEntry toRemove = hand;
+ hand = hand.prev;
+ final WeakCacheEntry removed = weakCacheEntries.remove(toRemove.cacheEntry.getId());
+ if (removed == null) {
+ throw DruidException.defensive(
+ "Weakly held cache entry[%s] already removed from map, how can this be?",
+ toRemove.cacheEntry.getId()
+ );
+ }
+ unlinkWeakEntry(removed);
+ stats.get().evict();
+ toRemove.next = null;
+ toRemove.prev = null;
+ droppedEntries.add(toRemove);
+ sizeFreed += toRemove.cacheEntry.getSize();
+ startEntry = null;
+ }
+
+ // if we reach the end of the queue, loop around
+ if (hand == null) {
+ hand = tail;
+ }
+ }
+ // if we unmarked visited stuff, try again
+ if (unmarked && sizeFreed < sizeToReclaim) {
+ return reclaimHelper(sizeToReclaim - sizeFreed, droppedEntries);
+ }
+ if (sizeFreed >= sizeToReclaim) {
+ return new ReclaimResult(true, sizeToReclaim, sizeFreed, droppedEntries);
+ }
+ // if we didn't free up enough space, return everything we removed to the cache
+ for (WeakCacheEntry entry : droppedEntries) {
+ linkNewWeakEntry(new WeakCacheEntry(entry.cacheEntry));
+ weakCacheEntries.put(entry.cacheEntry.getId(), entry);
+ }
+ return ReclaimResult.failed(sizeToReclaim);
+ }
+
+ public long availableSizeBytes()
+ {
+ return maxSizeBytes - currSizeBytes.get();
+ }
+
+ public long currentSizeBytes()
+ {
+ return currSizeBytes.get();
+ }
+
+ public long currentWeakSizeBytes()
+ {
+ return currWeakSizeBytes.get();
+ }
+
+ public static final class ReclaimResult
+ {
+ public static ReclaimResult failed(long spaceRequired)
+ {
+ return new ReclaimResult(false, spaceRequired, 0, List.of());
+ }
+
+ private final boolean success;
+ private final long spaceRequired;
+ private final long bytesReclaimed;
+ private final List<WeakCacheEntry> evictions;
+
+ ReclaimResult(
+ boolean success,
+ long spaceRequired,
+ long bytesReclaimed,
+ List<WeakCacheEntry> evictions
+ )
+ {
+ this.success = success;
+ this.spaceRequired = spaceRequired;
+ this.bytesReclaimed = bytesReclaimed;
+ this.evictions = evictions;
+ }
+
+ public boolean isSuccess()
+ {
+ return success;
+ }
+
+ public List<WeakCacheEntry> getEvictions()
+ {
+ return evictions;
+ }
+ }
+ /**
+ * Wrapper for a {@link CacheEntry} which can be reclaimed if there is not enough space available to add some other
+ * {@link CacheEntry} later.
+ */
+ static final class WeakCacheEntry
+ {
+ private final CacheEntry cacheEntry;
+ /**
+ * Phaser that allows callers to place a hold on an entry, which will prevent {@link #reclaim(long)} from being able
+ * to remove this entry until the hold is released. When the phaser arrives at 0, calls {@link CacheEntry#unmount()}
+ */
+ private final Phaser holdReferents = new Phaser(1)
+ {
+ @Override
+ protected boolean onAdvance(int phase, int registeredParties)
+ {
+ // Ensure that onAdvance() doesn't throw exception, otherwise termination won't happen
+ if (registeredParties != 0) {
+ log.error("registeredParties[%s] is not 0", registeredParties);
+ }
+ try {
+ cacheEntry.unmount();
+ }
+ catch (Exception e) {
+ try {
+ log.error(e, "Exception while closing reference counted object[%s]", cacheEntry.getId());
+ }
+ catch (Exception e2) {
+ // ignore
+ }
+ }
+ // Always terminate.
+ return true;
+ }
+ };
+
+ private WeakCacheEntry prev;
+ private WeakCacheEntry next;
+
+ /**
+ * Set to true when an entry is used by a caller, which will cause {@link #reclaim(long)} to skip this entry
+ * (and set to false). this is volatile because we allow setting it to true without holding {@link #lock}
+ */
+ private volatile boolean visited;
+
+ private WeakCacheEntry(CacheEntry cacheEntry)
+ {
+ this.cacheEntry = cacheEntry;
+ }
+
+ /**
+ * Returns true if there is 1 or more {@link #hold()} currently placed on this entry
+ */
+ boolean isHeld()
+ {
+ return holdReferents.getRegisteredParties() > 1;
+ }
+
+ /**
+ * Place a hold on this entry to prevent it from being dropped by {@link #reclaim(long)}
+ */
+ private boolean hold()
+ {
+ return holdReferents.register() >= 0;
+ }
+
+ /**
+ * Release a {@link #hold()}
+ */
+ private int release()
+ {
+ return holdReferents.arriveAndDeregister();
+ }
+
+ /**
+ * Call {@link CacheEntry#unmount()} after all holds are released ({@link #holdReferents})
+ */
+ private void unmount()
+ {
+ holdReferents.arriveAndDeregister();
+ }
+ }
+
+ /**
+ * A {@link Closeable} {@link CacheEntry} wrapper representing both the entry and a 'hold' that is placed on it to
+ * prevent the entry from being dropped by {@link #reclaim(long)} at least until the wrapper is closed.
+ * <p>
+ * In practice, if the entry is {@link #weakCacheEntries} the entry contained in this object was placed under a hold
+ * with {@link WeakCacheEntry#hold()}, and {@link #close()} with then call {@link WeakCacheEntry#release()} to finish
+ * the hold. If the entry is instead {@link #staticCacheEntries}, a hold is not necessary since these entries will
+ * not be removed automatically during {@link #reclaim(long)}, and instead are only ever being dropped if
+ * {@link #release(CacheEntry)} is explicitly called. Close is a no-op for these entries.
+ * <p>
+ * Callers MUST be sure to close this object when finished to release the hold
+ */
+ public static class ReservationHold<TEntry extends CacheEntry> implements Closeable
+ {
+ private final TEntry entry;
+ private final Runnable releaseHold;
+
+ public ReservationHold(TEntry entry, Runnable releaseHold)
+ {
+ this.entry = entry;
+ this.releaseHold = releaseHold;
+ }
+
+ public TEntry getEntry()
+ {
+ return entry;
+ }
+
+ @Override
+ public void close()
+ {
+ releaseHold.run();
+ }
+ }
+
+ public static final class Stats
+ {
+ private final AtomicLong loadCount = new AtomicLong(0);
+ private final AtomicLong rejectionCount = new AtomicLong(0);
+ private final AtomicLong hitCount = new AtomicLong(0);
+ private final AtomicLong evictionCount = new AtomicLong(0);
+ private final AtomicLong unmountCount = new AtomicLong(0);
+
+ public void hit()
+ {
+ hitCount.getAndIncrement();
+ }
+
+ public long getHitCount()
+ {
+ return hitCount.get();
+ }
+
+ public void load()
+ {
+ loadCount.getAndIncrement();
+ }
+
+ public long getLoadCount()
+ {
+ return loadCount.get();
+ }
+
+ public void evict()
+ {
+ evictionCount.getAndIncrement();
+ }
+
+ public long getEvictionCount()
+ {
+ return evictionCount.get();
+ }
+
+ public void unmount()
+ {
+ unmountCount.getAndIncrement();
+ }
+
+ public long getUnmountCount()
+ {
+ return unmountCount.get();
+ }
+
+ public void reject()
+ {
+ rejectionCount.getAndIncrement();
+ }
+
+ public long getRejectCount()
+ {
+ return rejectionCount.get();
+ }
}
}
diff --git a/server/src/main/java/org/apache/druid/segment/loading/VirtualPlaceholderSegment.java b/server/src/main/java/org/apache/druid/segment/loading/VirtualPlaceholderSegment.java
new file mode 100644
index 00000000000..4099274edb8
--- /dev/null
+++ b/server/src/main/java/org/apache/druid/segment/loading/VirtualPlaceholderSegment.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.segment.loading;
+
+import org.apache.druid.data.input.Row;
+import org.apache.druid.java.util.common.guava.Sequences;
+import org.apache.druid.segment.DimensionDictionarySelector;
+import org.apache.druid.segment.Metadata;
+import org.apache.druid.segment.PhysicalSegmentInspector;
+import org.apache.druid.segment.RowAdapters;
+import org.apache.druid.segment.RowBasedSegment;
+import org.apache.druid.segment.column.ColumnCapabilities;
+import org.apache.druid.segment.column.ColumnCapabilitiesImpl;
+import org.apache.druid.segment.column.ColumnHolder;
+import org.apache.druid.segment.column.ColumnType;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.timeline.DataSegment;
+import org.apache.druid.timeline.SegmentId;
+import org.joda.time.Interval;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+/**
+ * Empty segment with nothing but a time column, used when {@link SegmentLoaderConfig#isVirtualStorage()} is true
+ * to create synthetic segments for {@link org.apache.druid.query.metadata.metadata.SegmentMetadataQuery} so to not
+ * force download of segments from deep storage when computing the SQL schema.
+ */
+public class VirtualPlaceholderSegment extends RowBasedSegment<Row>
+{
+ private final DataSegment dataSegment;
+
+ public VirtualPlaceholderSegment(DataSegment dataSegment)
+ {
+ super(
+ Sequences.empty(),
+ RowAdapters.standardRow(),
+ RowSignature.builder().addTimeColumn().build()
+ );
+ this.dataSegment = dataSegment;
+ }
+
+ @Override
+ public SegmentId getId()
+ {
+ return dataSegment.getId();
+ }
+
+ @Override
+ @Nonnull
+ public Interval getDataInterval()
+ {
+ return dataSegment.getInterval();
+ }
+
+ @Nullable
+ @Override
+ public <T> T as(@Nonnull Class<T> clazz)
+ {
+ if (PhysicalSegmentInspector.class.equals(clazz)) {
+ return (T) EmptyPhysicalInspector.INSTANCE;
+ }
+ return super.as(clazz);
+ }
+
+ private static class EmptyPhysicalInspector implements PhysicalSegmentInspector
+ {
+ private static final EmptyPhysicalInspector INSTANCE = new EmptyPhysicalInspector();
+
+ @Nullable
+ @Override
+ public ColumnCapabilities getColumnCapabilities(String column)
+ {
+ if (ColumnHolder.TIME_COLUMN_NAME.equals(column)) {
+ return ColumnCapabilitiesImpl.createDefault().setType(ColumnType.LONG);
+ }
+ return null;
+ }
+
+ @Nullable
+ @Override
+ public Metadata getMetadata()
+ {
+ return null;
+ }
+
+ @Nullable
+ @Override
+ public Comparable getMinValue(String column)
+ {
+ return null;
+ }
+
+ @Nullable
+ @Override
+ public Comparable getMaxValue(String column)
+ {
+ return null;
+ }
+
+ @Override
+ public int getDimensionCardinality(String column)
+ {
+ return DimensionDictionarySelector.CARDINALITY_UNKNOWN;
+ }
+
+ @Override
+ public int getNumRows()
+ {
+ return 0;
+ }
+ }
+}
diff --git a/server/src/main/java/org/apache/druid/segment/realtime/FireHydrant.java b/server/src/main/java/org/apache/druid/segment/realtime/FireHydrant.java
index 7003a1a1bd0..63306d95a93 100644
--- a/server/src/main/java/org/apache/druid/segment/realtime/FireHydrant.java
+++ b/server/src/main/java/org/apache/druid/segment/realtime/FireHydrant.java
@@ -48,7 +48,7 @@ public class FireHydrant
{
this.index = index;
this.segmentReferenceProvider = new AtomicReference<>(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(new IncrementalIndexSegment(index, segmentId))
+ ReferenceCountedSegmentProvider.of(new IncrementalIndexSegment(index, segmentId))
);
this.count = count;
}
@@ -57,7 +57,7 @@ public class FireHydrant
{
this.index = null;
this.segmentReferenceProvider = new AtomicReference<>(
- ReferenceCountedSegmentProvider.wrapRootGenerationSegment(segment)
+ ReferenceCountedSegmentProvider.of(segment)
);
this.count = count;
}
@@ -130,7 +130,7 @@ public class FireHydrant
throw new ISE("Cannot swap to the same segment");
}
ReferenceCountedSegmentProvider newReferenceCountingSegment =
- newSegment != null ? ReferenceCountedSegmentProvider.wrapRootGenerationSegment(newSegment) : null;
+ newSegment != null ? ReferenceCountedSegmentProvider.of(newSegment) : null;
if (segmentReferenceProvider.compareAndSet(currentSegment, newReferenceCountingSegment)) {
if (currentSegment != null) {
currentSegment.close();
@@ -179,7 +179,7 @@ public class FireHydrant
return Optional.empty();
}
- Optional<Segment> segment = segmentMapFn.apply(sinkSegment);
+ Optional<Segment> segment = segmentMapFn.apply(sinkSegment.acquireReference());
while (true) {
if (segment.isPresent()) {
return segment;
@@ -199,7 +199,7 @@ public class FireHydrant
// of a HashJoinSegment created by segmentMapFn
return Optional.empty();
}
- segment = segmentMapFn.apply(newSinkSegment);
+ segment = segmentMapFn.apply(newSinkSegment.acquireReference());
// Spin loop.
}
}
diff --git a/server/src/main/java/org/apache/druid/segment/realtime/appenderator/AppenderatorsManager.java b/server/src/main/java/org/apache/druid/segment/realtime/appenderator/AppenderatorsManager.java
index dea08ecddbf..6a9475e11f9 100644
--- a/server/src/main/java/org/apache/druid/segment/realtime/appenderator/AppenderatorsManager.java
+++ b/server/src/main/java/org/apache/druid/segment/realtime/appenderator/AppenderatorsManager.java
@@ -40,6 +40,8 @@ import org.apache.druid.segment.loading.DataSegmentPusher;
import org.apache.druid.segment.loading.SegmentLoaderConfig;
import org.apache.druid.segment.metadata.CentralizedDatasourceSchemaConfig;
import org.apache.druid.segment.realtime.SegmentGenerationMetrics;
+import org.apache.druid.server.SegmentManager;
+import org.apache.druid.server.ServerManager;
import org.apache.druid.server.coordination.DataSegmentAnnouncer;
import org.joda.time.Interval;
@@ -57,8 +59,8 @@ import org.joda.time.Interval;
*
* The methods on AppenderatorsManager can be called by multiple threads.
*
- * This class provides similar functionality to the {@link org.apache.druid.server.coordination.ServerManager} and
- * {@link org.apache.druid.server.SegmentManager} on the Historical processes.
+ * This class provides similar functionality to the {@link ServerManager} and
+ * {@link SegmentManager} on the Historical processes.
*/
public interface AppenderatorsManager
{
diff --git a/server/src/main/java/org/apache/druid/server/LocalQuerySegmentWalker.java b/server/src/main/java/org/apache/druid/server/LocalQuerySegmentWalker.java
index 4c5d886eaa9..ce453f409dd 100644
--- a/server/src/main/java/org/apache/druid/server/LocalQuerySegmentWalker.java
+++ b/server/src/main/java/org/apache/druid/server/LocalQuerySegmentWalker.java
@@ -35,7 +35,6 @@ import org.apache.druid.query.QuerySegmentWalker;
import org.apache.druid.query.SegmentDescriptor;
import org.apache.druid.query.planning.ExecutionVertex;
import org.apache.druid.query.policy.PolicyEnforcer;
-import org.apache.druid.segment.ReferenceCountedObjectProvider;
import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentMapFunction;
@@ -43,6 +42,7 @@ import org.apache.druid.segment.SegmentWrangler;
import org.apache.druid.segment.join.JoinableFactoryWrapper;
import org.joda.time.Interval;
+import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
@@ -93,9 +93,9 @@ public class LocalQuerySegmentWalker implements QuerySegmentWalker
// wrap in ReferenceCountingSegment, these aren't currently managed by SegmentManager so reference tracking doesn't
// matter, but at least some or all will be in a future PR
- final Iterable<ReferenceCountedObjectProvider<Segment>> segments =
+ final Iterable<Optional<Segment>> segments =
FunctionalIterable.create(segmentWrangler.getSegmentsForIntervals(ev.getBaseDataSource(), intervals))
- .transform(ReferenceCountedSegmentProvider::wrapUnmanaged);
+ .transform(ReferenceCountedSegmentProvider::unmanaged);
final AtomicLong cpuAccumulator = new AtomicLong(0L);
diff --git a/server/src/main/java/org/apache/druid/server/SegmentManager.java b/server/src/main/java/org/apache/druid/server/SegmentManager.java
index 060bf285114..3ac628bbbd7 100644
--- a/server/src/main/java/org/apache/druid/server/SegmentManager.java
+++ b/server/src/main/java/org/apache/druid/server/SegmentManager.java
@@ -29,11 +29,12 @@ import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.query.TableDataSource;
import org.apache.druid.segment.PhysicalSegmentInspector;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentLazyLoadFailCallback;
+import org.apache.druid.segment.SegmentMapFunction;
import org.apache.druid.segment.join.table.IndexedTable;
import org.apache.druid.segment.join.table.ReferenceCountedIndexedTableProvider;
+import org.apache.druid.segment.loading.AcquireSegmentAction;
import org.apache.druid.segment.loading.SegmentCacheManager;
import org.apache.druid.segment.loading.SegmentLoadingException;
import org.apache.druid.server.metrics.SegmentRowCountDistribution;
@@ -41,7 +42,7 @@ import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.PartitionChunk;
-import org.apache.druid.timeline.partition.ShardSpec;
+import org.apache.druid.utils.CloseableUtils;
import org.apache.druid.utils.CollectionUtils;
import java.io.IOException;
@@ -51,7 +52,6 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
@@ -106,7 +106,7 @@ public class SegmentManager
}
/**
- * Returns a map of dataSource to the number of segments managed by this segmentManager. This method should be
+ * Returns a map of dataSource to the number of segments managed by this segmentManager. This method should be used
* carefully because the returned map might be different from the actual data source states.
*
* @return a map of dataSources and number of segments
@@ -120,41 +120,68 @@ public class SegmentManager
* Returns the timeline for a datasource, if it exists. The analysis object passed in must represent a scan-based
* datasource of a single table.
*/
- public Optional<VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> getTimeline(TableDataSource dataSource)
+ public Optional<VersionedIntervalTimeline<String, DataSegment>> getTimeline(TableDataSource dataSource)
{
return Optional.ofNullable(dataSources.get(dataSource.getName())).map(DataSourceState::getTimeline);
}
+ /**
+ * Returns a {@link Segment} transformed with a {@link SegmentMapFunction}, if it is available in the cache. The
+ * returned {@link Segment} must be closed when the caller is finished doing segment things. This method will not
+ * download a {@link DataSegment} if it is not already present in {@link #cacheManager}, use
+ * {@link #acquireSegment(DataSegment)} instead.
+ */
+ public Optional<Segment> acquireCachedSegment(DataSegment dataSegment)
+ {
+ return cacheManager.acquireCachedSegment(dataSegment);
+ }
+
+ /**
+ * Returns a {@link AcquireSegmentAction}, where calling {@link AcquireSegmentAction#getSegmentFuture()} will either return
+ * immediately if the {@link Segment} is in the cache, or possibly try to fetch the segment from deep storage if not.
+ * The returned {@link Segment}, if present, must be closed when the caller is finished doing segment things.
+ * <p>
+ * Calling this method is treated as an intent to acquire and use the segment via resolving the future, and cache
+ * manager implementations will place a hold on this segment until the 'loadCleanup' closer is closed - typically
+ * after resolving the future to acquire the reference to the actual {@link Segment} object.
+ */
+ public AcquireSegmentAction acquireSegment(DataSegment dataSegment) throws SegmentLoadingException
+ {
+ return cacheManager.acquireSegment(dataSegment);
+ }
+
/**
* Returns the collection of {@link IndexedTable} for the entire timeline (since join conditions do not currently
* consider the queries intervals), if the timeline exists for each of its segments that are joinable.
*/
- public Optional<Stream<ReferenceCountedIndexedTableProvider>> getIndexedTables(TableDataSource dataSource)
+ public Optional<Stream<ReferenceCountedIndexedTableProvider>> getIndexedTables(
+ TableDataSource dataSource
+ )
{
return getTimeline(dataSource).map(timeline -> {
// join doesn't currently consider intervals, so just consider all segments
- final Stream<ReferenceCountedSegmentProvider> segments =
+ final Stream<DataSegment> segments =
timeline.lookup(Intervals.ETERNITY)
.stream()
.flatMap(x -> StreamSupport.stream(x.getObject().payloads().spliterator(), false));
ConcurrentHashMap<SegmentId, ReferenceCountedIndexedTableProvider> tables =
Optional.ofNullable(dataSources.get(dataSource.getName())).map(DataSourceState::getTablesLookup)
.orElseThrow(() -> new ISE("dataSource[%s] does not have IndexedTables", dataSource.getName()));
- return segments.map(segment -> tables.get(segment.getBaseSegment().getId())).filter(Objects::nonNull);
+ return segments.map(segment -> tables.get(segment.getId())).filter(Objects::nonNull);
});
}
public boolean hasIndexedTables(String dataSourceName)
{
if (dataSources.containsKey(dataSourceName)) {
- return dataSources.get(dataSourceName).tablesLookup.size() > 0;
+ return !dataSources.get(dataSourceName).tablesLookup.isEmpty();
}
return false;
}
/**
- * Load the supplied segment into page cache on bootstrap. If the segment is already loaded, this method does not
- * reload the segment into the page cache.
+ * Load the supplied segment into segment cache on bootstrap. If the segment is already loaded, this method does not
+ * reload the segment into the segment cache.
*
* @param dataSegment segment to bootstrap
* @param loadFailed callback to execute when segment lazy load fails. This applies only
@@ -168,26 +195,20 @@ public class SegmentManager
final SegmentLazyLoadFailCallback loadFailed
) throws SegmentLoadingException, IOException
{
- final ReferenceCountedSegmentProvider segment;
try {
- segment = cacheManager.getBootstrapSegment(dataSegment, loadFailed);
- if (segment == null) {
- throw new SegmentLoadingException(
- "No segment adapter found for bootstrap segment[%s] with loadSpec[%s].",
- dataSegment.getId(), dataSegment.getLoadSpec()
- );
- }
+ cacheManager.bootstrap(dataSegment, loadFailed);
}
catch (SegmentLoadingException e) {
- cacheManager.cleanup(dataSegment);
+ cacheManager.drop(dataSegment);
throw e;
}
- loadSegmentInternal(dataSegment, segment, cacheManager::loadSegmentIntoPageCacheOnBootstrap);
+ loadSegmentInternal(dataSegment);
}
+
/**
- * Load the supplied segment into page cache. If the segment is already loaded, this method does not reload the
- * segment into the page cache. This method should be called for non-bootstrapping flows. Unlike
+ * Load the supplied segment into segment cache. If the segment is already loaded, this method does not reload the
+ * segment into the segment cache. This method should be called for non-bootstrapping flows. Unlike
* {@link #loadSegmentOnBootstrap(DataSegment, SegmentLazyLoadFailCallback)}, this method doesn't accept a lazy load
* fail callback because the segment is loaded immediately.
*
@@ -198,27 +219,18 @@ public class SegmentManager
*/
public void loadSegment(final DataSegment dataSegment) throws SegmentLoadingException, IOException
{
- final ReferenceCountedSegmentProvider segment;
try {
- segment = cacheManager.getSegment(dataSegment);
- if (segment == null) {
- throw new SegmentLoadingException(
- "No segment adapter found for segment[%s] with loadSpec[%s].",
- dataSegment.getId(), dataSegment.getLoadSpec()
- );
- }
+ cacheManager.load(dataSegment);
}
catch (SegmentLoadingException e) {
- cacheManager.cleanup(dataSegment);
+ cacheManager.drop(dataSegment);
throw e;
}
- loadSegmentInternal(dataSegment, segment, cacheManager::loadSegmentIntoPageCache);
+ loadSegmentInternal(dataSegment);
}
private void loadSegmentInternal(
- final DataSegment dataSegment,
- final ReferenceCountedSegmentProvider segment,
- final Consumer<DataSegment> pageCacheLoadFunction
+ final DataSegment dataSegment
) throws IOException
{
final SettableSupplier<Boolean> resultSupplier = new SettableSupplier<>();
@@ -228,44 +240,55 @@ public class SegmentManager
dataSegment.getDataSource(),
(k, v) -> {
final DataSourceState dataSourceState = v == null ? new DataSourceState() : v;
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> loadedIntervals =
+ final VersionedIntervalTimeline<String, DataSegment> loadedIntervals =
dataSourceState.getTimeline();
- final PartitionChunk<ReferenceCountedSegmentProvider> entry = loadedIntervals.findChunk(
+ final PartitionChunk<DataSegment> entry = loadedIntervals.findChunk(
dataSegment.getInterval(),
dataSegment.getVersion(),
dataSegment.getShardSpec().getPartitionNum()
);
if (entry != null) {
- log.warn("Told to load an adapter for segment[%s] that already exists", dataSegment.getId());
+ log.warn("Told to load segment[%s] that already exists", dataSegment.getId());
resultSupplier.set(false);
} else {
- final Segment baseSegment = segment.getBaseSegment();
- final IndexedTable table = baseSegment.as(IndexedTable.class);
- if (table != null) {
- if (dataSourceState.isEmpty() || dataSourceState.numSegments == dataSourceState.tablesLookup.size()) {
- dataSourceState.tablesLookup.put(baseSegment.getId(), new ReferenceCountedIndexedTableProvider(table));
- } else {
- log.error("Cannot load segment[%s] with IndexedTable, no existing segments are joinable", baseSegment.getId());
- }
- } else if (dataSourceState.tablesLookup.size() > 0) {
- log.error("Cannot load segment[%s] without IndexedTable, all existing segments are joinable", baseSegment.getId());
- }
+
loadedIntervals.add(
dataSegment.getInterval(),
dataSegment.getVersion(),
- dataSegment.getShardSpec().createChunk(segment)
+ dataSegment.getShardSpec().createChunk(dataSegment)
);
- final PhysicalSegmentInspector countInspector = baseSegment.as(PhysicalSegmentInspector.class);
- final long numOfRows;
- if (dataSegment.isTombstone() || countInspector == null) {
- numOfRows = 0;
- } else {
- numOfRows = countInspector.getNumRows();
+
+ long numOfRows = 0;
+ final Optional<Segment> loadedSegment = cacheManager.acquireCachedSegment(dataSegment);
+ if (loadedSegment.isPresent()) {
+ final Segment segment = loadedSegment.get();
+ final IndexedTable table = segment.as(IndexedTable.class);
+ if (table != null) {
+ if (dataSourceState.isEmpty() || dataSourceState.numSegments == dataSourceState.tablesLookup.size()) {
+ dataSourceState.tablesLookup.put(
+ segment.getId(),
+ new ReferenceCountedIndexedTableProvider(table)
+ );
+ } else {
+ log.error(
+ "Cannot load segment[%s] with IndexedTable, no existing segments are joinable",
+ segment.getId()
+ );
+ }
+ } else if (!dataSourceState.tablesLookup.isEmpty()) {
+ log.error(
+ "Cannot load segment[%s] without IndexedTable, all existing segments are joinable",
+ segment.getId()
+ );
+ }
+ final PhysicalSegmentInspector countInspector = segment.as(PhysicalSegmentInspector.class);
+ if (countInspector != null) {
+ numOfRows = countInspector.getNumRows();
+ }
+ CloseableUtils.closeAndWrapExceptions(segment);
}
dataSourceState.addSegment(dataSegment, numOfRows);
-
- pageCacheLoadFunction.accept(dataSegment);
resultSupplier.set(true);
}
@@ -278,9 +301,9 @@ public class SegmentManager
}
}
- public void dropSegment(final DataSegment segment)
+ public void dropSegment(final DataSegment dataSegment)
{
- final String dataSource = segment.getDataSource();
+ final String dataSource = dataSegment.getDataSource();
// compute() is used to ensure that the operation for a data source is executed atomically
dataSources.compute(
@@ -290,33 +313,34 @@ public class SegmentManager
log.info("Told to delete a queryable for a dataSource[%s] that doesn't exist.", dataSourceName);
return null;
} else {
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> loadedIntervals =
+ final VersionedIntervalTimeline<String, DataSegment> loadedIntervals =
dataSourceState.getTimeline();
- final ShardSpec shardSpec = segment.getShardSpec();
- final PartitionChunk<ReferenceCountedSegmentProvider> removed = loadedIntervals.remove(
- segment.getInterval(),
- segment.getVersion(),
+ final PartitionChunk<DataSegment> removed = loadedIntervals.remove(
+ dataSegment.getInterval(),
+ dataSegment.getVersion(),
// remove() internally searches for a partitionChunk to remove which is *equal* to the given
// partitionChunk. Note that partitionChunk.equals() checks only the partitionNum, but not the object.
- segment.getShardSpec().createChunk(ReferenceCountedSegmentProvider.wrapSegment(null, shardSpec))
+ dataSegment.getShardSpec().createChunk(dataSegment)
);
- final ReferenceCountedSegmentProvider oldSegmentRef = (removed == null) ? null : removed.getObject();
+ final DataSegment oldSegmentRef = (removed == null) ? null : removed.getObject();
if (oldSegmentRef != null) {
try (final Closer closer = Closer.create()) {
- final PhysicalSegmentInspector countInspector = oldSegmentRef.getBaseSegment().as(PhysicalSegmentInspector.class);
- final long numOfRows;
- if (segment.isTombstone() || countInspector == null) {
- numOfRows = 0;
- } else {
- numOfRows = countInspector.getNumRows();
- }
- dataSourceState.removeSegment(segment, numOfRows);
-
- closer.register(oldSegmentRef);
- log.info("Attempting to close segment[%s]", segment.getId());
- final ReferenceCountedIndexedTableProvider oldTable = dataSourceState.tablesLookup.remove(segment.getId());
+ final Optional<Segment> oldSegment = cacheManager.acquireCachedSegment(oldSegmentRef);
+ long numberOfRows = oldSegment.map(segment -> {
+ final PhysicalSegmentInspector countInspector = segment.as(PhysicalSegmentInspector.class);
+ if (countInspector != null) {
+ return countInspector.getNumRows();
+ }
+ CloseableUtils.closeAndWrapExceptions(segment);
+ return 0;
+ }).orElse(0);
+
+ dataSourceState.removeSegment(dataSegment, numberOfRows);
+
+ log.info("Attempting to close segment[%s]", dataSegment.getId());
+ final ReferenceCountedIndexedTableProvider oldTable = dataSourceState.tablesLookup.remove(dataSegment.getId());
if (oldTable != null) {
closer.register(oldTable);
}
@@ -328,8 +352,8 @@ public class SegmentManager
log.info(
"Told to delete a queryable on dataSource[%s] for interval[%s] and version[%s] that I don't have.",
dataSourceName,
- segment.getInterval(),
- segment.getVersion()
+ dataSegment.getInterval(),
+ dataSegment.getVersion()
);
}
@@ -339,8 +363,8 @@ public class SegmentManager
}
);
- cacheManager.removeInfoFile(segment);
- cacheManager.cleanup(segment);
+ cacheManager.removeInfoFile(dataSegment);
+ cacheManager.drop(dataSegment);
}
/**
@@ -369,13 +393,18 @@ public class SegmentManager
cacheManager.shutdownBootstrap();
}
+ public void shutdown()
+ {
+ cacheManager.shutdown();
+ }
+
/**
* Represent the state of a data source including the timeline, total segment size, and number of segments.
*/
public static class DataSourceState
{
- private final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline =
+ private final VersionedIntervalTimeline<String, DataSegment> timeline =
new VersionedIntervalTimeline<>(Ordering.natural());
private final ConcurrentHashMap<SegmentId, ReferenceCountedIndexedTableProvider> tablesLookup = new ConcurrentHashMap<>();
@@ -408,7 +437,7 @@ public class SegmentManager
}
}
- public VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> getTimeline()
+ public VersionedIntervalTimeline<String, DataSegment> getTimeline()
{
return timeline;
}
diff --git a/server/src/main/java/org/apache/druid/server/coordination/ServerManager.java b/server/src/main/java/org/apache/druid/server/ServerManager.java
similarity index 57%
rename from server/src/main/java/org/apache/druid/server/coordination/ServerManager.java
rename to server/src/main/java/org/apache/druid/server/ServerManager.java
index 0e8a0602474..732645b42ae 100644
--- a/server/src/main/java/org/apache/druid/server/coordination/ServerManager.java
+++ b/server/src/main/java/org/apache/druid/server/ServerManager.java
@@ -17,15 +17,18 @@
* under the License.
*/
-package org.apache.druid.server.coordination;
+package org.apache.druid.server;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.Inject;
import org.apache.druid.client.CachingQueryRunner;
import org.apache.druid.client.cache.Cache;
import org.apache.druid.client.cache.CacheConfig;
import org.apache.druid.client.cache.CachePopulator;
+import org.apache.druid.error.DruidException;
import org.apache.druid.guice.annotations.Smile;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.guava.FunctionalIterable;
@@ -35,6 +38,7 @@ import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.query.BySegmentQueryRunner;
import org.apache.druid.query.CPUTimeMetricQueryRunner;
+import org.apache.druid.query.DataSegmentAndDescriptor;
import org.apache.druid.query.DataSource;
import org.apache.druid.query.FinalizeResultsQueryRunner;
import org.apache.druid.query.MetricsEmittingQueryRunner;
@@ -55,18 +59,20 @@ import org.apache.druid.query.QueryUnsupportedException;
import org.apache.druid.query.ReportTimelineMissingSegmentQueryRunner;
import org.apache.druid.query.SegmentDescriptor;
import org.apache.druid.query.context.ResponseContext;
+import org.apache.druid.query.metadata.metadata.SegmentMetadataQuery;
import org.apache.druid.query.planning.ExecutionVertex;
import org.apache.druid.query.policy.PolicyEnforcer;
import org.apache.druid.query.spec.SpecificSegmentQueryRunner;
import org.apache.druid.query.spec.SpecificSegmentSpec;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
+import org.apache.druid.segment.ReferenceCountedObjectProvider;
import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.segment.SegmentReference;
import org.apache.druid.segment.TimeBoundaryInspector;
-import org.apache.druid.server.ResourceIdPopulatingQueryRunner;
-import org.apache.druid.server.SegmentManager;
-import org.apache.druid.server.SetAndVerifyContextQueryRunner;
+import org.apache.druid.segment.loading.AcquireSegmentAction;
+import org.apache.druid.segment.loading.VirtualPlaceholderSegment;
import org.apache.druid.server.initialization.ServerConfig;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.PartitionChunk;
@@ -74,8 +80,11 @@ import org.apache.druid.utils.CloseableUtils;
import org.apache.druid.utils.JvmUtils;
import org.joda.time.Interval;
+import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
/**
@@ -128,8 +137,8 @@ public class ServerManager implements QuerySegmentWalker
@Override
public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals)
{
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline;
- final Optional<VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> maybeTimeline =
+ final VersionedIntervalTimeline<String, DataSegment> timeline;
+ final Optional<VersionedIntervalTimeline<String, DataSegment>> maybeTimeline =
segmentManager.getTimeline(ExecutionVertex.of(query).getBaseTableDataSource());
if (maybeTimeline.isPresent()) {
@@ -170,7 +179,7 @@ public class ServerManager implements QuerySegmentWalker
public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs)
{
final ExecutionVertex ev = ExecutionVertex.of(query);
- final Optional<VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> maybeTimeline =
+ final Optional<VersionedIntervalTimeline<String, DataSegment>> maybeTimeline =
segmentManager.getTimeline(ev.getBaseTableDataSource());
if (maybeTimeline.isEmpty()) {
return new ReportTimelineMissingSegmentQueryRunner<>(Lists.newArrayList(specs));
@@ -178,51 +187,234 @@ public class ServerManager implements QuerySegmentWalker
final QueryRunnerFactory<T, Query<T>> factory = getQueryRunnerFactory(query);
final QueryToolChest<T, Query<T>> toolChest = getQueryToolChest(query, factory);
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline = maybeTimeline.get();
+ final VersionedIntervalTimeline<String, DataSegment> timeline = maybeTimeline.get();
return new ResourceManagingQueryRunner<>(timeline, factory, toolChest, ev, specs);
}
/**
- * For each {@link SegmentDescriptor}, we try to fetch a {@link ReferenceCountedSegmentProvider} from the supplied
- * {@link VersionedIntervalTimeline} and apply {@link SegmentMapFunction} to acquire a reference and transform the
- * segment as appropriate for query processing, returning a {@link SegmentReference} wrapper. The wrapper contains the
- * {@link SegmentDescriptor} and an {@link Optional<Segment>}, which if present the {@link Segment} will be registered
- * to the {@link Closer}, and will be empty if the segment was not actually in the timeline, or if unable to apply
- * the reference
+ * For each {@link SegmentDescriptor}, we try to fetch a {@link DataSegment} from the supplied
+ * {@link VersionedIntervalTimeline} to build a list of {@link DataSegmentAndDescriptor} and then hand off to
+ * {@link #getSegmentReferences(List, SegmentMapFunction, long)} to transform into {@link SegmentReference}
+ * wrappers. The wrappers contain the {@link SegmentDescriptor} and an {@link Optional<Segment>}, and MUST BE
+ * CLOSED to release the references when processing is complete.
*/
- protected List<SegmentReference> acquireAllSegments(
- VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline,
+ protected List<SegmentReference> getSegmentReferences(
+ VersionedIntervalTimeline<String, DataSegment> timeline,
Iterable<SegmentDescriptor> segments,
- SegmentMapFunction segmentMapFn,
- Closer closer
+ SegmentMapFunction segmentMapFunction,
+ final long timeout
)
{
- // materialize to list to acquire all of the references
- return Lists.newArrayList(
- FunctionalIterable
- .create(segments)
- .transform(
- descriptor -> {
- final PartitionChunk<ReferenceCountedSegmentProvider> chunk = timeline.findChunk(
- descriptor.getInterval(),
- descriptor.getVersion(),
- descriptor.getPartitionNumber()
- );
+ // first we build a list of DataSegment we need to get references for, paired with the descriptor from the query
+ final List<DataSegmentAndDescriptor> segmentsToMap = new ArrayList<>();
+ for (SegmentDescriptor descriptor : segments) {
+ final PartitionChunk<DataSegment> chunk = timeline.findChunk(
+ descriptor.getInterval(),
+ descriptor.getVersion(),
+ descriptor.getPartitionNumber()
+ );
+
+ if (chunk != null) {
+ segmentsToMap.add(new DataSegmentAndDescriptor(chunk.getObject(), descriptor));
+ } else {
+ segmentsToMap.add(new DataSegmentAndDescriptor(null, descriptor));
+ }
+ }
- if (chunk == null) {
- return new SegmentReference(descriptor, Optional.empty());
- }
+ return getSegmentReferences(segmentsToMap, segmentMapFunction, timeout);
+ }
- final ReferenceCountedSegmentProvider referenceCounter = chunk.getObject();
- return new SegmentReference(descriptor, segmentMapFn.apply(referenceCounter).map(closer::register));
- }
- )
- );
+ /**
+ * Given a list of {@link DataSegmentAndDescriptor}, uses {@link SegmentManager#acquireSegment(DataSegment)} for each
+ * to obtain a 'reference' to segments in the cache (or loaded from deep storage if necessary/supported by the
+ * storage layer).
+ * <p>
+ * For each of these segments, we then apply a {@link SegmentMapFunction} to prepare for processing. The returned
+ * {@link SegmentReference} MUST BE CLOSED to release the reference.
+ */
+ private ArrayList<SegmentReference> getSegmentReferences(
+ List<DataSegmentAndDescriptor> segmentsToMap,
+ SegmentMapFunction segmentMapFunction,
+ long timeout
+ )
+ {
+ // closer to collect everything that needs cleaned up in the event of failure, if we make it out of this function,
+ // closing the segment reference handles everything and it is the callers responsibility
+ final Closer safetyNet = Closer.create();
+
+ // build list of acquire reference actions, this does not initiate the actions until we collect the futures. this
+ // does place a hold on any weakly held references if the cache includes segments that reside on virtual storage
+ // fabric
+ final List<AcquireSegmentAction> actions = new ArrayList<>();
+ try {
+ for (DataSegmentAndDescriptor segment : segmentsToMap) {
+ if (segment.getDataSegment() == null) {
+ actions.add(safetyNet.register(AcquireSegmentAction.missingSegment()));
+ } else {
+ actions.add(safetyNet.register(segmentManager.acquireSegment(segment.getDataSegment())));
+ }
+ }
+ }
+ catch (Throwable t) {
+ throw CloseableUtils.closeInCatch(
+ t instanceof DruidException
+ ? (DruidException) t
+ : DruidException.forPersona(DruidException.Persona.OPERATOR)
+ .ofCategory(DruidException.Category.RUNTIME_FAILURE)
+ .build(t, t.getMessage()),
+ safetyNet
+ );
+ }
+
+ long timeoutAt = System.currentTimeMillis() + timeout;
+
+ Throwable failure = null;
+
+ // getting the future kicks off any background action, so materialize them all to a list to get things started
+ final List<ListenableFuture<ReferenceCountedObjectProvider<Segment>>> futures = new ArrayList<>(actions.size());
+ for (AcquireSegmentAction acquireSegmentAction : actions) {
+ // if we haven't failed yet, keep collecting futures
+ if (failure == null) {
+ try {
+ futures.add(acquireSegmentAction.getSegmentFuture());
+ }
+ catch (Throwable t) {
+ failure = t;
+ }
+ } else {
+ futures.add(Futures.immediateFuture(Optional::empty));
+ }
+ }
+
+ if (failure != null) {
+ throw CloseableUtils.closeInCatch(
+ failure instanceof DruidException
+ ? (DruidException) failure
+ : DruidException.forPersona(DruidException.Persona.OPERATOR)
+ .ofCategory(DruidException.Category.RUNTIME_FAILURE)
+ .build(failure, "Failed to acquire segment references to process query"),
+ safetyNet
+ );
+ }
+
+ final ArrayList<SegmentReference> segmentReferences = new ArrayList<>(actions.size());
+ boolean timedOut = false;
+ boolean interrupted = false;
+ for (int i = 0; i < actions.size(); i++) {
+ try {
+ final DataSegmentAndDescriptor segmentAndDescriptor = segmentsToMap.get(i);
+ final AcquireSegmentAction action = actions.get(i);
+ final ListenableFuture<ReferenceCountedObjectProvider<Segment>> future = futures.get(i);
+ final ReferenceCountedObjectProvider<Segment> referenceProvider =
+ future.get(timeoutAt - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
+ final Optional<Segment> segment = referenceProvider.acquireReference();
+ try {
+ final Optional<Segment> mappedSegment = segmentMapFunction.apply(segment).map(safetyNet::register);
+ segmentReferences.add(
+ new SegmentReference(
+ segmentAndDescriptor.getDescriptor(),
+ mappedSegment,
+ action
+ )
+ );
+ }
+ catch (Throwable t) {
+ // if applying the mapFn failed, attach the base segment to the closer and rethrow
+ segment.ifPresent(safetyNet::register);
+ throw t;
+ }
+ }
+ catch (Throwable t) {
+ if (t instanceof InterruptedException) {
+ interrupted = true;
+ }
+ if (t instanceof TimeoutException) {
+ timedOut = true;
+ }
+ if (failure == null) {
+ failure = t;
+ } else {
+ // no need to get carried away, if a bunch fail this ceases to be useful
+ if (failure.getSuppressed().length <= 10) {
+ failure.addSuppressed(t);
+ }
+ }
+ }
+ }
+ if (failure != null) {
+ final DruidException toThrow;
+ if (failure instanceof DruidException) {
+ toThrow = (DruidException) failure;
+ } else if (timedOut) {
+ toThrow = DruidException.forPersona(DruidException.Persona.USER)
+ .ofCategory(DruidException.Category.TIMEOUT)
+ .build(failure, "Failed to acquire segment references to process query");
+ } else if (interrupted) {
+ Thread.currentThread().interrupt();
+ toThrow = DruidException.forPersona(DruidException.Persona.OPERATOR)
+ .ofCategory(DruidException.Category.RUNTIME_FAILURE)
+ .build(failure, "Interrupted waiting for segments");
+ } else {
+ toThrow = DruidException.forPersona(DruidException.Persona.OPERATOR)
+ .ofCategory(DruidException.Category.RUNTIME_FAILURE)
+ .build(failure, "Failed to acquire segment references to process query");
+ }
+ throw CloseableUtils.closeInCatch(toThrow, safetyNet);
+ }
+ return segmentReferences;
+ }
+
+
+ /**
+ * Special handling for {@link SegmentMetadataQuery}, to force it to only use segments that are already stored in the
+ * cache as strong references, using empty placeholder segments with a __time column and 0 rows for all segments that
+ * are in the timeline but are missing from the cache (e.g. weak references)
+ */
+ private List<SegmentReference> getSegmentMetadataSegmentReferences(
+ VersionedIntervalTimeline<String, DataSegment> timeline,
+ Iterable<SegmentDescriptor> segments,
+ SegmentMapFunction segmentMapFn
+ )
+ {
+ // materialize to list to acquire all of the references
+ List<SegmentReference> segmentReferences = new ArrayList<>();
+ for (SegmentDescriptor descriptor : segments) {
+ final PartitionChunk<DataSegment> chunk = timeline.findChunk(
+ descriptor.getInterval(),
+ descriptor.getVersion(),
+ descriptor.getPartitionNumber()
+ );
+ if (chunk == null) {
+ segmentReferences.add(SegmentReference.missing(descriptor));
+ } else {
+ final DataSegment dataSegment = chunk.getObject();
+ final Optional<Segment> theSegment = segmentMapFn.apply(segmentManager.acquireCachedSegment(dataSegment));
+ if (theSegment.isPresent()) {
+ segmentReferences.add(
+ new SegmentReference(
+ descriptor,
+ theSegment,
+ null
+ )
+ );
+ } else {
+ // make a stub to run the segment metadata query instead of being a 'missing' segment
+ segmentReferences.add(
+ new SegmentReference(
+ descriptor,
+ Optional.of(new VirtualPlaceholderSegment(dataSegment)),
+ null
+ )
+ );
+ }
+ }
+ }
+ return segmentReferences;
}
protected <T> FunctionalIterable<QueryRunner<T>> getQueryRunnersForSegments(
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline,
+ final VersionedIntervalTimeline<String, DataSegment> timeline,
final Iterable<SegmentDescriptor> specs,
final Query<T> query,
final QueryRunnerFactory<T, Query<T>> factory,
@@ -233,8 +425,23 @@ public class ServerManager implements QuerySegmentWalker
final Closer closer
)
{
+ final List<SegmentReference> segmentReferences;
+ // this is kind of gross, but otherwise we're going to be loading weak assignments more or less as soon as they
+ // are assigned instead of on demand at query time
+ if (query instanceof SegmentMetadataQuery) {
+ segmentReferences = getSegmentMetadataSegmentReferences(timeline, specs, segmentMapFn);
+ } else {
+ segmentReferences = getSegmentReferences(
+ timeline,
+ specs,
+ segmentMapFn,
+ query.context().getTimeout()
+ );
+ }
+ closer.registerAll(segmentReferences);
+
return FunctionalIterable
- .create(acquireAllSegments(timeline, specs, segmentMapFn, closer))
+ .create(segmentReferences)
.transform(
ref ->
ref.getSegmentReference()
@@ -268,10 +475,10 @@ public class ServerManager implements QuerySegmentWalker
final SegmentId segmentId = segment.getId();
final Interval segmentInterval = segment.getDataInterval();
- String segmentIdString = segmentId.toString();
+ final String segmentIdString = segmentId.toString();
final SpecificSegmentSpec segmentSpec = new SpecificSegmentSpec(segmentDescriptor);
- MetricsEmittingQueryRunner<T> metricsEmittingQueryRunnerInner = new MetricsEmittingQueryRunner<>(
+ final MetricsEmittingQueryRunner<T> metricsEmittingQueryRunnerInner = new MetricsEmittingQueryRunner<>(
emitter,
toolChest,
factory.createRunner(segment),
@@ -369,14 +576,14 @@ public class ServerManager implements QuerySegmentWalker
*/
public final class ResourceManagingQueryRunner<T> implements QueryRunner<T>
{
- private final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline;
+ private final VersionedIntervalTimeline<String, DataSegment> timeline;
private final QueryRunnerFactory<T, Query<T>> factory;
private final QueryToolChest<T, Query<T>> toolChest;
private final ExecutionVertex ev;
private final Iterable<SegmentDescriptor> specs;
public ResourceManagingQueryRunner(
- VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline,
+ VersionedIntervalTimeline<String, DataSegment> timeline,
QueryRunnerFactory<T, Query<T>> factory,
QueryToolChest<T, Query<T>> toolChest,
ExecutionVertex ev,
@@ -438,30 +645,4 @@ public class ServerManager implements QuerySegmentWalker
}
}
}
-
- /**
- * Wrapper for a {@link SegmentDescriptor} and {@link Optional<Segment>}, the latter being created by a
- * {@link SegmentMapFunction} being applied to a {@link ReferenceCountedSegmentProvider}.
- */
- public static final class SegmentReference
- {
- private final SegmentDescriptor segmentDescriptor;
- private final Optional<Segment> segmentReference;
-
- public SegmentReference(SegmentDescriptor segmentDescriptor, Optional<Segment> segmentReference)
- {
- this.segmentDescriptor = segmentDescriptor;
- this.segmentReference = segmentReference;
- }
-
- public SegmentDescriptor getSegmentDescriptor()
- {
- return segmentDescriptor;
- }
-
- public Optional<Segment> getSegmentReference()
- {
- return segmentReference;
- }
- }
}
diff --git a/server/src/main/java/org/apache/druid/server/coordination/SegmentBootstrapper.java b/server/src/main/java/org/apache/druid/server/coordination/SegmentCacheBootstrapper.java
similarity index 98%
rename from server/src/main/java/org/apache/druid/server/coordination/SegmentBootstrapper.java
rename to server/src/main/java/org/apache/druid/server/coordination/SegmentCacheBootstrapper.java
index 7eec82e80b1..42ac9fec70a 100644
--- a/server/src/main/java/org/apache/druid/server/coordination/SegmentBootstrapper.java
+++ b/server/src/main/java/org/apache/druid/server/coordination/SegmentCacheBootstrapper.java
@@ -64,7 +64,7 @@ import java.util.concurrent.atomic.AtomicInteger;
* are complete.
*/
@ManageLifecycle
-public class SegmentBootstrapper
+public class SegmentCacheBootstrapper
{
private final SegmentLoadDropHandler loadDropHandler;
private final SegmentLoaderConfig config;
@@ -80,12 +80,12 @@ public class SegmentBootstrapper
// Synchronizes start/stop of this object.
private final Object startStopLock = new Object();
- private static final EmittingLogger log = new EmittingLogger(SegmentBootstrapper.class);
+ private static final EmittingLogger log = new EmittingLogger(SegmentCacheBootstrapper.class);
private final DataSourceTaskIdHolder datasourceHolder;
@Inject
- public SegmentBootstrapper(
+ public SegmentCacheBootstrapper(
SegmentLoadDropHandler loadDropHandler,
SegmentLoaderConfig config,
DataSegmentAnnouncer segmentAnnouncer,
@@ -148,6 +148,7 @@ public class SegmentBootstrapper
if (shouldAnnounce()) {
serverAnnouncer.unannounce();
}
+ segmentManager.shutdown();
}
catch (Exception e) {
throw new RuntimeException(e);
@@ -179,12 +180,14 @@ public class SegmentBootstrapper
// Start a temporary thread pool to load segments into page cache during bootstrap
final ExecutorService bootstrapExecutor = Execs.multiThreaded(
- config.getNumBootstrapThreads(), "Segment-Bootstrap-%s"
+ config.getNumBootstrapThreads(),
+ "Segment-Bootstrap-%s"
);
// Start a temporary scheduled executor for background segment announcing
final ScheduledExecutorService backgroundAnnouncerExecutor = Executors.newScheduledThreadPool(
- config.getNumLoadingThreads(), Execs.makeThreadFactory("Background-Segment-Announcer-%s")
+ config.getNumLoadingThreads(),
+ Execs.makeThreadFactory("Background-Segment-Announcer-%s")
);
try (final BackgroundSegmentAnnouncer backgroundSegmentAnnouncer =
diff --git a/server/src/main/java/org/apache/druid/server/coordinator/duty/CompactSegments.java b/server/src/main/java/org/apache/druid/server/coordinator/duty/CompactSegments.java
index 543bc2b8213..135852c1de9 100644
--- a/server/src/main/java/org/apache/druid/server/coordinator/duty/CompactSegments.java
+++ b/server/src/main/java/org/apache/druid/server/coordinator/duty/CompactSegments.java
@@ -472,6 +472,7 @@ public class CompactSegments implements CoordinatorCustomDuty
final DataSourceCompactionConfig config = compactionConfigs.get(dataSourceName);
final List<DataSegment> segmentsToCompact = entry.getSegments();
+ // ^ feed segmentsToCompact to config to get grouping of configs to segments
// Create granularitySpec to send to compaction task
Granularity segmentGranularityToUse = null;
diff --git a/server/src/main/java/org/apache/druid/server/http/HistoricalResource.java b/server/src/main/java/org/apache/druid/server/http/HistoricalResource.java
index 223e1a2dea2..8a049fa4d8e 100644
--- a/server/src/main/java/org/apache/druid/server/http/HistoricalResource.java
+++ b/server/src/main/java/org/apache/druid/server/http/HistoricalResource.java
@@ -21,7 +21,7 @@ package org.apache.druid.server.http;
import com.google.common.collect.ImmutableMap;
import com.sun.jersey.spi.container.ResourceFilters;
-import org.apache.druid.server.coordination.SegmentBootstrapper;
+import org.apache.druid.server.coordination.SegmentCacheBootstrapper;
import org.apache.druid.server.http.security.StateResourceFilter;
import javax.inject.Inject;
@@ -34,14 +34,14 @@ import javax.ws.rs.core.Response;
@Path("/druid/historical/v1")
public class HistoricalResource
{
- private final SegmentBootstrapper segmentBootstrapper;
+ private final SegmentCacheBootstrapper segmentCacheBootstrapper;
@Inject
public HistoricalResource(
- SegmentBootstrapper segmentBootstrapper
+ SegmentCacheBootstrapper segmentCacheBootstrapper
)
{
- this.segmentBootstrapper = segmentBootstrapper;
+ this.segmentCacheBootstrapper = segmentCacheBootstrapper;
}
@GET
@@ -50,14 +50,14 @@ public class HistoricalResource
@Produces(MediaType.APPLICATION_JSON)
public Response getLoadStatus()
{
- return Response.ok(ImmutableMap.of("cacheInitialized", segmentBootstrapper.isBootstrappingComplete())).build();
+ return Response.ok(ImmutableMap.of("cacheInitialized", segmentCacheBootstrapper.isBootstrappingComplete())).build();
}
@GET
@Path("/readiness")
public Response getReadiness()
{
- if (segmentBootstrapper.isBootstrappingComplete()) {
+ if (segmentCacheBootstrapper.isBootstrappingComplete()) {
return Response.ok().build();
} else {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
diff --git a/server/src/test/java/org/apache/druid/segment/loading/NoopSegmentCacheManager.java b/server/src/test/java/org/apache/druid/segment/loading/NoopSegmentCacheManager.java
index b64d8f68538..3e5af5c8cfb 100644
--- a/server/src/test/java/org/apache/druid/segment/loading/NoopSegmentCacheManager.java
+++ b/server/src/test/java/org/apache/druid/segment/loading/NoopSegmentCacheManager.java
@@ -19,12 +19,13 @@
package org.apache.druid.segment.loading;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
+import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentLazyLoadFailCallback;
import org.apache.druid.timeline.DataSegment;
import java.io.File;
import java.util.List;
+import java.util.Optional;
/**
* Test implementation of {@link SegmentCacheManager} which throws an
@@ -57,13 +58,13 @@ public class NoopSegmentCacheManager implements SegmentCacheManager
}
@Override
- public ReferenceCountedSegmentProvider getSegment(DataSegment segment)
+ public void load(DataSegment segment)
{
throw new UnsupportedOperationException();
}
@Override
- public ReferenceCountedSegmentProvider getBootstrapSegment(DataSegment segment, SegmentLazyLoadFailCallback loadFailed)
+ public void bootstrap(DataSegment segment, SegmentLazyLoadFailCallback loadFailed)
{
throw new UnsupportedOperationException();
}
@@ -75,37 +76,31 @@ public class NoopSegmentCacheManager implements SegmentCacheManager
}
@Override
- public boolean reserve(DataSegment segment)
+ public void drop(DataSegment segment)
{
throw new UnsupportedOperationException();
}
@Override
- public boolean release(DataSegment segment)
+ public Optional<Segment> acquireCachedSegment(DataSegment dataSegment)
{
throw new UnsupportedOperationException();
}
@Override
- public void cleanup(DataSegment segment)
+ public AcquireSegmentAction acquireSegment(DataSegment dataSegment)
{
throw new UnsupportedOperationException();
}
@Override
- public void loadSegmentIntoPageCache(DataSegment segment)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void loadSegmentIntoPageCacheOnBootstrap(DataSegment segment)
+ public void shutdownBootstrap()
{
throw new UnsupportedOperationException();
}
@Override
- public void shutdownBootstrap()
+ public void shutdown()
{
throw new UnsupportedOperationException();
}
diff --git a/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerConcurrencyTest.java b/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerConcurrencyTest.java
index 63dac55ff35..4f23d2cd74f 100644
--- a/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerConcurrencyTest.java
+++ b/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerConcurrencyTest.java
@@ -24,51 +24,67 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import org.apache.druid.error.DruidException;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.DateTimes;
-import org.apache.druid.java.util.common.FileUtils;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
+import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.segment.IndexIO;
+import org.apache.druid.segment.PhysicalSegmentInspector;
+import org.apache.druid.segment.ReferenceCountedObjectProvider;
+import org.apache.druid.segment.Segment;
+import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.TestIndex;
import org.apache.druid.server.metrics.NoopServiceEmitter;
import org.apache.druid.timeline.DataSegment;
+import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.partition.NumberedShardSpec;
-import org.hamcrest.CoreMatchers;
+import org.apache.druid.utils.CloseableUtils;
import org.joda.time.Interval;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
-public class SegmentLocalCacheManagerConcurrencyTest
+class SegmentLocalCacheManagerConcurrencyTest
{
- @Rule
- public final TemporaryFolder tmpFolder = new TemporaryFolder();
-
- @Rule
- public final ExpectedException expectedException = ExpectedException.none();
-
private final ObjectMapper jsonMapper;
private final String dataSource = "test_ds";
private final String segmentVersion;
+ @TempDir
+ File tempDir;
+
private File localSegmentCacheFolder;
+ private File otherLocalSegmentCacheFolder;
private SegmentLocalCacheManager manager;
+ private SegmentLocalCacheManager virtualStorageManager;
+ private StorageLocation location;
+ private StorageLocation location2;
private ExecutorService executorService;
+ private List<DataSegment> segmentsToLoad;
+ private List<DataSegment> segmentsToWeakLoad;
public SegmentLocalCacheManagerConcurrencyTest()
{
@@ -78,48 +94,595 @@ public class SegmentLocalCacheManagerConcurrencyTest
new InjectableValues.Std().addValue(
LocalDataSegmentPuller.class,
new LocalDataSegmentPuller()
+ ).addValue(
+ IndexIO.class,
+ TestHelper.getTestIndexIO()
)
);
segmentVersion = DateTimes.nowUtc().toString();
}
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
EmittingLogger.registerEmitter(new NoopServiceEmitter());
- localSegmentCacheFolder = tmpFolder.newFolder("segment_cache_folder");
+ localSegmentCacheFolder = new File(tempDir, "segment_cache_folder");
+ otherLocalSegmentCacheFolder = new File(tempDir, "other_segment_cache_folder");
+ segmentsToLoad = new ArrayList<>();
+ segmentsToWeakLoad = new ArrayList<>();
final List<StorageLocationConfig> locations = new ArrayList<>();
- // Each segment has the size of 1000 bytes. This deep storage is capable of storing up to 2 segments.
- final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheFolder, 2000L, null);
+ // Each segment has the synthetic size of 1000 bytes. This segment cache is capable of storing up to 8 segments,
+ // 4 per storage location
+ final StorageLocationConfig locationConfig = new StorageLocationConfig(
+ localSegmentCacheFolder,
+ 4000,
+ null
+ );
+ final StorageLocationConfig locationConfig2 = new StorageLocationConfig(
+ otherLocalSegmentCacheFolder,
+ 4000,
+ null
+ );
locations.add(locationConfig);
+ locations.add(locationConfig2);
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locations);
+ final SegmentLoaderConfig vsfLoaderConfig = new SegmentLoaderConfig()
+ {
+ @Override
+ public List<StorageLocationConfig> getLocations()
+ {
+ return locations;
+ }
+
+ @Override
+ public boolean isVirtualStorage()
+ {
+ return true;
+ }
+
+ @Override
+ public int getVirtualStorageLoadThreads()
+ {
+ return Runtime.getRuntime().availableProcessors();
+ }
+ };
final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
+ location = storageLocations.get(0);
+ location2 = storageLocations.get(1);
manager = new SegmentLocalCacheManager(
storageLocations,
- new SegmentLoaderConfig().withLocations(locations),
+ loaderConfig,
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
TestIndex.INDEX_IO,
jsonMapper
);
- executorService = Execs.multiThreaded(4, "segment-loader-local-cache-manager-concurrency-test-%d");
+ virtualStorageManager = new SegmentLocalCacheManager(
+ storageLocations,
+ vsfLoaderConfig,
+ new RoundRobinStorageLocationSelectorStrategy(storageLocations),
+ TestIndex.INDEX_IO,
+ jsonMapper
+ );
+ executorService = Execs.multiThreaded(
+ 10,
+ "segment-loader-local-cache-manager-concurrency-test-%d"
+ );
}
- @After
+ @AfterEach
public void tearDown()
{
executorService.shutdownNow();
+ for (DataSegment segment : segmentsToLoad) {
+ manager.drop(segment);
+ }
+ for (DataSegment segment : segmentsToWeakLoad) {
+ virtualStorageManager.drop(segment);
+ }
+ for (StorageLocation location : virtualStorageManager.getLocations()) {
+ location.resetStats();
+ }
+ }
+
+ @Test
+ public void testAcquireSegment() throws IOException, ExecutionException, InterruptedException
+ {
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
+
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+ makeSegmentsToLoad(8, localStorageFolder, interval, segmentsToLoad);
+
+ final List<Future<?>> futures = segmentsToLoad
+ .stream()
+ .map(segment -> executorService.submit(new Load(manager, segment)))
+ .collect(Collectors.toList());
+
+ for (Future<?> future : futures) {
+ future.get();
+ }
+ Assertions.assertTrue(true);
+ }
+
+ @Test
+ public void testAcquireSegmentFailTooManySegments() throws IOException
+ {
+ final File localStorageFolder = new File("local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+ makeSegmentsToLoad(20, localStorageFolder, interval, segmentsToLoad);
+
+ final List<Future<?>> futures = segmentsToLoad
+ .stream()
+ .map(segment -> executorService.submit(new Load(manager, segment)))
+ .collect(Collectors.toList());
+
+ Throwable t = Assertions.assertThrows(
+ ExecutionException.class,
+ () -> {
+ for (Future<?> future : futures) {
+ future.get();
+ }
+ }
+ );
+ Assertions.assertInstanceOf(SegmentLoadingException.class, t.getCause());
+ Assertions.assertTrue(t.getCause().getMessage().contains("Failed to load segment"));
+ Assertions.assertTrue(t.getCause().getMessage().contains("in all locations."));
+ }
+
+ @Test
+ public void testAcquireSegmentBulkFailTooManySegments() throws IOException
+ {
+ final File localStorageFolder = new File("local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+ makeSegmentsToLoad(30, localStorageFolder, interval, segmentsToLoad);
+
+ final List<WeakLoad> weakLoads = segmentsToLoad
+ .stream()
+ .map(segment -> new WeakLoad(virtualStorageManager, segment, 10, 100, 1000L, false))
+ .collect(Collectors.toList());
+ final List<Future<Integer>> futures = new ArrayList<>();
+ for (WeakLoad weakLoad : weakLoads) {
+ futures.add(executorService.submit(weakLoad));
+ }
+ Throwable t = Assertions.assertThrows(
+ ExecutionException.class,
+ () -> {
+ for (Future<?> future : futures) {
+ future.get();
+ }
+ }
+ );
+ Assertions.assertInstanceOf(DruidException.class, t.getCause());
+ Assertions.assertTrue(t.getCause().getMessage().contains("Unable to load segment"));
+ Assertions.assertTrue(t.getCause().getMessage().contains("on demand, ensure enough disk space has been allocated"));
+ }
+
+ @Test
+ public void testAcquireSegmentOnDemand() throws IOException
+ {
+ final int segmentCount = 100;
+ final int iterations = 2000;
+ final int concurrentReads = 10;
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+ makeSegmentsToLoad(segmentCount, localStorageFolder, interval, segmentsToWeakLoad);
+
+ for (boolean sleepy : new boolean[]{true, false}) {
+ testWeakLoad(iterations, segmentCount, concurrentReads, false, sleepy, false);
+ }
+ }
+
+ @Test
+ public void testAcquireSegmentOnDemandRandomSegment() throws IOException
+ {
+ // moderate number of segments compared to threads, expect to have a decent hit rate
+ final int segmentCount = 24;
+ final int iterations = 2000;
+ final int concurrentReads = 10;
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+
+ makeSegmentsToLoad(segmentCount, localStorageFolder, interval, segmentsToWeakLoad);
+
+ for (boolean sleepy : new boolean[]{true, false}) {
+ testWeakLoad(iterations, segmentCount, concurrentReads, true, sleepy, true);
+ }
+ }
+
+ @Test
+ public void testAcquireSegmentOnDemandRandomSegmentHighHitRate() throws IOException
+ {
+ // low number of total segments so expect many cache hits and few evictions
+ final int segmentCount = 10;
+ final int iterations = 2000;
+ final int concurrentReads = 10;
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+
+ makeSegmentsToLoad(segmentCount, localStorageFolder, interval, segmentsToWeakLoad);
+
+ for (boolean sleepy : new boolean[]{true, false}) {
+ testWeakLoad(iterations, segmentCount, concurrentReads, true, sleepy, true);
+ }
+ }
+
+ @Test
+ public void testAcquireSegmentOnDemandRandomSegmentNoEvictions() throws IOException
+ {
+ // low number of total segments so expect many cache hits and few evictions
+ final int segmentCount = 8;
+ final int iterations = 2000;
+ final int concurrentReads = 10;
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+
+ makeSegmentsToLoad(segmentCount, localStorageFolder, interval, segmentsToWeakLoad);
+
+ for (boolean sleepy : new boolean[]{true, false}) {
+ testWeakLoad(iterations, segmentCount, concurrentReads, true, sleepy, true);
+ }
+ }
+
+ @Test
+ public void testAcquireSegmentOnDemandRandomSegmentWithTimeoutBeforeAcquire() throws IOException, InterruptedException
+ {
+ final int segmentCount = 24;
+ final int iterations = 2000;
+ final int concurrentReads = 10;
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+
+ makeSegmentsToLoad(segmentCount, localStorageFolder, interval, segmentsToWeakLoad);
+
+ final List<DataSegment> currentBatch = new ArrayList<>();
+ for (int i = 0; i < iterations; i++) {
+ currentBatch.add(segmentsToWeakLoad.get(ThreadLocalRandom.current().nextInt(segmentCount)));
+ // process batches of 10 requests at a time
+ if (currentBatch.size() == concurrentReads) {
+ final List<WeakLoad> weakLoads = currentBatch
+ .stream()
+ .map(segment -> new WeakLoad(virtualStorageManager, segment, 0, 0, 1L, true))
+ .collect(Collectors.toList());
+ final List<Future<Integer>> futures = new ArrayList<>();
+ for (WeakLoad weakLoad : weakLoads) {
+ futures.add(executorService.submit(weakLoad));
+ }
+ List<Throwable> exceptions = new ArrayList<>();
+ for (Future<Integer> future : futures) {
+ try {
+ future.get();
+ }
+ catch (Throwable t) {
+ exceptions.add(t);
+ }
+ }
+ Assertions.assertFalse(exceptions.isEmpty());
+ for (Throwable t : exceptions) {
+ Assertions.assertTrue(t instanceof TimeoutException || t instanceof ExecutionException, t.toString());
+ }
+ Thread.sleep(20);
+ Assertions.assertEquals(0, location.getActiveWeakHolds());
+ Assertions.assertEquals(0, location2.getActiveWeakHolds());
+
+ currentBatch.clear();
+ }
+ }
+
+ Assertions.assertEquals(0, location.getActiveWeakHolds());
+ Assertions.assertEquals(0, location2.getActiveWeakHolds());
+ Assertions.assertTrue(4 >= location.getWeakEntryCount());
+ Assertions.assertTrue(4 >= location2.getWeakEntryCount());
+ Assertions.assertTrue(4 >= location.getPath().listFiles().length);
+ Assertions.assertTrue(4 >= location2.getPath().listFiles().length);
+ Assertions.assertEquals(location.getStats().getEvictionCount(), location.getStats().getUnmountCount());
+ Assertions.assertEquals(location2.getStats().getEvictionCount(), location2.getStats().getUnmountCount());
}
@Test
- public void testGetSegment() throws IOException, ExecutionException, InterruptedException
+ public void testAcquireSegmentOnDemandRandomSegmentWithTimeoutAfterAcquire() throws IOException, InterruptedException
{
- final File localStorageFolder = tmpFolder.newFolder("local_storage_folder");
- final List<DataSegment> segmentsToLoad = new ArrayList<>(4);
+ final int segmentCount = 24;
+ final int iterations = 2000;
+ final int concurrentReads = 10;
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
final Interval interval = Intervals.of("2019-01-01/P1D");
- for (int partitionId = 0; partitionId < 4; partitionId++) {
+
+ makeSegmentsToLoad(segmentCount, localStorageFolder, interval, segmentsToWeakLoad);
+
+ final List<DataSegment> currentBatch = new ArrayList<>();
+ for (int i = 0; i < iterations; i++) {
+ currentBatch.add(segmentsToWeakLoad.get(ThreadLocalRandom.current().nextInt(segmentCount)));
+ // process batches of 10 requests at a time
+ if (currentBatch.size() == concurrentReads) {
+ final List<WeakLoad> weakLoads = currentBatch
+ .stream()
+ .map(segment -> new WeakLoad(virtualStorageManager, segment, 10, 100, Long.MAX_VALUE, false))
+ .collect(Collectors.toList());
+ final List<Future<Integer>> futures = new ArrayList<>();
+ for (WeakLoad weakLoad : weakLoads) {
+ futures.add(executorService.submit(weakLoad));
+ }
+ List<Throwable> exceptions = new ArrayList<>();
+ for (Future<Integer> future : futures) {
+ try {
+ future.get(20L, TimeUnit.MILLISECONDS);
+ }
+ catch (Throwable t) {
+ exceptions.add(t);
+ }
+ }
+ Assertions.assertFalse(exceptions.isEmpty());
+ for (Throwable t : exceptions) {
+ Assertions.assertTrue(t instanceof TimeoutException || t instanceof ExecutionException, t.toString());
+ }
+ while (true) {
+ boolean allDone = true;
+ for (Future<?> f : futures) {
+ allDone = allDone && f.isDone();
+ }
+ if (allDone) {
+ break;
+ }
+ Thread.sleep(5);
+ }
+ Assertions.assertEquals(0, location.getActiveWeakHolds());
+ Assertions.assertEquals(0, location2.getActiveWeakHolds());
+ currentBatch.clear();
+ }
+ }
+
+ Assertions.assertTrue(location.getStats().getHitCount() >= 0);
+ Assertions.assertTrue(location2.getStats().getHitCount() >= 0);
+ assertNoLooseEnds();
+ }
+
+ @Test
+ public void testMixedWeakLoadAndAcquireCachedSegmentOfWeakLoads() throws IOException, InterruptedException
+ {
+ final int segmentCount = 10;
+ final int iterations = 2000;
+ final int concurrentReads = 10;
+ final File localStorageFolder = new File(tempDir, "local_storage_folder");
+
+ final Interval interval = Intervals.of("2019-01-01/P1D");
+
+ makeSegmentsToLoad(segmentCount, localStorageFolder, interval, segmentsToWeakLoad);
+
+ final List<DataSegment> currentBatch = new ArrayList<>();
+ final int minLoadCount = 5;
+ int totalSuccess = 0;
+ int totalEmpty = 0;
+ int totalRows = 0;
+ for (int i = 0; i < iterations; i++) {
+ currentBatch.add(segmentsToWeakLoad.get(ThreadLocalRandom.current().nextInt(segmentCount)));
+ // process batches of 10 requests at a time
+ if (currentBatch.size() == concurrentReads) {
+ int weakLoadCount = 0;
+ List<Callable<Integer>> callables = new ArrayList<>();
+ for (DataSegment segment : currentBatch) {
+ // do a weak load for at most minLoadCount segments to populate the cache (and occasionally evict stuff as we
+ // progress through iterations)
+ if (weakLoadCount < minLoadCount && ThreadLocalRandom.current().nextBoolean()) {
+ callables.add(new WeakLoad(virtualStorageManager, segment, 0, 50, Long.MAX_VALUE, false));
+ weakLoadCount++;
+ } else {
+ // do the rest as calls that only acquire reference to segments that are already loaded
+ callables.add(new LoadCached(virtualStorageManager, segment, 50, 50));
+ }
+ }
+ final List<Future<Integer>> futures = new ArrayList<>();
+ for (Callable<Integer> load : callables) {
+ futures.add(executorService.submit(load));
+ }
+ int success = 0;
+ int rows = 0;
+ int empty = 0;
+ for (Future<Integer> future : futures) {
+ try {
+ Integer s = future.get();
+ success++;
+ if (s != null) {
+ rows += s;
+ } else {
+ empty++;
+ }
+ }
+ catch (Throwable t) {
+ Assertions.fail();
+ }
+ }
+
+ Assertions.assertEquals(0, location.getActiveWeakHolds());
+ Assertions.assertEquals(0, location2.getActiveWeakHolds());
+ totalSuccess += success;
+ totalEmpty += empty;
+ totalRows += rows;
+ currentBatch.clear();
+ }
+ }
+
+ Assertions.assertEquals(iterations, totalSuccess);
+ Assertions.assertEquals(totalRows, (totalSuccess * 1209) - (totalEmpty * 1209));
+ // expect at least some of the load cached calls to succeed
+ Assertions.assertTrue(totalSuccess > ((iterations / 10) * minLoadCount));
+ // expect at least some empties from the segment not being cached
+ Assertions.assertTrue(totalEmpty > 0);
+ Assertions.assertTrue(location.getStats().getHitCount() >= 0);
+ Assertions.assertTrue(location2.getStats().getHitCount() >= 0);
+
+ assertNoLooseEnds();
+ }
+
+ private void testWeakLoad(
+ int iterations,
+ int segmentCount,
+ int concurrentReads,
+ boolean random,
+ boolean sleepy,
+ boolean expectHits
+ )
+ {
+ int totalSuccess = 0;
+ int totalFailures = 0;
+ final List<DataSegment> currentBatch = new ArrayList<>();
+ // start fresh
+ for (DataSegment segment : segmentsToWeakLoad) {
+ virtualStorageManager.drop(segment);
+ }
+ location.resetStats();
+ location2.resetStats();
+ for (int i = 0; i < iterations; i++) {
+ int segment = random ? ThreadLocalRandom.current().nextInt(segmentCount) : i % segmentCount;
+ currentBatch.add(segmentsToWeakLoad.get(segment));
+ // process batches of 10 requests at a time
+ if (currentBatch.size() == concurrentReads) {
+
+ BatchResult result = testWeakBatch(i, currentBatch, sleepy);
+ totalSuccess += result.success;
+ totalFailures += result.exceptions.size();
+ Assertions.assertEquals(
+ totalSuccess,
+ location.getStats().getLoadCount() +
+ location.getStats().getHitCount() +
+ location2.getStats().getLoadCount() +
+ location2.getStats().getHitCount(),
+ StringUtils.format(
+ "iteration[%s] - loc1: loads[%s] hits[%s] loc2: loads[%s] hits[%s]",
+ i,
+ location.getStats().getLoadCount(),
+ location.getStats().getHitCount(),
+ location2.getStats().getLoadCount(),
+ location2.getStats().getHitCount()
+ )
+ );
+
+ currentBatch.clear();
+ }
+ }
+
+ if (!currentBatch.isEmpty()) {
+ BatchResult result = testWeakBatch(iterations, currentBatch, sleepy);
+ totalSuccess += result.success;
+ totalFailures += result.exceptions.size();
+ }
+
+ Assertions.assertEquals(iterations, totalSuccess + totalFailures);
+ Assertions.assertEquals(
+ totalSuccess,
+ location.getStats().getLoadCount()
+ + location.getStats().getHitCount()
+ + location2.getStats().getLoadCount()
+ + location2.getStats().getHitCount()
+ );
+ Assertions.assertTrue(totalFailures <= location.getStats().getRejectCount() + location2.getStats()
+ .getRejectCount());
+
+ if (expectHits) {
+ Assertions.assertTrue(location.getStats().getHitCount() >= 0);
+ Assertions.assertTrue(location2.getStats().getHitCount() >= 0);
+ } else {
+ Assertions.assertEquals(0, location.getStats().getHitCount());
+ Assertions.assertEquals(0, location2.getStats().getHitCount());
+ }
+
+ assertNoLooseEnds();
+ }
+
+ private BatchResult testWeakBatch(int iteration, List<DataSegment> currentBatch, boolean sleepy)
+ {
+ final List<WeakLoad> weakLoads = new ArrayList<>();
+ Set<SegmentId> segments = new HashSet<>();
+ for (DataSegment segment : currentBatch) {
+ weakLoads.add(new WeakLoad(virtualStorageManager, segment, 0, sleepy ? 20 : 0, Long.MAX_VALUE, false));
+ segments.add(segment.getId());
+ }
+ final List<Future<Integer>> futures = new ArrayList<>();
+ for (WeakLoad weakLoad : weakLoads) {
+ futures.add(executorService.submit(weakLoad));
+ }
+ List<Throwable> exceptions = new ArrayList<>();
+ int success = 0;
+ int rows = 0;
+ for (Future<Integer> future : futures) {
+ try {
+ Integer s = future.get();
+ if (s != null) {
+ success++;
+ rows += s;
+ }
+ }
+ catch (Throwable t) {
+ exceptions.add(t);
+ }
+ }
+
+ // cache has enough space to store 8 segments, so we should always be able to handle 8, but also sometimes more,
+ // such as if multiple threads have the same segment
+ final int expectedSuccess = Math.min(8, segments.size());
+ // expect at most 2 failures if there are more unique segments than cache slots
+ final int maxExpectedFailures = segments.size() > 8 ? 2 : 0;
+ Assertions.assertEquals(success * 1209, rows);
+ Assertions.assertTrue(
+ expectedSuccess <= success,
+ "iteration " + iteration + " expected " + expectedSuccess + " tasks to succeed but got " + success
+ );
+ Assertions.assertTrue(
+ maxExpectedFailures >= exceptions.size(),
+ "iteration " + iteration + " expected " + maxExpectedFailures + " tasks to fail but got " + exceptions.size()
+ );
+ // we only expect DruidException in happy path tests from disk space being unavailable to satisy the query
+ for (Throwable t : exceptions) {
+ Assertions.assertInstanceOf(DruidException.class, t.getCause());
+ Assertions.assertTrue(t.getCause().getMessage().contains("Unable to load segment["));
+ Assertions.assertTrue(t.getCause()
+ .getMessage()
+ .contains(
+ "on demand, ensure enough disk space has been allocated to load all segments involved in the query"));
+ }
+
+ return new BatchResult(exceptions, success, rows);
+ }
+
+
+
+ private void assertNoLooseEnds()
+ {
+ Assertions.assertEquals(0, location.getActiveWeakHolds());
+ Assertions.assertEquals(0, location2.getActiveWeakHolds());
+ Assertions.assertTrue(4 >= location.getWeakEntryCount());
+ Assertions.assertTrue(4 >= location2.getWeakEntryCount());
+ Assertions.assertTrue(4 >= location.getPath().listFiles().length);
+ Assertions.assertTrue(4 >= location2.getPath().listFiles().length);
+ Assertions.assertTrue(location.getStats().getLoadCount() >= 4);
+ Assertions.assertTrue(location2.getStats().getLoadCount() >= 4);
+ Assertions.assertEquals(location.getStats().getEvictionCount(), location.getStats().getUnmountCount());
+ Assertions.assertEquals(location2.getStats().getEvictionCount(), location2.getStats().getUnmountCount());
+ Assertions.assertEquals(location.getStats().getLoadCount() - 4, location.getStats().getEvictionCount());
+ Assertions.assertEquals(location2.getStats().getLoadCount() - 4, location2.getStats().getEvictionCount());
+ Assertions.assertEquals(location.getStats().getLoadCount() - 4, location.getStats().getUnmountCount());
+ Assertions.assertEquals(location2.getStats().getLoadCount() - 4, location2.getStats().getUnmountCount());
+ }
+
+ private void makeSegmentsToLoad(
+ int segmentCount,
+ File localStorageFolder,
+ Interval interval,
+ List<DataSegment> segmentsToLoad
+ )
+ throws IOException
+ {
+ segmentsToLoad.clear();
+ for (int partitionId = 0; partitionId < segmentCount; partitionId++) {
final String segmentPath = Paths.get(
localStorageFolder.getCanonicalPath(),
dataSource,
@@ -127,40 +690,27 @@ public class SegmentLocalCacheManagerConcurrencyTest
segmentVersion,
String.valueOf(partitionId)
).toString();
- // manually create a local segment under localStorageFolder
final File localSegmentFile = new File(
localStorageFolder,
- segmentPath
- );
- FileUtils.mkdirp(localSegmentFile);
- final File indexZip = new File(localSegmentFile, "index.zip");
- indexZip.createNewFile();
-
- final DataSegment segment = newSegment(interval, partitionId).withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- localSegmentFile.getAbsolutePath()
- )
+ segmentPath + "_build"
);
- segmentsToLoad.add(segment);
- }
-
- final List<Future> futures = segmentsToLoad
- .stream()
- .map(segment -> executorService.submit(() -> manager.getSegmentFiles(segment)))
- .collect(Collectors.toList());
+ final File indexZip = new File(new File(localStorageFolder, segmentPath), "index.zip");
+ SegmentLocalCacheManagerTest.makeSegmentZip(localSegmentFile, indexZip);
- expectedException.expect(ExecutionException.class);
- expectedException.expectCause(CoreMatchers.instanceOf(SegmentLoadingException.class));
- expectedException.expectMessage("Failed to load segment");
- for (Future future : futures) {
- future.get();
+ final DataSegment segment =
+ newSegment(interval, partitionId, 1000).withLoadSpec(
+ ImmutableMap.of(
+ "type",
+ "local",
+ "path",
+ indexZip.getAbsolutePath()
+ )
+ );
+ segmentsToLoad.add(segment);
}
}
- private DataSegment newSegment(Interval interval, int partitionId)
+ private DataSegment newSegment(Interval interval, int partitionId, long size)
{
return DataSegment.builder()
.dataSource(dataSource)
@@ -178,7 +728,145 @@ public class SegmentLocalCacheManagerConcurrencyTest
.metrics(ImmutableList.of())
.shardSpec(new NumberedShardSpec(partitionId, 0))
.binaryVersion(9)
- .size(1000L)
+ .size(size)
.build();
}
+
+ private static class BatchResult
+ {
+ public final List<Throwable> exceptions;
+ public final int success;
+ public final int rows;
+
+ public BatchResult(List<Throwable> exceptions, int success, int rows)
+ {
+ this.exceptions = exceptions;
+ this.success = success;
+ this.rows = rows;
+ }
+ }
+
+ private static class Load implements Callable<Void>
+ {
+ private final SegmentLocalCacheManager segmentManager;
+ private final DataSegment segment;
+
+ private Load(SegmentLocalCacheManager segmentManager, DataSegment segment)
+ {
+ this.segmentManager = segmentManager;
+ this.segment = segment;
+ }
+
+ @Override
+ public Void call() throws SegmentLoadingException
+ {
+ segmentManager.load(segment);
+ return null;
+ }
+ }
+
+ private static class WeakLoad implements Callable<Integer>
+ {
+ private final int delayMin;
+ private final int delayMax;
+ private final long timeout;
+ private final SegmentLocalCacheManager segmentManager;
+ private final DataSegment segment;
+ private final boolean expectTimeout;
+
+ private WeakLoad(
+ SegmentLocalCacheManager segmentManager,
+ DataSegment segment,
+ int delayMin,
+ int delayMax,
+ long timeout,
+ boolean expectTimeout
+ )
+ {
+ this.segmentManager = segmentManager;
+ this.segment = segment;
+ this.delayMin = delayMin;
+ this.delayMax = delayMax;
+ this.timeout = timeout;
+ this.expectTimeout = expectTimeout;
+ }
+
+ @Override
+ public Integer call() throws SegmentLoadingException
+ {
+ final Closer closer = Closer.create();
+ final AcquireSegmentAction action = closer.register(
+ segmentManager.acquireSegment(segment)
+ );
+ try {
+ final ReferenceCountedObjectProvider<Segment> referenceProvider =
+ action.getSegmentFuture().get(timeout, TimeUnit.MILLISECONDS);
+ if (referenceProvider == null) {
+ Assertions.fail("this shouldn't happen");
+ }
+ final Optional<Segment> segment = referenceProvider.acquireReference().map(closer::register);
+ if (segment.isPresent()) {
+ PhysicalSegmentInspector gadget = segment.get().as(PhysicalSegmentInspector.class);
+ if (delayMin >= 0 && delayMax > 0) {
+ Thread.sleep(ThreadLocalRandom.current().nextInt(delayMin, delayMax));
+ }
+ return gadget.getNumRows();
+ }
+ return null;
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t);
+ }
+ finally {
+ CloseableUtils.closeAndWrapExceptions(closer);
+ }
+ }
+ }
+
+ private static class LoadCached implements Callable<Integer>
+ {
+ private final int maxDelayBefore;
+ private final int maxDelayAfter;
+ private final SegmentLocalCacheManager segmentManager;
+ private final DataSegment segment;
+
+ private LoadCached(
+ SegmentLocalCacheManager segmentManager,
+ DataSegment segment,
+ int maxDelayBefore,
+ int maxDelayAfter
+ )
+ {
+ this.segmentManager = segmentManager;
+ this.segment = segment;
+ this.maxDelayBefore = maxDelayBefore;
+ this.maxDelayAfter = maxDelayAfter;
+ }
+
+ @Override
+ public Integer call()
+ {
+ final Closer closer = Closer.create();
+ try {
+ if (maxDelayBefore > 0) {
+ Thread.sleep(ThreadLocalRandom.current().nextInt(maxDelayBefore));
+ }
+ final Optional<Segment> segmentReference = segmentManager.acquireCachedSegment(segment).map(closer::register);
+ if (segmentReference.isPresent()) {
+ PhysicalSegmentInspector gadget = segmentReference.get().as(PhysicalSegmentInspector.class);
+ if (maxDelayAfter > 0) {
+ Thread.sleep(ThreadLocalRandom.current().nextInt(maxDelayAfter));
+ }
+ return gadget.getNumRows();
+ }
+ return null;
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t);
+ }
+ finally {
+ CloseableUtils.closeAndWrapExceptions(closer);
+ }
+ }
+ }
}
diff --git a/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerTest.java b/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerTest.java
index bc2c357c4fa..ce19115b578 100644
--- a/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerTest.java
+++ b/server/src/test/java/org/apache/druid/segment/loading/SegmentLocalCacheManagerTest.java
@@ -26,20 +26,30 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.error.DruidException;
import org.apache.druid.error.DruidExceptionMatcher;
+import org.apache.druid.guice.LocalDataStorageDruidModule;
+import org.apache.druid.jackson.SegmentizerModule;
import org.apache.druid.java.util.common.FileUtils;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.expression.TestExprMacroTable;
import org.apache.druid.segment.CursorFactory;
+import org.apache.druid.segment.IndexIO;
+import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.QueryableIndex;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
+import org.apache.druid.segment.ReferenceCountedObjectProvider;
+import org.apache.druid.segment.Segment;
import org.apache.druid.segment.SegmentLazyLoadFailCallback;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.TestIndex;
import org.apache.druid.segment.TestSegmentUtils;
+import org.apache.druid.segment.column.ColumnConfig;
import org.apache.druid.server.metrics.NoopServiceEmitter;
+import org.apache.druid.testing.InitializedNullHandlingTest;
import org.apache.druid.timeline.DataSegment;
-import org.apache.druid.timeline.partition.NoneShardSpec;
+import org.apache.druid.timeline.partition.LinearShardSpec;
import org.apache.druid.timeline.partition.TombstoneShardSpec;
+import org.apache.druid.utils.CompressionUtils;
import org.hamcrest.MatcherAssert;
import org.joda.time.Interval;
import org.junit.Assert;
@@ -51,50 +61,56 @@ import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
-public class SegmentLocalCacheManagerTest
+public class SegmentLocalCacheManagerTest extends InitializedNullHandlingTest
{
+ private static final String TEST_DATA_BASE_RELATIVE_PATH =
+ "test_segment_loader/2011-01-12T00:00:00.000Z_2011-04-15T00:00:00.001Z/2015-05-27T03:38:35.683Z/";
+ private static final String TEST_DATA_RELATIVE_PATH = TEST_DATA_BASE_RELATIVE_PATH + "0";
+ private static final String TEST_DATA_RELATIVE_PATH_2 = TEST_DATA_BASE_RELATIVE_PATH + "1";
+ private static final String TEST_DATA_RELATIVE_PATH_3 = TEST_DATA_BASE_RELATIVE_PATH + "2";
+ private static final String TEST_DATA_RELATIVE_PATH_4 = TEST_DATA_BASE_RELATIVE_PATH + "3";
+
@Rule
public final TemporaryFolder tmpFolder = new TemporaryFolder();
private ObjectMapper jsonMapper;
- private File localSegmentCacheFolder;
+ private File segmentDeepStorageDir;
+ private File localSegmentCacheDir;
private SegmentLocalCacheManager manager;
@Before
public void setUp() throws Exception
{
jsonMapper = TestHelper.makeJsonMapper();
- jsonMapper.registerSubtypes(new NamedType(LocalLoadSpec.class, "local"),
- new NamedType(TombstoneLoadSpec.class, "tombstone"));
+ jsonMapper.registerSubtypes(
+ new NamedType(LocalLoadSpec.class, "local"),
+ new NamedType(TombstoneLoadSpec.class, "tombstone")
+ );
+ jsonMapper.registerSubtypes(TestSegmentUtils.TestLoadSpec.class);
+ jsonMapper.registerSubtypes(TestSegmentUtils.TestSegmentizerFactory.class);
+ jsonMapper.registerModule(new SegmentizerModule());
+ jsonMapper.registerModules(new LocalDataStorageDruidModule().getJacksonModules());
jsonMapper.setInjectableValues(
- new InjectableValues.Std().addValue(
- LocalDataSegmentPuller.class,
- new LocalDataSegmentPuller()
- )
+ new InjectableValues.Std()
+ .addValue(LocalDataSegmentPuller.class, new LocalDataSegmentPuller())
+ .addValue(IndexIO.class, TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT))
+ .addValue(ObjectMapper.class, jsonMapper)
+ .addValue(DataSegment.PruneSpecsHolder.class, DataSegment.PruneSpecsHolder.DEFAULT)
+ .addValue(ExprMacroTable.class, TestExprMacroTable.INSTANCE)
);
EmittingLogger.registerEmitter(new NoopServiceEmitter());
- localSegmentCacheFolder = tmpFolder.newFolder("segment_cache_folder");
-
- final List<StorageLocationConfig> locationConfigs = new ArrayList<>();
- final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheFolder, 10000000000L, null);
- locationConfigs.add(locationConfig);
+ segmentDeepStorageDir = tmpFolder.newFolder("segment_deep_storage");
+ localSegmentCacheDir = tmpFolder.newFolder("segment_cache");
- final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locationConfigs);
- manager = new SegmentLocalCacheManager(
- loaderConfig.toStorageLocations(),
- loaderConfig,
- new LeastBytesUsedStorageLocationSelectorStrategy(loaderConfig.toStorageLocations()),
- TestIndex.INDEX_IO,
- jsonMapper
- );
+ manager = makeDefaultManager(jsonMapper);
Assert.assertTrue(manager.canHandleSegments());
}
@@ -109,7 +125,7 @@ public class SegmentLocalCacheManagerTest
public List<StorageLocationConfig> getLocations()
{
return Collections.singletonList(
- new StorageLocationConfig(localSegmentCacheFolder, null, null)
+ new StorageLocationConfig(localSegmentCacheDir, null, null)
);
}
};
@@ -128,9 +144,9 @@ public class SegmentLocalCacheManagerTest
public void testCanHandleSegmentsWithLocations()
{
final ImmutableList<StorageLocation> locations = ImmutableList.of(
- new StorageLocation(localSegmentCacheFolder, 10000000000L, null)
+ new StorageLocation(localSegmentCacheDir, 10000000000L, null)
);
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
locations,
new SegmentLoaderConfig(),
new LeastBytesUsedStorageLocationSelectorStrategy(locations),
@@ -143,7 +159,7 @@ public class SegmentLocalCacheManagerTest
@Test
public void testCanHandleSegmentsWithEmptyLocationsAndConfigLocations()
{
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
ImmutableList.of(),
new SegmentLoaderConfig(),
new LeastBytesUsedStorageLocationSelectorStrategy(ImmutableList.of()),
@@ -156,7 +172,7 @@ public class SegmentLocalCacheManagerTest
@Test
public void testGetCachedSegmentsWhenCanHandleSegmentsIsFalse()
{
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
null,
new SegmentLoaderConfig(),
new LeastBytesUsedStorageLocationSelectorStrategy(null),
@@ -177,26 +193,11 @@ public class SegmentLocalCacheManagerTest
@Test
public void testGetCachedSegments() throws IOException
{
- final ObjectMapper jsonMapper = TestHelper.makeJsonMapper();
- jsonMapper.registerSubtypes(TestSegmentUtils.TestLoadSpec.class);
- jsonMapper.registerSubtypes(TestSegmentUtils.TestSegmentizerFactory.class);
-
- final List<StorageLocationConfig> locationConfigs = new ArrayList<>();
- final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheFolder, 10000000000L, null);
- locationConfigs.add(locationConfig);
-
- final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locationConfigs);
- final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
- storageLocations,
- loaderConfig,
- new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
- jsonMapper
- );
- final File baseInfoDir = new File(storageLocations.get(0).getPath(), "/info_dir/");
+ SegmentLocalCacheManager manager = makeDefaultManager(jsonMapper);
+ final File baseInfoDir = new File(manager.getLocations().get(0).getPath(), "/info_dir/");
FileUtils.mkdirp(baseInfoDir);
+ // can use fake segments since we aren't loading them for real
final DataSegment segment1 = TestSegmentUtils.makeSegment(
"test_segment_loader", "v0", Intervals.of("2014-10-20T00:00:00Z/P1D")
);
@@ -216,27 +217,11 @@ public class SegmentLocalCacheManagerTest
@Test
public void testGetCachedSegmentsWithMissingSegmentFile() throws IOException
{
- final ObjectMapper jsonMapper = TestHelper.makeJsonMapper();
- jsonMapper.registerSubtypes(TestSegmentUtils.TestLoadSpec.class);
- jsonMapper.registerSubtypes(TestSegmentUtils.TestSegmentizerFactory.class);
-
- final List<StorageLocationConfig> locationConfigs = new ArrayList<>();
- final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheFolder, 10000000000L, null);
- locationConfigs.add(locationConfig);
-
- final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locationConfigs);
- final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
- storageLocations,
- loaderConfig,
- new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
- jsonMapper
- );
-
- final File baseInfoDir = new File(storageLocations.get(0).getPath(), "/info_dir/");
+ SegmentLocalCacheManager manager = makeDefaultManager(jsonMapper);
+ final File baseInfoDir = new File(manager.getLocations().get(0).getPath(), "/info_dir/");
FileUtils.mkdirp(baseInfoDir);
+ // can use fake segments since we aren't loading them for real
final DataSegment segment1 = TestSegmentUtils.makeSegment(
"test_segment_loader", "v0", Intervals.of("2014-10-20T00:00:00Z/P1D")
);
@@ -262,14 +247,47 @@ public class SegmentLocalCacheManagerTest
Assert.assertFalse(segment3InfoFile.exists());
}
+ @Test
+ public void testGetCachedSegmentsLegacyPathsMigrated() throws Exception
+ {
+ final DataSegment segmentToBootstrap = makeTestDataSegment(segmentDeepStorageDir);
+ FileUtils.mkdirp(new File(localSegmentCacheDir, "info_dir"));
+ manager.storeInfoFile(segmentToBootstrap);
+ File segmentZip = createSegmentZipInLocation(
+ segmentDeepStorageDir,
+ TEST_DATA_RELATIVE_PATH
+ );
+ File unzippedSegmentPathInLocation = new File(
+ localSegmentCacheDir,
+ DataSegmentPusher.getDefaultStorageDir(segmentToBootstrap, false)
+ );
+ FileUtils.mkdirp(unzippedSegmentPathInLocation);
+ CompressionUtils.unzip(
+ segmentZip,
+ unzippedSegmentPathInLocation
+ );
+
+ for (DataSegment segment : manager.getCachedSegments()) {
+ manager.bootstrap(segment, SegmentLazyLoadFailCallback.NOOP);
+ }
+
+ // if bootstrapping a file that already exists it will be mounted by bootsrap
+ Assert.assertNotNull(manager.getSegmentFiles(segmentToBootstrap));
+
+ Assert.assertFalse(unzippedSegmentPathInLocation.exists());
+ Assert.assertFalse(new File(localSegmentCacheDir, segmentToBootstrap.getDataSource()).exists());
+ Assert.assertTrue(new File(localSegmentCacheDir, segmentToBootstrap.getId().toString()).exists());
+ }
+
@Test
public void testIfSegmentIsLoaded() throws IOException
{
+ // can use fake segments since we aren't loading them for real and just using utility method
final DataSegment cachedSegment = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D");
final File cachedSegmentFile = new File(
- localSegmentCacheFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
+ localSegmentCacheDir,
+ cachedSegment.getId().toString()
);
FileUtils.mkdirp(cachedSegmentFile);
@@ -280,19 +298,7 @@ public class SegmentLocalCacheManagerTest
}
@Test
- public void testNoLoadingOfSegmentInPageCache() throws IOException
- {
- final DataSegment segment = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D");
- final File segmentFile = new File(
- localSegmentCacheFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(segmentFile);
- manager.loadSegmentIntoPageCache(segment);
- }
-
- @Test
- public void testLoadSegmentInPageCache() throws IOException
+ public void testLoadSegmentInPageCache() throws IOException, SegmentLoadingException
{
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig()
{
@@ -306,86 +312,45 @@ public class SegmentLocalCacheManagerTest
public List<StorageLocationConfig> getLocations()
{
return Collections.singletonList(
- new StorageLocationConfig(localSegmentCacheFolder, null, null)
+ new StorageLocationConfig(localSegmentCacheDir, null, null)
);
}
};
-
- manager = new SegmentLocalCacheManager(
- loaderConfig.toStorageLocations(),
+ final List<StorageLocation> locations = loaderConfig.toStorageLocations();
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
+ locations,
loaderConfig,
- new LeastBytesUsedStorageLocationSelectorStrategy(loaderConfig.toStorageLocations()),
- TestIndex.INDEX_IO,
+ new LeastBytesUsedStorageLocationSelectorStrategy(locations),
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final DataSegment segment = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D");
- final File segmentFile = new File(
- localSegmentCacheFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(segmentFile);
- manager.loadSegmentIntoPageCacheInternal(segment);
- }
-
- @Test
- public void testIfTombstoneIsLoaded() throws IOException, SegmentLoadingException
- {
- final DataSegment tombstone = DataSegment.builder()
- .dataSource("foo")
- .interval(Intervals.of("2014-10-20T00:00:00Z/P1D"))
- .version("version")
- .loadSpec(Collections.singletonMap(
- "type",
- DataSegment.TOMBSTONE_LOADSPEC_TYPE
- ))
- .shardSpec(TombstoneShardSpec.INSTANCE)
- .size(1)
- .build();
-
-
- final File cachedSegmentFile = new File(
- localSegmentCacheFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
+ final DataSegment segmentToDownload = makeTestDataSegment(localSegmentCacheDir);
+ final File localSegmentFile = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+ makeSegmentZip(
+ localSegmentFile,
+ new File(segmentDeepStorageDir.getCanonicalPath() + "/" + TEST_DATA_RELATIVE_PATH + "/index.zip")
);
- FileUtils.mkdirp(cachedSegmentFile);
-
- manager.getSegmentFiles(tombstone);
- Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(tombstone));
+ manager.getSegmentFiles(segmentToDownload);
}
@Test
public void testGetAndCleanSegmentFiles() throws Exception
{
- final File localStorageFolder = tmpFolder.newFolder("local_storage_folder");
-
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- localStorageFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
+ final File localSegmentFile = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+ makeSegmentZip(
+ localSegmentFile,
+ new File(segmentDeepStorageDir.getCanonicalPath() + "/" + TEST_DATA_RELATIVE_PATH + "/index.zip")
);
- // manually create a local segment under localStorageFolder
- final File localSegmentFile = new File(
- localStorageFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(localSegmentFile);
- final File indexZip = new File(localSegmentFile, "index.zip");
- indexZip.createNewFile();
-
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload));
+ manager.load(segmentToDownload);
manager.getSegmentFiles(segmentToDownload);
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
- manager.cleanup(segmentToDownload);
+ manager.drop(segmentToDownload);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload));
}
@@ -403,41 +368,26 @@ public class SegmentLocalCacheManagerTest
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locations);
final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
storageLocations,
- new SegmentLoaderConfig().withLocations(locations),
+ loaderConfig,
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- final File localSegmentFile = new File(
- segmentSrcFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(localSegmentFile);
- final File indexZip = new File(localSegmentFile, "index.zip");
- indexZip.createNewFile();
+
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
+ final File localSegmentFile = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+ makeSegmentZip(localSegmentFile, new File(localSegmentFile, "index.zip"));
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload));
+ manager.load(segmentToDownload);
File segmentFile = manager.getSegmentFiles(segmentToDownload);
Assert.assertTrue(segmentFile.getAbsolutePath().contains("/local_storage_folder/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
- manager.cleanup(segmentToDownload);
+ manager.drop(segmentToDownload);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload));
}
@@ -456,41 +406,26 @@ public class SegmentLocalCacheManagerTest
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locations);
final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
storageLocations,
new SegmentLoaderConfig().withLocations(locations),
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- final File localSegmentFile = new File(
- segmentSrcFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(localSegmentFile);
- final File indexZip = new File(localSegmentFile, "index.zip");
- indexZip.createNewFile();
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
+ final File localSegmentFile = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+
+ makeSegmentZip(localSegmentFile, new File(localSegmentFile, "index.zip"));
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload));
+ manager.load(segmentToDownload);
File segmentFile = manager.getSegmentFiles(segmentToDownload);
Assert.assertTrue(segmentFile.getAbsolutePath().contains("/local_storage_folder2/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
- manager.cleanup(segmentToDownload);
+ manager.drop(segmentToDownload);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload));
}
@@ -511,43 +446,28 @@ public class SegmentLocalCacheManagerTest
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locations);
final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
storageLocations,
new SegmentLoaderConfig().withLocations(locations),
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- final File localSegmentFile = new File(
- segmentSrcFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
+ final File localSegmentFile = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
FileUtils.mkdirp(localSegmentFile);
final File indexZip = new File(localSegmentFile, "index.zip");
indexZip.createNewFile();
try {
// expect failure
- manager.getSegmentFiles(segmentToDownload);
+ manager.load(segmentToDownload);
Assert.fail();
}
catch (SegmentLoadingException e) {
}
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload));
- manager.cleanup(segmentToDownload);
+ manager.drop(segmentToDownload);
}
@Test
@@ -565,95 +485,38 @@ public class SegmentLocalCacheManagerTest
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locations);
final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
storageLocations,
new SegmentLoaderConfig().withLocations(locations),
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- final File localSegmentFile = new File(
- segmentSrcFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(localSegmentFile);
- final File indexZip = new File(localSegmentFile, "index.zip");
- indexZip.createNewFile();
+
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
+ final File localSegmentFile = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+ makeSegmentZip(localSegmentFile, new File(segmentDeepStorageDir + "/" + TEST_DATA_RELATIVE_PATH + "/index.zip"));
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload));
+ manager.load(segmentToDownload);
File segmentFile = manager.getSegmentFiles(segmentToDownload);
Assert.assertTrue(segmentFile.getAbsolutePath().contains("/local_storage_folder/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
- final DataSegment segmentToDownload2 = dataSegmentWithInterval("2014-11-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- final File localSegmentFile2 = new File(
- segmentSrcFolder,
- "test_segment_loader/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(localSegmentFile2);
- final File indexZip2 = new File(localSegmentFile2, "index.zip");
- indexZip2.createNewFile();
+ final DataSegment segmentToDownload2 = makeTestDataSegment(segmentDeepStorageDir, 1, TEST_DATA_RELATIVE_PATH_2);
+ final File localSegmentFile2 = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_2);
+ makeSegmentZip(localSegmentFile2, new File(segmentDeepStorageDir + "/" + TEST_DATA_RELATIVE_PATH_2 + "/index.zip"));
+ manager.load(segmentToDownload2);
File segmentFile2 = manager.getSegmentFiles(segmentToDownload2);
Assert.assertTrue(segmentFile2.getAbsolutePath().contains("/local_storage_folder2/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload2));
- manager.cleanup(segmentToDownload2);
+ manager.drop(segmentToDownload2);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload2));
}
- private DataSegment dataSegmentWithInterval(String intervalStr)
- {
- return dataSegmentWithInterval(intervalStr, 10L);
- }
-
- private DataSegment dataSegmentWithInterval(String intervalStr, long size)
- {
- return DataSegment.builder()
- .dataSource("test_segment_loader")
- .interval(Intervals.of(intervalStr))
- .loadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- "somewhere"
- )
- )
- .version("2015-05-27T03:38:35.683Z")
- .dimensions(ImmutableList.of())
- .metrics(ImmutableList.of())
- .shardSpec(NoneShardSpec.instance())
- .binaryVersion(9)
- .size(size)
- .build();
- }
-
@Test
public void testSegmentDistributionUsingRoundRobinStrategy() throws Exception
{
@@ -676,129 +539,68 @@ public class SegmentLocalCacheManagerTest
);
}
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
locations,
new SegmentLoaderConfig().withLocations(locationConfigs),
new RoundRobinStorageLocationSelectorStrategy(locations),
- TestIndex.INDEX_IO,
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
// Segment 1 should be downloaded in local_storage_folder
- final DataSegment segmentToDownload1 = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder, "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload1 = makeTestDataSegment(segmentDeepStorageDir);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload1));
+ manager.load(segmentToDownload1);
File segmentFile = manager.getSegmentFiles(segmentToDownload1);
Assert.assertTrue(segmentFile.getAbsolutePath().contains("/local_storage_folder/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload1));
- manager.cleanup(segmentToDownload1);
+ manager.drop(segmentToDownload1);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload1));
// Segment 2 should be downloaded in local_storage_folder2
- final DataSegment segmentToDownload2 = dataSegmentWithInterval("2014-11-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder, "test_segment_loader/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload2 = makeTestDataSegment(segmentDeepStorageDir, 1, TEST_DATA_RELATIVE_PATH_2);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_2);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload2));
+ manager.load(segmentToDownload2);
File segmentFile2 = manager.getSegmentFiles(segmentToDownload2);
Assert.assertTrue(segmentFile2.getAbsolutePath().contains("/local_storage_folder2/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload2));
- manager.cleanup(segmentToDownload2);
+ manager.drop(segmentToDownload2);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload2));
// Segment 3 should be downloaded in local_storage_folder3
- final DataSegment segmentToDownload3 = dataSegmentWithInterval("2014-12-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-12-20T00:00:00.000Z_2014-12-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder,
- "test_segment_loader/2014-12-20T00:00:00.000Z_2014-12-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload3 = makeTestDataSegment(segmentDeepStorageDir, 2, TEST_DATA_RELATIVE_PATH_3);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_3);
+ manager.load(segmentToDownload3);
File segmentFile3 = manager.getSegmentFiles(segmentToDownload3);
Assert.assertTrue(segmentFile3.getAbsolutePath().contains("/local_storage_folder3/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload3));
- manager.cleanup(segmentToDownload3);
+ manager.drop(segmentToDownload3);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload3));
// Segment 4 should be downloaded in local_storage_folder again, asserting round robin distribution of segments
- final DataSegment segmentToDownload4 = dataSegmentWithInterval("2014-08-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-08-20T00:00:00.000Z_2014-08-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder, "test_segment_loader/2014-08-20T00:00:00.000Z_2014-08-21T00:00:00" +
- ".000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload4 = makeTestDataSegment(segmentDeepStorageDir, 3, TEST_DATA_RELATIVE_PATH_4);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_4);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload4));
+ manager.load(segmentToDownload4);
File segmentFile1 = manager.getSegmentFiles(segmentToDownload4);
Assert.assertTrue(segmentFile1.getAbsolutePath().contains("/local_storage_folder/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload4));
- manager.cleanup(segmentToDownload4);
+ manager.drop(segmentToDownload4);
Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload4));
}
- private void createLocalSegmentFile(File segmentSrcFolder, String localSegmentPath) throws Exception
- {
- // manually create a local segment under segmentSrcFolder
- final File localSegmentFile = new File(segmentSrcFolder, localSegmentPath);
- FileUtils.mkdirp(localSegmentFile);
- final File indexZip = new File(localSegmentFile, "index.zip");
- indexZip.createNewFile();
- }
-
- private StorageLocationConfig createStorageLocationConfig(String localPath, long maxSize, boolean writable) throws Exception
- {
-
- final File localStorageFolder = tmpFolder.newFolder(localPath);
- localStorageFolder.setWritable(writable);
- final StorageLocationConfig locationConfig = new StorageLocationConfig(localStorageFolder, maxSize, 1.0);
- return locationConfig;
- }
-
@Test
public void testSegmentDistributionUsingLeastBytesUsedStrategy() throws Exception
{
@@ -815,76 +617,43 @@ public class SegmentLocalCacheManagerTest
final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locations);
final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
storageLocations,
new SegmentLoaderConfig().withLocations(locations),
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
// Segment 1 should be downloaded in local_storage_folder, segment1 size 10L
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D", 10L).withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
+
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload));
+ manager.load(segmentToDownload);
File segmentFile = manager.getSegmentFiles(segmentToDownload);
Assert.assertTrue(segmentFile.getAbsolutePath().contains("/local_storage_folder/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
// Segment 2 should be downloaded in local_storage_folder2, segment2 size 5L
- final DataSegment segmentToDownload2 = dataSegmentWithInterval("2014-11-20T00:00:00Z/P1D", 5L).withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder,
- "test_segment_loader/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload2 = makeTestDataSegment(segmentDeepStorageDir, 5L, 1, TEST_DATA_RELATIVE_PATH_2);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_2);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload2));
+ manager.load(segmentToDownload2);
File segmentFile2 = manager.getSegmentFiles(segmentToDownload2);
Assert.assertTrue(segmentFile2.getAbsolutePath().contains("/local_storage_folder2/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload2));
// Segment 3 should be downloaded in local_storage_folder3, segment3 size 20L
- final DataSegment segmentToDownload3 = dataSegmentWithInterval("2014-12-20T00:00:00Z/P1D", 20L).withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-12-20T00:00:00.000Z_2014-12-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder,
- "test_segment_loader/2014-12-20T00:00:00.000Z_2014-12-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload3 = makeTestDataSegment(segmentDeepStorageDir, 20L, 2, TEST_DATA_RELATIVE_PATH_3);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_3);
+ manager.load(segmentToDownload3);
File segmentFile3 = manager.getSegmentFiles(segmentToDownload3);
Assert.assertTrue(segmentFile3.getAbsolutePath().contains("/local_storage_folder3/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload3));
@@ -892,23 +661,12 @@ public class SegmentLocalCacheManagerTest
// Now the storage locations local_storage_folder1, local_storage_folder2 and local_storage_folder3 have 10, 5 and
// 20 bytes occupied respectively. The default strategy should pick location2 (as it has least bytes used) for the
// next segment to be downloaded asserting the least bytes used distribution of segments.
- final DataSegment segmentToDownload4 = dataSegmentWithInterval("2014-08-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-08-20T00:00:00.000Z_2014-08-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder, "test_segment_loader/2014-08-20T00:00:00.000Z_2014-08-21T00:00:00" +
- ".000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload4 = makeTestDataSegment(segmentDeepStorageDir, 10L, 3, TEST_DATA_RELATIVE_PATH_4);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_4);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload4));
+ manager.load(segmentToDownload4);
File segmentFile1 = manager.getSegmentFiles(segmentToDownload4);
Assert.assertTrue(segmentFile1.getAbsolutePath().contains("/local_storage_folder2/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload4));
@@ -919,92 +677,67 @@ public class SegmentLocalCacheManagerTest
public void testSegmentDistributionUsingRandomStrategy() throws Exception
{
final List<StorageLocationConfig> locationConfigs = new ArrayList<>();
- final StorageLocationConfig locationConfig = createStorageLocationConfig("local_storage_folder", 10L,
- true);
- final StorageLocationConfig locationConfig2 = createStorageLocationConfig("local_storage_folder2", 100L,
- false);
- final StorageLocationConfig locationConfig3 = createStorageLocationConfig("local_storage_folder3", 9L,
- true);
+ final StorageLocationConfig locationConfig = createStorageLocationConfig(
+ "local_storage_folder",
+ 10L,
+ true
+ );
+ final StorageLocationConfig locationConfig2 = createStorageLocationConfig(
+ "local_storage_folder2",
+ 100L,
+ false
+ );
+ final StorageLocationConfig locationConfig3 = createStorageLocationConfig(
+ "local_storage_folder3",
+ 9L,
+ true
+ );
locationConfigs.add(locationConfig);
locationConfigs.add(locationConfig2);
locationConfigs.add(locationConfig3);
SegmentLoaderConfig segmentLoaderConfig = new SegmentLoaderConfig().withLocations(locationConfigs);
- manager = new SegmentLocalCacheManager(
- segmentLoaderConfig.toStorageLocations(),
+ final List<StorageLocation> locations = segmentLoaderConfig.toStorageLocations();
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
+ locations,
segmentLoaderConfig,
- new RandomStorageLocationSelectorStrategy(segmentLoaderConfig.toStorageLocations()),
- TestIndex.INDEX_IO,
+ new RandomStorageLocationSelectorStrategy(locations),
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
-
// Segment 1 should be downloaded in local_storage_folder, segment1 size 10L
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D", 10L).withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
+
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload));
+ manager.load(segmentToDownload);
File segmentFile = manager.getSegmentFiles(segmentToDownload);
Assert.assertTrue(segmentFile.getAbsolutePath().contains("/local_storage_folder/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
// Segment 2 should be downloaded in local_storage_folder3, segment2 size 9L
- final DataSegment segmentToDownload2 = dataSegmentWithInterval("2014-11-20T00:00:00Z/P1D", 9L).withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder,
- "test_segment_loader/2014-11-20T00:00:00.000Z_2014-11-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload2 = makeTestDataSegment(segmentDeepStorageDir, 9L, 1, TEST_DATA_RELATIVE_PATH_2);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_2);
Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload2));
+ manager.load(segmentToDownload2);
File segmentFile2 = manager.getSegmentFiles(segmentToDownload2);
Assert.assertTrue(segmentFile2.getAbsolutePath().contains("/local_storage_folder3/"));
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload2));
// Segment 3 should not be downloaded, segment3 size 20L
- final DataSegment segmentToDownload3 = dataSegmentWithInterval("2014-12-20T00:00:00Z/P1D", 20L).withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-12-20T00:00:00.000Z_2014-12-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder,
- "test_segment_loader/2014-12-20T00:00:00.000Z_2014-12-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
+ final DataSegment segmentToDownload3 = makeTestDataSegment(segmentDeepStorageDir, 20L, 2, TEST_DATA_RELATIVE_PATH_3);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH_3);
try {
// expect failure
- manager.getSegmentFiles(segmentToDownload3);
+ manager.load(segmentToDownload3);
Assert.fail();
}
catch (SegmentLoadingException e) {
@@ -1015,222 +748,251 @@ public class SegmentLocalCacheManagerTest
@Test
public void testGetSegmentFilesWhenDownloadStartMarkerExists() throws Exception
{
- final File localStorageFolder = tmpFolder.newFolder("local_storage_folder");
+ final DataSegment segmentToDownload = makeTestDataSegment(segmentDeepStorageDir);
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- localStorageFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
-
- // manually create a local segment under localStorageFolder
- final File localSegmentFile = new File(
- localStorageFolder,
- "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
- );
- FileUtils.mkdirp(localSegmentFile);
- final File indexZip = new File(localSegmentFile, "index.zip");
- Assert.assertTrue(indexZip.createNewFile());
+ final File localSegmentFile = new File(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+ makeSegmentZip(localSegmentFile, new File(localSegmentFile, "index.zip"));
+ manager.load(segmentToDownload);
final File cachedSegmentDir = manager.getSegmentFiles(segmentToDownload);
Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
// Emulate a corrupted segment file
final File downloadMarker = new File(
- cachedSegmentDir,
+ new File(localSegmentCacheDir, segmentToDownload.getId().toString()),
SegmentLocalCacheManager.DOWNLOAD_START_MARKER_FILE_NAME
);
Assert.assertTrue(downloadMarker.createNewFile());
+ // create a new manager, expect corrupted segment to be cleaned out and freshly downloaded after startup
+ SegmentLocalCacheManager manager = makeDefaultManager(jsonMapper);
- Assert.assertFalse("Expect cache miss for corrupted segment file", manager.isSegmentCached(segmentToDownload));
- Assert.assertFalse(cachedSegmentDir.exists());
- }
-
- @Test
- public void testReserveSegment()
- {
- final DataSegment dataSegment = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withSize(100L);
- final StorageLocation firstLocation = new StorageLocation(localSegmentCacheFolder, 200L, 0.0d);
- final StorageLocation secondLocation = new StorageLocation(localSegmentCacheFolder, 150L, 0.0d);
-
- manager = new SegmentLocalCacheManager(
- Arrays.asList(secondLocation, firstLocation),
- new SegmentLoaderConfig(),
- new RoundRobinStorageLocationSelectorStrategy(Arrays.asList(firstLocation, secondLocation)),
- TestIndex.INDEX_IO,
- jsonMapper
- );
- Assert.assertTrue(manager.reserve(dataSegment));
- Assert.assertTrue(firstLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(dataSegment, false)));
- Assert.assertEquals(100L, firstLocation.availableSizeBytes());
- Assert.assertEquals(150L, secondLocation.availableSizeBytes());
-
- // Reserving again should be no-op
- Assert.assertTrue(manager.reserve(dataSegment));
- Assert.assertTrue(firstLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(dataSegment, false)));
- Assert.assertEquals(100L, firstLocation.availableSizeBytes());
- Assert.assertEquals(150L, secondLocation.availableSizeBytes());
-
- // Reserving a second segment should now go to a different location
- final DataSegment otherSegment = dataSegmentWithInterval("2014-10-21T00:00:00Z/P1D").withSize(100L);
- Assert.assertTrue(manager.reserve(otherSegment));
- Assert.assertTrue(firstLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(dataSegment, false)));
- Assert.assertFalse(firstLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(otherSegment, false)));
- Assert.assertTrue(secondLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(otherSegment, false)));
- Assert.assertEquals(100L, firstLocation.availableSizeBytes());
- Assert.assertEquals(50L, secondLocation.availableSizeBytes());
+ manager.load(segmentToDownload);
+ manager.getSegmentFiles(segmentToDownload);
+ // this is still true becuase
+ Assert.assertTrue("Don't expect cache miss for corrupted segment file", manager.isSegmentCached(segmentToDownload));
+ Assert.assertTrue(cachedSegmentDir.exists());
+ Assert.assertFalse(downloadMarker.exists());
}
@Test
- public void testReserveNotEnoughSpace()
+ public void testGetBootstrapSegment() throws SegmentLoadingException
{
- final DataSegment dataSegment = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withSize(100L);
- final StorageLocation firstLocation = new StorageLocation(localSegmentCacheFolder, 50L, 0.0d);
- final StorageLocation secondLocation = new StorageLocation(localSegmentCacheFolder, 150L, 0.0d);
-
- manager = new SegmentLocalCacheManager(
- Arrays.asList(secondLocation, firstLocation),
- new SegmentLoaderConfig(),
- new RoundRobinStorageLocationSelectorStrategy(Arrays.asList(firstLocation, secondLocation)),
- TestIndex.INDEX_IO,
+ final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheDir, 10000L, null);
+ final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(ImmutableList.of(locationConfig));
+ final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
+ storageLocations,
+ loaderConfig,
+ new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- // should go to second location if first one doesn't have enough space
- Assert.assertTrue(manager.reserve(dataSegment));
- Assert.assertTrue(secondLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(dataSegment, false)));
- Assert.assertEquals(50L, firstLocation.availableSizeBytes());
- Assert.assertEquals(50L, secondLocation.availableSizeBytes());
+ final DataSegment dataSegment = TestSegmentUtils.makeSegment("foo", "v1", Intervals.of("2020/2021"));
- final DataSegment otherSegment = dataSegmentWithInterval("2014-10-21T00:00:00Z/P1D").withSize(100L);
- Assert.assertFalse(manager.reserve(otherSegment));
- Assert.assertEquals(50L, firstLocation.availableSizeBytes());
- Assert.assertEquals(50L, secondLocation.availableSizeBytes());
+ manager.bootstrap(dataSegment, SegmentLazyLoadFailCallback.NOOP);
+ Segment actualBootstrapSegment = manager.acquireCachedSegment(dataSegment).orElse(null);
+ Assert.assertNotNull(actualBootstrapSegment);
+ Assert.assertEquals(dataSegment.getId(), actualBootstrapSegment.getId());
+ Assert.assertEquals(dataSegment.getInterval(), actualBootstrapSegment.getDataInterval());
}
@Test
- public void testSegmentDownloadWhenLocationReserved() throws Exception
+ public void testGetSegmentVirtualStorage() throws Exception
{
- final List<StorageLocationConfig> locationConfigs = new ArrayList<>();
- final StorageLocationConfig locationConfig = createStorageLocationConfig("local_storage_folder", 10000000000L, true);
- final StorageLocationConfig locationConfig2 = createStorageLocationConfig("local_storage_folder2", 1000000000L, true);
- final StorageLocationConfig locationConfig3 = createStorageLocationConfig("local_storage_folder3", 1000000000L, true);
- locationConfigs.add(locationConfig);
- locationConfigs.add(locationConfig2);
- locationConfigs.add(locationConfig3);
-
- List<StorageLocation> locations = new ArrayList<>();
- for (StorageLocationConfig locConfig : locationConfigs) {
- locations.add(
- new StorageLocation(
- locConfig.getPath(),
- locConfig.getMaxSize(),
- locConfig.getFreeSpacePercent()
- )
- );
- }
+ final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheDir, 10000L, null);
+ final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig()
+ {
+ @Override
+ public List<StorageLocationConfig> getLocations()
+ {
+ return ImmutableList.of(locationConfig);
+ }
- manager = new SegmentLocalCacheManager(
- locations,
- new SegmentLoaderConfig().withLocations(locationConfigs),
- new RoundRobinStorageLocationSelectorStrategy(locations),
- TestIndex.INDEX_IO,
+ @Override
+ public boolean isVirtualStorage()
+ {
+ return true;
+ }
+ };
+ final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
+ storageLocations,
+ loaderConfig,
+ new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- StorageLocation location3 = manager.getLocations().get(2);
- Assert.assertEquals(locationConfig3.getPath(), location3.getPath());
- final File segmentSrcFolder = tmpFolder.newFolder("segmentSrcFolder");
-
- // Segment should be downloaded in local_storage_folder3 even if that is the third location
- final DataSegment segmentToDownload = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withLoadSpec(
- ImmutableMap.of(
- "type",
- "local",
- "path",
- segmentSrcFolder.getCanonicalPath()
- + "/test_segment_loader"
- + "/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z"
- + "/0/index.zip"
- )
- );
- String segmentDir = DataSegmentPusher.getDefaultStorageDir(segmentToDownload, false);
- location3.reserve(segmentDir, segmentToDownload);
- // manually create a local segment under segmentSrcFolder
- createLocalSegmentFile(segmentSrcFolder, "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0");
-
- Assert.assertFalse("Expect cache miss before downloading segment", manager.isSegmentCached(segmentToDownload));
-
- File segmentFile = manager.getSegmentFiles(segmentToDownload);
- Assert.assertTrue(segmentFile.getAbsolutePath().contains("/local_storage_folder3/"));
- Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(segmentToDownload));
-
- manager.cleanup(segmentToDownload);
- Assert.assertFalse("Expect cache miss after dropping segment", manager.isSegmentCached(segmentToDownload));
- Assert.assertFalse(location3.isReserved(segmentDir));
+ final DataSegment segmentToLoad = makeTestDataSegment(segmentDeepStorageDir);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+
+ manager.load(segmentToLoad);
+ Assert.assertNull(manager.getSegmentFiles(segmentToLoad));
+ Assert.assertFalse(manager.acquireCachedSegment(segmentToLoad).isPresent());
+ AcquireSegmentAction segmentAction = manager.acquireSegment(segmentToLoad);
+ ReferenceCountedObjectProvider<Segment> referenceProvider = segmentAction.getSegmentFuture().get();
+ Optional<Segment> theSegment = referenceProvider.acquireReference();
+ Assert.assertTrue(theSegment.isPresent());
+ Assert.assertNotNull(manager.getSegmentFiles(segmentToLoad));
+ Assert.assertEquals(segmentToLoad.getId(), theSegment.get().getId());
+ Assert.assertEquals(segmentToLoad.getInterval(), theSegment.get().getDataInterval());
+ theSegment.get().close();
+ segmentAction.close();
+
+ manager.drop(segmentToLoad);
+ Assert.assertNull(manager.getSegmentFiles(segmentToLoad));
+
+ // can actually load them again because load doesn't really do anything
+ AcquireSegmentAction segmentActionAfterDrop = manager.acquireSegment(segmentToLoad);
+ ReferenceCountedObjectProvider<Segment> referenceProviderAfterDrop = segmentActionAfterDrop.getSegmentFuture().get();
+ Optional<Segment> theSegmentAfterDrop = referenceProviderAfterDrop.acquireReference();
+ Assert.assertTrue(theSegmentAfterDrop.isPresent());
+ Assert.assertNotNull(manager.getSegmentFiles(segmentToLoad));
+ Assert.assertEquals(segmentToLoad.getId(), theSegmentAfterDrop.get().getId());
+ Assert.assertEquals(segmentToLoad.getInterval(), theSegmentAfterDrop.get().getDataInterval());
+
+ theSegmentAfterDrop.get().close();
+ segmentActionAfterDrop.close();
}
@Test
- public void testRelease()
+ public void testGetBootstrapSegmentVirtualStorage() throws Exception
{
- final DataSegment dataSegment = dataSegmentWithInterval("2014-10-20T00:00:00Z/P1D").withSize(100L);
- final StorageLocation firstLocation = new StorageLocation(localSegmentCacheFolder, 50L, 0.0d);
- final StorageLocation secondLocation = new StorageLocation(localSegmentCacheFolder, 150L, 0.0d);
+ final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheDir, 10000L, null);
+ final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig()
+ {
+ @Override
+ public List<StorageLocationConfig> getLocations()
+ {
+ return ImmutableList.of(locationConfig);
+ }
- manager = new SegmentLocalCacheManager(
- Arrays.asList(secondLocation, firstLocation),
- new SegmentLoaderConfig(),
- new RoundRobinStorageLocationSelectorStrategy(Arrays.asList(firstLocation, secondLocation)),
- TestIndex.INDEX_IO,
+ @Override
+ public boolean isVirtualStorage()
+ {
+ return true;
+ }
+ };
+ final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
+ storageLocations,
+ loaderConfig,
+ new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
-
- manager.reserve(dataSegment);
- manager.release(dataSegment);
- Assert.assertEquals(50L, firstLocation.availableSizeBytes());
- Assert.assertEquals(150L, secondLocation.availableSizeBytes());
- Assert.assertFalse(firstLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(dataSegment, false)));
- Assert.assertFalse(secondLocation.isReserved(DataSegmentPusher.getDefaultStorageDir(dataSegment, false)));
-
- // calling release again should have no effect
- manager.release(dataSegment);
- Assert.assertEquals(50L, firstLocation.availableSizeBytes());
- Assert.assertEquals(150L, secondLocation.availableSizeBytes());
+ final DataSegment segmentToBootstrap = makeTestDataSegment(segmentDeepStorageDir);
+ createSegmentZipInLocation(segmentDeepStorageDir, TEST_DATA_RELATIVE_PATH);
+
+ manager.bootstrap(segmentToBootstrap, SegmentLazyLoadFailCallback.NOOP);
+ Assert.assertNull(manager.getSegmentFiles(segmentToBootstrap));
+ Assert.assertFalse(manager.acquireCachedSegment(segmentToBootstrap).isPresent());
+ AcquireSegmentAction segmentAction = manager.acquireSegment(segmentToBootstrap);
+ ReferenceCountedObjectProvider<Segment> referenceProvider = segmentAction.getSegmentFuture().get();
+ Optional<Segment> theSegment = referenceProvider.acquireReference();
+ Assert.assertTrue(theSegment.isPresent());
+ Assert.assertNotNull(manager.getSegmentFiles(segmentToBootstrap));
+ Assert.assertEquals(segmentToBootstrap.getId(), theSegment.get().getId());
+ Assert.assertEquals(segmentToBootstrap.getInterval(), theSegment.get().getDataInterval());
+
+ theSegment.get().close();
+ segmentAction.close();
+
+ manager.drop(segmentToBootstrap);
+ Assert.assertNull(manager.getSegmentFiles(segmentToBootstrap));
+
+ // can actually load them again because bootstrap doesn't really do anything unless the segment is already
+ // present in the cache
+ AcquireSegmentAction segmentActionAfterDrop = manager.acquireSegment(segmentToBootstrap);
+ ReferenceCountedObjectProvider<Segment> referenceProviderDrop = segmentActionAfterDrop.getSegmentFuture().get();
+ Optional<Segment> theSegmentAfterDrop = referenceProviderDrop.acquireReference();
+ Assert.assertTrue(theSegmentAfterDrop.isPresent());
+ Assert.assertNotNull(manager.getSegmentFiles(segmentToBootstrap));
+ Assert.assertEquals(segmentToBootstrap.getId(), theSegmentAfterDrop.get().getId());
+ Assert.assertEquals(segmentToBootstrap.getInterval(), theSegmentAfterDrop.get().getDataInterval());
+
+ theSegmentAfterDrop.get().close();
+ segmentActionAfterDrop.close();
}
@Test
- public void testGetBootstrapSegment() throws SegmentLoadingException
+ public void testGetBootstrapSegmentVirtualStorageSegmentAlreadyCached() throws Exception
{
- final ObjectMapper jsonMapper = TestHelper.makeJsonMapper();
- jsonMapper.registerSubtypes(TestSegmentUtils.TestLoadSpec.class);
- jsonMapper.registerSubtypes(TestSegmentUtils.TestSegmentizerFactory.class);
+ final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheDir, 10000L, null);
+ final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig()
+ {
+ @Override
+ public List<StorageLocationConfig> getLocations()
+ {
+ return ImmutableList.of(locationConfig);
+ }
- final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheFolder, 10000L, null);
- final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(ImmutableList.of(locationConfig));
+ @Override
+ public boolean isVirtualStorage()
+ {
+ return true;
+ }
+ };
final List<StorageLocation> storageLocations = loaderConfig.toStorageLocations();
- manager = new SegmentLocalCacheManager(
+ SegmentLocalCacheManager manager = new SegmentLocalCacheManager(
storageLocations,
loaderConfig,
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations),
- TestIndex.INDEX_IO,
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
jsonMapper
);
- final DataSegment dataSegment = TestSegmentUtils.makeSegment("foo", "v1", Intervals.of("2020/2021"));
+ final DataSegment segmentToBootstrap = makeTestDataSegment(segmentDeepStorageDir);
+ FileUtils.mkdirp(new File(localSegmentCacheDir, "info_dir"));
+ manager.storeInfoFile(segmentToBootstrap);
+ File segmentZip = createSegmentZipInLocation(
+ segmentDeepStorageDir,
+ TEST_DATA_RELATIVE_PATH
+ );
+ File unzippedSegmentPathInLocation = new File(
+ localSegmentCacheDir,
+ segmentToBootstrap.getId().toString()
+ );
+ FileUtils.mkdirp(unzippedSegmentPathInLocation);
+ CompressionUtils.unzip(
+ segmentZip,
+ unzippedSegmentPathInLocation
+ );
+
+ for (DataSegment segment : manager.getCachedSegments()) {
+ manager.bootstrap(segment, SegmentLazyLoadFailCallback.NOOP);
+ }
+
+ // if bootstrapping a file that already exists it will be mounted by bootsrap
+ Assert.assertNotNull(manager.getSegmentFiles(segmentToBootstrap));
+ }
+
+ @Test
+ public void testIfTombstoneIsLoaded() throws IOException, SegmentLoadingException
+ {
+ final DataSegment tombstone = DataSegment.builder()
+ .dataSource("foo")
+ .interval(Intervals.of("2014-10-20T00:00:00Z/P1D"))
+ .version("version")
+ .loadSpec(Collections.singletonMap(
+ "type",
+ DataSegment.TOMBSTONE_LOADSPEC_TYPE
+ ))
+ .shardSpec(TombstoneShardSpec.INSTANCE)
+ .size(1)
+ .build();
+
- final ReferenceCountedSegmentProvider actualBootstrapSegment = manager.getBootstrapSegment(
- dataSegment,
- SegmentLazyLoadFailCallback.NOOP
+ final File cachedSegmentFile = new File(
+ localSegmentCacheDir,
+ "test_segment_loader/2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z/2015-05-27T03:38:35.683Z/0"
);
- Assert.assertNotNull(actualBootstrapSegment);
- Assert.assertEquals(dataSegment.getId(), actualBootstrapSegment.getBaseSegment().getId());
- Assert.assertEquals(dataSegment.getInterval(), actualBootstrapSegment.getBaseSegment().getDataInterval());
+ FileUtils.mkdirp(cachedSegmentFile);
+
+ manager.load(tombstone);
+ manager.getSegmentFiles(tombstone);
+ Assert.assertTrue("Expect cache hit after downloading segment", manager.isSegmentCached(tombstone));
}
@Test
@@ -1246,16 +1008,17 @@ public class SegmentLocalCacheManagerTest
.size(100)
.build();
- final ReferenceCountedSegmentProvider segment = manager.getSegment(tombstone);
+ manager.load(tombstone);
+ Segment segment = manager.acquireCachedSegment(tombstone).orElse(null);
- Assert.assertEquals(tombstone.getId(), segment.getBaseSegment().getId());
- Assert.assertEquals(interval, segment.getBaseSegment().getDataInterval());
+ Assert.assertEquals(tombstone.getId(), segment.getId());
+ Assert.assertEquals(interval, segment.getDataInterval());
- final CursorFactory cursorFactory = segment.getBaseSegment().as(CursorFactory.class);
+ final CursorFactory cursorFactory = segment.as(CursorFactory.class);
Assert.assertNotNull(cursorFactory);
- Assert.assertTrue(segment.getBaseSegment().isTombstone());
+ Assert.assertTrue(segment.isTombstone());
- final QueryableIndex queryableIndex = segment.getBaseSegment().as(QueryableIndex.class);
+ final QueryableIndex queryableIndex = segment.as(QueryableIndex.class);
Assert.assertNotNull(queryableIndex);
Assert.assertEquals(interval, queryableIndex.getDataInterval());
Assert.assertThrows(UnsupportedOperationException.class, queryableIndex::getMetadata);
@@ -1266,12 +1029,109 @@ public class SegmentLocalCacheManagerTest
Assert.assertThrows(UnsupportedOperationException.class, () -> queryableIndex.getColumnHolder("foo"));
}
+ private SegmentLocalCacheManager makeDefaultManager(ObjectMapper jsonMapper)
+ {
+ final List<StorageLocationConfig> locationConfigs = new ArrayList<>();
+ final StorageLocationConfig locationConfig = new StorageLocationConfig(localSegmentCacheDir, 10000000000L, null);
+ locationConfigs.add(locationConfig);
+ final SegmentLoaderConfig loaderConfig = new SegmentLoaderConfig().withLocations(locationConfigs);
+ final List<StorageLocation> locations = loaderConfig.toStorageLocations();
+ return new SegmentLocalCacheManager(
+ locations,
+ loaderConfig,
+ new LeastBytesUsedStorageLocationSelectorStrategy(locations),
+ TestHelper.getTestIndexIO(jsonMapper, ColumnConfig.DEFAULT),
+ jsonMapper
+ );
+ }
+
+ private File createSegmentZipInLocation(File src, String relativePath) throws Exception
+ {
+ final File tmpSegmentFile = tmpFolder.newFile();
+ FileUtils.mkdirp(new File(src, relativePath));
+ return makeSegmentZip(tmpSegmentFile, new File(src, relativePath + "/index.zip"));
+ }
+
+ private StorageLocationConfig createStorageLocationConfig(String localPath, long maxSize, boolean writable) throws Exception
+ {
+
+ final File localStorageFolder = tmpFolder.newFolder(localPath);
+ localStorageFolder.setWritable(writable);
+ final StorageLocationConfig locationConfig = new StorageLocationConfig(localStorageFolder, maxSize, 1.0);
+ return locationConfig;
+ }
+
+ private DataSegment dataSegmentWithInterval(String intervalStr)
+ {
+ return dataSegmentWithInterval(intervalStr, 10L);
+ }
+
+ private DataSegment dataSegmentWithInterval(String intervalStr, long size)
+ {
+ return dataSegmentWithInterval(intervalStr, size, 0);
+ }
+
+ private DataSegment dataSegmentWithInterval(String intervalStr, long size, int partition)
+ {
+ return DataSegment.builder()
+ .dataSource("test_segment_loader")
+ .interval(Intervals.of(intervalStr))
+ .loadSpec(
+ ImmutableMap.of(
+ "type",
+ "local",
+ "path",
+ "somewhere"
+ )
+ )
+ .version("2015-05-27T03:38:35.683Z")
+ .dimensions(ImmutableList.of())
+ .metrics(ImmutableList.of())
+ .shardSpec(new LinearShardSpec(partition))
+ .binaryVersion(9)
+ .size(size)
+ .build();
+ }
+
+
+
+ private DataSegment makeTestDataSegment(File segmentSrcFolder) throws IOException
+ {
+ return makeTestDataSegment(segmentSrcFolder, 10L, 0, TEST_DATA_RELATIVE_PATH);
+ }
+
+ private DataSegment makeTestDataSegment(File segmentSrcFolder, int partition, String relativePath) throws IOException
+ {
+ return makeTestDataSegment(segmentSrcFolder, 10L, partition, relativePath);
+ }
+
+ private DataSegment makeTestDataSegment(File segmentSrcFolder, long size, int partition, String relativePath) throws IOException
+ {
+ return dataSegmentWithInterval("2011-01-12T00:00:00.000Z/2011-04-15T00:00:00.001Z", size, partition)
+ .withLoadSpec(
+ ImmutableMap.of(
+ "type",
+ "local",
+ "path",
+ segmentSrcFolder.getCanonicalPath() + "/" + relativePath + "/index.zip"
+ )
+ );
+ }
+
private void writeSegmentFile(final DataSegment segment) throws IOException
{
final File segmentFile = new File(
- localSegmentCacheFolder,
- DataSegmentPusher.getDefaultStorageDir(segment, false)
+ localSegmentCacheDir,
+ segment.getId().toString()
);
FileUtils.mkdirp(segmentFile);
}
+
+ static File makeSegmentZip(File segmentFiles, File zipOutFile) throws IOException
+ {
+ TestIndex.persist(TestIndex.getIncrementalTestIndex(), IndexSpec.DEFAULT, segmentFiles);
+ FileUtils.mkdirp(zipOutFile.getParentFile());
+ CompressionUtils.zip(segmentFiles, zipOutFile);
+ return zipOutFile;
+ }
}
diff --git a/server/src/test/java/org/apache/druid/segment/loading/StorageLocationSelectorStrategyTest.java b/server/src/test/java/org/apache/druid/segment/loading/StorageLocationSelectorStrategyTest.java
index a2bfb5b4f86..94e5c7250f8 100644
--- a/server/src/test/java/org/apache/druid/segment/loading/StorageLocationSelectorStrategyTest.java
+++ b/server/src/test/java/org/apache/druid/segment/loading/StorageLocationSelectorStrategyTest.java
@@ -70,7 +70,7 @@ public class StorageLocationSelectorStrategyTest
StorageLocationSelectorStrategy leastBytesUsedStrategy =
new LeastBytesUsedStorageLocationSelectorStrategy(storageLocations);
- storageLocation1.reserve("tmp_loc1", "__seg1", 1024L);
+ storageLocation1.reserve(makeCacheEntry("tmp_loc1", 1024L));
Iterator<StorageLocation> locations = leastBytesUsedStrategy.getLocations();
@@ -256,7 +256,7 @@ public class StorageLocationSelectorStrategyTest
Assert.assertEquals("The next element of the iterator should point to path local_storage_folder_1",
localStorageFolder1, loc3.getPath());
- storageLocation2.reserve("tmp_loc2", "__seg2", 6000000000L);
+ storageLocation2.reserve(makeCacheEntry("tmp_loc2", 6000000000L));
locations = mostAvailableStrategy.getLocations();
loc1 = locations.next();
@@ -374,4 +374,44 @@ public class StorageLocationSelectorStrategyTest
}
);
}
+
+ private static CacheEntry makeCacheEntry(String label, long size)
+ {
+ final StorageLocationTest.StringCacheIdentifier identifier = new StorageLocationTest.StringCacheIdentifier(label);
+ return new CacheEntry()
+ {
+ private boolean isMounted = false;
+
+ @Override
+ public CacheEntryIdentifier getId()
+ {
+ return identifier;
+ }
+
+ @Override
+ public long getSize()
+ {
+ return size;
+ }
+
+ @Override
+ public boolean isMounted()
+ {
+ return isMounted;
+ }
+
+ @Override
+ public void mount(StorageLocation location)
+ {
+ isMounted = true;
+ }
+
+ @Override
+ public void unmount()
+ {
+ isMounted = false;
+ }
+ };
+ }
+
}
diff --git a/server/src/test/java/org/apache/druid/segment/loading/StorageLocationTest.java b/server/src/test/java/org/apache/druid/segment/loading/StorageLocationTest.java
index 5048f7775d3..a1d459d1ec1 100644
--- a/server/src/test/java/org/apache/druid/segment/loading/StorageLocationTest.java
+++ b/server/src/test/java/org/apache/druid/segment/loading/StorageLocationTest.java
@@ -21,178 +21,370 @@ package org.apache.druid.segment.loading;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.java.util.common.Intervals;
-import org.apache.druid.java.util.emitter.EmittingLogger;
-import org.apache.druid.java.util.emitter.service.AlertBuilder;
-import org.apache.druid.java.util.emitter.service.ServiceEmitter;
-import org.apache.druid.java.util.emitter.service.ServiceEventBuilder;
+import org.apache.druid.java.util.common.concurrent.Execs;
+import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
+import org.apache.druid.utils.CloseableUtils;
import org.easymock.EasyMock;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
-import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collections;
-
-/**
- */
-public class StorageLocationTest
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadLocalRandom;
+
+class StorageLocationTest
{
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ File tempDir;
+
+ ExecutorService executorService;
+
+ @BeforeEach
+ public void setup()
+ {
+ executorService = Execs.multiThreaded(
+ 10,
+ "storage-location-test-%d"
+ );
+ }
+
+ @Test
+ public void testWeakReserveAndReclaim()
+ {
+ StorageLocation location = new StorageLocation(tempDir, 100L, null);
+ CacheEntry entry1 = new TestCacheEntry("1", 25);
+ CacheEntry entry2 = new TestCacheEntry("2", 25);
+ CacheEntry entry3 = new TestCacheEntry("3", 25);
+ CacheEntry entry4 = new TestCacheEntry("4", 25);
+ CacheEntry entry5 = new TestCacheEntry("5", 25);
+
+ location.reserveWeak(entry1);
+ location.reserveWeak(entry2);
+ location.reserveWeak(entry3);
+ location.reserveWeak(entry4);
+ Assertions.assertEquals(100, location.currentWeakSizeBytes());
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry3.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry4.getId()));
+ location.reserveWeak(entry5);
+ Assertions.assertEquals(100, location.currentWeakSizeBytes());
+ Assertions.assertFalse(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry5.getId()));
+ Assertions.assertEquals(100, location.currentWeakSizeBytes());
+ }
+
+ @Test
+ public void testRemoveFromHead()
+ {
+ StorageLocation location = new StorageLocation(tempDir, 100L, null);
+ CacheEntry entry1 = new TestCacheEntry("1", 25);
+ CacheEntry entry2 = new TestCacheEntry("2", 25);
+ CacheEntry entry3 = new TestCacheEntry("3", 25);
+ CacheEntry entry4 = new TestCacheEntry("4", 25);
+
+ location.reserveWeak(entry1);
+ location.reserveWeak(entry2);
+ location.reserveWeak(entry3);
+ location.reserveWeak(entry4);
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry3.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry4.getId()));
+ location.release(entry1);
+ location.release(entry2);
+ location.release(entry3);
+ location.release(entry4);
+ Assertions.assertFalse(location.isWeakReserved(entry1.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry2.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry3.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry4.getId()));
+ }
+
+ @Test
+ public void testRemoveFromTail()
+ {
+ StorageLocation location = new StorageLocation(tempDir, 100L, null);
+ CacheEntry entry1 = new TestCacheEntry("1", 25);
+ CacheEntry entry2 = new TestCacheEntry("2", 25);
+ CacheEntry entry3 = new TestCacheEntry("3", 25);
+ CacheEntry entry4 = new TestCacheEntry("4", 25);
+
+ location.reserveWeak(entry1);
+ location.reserveWeak(entry2);
+ location.reserveWeak(entry3);
+ location.reserveWeak(entry4);
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry3.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry4.getId()));
+ location.release(entry4);
+ location.release(entry3);
+ location.release(entry2);
+ location.release(entry1);
+ Assertions.assertFalse(location.isWeakReserved(entry1.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry2.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry3.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry4.getId()));
+ }
+
+ @Test
+ public void testRemoveRandom()
+ {
+ StorageLocation location = new StorageLocation(tempDir, 100L, null);
+ CacheEntry entry1 = new TestCacheEntry("1", 25);
+ CacheEntry entry2 = new TestCacheEntry("2", 25);
+ CacheEntry entry3 = new TestCacheEntry("3", 25);
+ CacheEntry entry4 = new TestCacheEntry("4", 25);
+ List<CacheEntry> entries = new ArrayList<>();
+ entries.add(entry1);
+ entries.add(entry2);
+ entries.add(entry3);
+ entries.add(entry4);
+
+ location.reserveWeak(entry1);
+ location.reserveWeak(entry2);
+ location.reserveWeak(entry3);
+ location.reserveWeak(entry4);
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry3.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry4.getId()));
+ while (!entries.isEmpty()) {
+ int toRemove = ThreadLocalRandom.current().nextInt(entries.size());
+ CacheEntry entry = entries.get(toRemove);
+ location.release(entry);
+ entries.remove(toRemove);
+ }
+ Assertions.assertFalse(location.isWeakReserved(entry1.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry2.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry3.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry4.getId()));
+ Assertions.assertEquals(0, location.currentSizeBytes());
+ Assertions.assertEquals(0, location.currentWeakSizeBytes());
+ }
+
+ @Test
+ public void testBulkReservation()
+ {
+ StorageLocation location = new StorageLocation(tempDir, 100L, null);
+ CacheEntry entry1 = new TestCacheEntry("1", 25);
+ CacheEntry entry2 = new TestCacheEntry("2", 25);
+ CacheEntry entry3 = new TestCacheEntry("3", 25);
+ CacheEntry entry4 = new TestCacheEntry("4", 25);
+ CacheEntry entry5 = new TestCacheEntry("5", 25);
+ CacheEntry entry6 = new TestCacheEntry("6", 25);
+ CacheEntry entry7 = new TestCacheEntry("7", 25);
+ CacheEntry entry8 = new TestCacheEntry("8", 25);
+
+ final Closer closer = Closer.create();
+ Assertions.assertNotNull(closer.register(location.addWeakReservationHold(entry1.getId(), () -> entry1)));
+ Assertions.assertNotNull(closer.register(location.addWeakReservationHold(entry2.getId(), () -> entry2)));
+ Assertions.assertTrue(location.reserveWeak(entry3));
+ Assertions.assertTrue(location.reserveWeak(entry4));
+
+ Assertions.assertEquals(100, location.currentWeakSizeBytes());
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry3.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry4.getId()));
+
+ Assertions.assertNotNull(closer.register(location.addWeakReservationHold(entry5.getId(), () -> entry5)));
+
+ Assertions.assertEquals(100, location.currentWeakSizeBytes());
+
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry3.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry4.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry5.getId()));
+
+ Assertions.assertTrue(location.reserveWeak(entry6));
+
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry3.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry4.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry5.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry6.getId()));
+
+ Assertions.assertTrue(location.reserveWeak(entry7));
+
+ Assertions.assertTrue(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry3.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry4.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry5.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry6.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry7.getId()));
+
+ CloseableUtils.closeAndWrapExceptions(closer);
+ Assertions.assertTrue(location.reserveWeak(entry8));
+
+ Assertions.assertFalse(location.isWeakReserved(entry1.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry2.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry3.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry4.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry5.getId()));
+ Assertions.assertFalse(location.isWeakReserved(entry6.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry7.getId()));
+ Assertions.assertTrue(location.isWeakReserved(entry8.getId()));
+ Assertions.assertEquals(100, location.currentWeakSizeBytes());
+ }
@Test
- @SuppressWarnings("GuardedBy")
+ @SuppressWarnings({"GuardedBy", "FieldAccessNotGuarded"})
public void testStorageLocationFreePercent()
{
// free space ignored only maxSize matters
StorageLocation locationPlain = fakeLocation(100_000, 5_000, 10_000, null);
- Assert.assertTrue(locationPlain.canHandle(newSegmentId("2012/2013").toString(), 9_000));
- Assert.assertFalse(locationPlain.canHandle(newSegmentId("2012/2013").toString(), 11_000));
+ Assertions.assertTrue(locationPlain.canHandle(makeSegmentEntry("2012/2013", 9_000)).isSuccess());
+ Assertions.assertFalse(locationPlain.canHandle(makeSegmentEntry("2012/2013", 11_000)).isSuccess());
// enough space available maxSize is the limit
StorageLocation locationFree = fakeLocation(100_000, 25_000, 10_000, 10.0);
- Assert.assertTrue(locationFree.canHandle(newSegmentId("2012/2013").toString(), 9_000));
- Assert.assertFalse(locationFree.canHandle(newSegmentId("2012/2013").toString(), 11_000));
+ Assertions.assertTrue(locationFree.canHandle(makeSegmentEntry("2012/2013", 9_000)).isSuccess());
+ Assertions.assertFalse(locationFree.canHandle(makeSegmentEntry("2012/2013", 11_000)).isSuccess());
// disk almost full percentage is the limit
StorageLocation locationFull = fakeLocation(100_000, 15_000, 10_000, 10.0);
- Assert.assertTrue(locationFull.canHandle(newSegmentId("2012/2013").toString(), 4_000));
- Assert.assertFalse(locationFull.canHandle(newSegmentId("2012/2013").toString(), 6_000));
+ Assertions.assertTrue(locationFull.canHandle(makeSegmentEntry("2012/2013", 4_000)).isSuccess());
+ Assertions.assertFalse(locationFull.canHandle(makeSegmentEntry("2012/2013", 6_000)).isSuccess());
}
@Test
- @SuppressWarnings("GuardedBy")
- public void testStorageLocationRealFileSystem() throws IOException
+ @SuppressWarnings({"GuardedBy", "FieldAccessNotGuarded"})
+ public void testStorageLocationRealFileSystem()
{
- File file = temporaryFolder.newFolder();
- StorageLocation location = new StorageLocation(file, 10_000, 100.0d);
- Assert.assertFalse(location.canHandle(newSegmentId("2012/2013").toString(), 5_000));
+ StorageLocation location = new StorageLocation(tempDir, 10_000, 100.0d);
+ Assertions.assertFalse(location.canHandle(makeSegmentEntry("2012/2013", 5_000)).isSuccess());
- location = new StorageLocation(file, 10_000, 0.0001d);
- Assert.assertTrue(location.canHandle(newSegmentId("2012/2013").toString(), 1));
+ location = new StorageLocation(tempDir, 10_000, 0.0001d);
+ Assertions.assertTrue(location.canHandle(makeSegmentEntry("2012/2013", 1)).isSuccess());
}
- private StorageLocation fakeLocation(long total, long free, long max, Double percent)
- {
- File file = EasyMock.mock(File.class);
- EasyMock.expect(file.getTotalSpace()).andReturn(total).anyTimes();
- EasyMock.expect(file.getFreeSpace()).andReturn(free).anyTimes();
- EasyMock.replay(file);
- return new StorageLocation(file, max, percent);
- }
@Test
- public void testStorageLocation() throws IOException
+ public void testStorageLocation()
{
- File dir = temporaryFolder.newFolder();
long expectedAvail = 1000L;
- StorageLocation loc = new StorageLocation(dir, expectedAvail, null);
+ StorageLocation loc = new StorageLocation(tempDir, expectedAvail, null);
verifyLoc(expectedAvail, loc);
- final DataSegment secondSegment = makeSegment("2012-01-02/2012-01-03", 23);
+ final CacheEntry entry1 = makeSegmentEntry("2012-01-01/2012-01-02", 10);
+ final CacheEntry entry2 = makeSegmentEntry("2012-01-01/2012-01-02", 10);
+ final CacheEntry entry3 = makeSegmentEntry("2012-01-02/2012-01-03", 23);
- loc.reserve("test1", makeSegment("2012-01-01/2012-01-02", 10));
+ loc.reserve(entry1);
expectedAvail -= 10;
verifyLoc(expectedAvail, loc);
- loc.reserve("test1", makeSegment("2012-01-01/2012-01-02", 10));
+ loc.reserve(entry2);
verifyLoc(expectedAvail, loc);
- loc.reserve("test2", secondSegment);
+ loc.reserve(entry3);
expectedAvail -= 23;
verifyLoc(expectedAvail, loc);
- loc.removeSegmentDir(new File(dir, "test1"), makeSegment("2012-01-01/2012-01-02", 10));
+ loc.release(entry1);
expectedAvail += 10;
verifyLoc(expectedAvail, loc);
- loc.removeSegmentDir(new File(dir, "test1"), makeSegment("2012-01-01/2012-01-02", 10));
+ loc.release(makeSegmentEntry("2012-01-01/2012-01-02", 10));
verifyLoc(expectedAvail, loc);
- loc.removeSegmentDir(new File(dir, "test2"), secondSegment);
+ loc.release(entry3);
expectedAvail += 23;
verifyLoc(expectedAvail, loc);
}
@Test
- public void testMaybeReserve() throws IOException
+ public void testReserveAndRelease()
{
- ServiceEmitter emitter = Mockito.mock(ServiceEmitter.class);
- ArgumentCaptor<ServiceEventBuilder> argumentCaptor = ArgumentCaptor.forClass(ServiceEventBuilder.class);
- EmittingLogger.registerEmitter(emitter);
-
- File dir = temporaryFolder.newFolder();
- long expectedAvail = 1000L;
- StorageLocation loc = new StorageLocation(dir, expectedAvail, null);
-
- verifyLoc(expectedAvail, loc);
+ StorageLocation loc = new StorageLocation(tempDir, 1000L, null);
+ CacheEntry entry1 = new TestCacheEntry("testPath", 100L);
+ CacheEntry entry2 = new TestCacheEntry("testPath", 100L);
- final DataSegment secondSegment = makeSegment("2012-01-02/2012-01-03", 23);
+ Assertions.assertTrue(loc.reserve(entry1));
- loc.maybeReserve("test1", makeSegment("2012-01-01/2012-01-02", 10));
- expectedAvail -= 10;
- verifyLoc(expectedAvail, loc);
+ Assertions.assertEquals(900L, loc.availableSizeBytes());
+ Assertions.assertTrue(loc.isReserved(entry1.getId()));
- loc.maybeReserve("test1", makeSegment("2012-01-01/2012-01-02", 10));
- verifyLoc(expectedAvail, loc);
+ Assertions.assertFalse(loc.reserve(entry2));
- loc.maybeReserve("test2", secondSegment);
- expectedAvail -= 23;
- verifyLoc(expectedAvail, loc);
+ loc.release(entry1);
+ Assertions.assertEquals(1000L, loc.availableSizeBytes());
+ Assertions.assertFalse(loc.isReserved(entry2.getId()));
- loc.removeSegmentDir(new File(dir, "test1"), makeSegment("2012-01-01/2012-01-02", 10));
- expectedAvail += 10;
- verifyLoc(expectedAvail, loc);
-
- loc.maybeReserve("test3", makeSegment("2012-01-01/2012-01-02", 999));
- expectedAvail -= 999;
- verifyLoc(expectedAvail, loc);
-
- Mockito.verify(emitter).emit(argumentCaptor.capture());
- AlertBuilder alertBuilder = (AlertBuilder) argumentCaptor.getValue();
- String description = alertBuilder.build(ImmutableMap.of()).getDescription();
- Assert.assertNotNull(description);
- Assert.assertTrue(description, description.contains("Please increase druid.segmentCache.locations maxSize param"));
+ loc.release(entry2);
}
@Test
- public void testReserveAndRelease() throws IOException
+ public void testReserveWeakExistsConcurrency() throws ExecutionException, InterruptedException
{
- File dir = temporaryFolder.newFolder();
- StorageLocation loc = new StorageLocation(dir, 1000L, null);
-
- File reserved = loc.reserve("testPath", "segmentId", 100L);
- Assert.assertNotNull(reserved);
- Assert.assertEquals(new File(dir, "testPath"), reserved.getAbsoluteFile());
- Assert.assertEquals(900L, loc.availableSizeBytes());
- Assert.assertTrue(loc.contains("testPath"));
-
- Assert.assertNull(loc.reserve("testPath", "segmentId", 100L));
-
- Assert.assertTrue(loc.release("testPath", 100L));
- Assert.assertEquals(1000L, loc.availableSizeBytes());
- Assert.assertFalse(loc.contains("testPath"));
+ StorageLocation loc = new StorageLocation(tempDir, 1000L, null);
+ final TestSegmentCacheEntry entry = makeSegmentEntry("2024/2025", 10);
+ loc.reserveWeak(entry);
+ entry.mount(loc);
+
+ for (int i = 0; i < 1000; i++) {
+ final List<Future<Boolean>> futures = new ArrayList<>();
+ for (int j = 0; j < 10; j++) {
+ futures.add(
+ executorService.submit(() -> {
+ try {
+ StorageLocation.ReservationHold<TestSegmentCacheEntry> hold =
+ loc.addWeakReservationHoldIfExists(entry.getId());
+ Assertions.assertNotNull(hold);
+ hold.close();
+ return true;
+ }
+ catch (Throwable t) {
+ return false;
+ }
+ })
+ );
+ }
+
+ for (Future<Boolean> future : futures) {
+ Assertions.assertTrue(future.get());
+ }
+ }
- Assert.assertFalse(loc.release("testPath", 100L));
+ Assertions.assertEquals(0, loc.getActiveWeakHolds());
}
- @SuppressWarnings("GuardedBy")
+ @SuppressWarnings({"GuardedBy", "FieldAccessNotGuarded"})
private void verifyLoc(long maxSize, StorageLocation loc)
{
- Assert.assertEquals(maxSize, loc.availableSizeBytes());
+ Assertions.assertEquals(maxSize, loc.availableSizeBytes());
for (int i = 0; i <= maxSize; ++i) {
- Assert.assertTrue(String.valueOf(i), loc.canHandle(newSegmentId("2013/2014").toString(), i));
+ Assertions.assertTrue(loc.canHandle(makeSegmentEntry("2013/2014", i)).isSuccess(), String.valueOf(i));
}
}
- private DataSegment makeSegment(String intervalString, long size)
+ private StorageLocation fakeLocation(long total, long free, long max, Double percent)
+ {
+ File file = EasyMock.mock(File.class);
+ EasyMock.expect(file.getTotalSpace()).andReturn(total).anyTimes();
+ EasyMock.expect(file.getFreeSpace()).andReturn(free).anyTimes();
+ EasyMock.replay(file);
+ return new StorageLocation(file, max, percent);
+ }
+
+ private static DataSegment makeSegment(String intervalString, long size)
{
return new DataSegment(
"test",
@@ -211,4 +403,121 @@ public class StorageLocationTest
{
return SegmentId.of("test", Intervals.of(intervalString), "1", 0);
}
+
+ private static TestSegmentCacheEntry makeSegmentEntry(String intervalString, long size)
+ {
+ return new TestSegmentCacheEntry(intervalString, size);
+ }
+
+ public static final class TestSegmentCacheEntry implements CacheEntry
+ {
+ private final SegmentCacheEntryIdentifier identifier;
+ private final DataSegment segment;
+ private boolean isMounted = false;
+
+ public TestSegmentCacheEntry(String intervalString, long size)
+ {
+ this.segment = makeSegment(intervalString, size);
+ this.identifier = new SegmentCacheEntryIdentifier(segment.getId());
+ }
+
+ @Override
+ public SegmentCacheEntryIdentifier getId()
+ {
+ return identifier;
+ }
+
+ @Override
+ public long getSize()
+ {
+ return segment.getSize();
+ }
+
+ @Override
+ public boolean isMounted()
+ {
+ return isMounted;
+ }
+
+ @Override
+ public void mount(StorageLocation location)
+ {
+ isMounted = true;
+ }
+
+ @Override
+ public void unmount()
+ {
+ isMounted = false;
+ }
+ }
+
+ private static final class TestCacheEntry implements CacheEntry
+ {
+ private final StringCacheIdentifier id;
+ private final long size;
+ private boolean isMounted = false;
+
+ private TestCacheEntry(String id, long size)
+ {
+ this.id = new StringCacheIdentifier(id);
+ this.size = size;
+ }
+
+ @Override
+ public StringCacheIdentifier getId()
+ {
+ return id;
+ }
+
+ @Override
+ public long getSize()
+ {
+ return size;
+ }
+
+ @Override
+ public boolean isMounted()
+ {
+ return true;
+ }
+
+ @Override
+ public void mount(StorageLocation location)
+ {
+ // do nothing
+ }
+
+ @Override
+ public void unmount()
+ {
+ // do nothing
+ }
+ }
+
+ public static final class StringCacheIdentifier implements CacheEntryIdentifier
+ {
+ private final String string;
+
+ public StringCacheIdentifier(String string)
+ {
+ this.string = string;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ StringCacheIdentifier that = (StringCacheIdentifier) o;
+ return Objects.equals(string, that.string);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hashCode(string);
+ }
+ }
}
diff --git a/server/src/test/java/org/apache/druid/server/ClientQuerySegmentWalkerTest.java b/server/src/test/java/org/apache/druid/server/ClientQuerySegmentWalkerTest.java
index db1b97bce63..021227a3ca3 100644
--- a/server/src/test/java/org/apache/druid/server/ClientQuerySegmentWalkerTest.java
+++ b/server/src/test/java/org/apache/druid/server/ClientQuerySegmentWalkerTest.java
@@ -91,6 +91,8 @@ import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
import org.apache.druid.server.initialization.ServerConfig;
import org.apache.druid.server.scheduling.ManualQueryPrioritizationStrategy;
import org.apache.druid.server.scheduling.NoQueryLaningStrategy;
+import org.apache.druid.timeline.DataSegment;
+import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.NumberedShardSpec;
import org.apache.druid.timeline.partition.ShardSpec;
@@ -1691,14 +1693,22 @@ public class ClientQuerySegmentWalkerTest
injector,
new CapturingWalker(
QueryStackTests.createClusterQuerySegmentWalker(
- ImmutableMap.<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>>builder()
- .put(FOO, makeTimeline(FOO, FOO_INLINE))
- .put(BAR, makeTimeline(BAR, BAR_INLINE))
- .put(MULTI, makeTimeline(MULTI, MULTI_VALUE_INLINE))
- .put(GLOBAL, makeTimeline(GLOBAL, FOO_INLINE))
- .put(ARRAY, makeTimeline(ARRAY, ARRAY_INLINE))
- .put(ARRAY_UNKNOWN, makeTimeline(ARRAY_UNKNOWN, ARRAY_INLINE_UNKNOWN))
- .build(),
+ Map.of(
+ FOO, makeTimeline(FOO),
+ BAR, makeTimeline(BAR),
+ MULTI, makeTimeline(MULTI),
+ GLOBAL, makeTimeline(GLOBAL),
+ ARRAY, makeTimeline(ARRAY),
+ ARRAY_UNKNOWN, makeTimeline(ARRAY_UNKNOWN)
+ ),
+ Map.of(
+ makeDataSegment(FOO), makeReferenceProvider(FOO_INLINE),
+ makeDataSegment(BAR), makeReferenceProvider(BAR_INLINE),
+ makeDataSegment(MULTI), makeReferenceProvider(MULTI_VALUE_INLINE),
+ makeDataSegment(GLOBAL), makeReferenceProvider(FOO_INLINE),
+ makeDataSegment(ARRAY), makeReferenceProvider(ARRAY_INLINE),
+ makeDataSegment(ARRAY_UNKNOWN), makeReferenceProvider(ARRAY_INLINE_UNKNOWN)
+ ),
conglomerate,
schedulerForTest,
injector
@@ -1838,27 +1848,36 @@ public class ClientQuerySegmentWalkerTest
}
}
- private static VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> makeTimeline(
- final String name,
+ private static DataSegment makeDataSegment(String name)
+ {
+ final SegmentId segmentId = SegmentId.of(name, INTERVAL, VERSION, SHARD_SPEC);
+ return DataSegment.builder(segmentId)
+ .shardSpec(SHARD_SPEC)
+ .size(1L)
+ .build();
+ }
+
+ private static ReferenceCountedSegmentProvider makeReferenceProvider(
final InlineDataSource dataSource
)
{
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline =
+ return ReferenceCountedSegmentProvider.of(
+ new RowBasedSegment<>(
+ Sequences.simple(dataSource.getRows()),
+ dataSource.rowAdapter(),
+ dataSource.getRowSignature()
+ )
+ );
+ }
+ private static VersionedIntervalTimeline<String, DataSegment> makeTimeline(final String name)
+ {
+ final VersionedIntervalTimeline<String, DataSegment> timeline =
new VersionedIntervalTimeline<>(Comparator.naturalOrder());
timeline.add(
INTERVAL,
VERSION,
- SHARD_SPEC.createChunk(
- ReferenceCountedSegmentProvider.wrapSegment(
- new RowBasedSegment<>(
- Sequences.simple(dataSource.getRows()),
- dataSource.rowAdapter(),
- dataSource.getRowSignature()
- ),
- SHARD_SPEC
- )
- )
+ SHARD_SPEC.createChunk(makeDataSegment(name))
);
return timeline;
diff --git a/server/src/test/java/org/apache/druid/server/QueryStackTests.java b/server/src/test/java/org/apache/druid/server/QueryStackTests.java
index 451bdd8d3d9..8e1372add6f 100644
--- a/server/src/test/java/org/apache/druid/server/QueryStackTests.java
+++ b/server/src/test/java/org/apache/druid/server/QueryStackTests.java
@@ -101,6 +101,7 @@ import org.apache.druid.server.scheduling.ManualQueryPrioritizationStrategy;
import org.apache.druid.server.scheduling.NoQueryLaningStrategy;
import org.apache.druid.sql.calcite.util.CacheTestHelperModule;
import org.apache.druid.sql.calcite.util.CacheTestHelperModule.ResultCacheMode;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.utils.JvmUtils;
import org.junit.Assert;
@@ -193,13 +194,14 @@ public class QueryStackTests
}
public static TestClusterQuerySegmentWalker createClusterQuerySegmentWalker(
- Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timelines,
+ Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines,
+ Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders,
QueryRunnerFactoryConglomerate conglomerate,
@Nullable QueryScheduler scheduler,
Injector injector
)
{
- return new TestClusterQuerySegmentWalker(timelines, conglomerate, scheduler, injector.getInstance(EtagProvider.KEY));
+ return new TestClusterQuerySegmentWalker(timelines, referenceProviders, conglomerate, scheduler, injector.getInstance(EtagProvider.KEY));
}
public static LocalQuerySegmentWalker createLocalQuerySegmentWalker(
diff --git a/server/src/test/java/org/apache/druid/server/SegmentManagerTest.java b/server/src/test/java/org/apache/druid/server/SegmentManagerTest.java
index 44067b1047d..fbb63a2d38d 100644
--- a/server/src/test/java/org/apache/druid/server/SegmentManagerTest.java
+++ b/server/src/test/java/org/apache/druid/server/SegmentManagerTest.java
@@ -24,10 +24,8 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Ordering;
import org.apache.druid.java.util.common.Intervals;
-import org.apache.druid.java.util.common.MapUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.query.TableDataSource;
-import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.SegmentLazyLoadFailCallback;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.TestIndex;
@@ -43,7 +41,6 @@ import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.NumberedOverwriteShardSpec;
import org.apache.druid.timeline.partition.PartitionIds;
-import org.joda.time.Interval;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -367,9 +364,9 @@ public class SegmentManagerTest
final Set<String> expectedDataSourceNames = expectedExistingSegments.stream()
.map(DataSegment::getDataSource)
.collect(Collectors.toSet());
- final Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> expectedTimelines = new HashMap<>();
+ final Map<String, VersionedIntervalTimeline<String, DataSegment>> expectedTimelines = new HashMap<>();
for (DataSegment segment : expectedExistingSegments) {
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> expectedTimeline =
+ final VersionedIntervalTimeline<String, DataSegment> expectedTimeline =
expectedTimelines.computeIfAbsent(
segment.getDataSource(),
k -> new VersionedIntervalTimeline<>(Ordering.natural())
@@ -377,15 +374,7 @@ public class SegmentManagerTest
expectedTimeline.add(
segment.getInterval(),
segment.getVersion(),
- segment.getShardSpec().createChunk(
- ReferenceCountedSegmentProvider.wrapSegment(
- new TestSegmentUtils.SegmentForTesting(
- segment.getDataSource(),
- (Interval) segment.getLoadSpec().get("interval"),
- MapUtils.getString(segment.getLoadSpec(), "version")
- ), segment.getShardSpec())
-
- )
+ segment.getShardSpec().createChunk(segment)
);
}
diff --git a/server/src/test/java/org/apache/druid/server/SpecificSegmentsQuerySegmentWalker.java b/server/src/test/java/org/apache/druid/server/SpecificSegmentsQuerySegmentWalker.java
index 5c672757826..585f66fb93c 100644
--- a/server/src/test/java/org/apache/druid/server/SpecificSegmentsQuerySegmentWalker.java
+++ b/server/src/test/java/org/apache/druid/server/SpecificSegmentsQuerySegmentWalker.java
@@ -80,7 +80,8 @@ import java.util.Set;
public class SpecificSegmentsQuerySegmentWalker implements QuerySegmentWalker, Closeable
{
private final QuerySegmentWalker walker;
- private final Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timelines;
+ private final Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines;
+ private final Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders;
private final List<CompleteSegment> segments = new ArrayList<>();
private static final LookupExtractorFactoryContainerProvider LOOKUP_EXTRACTOR_FACTORY_CONTAINER_PROVIDER =
new LookupExtractorFactoryContainerProvider()
@@ -105,7 +106,8 @@ public class SpecificSegmentsQuerySegmentWalker implements QuerySegmentWalker, C
};
public static SpecificSegmentsQuerySegmentWalker createWalker(
- final QueryRunnerFactoryConglomerate conglomerate)
+ final QueryRunnerFactoryConglomerate conglomerate
+ )
{
return createWalker(QueryStackTests.injectorWithLookup(), conglomerate);
}
@@ -123,16 +125,19 @@ public class SpecificSegmentsQuerySegmentWalker implements QuerySegmentWalker, C
final QueryScheduler scheduler
)
{
- Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timelines = new HashMap<>();
+ Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines = new HashMap<>();
+ Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders = new HashMap<>();
NoopServiceEmitter emitter = new NoopServiceEmitter();
ServerConfig serverConfig = new ServerConfig();
return new SpecificSegmentsQuerySegmentWalker(
timelines,
+ referenceProviders,
QueryStackTests.createClientQuerySegmentWalker(
injector,
QueryStackTests.createClusterQuerySegmentWalker(
timelines,
+ referenceProviders,
conglomerate,
scheduler,
injector
@@ -180,10 +185,13 @@ public class SpecificSegmentsQuerySegmentWalker implements QuerySegmentWalker, C
}
public SpecificSegmentsQuerySegmentWalker(
- Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timelines,
- QuerySegmentWalker walker)
+ Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines,
+ Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders,
+ QuerySegmentWalker walker
+ )
{
this.timelines = timelines;
+ this.referenceProviders = referenceProviders;
this.walker = walker;
}
@@ -197,20 +205,17 @@ public class SpecificSegmentsQuerySegmentWalker implements QuerySegmentWalker, C
DataSegment descriptor = completeSegment.getDataSegment();
Segment segment = completeSegment.getSegment();
- final ReferenceCountedSegmentProvider referenceCountingSegment =
- ReferenceCountedSegmentProvider.wrapSegment(
- segment,
- descriptor.getShardSpec()
- );
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline = timelines.computeIfAbsent(
+ final ReferenceCountedSegmentProvider referenceCountingSegment = ReferenceCountedSegmentProvider.of(segment);
+ final VersionedIntervalTimeline<String, DataSegment> timeline = timelines.computeIfAbsent(
descriptor.getDataSource(),
datasource -> new VersionedIntervalTimeline<>(Ordering.natural())
);
timeline.add(
descriptor.getInterval(),
descriptor.getVersion(),
- descriptor.getShardSpec().createChunk(referenceCountingSegment)
+ descriptor.getShardSpec().createChunk(descriptor)
);
+ referenceProviders.put(descriptor, referenceCountingSegment);
segments.add(completeSegment);
return this;
}
diff --git a/server/src/test/java/org/apache/druid/server/TestClusterQuerySegmentWalker.java b/server/src/test/java/org/apache/druid/server/TestClusterQuerySegmentWalker.java
index b5030aed5ed..a170e5888af 100644
--- a/server/src/test/java/org/apache/druid/server/TestClusterQuerySegmentWalker.java
+++ b/server/src/test/java/org/apache/druid/server/TestClusterQuerySegmentWalker.java
@@ -52,6 +52,7 @@ import org.apache.druid.query.spec.SpecificSegmentQueryRunner;
import org.apache.druid.query.spec.SpecificSegmentSpec;
import org.apache.druid.segment.ReferenceCountedSegmentProvider;
import org.apache.druid.segment.SegmentMapFunction;
+import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.partition.PartitionChunk;
@@ -69,14 +70,15 @@ import java.util.Set;
/**
* Mimics the behavior of {@link org.apache.druid.client.CachingClusteredClient} when it queries data servers (like
- * Historicals, which use {@link org.apache.druid.server.coordination.ServerManager}). Used by {@link QueryStackTests}.
+ * Historicals, which use {@link ServerManager}). Used by {@link QueryStackTests}.
*
* This class's logic is like a mashup of those two classes. With the right abstractions, it may be possible to get rid
* of this class and replace it with the production classes.
*/
public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
{
- private final Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timelines;
+ private final Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines;
+ private final Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders;
private final QueryRunnerFactoryConglomerate conglomerate;
@Nullable
private final QueryScheduler scheduler;
@@ -84,7 +86,8 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
public static class TestSegmentsBroker
{
- public final Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timelines = new HashMap<>();
+ public final Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines = new HashMap<>();
+ public final Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders = new HashMap<>();
}
@Inject
@@ -94,16 +97,19 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
@Nullable QueryScheduler scheduler,
EtagProvider etagProvider)
{
- this(testSegmentsBroker.timelines, conglomerate, scheduler, etagProvider);
+ this(testSegmentsBroker.timelines, testSegmentsBroker.referenceProviders, conglomerate, scheduler, etagProvider);
}
TestClusterQuerySegmentWalker(
- Map<String, VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider>> timelines,
+ Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines,
+ Map<DataSegment, ReferenceCountedSegmentProvider> referenceProviders,
QueryRunnerFactoryConglomerate conglomerate,
@Nullable QueryScheduler scheduler,
- EtagProvider etagProvider)
+ EtagProvider etagProvider
+ )
{
this.timelines = timelines;
+ this.referenceProviders = referenceProviders;
this.conglomerate = conglomerate;
this.scheduler = scheduler;
this.etagProvider = etagProvider;
@@ -247,8 +253,12 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
.transform(
segment ->
new SpecificSegmentQueryRunner<>(
- factory.createRunner(closer.register(segmentMapFn.apply(segment.getSegment())
- .orElseThrow())),
+ factory.createRunner(
+ closer.register(
+ segmentMapFn.apply(referenceProviders.get(segment.getSegment()).acquireReference())
+ .orElseThrow()
+ )
+ ),
new SpecificSegmentSpec(segment.getDescriptor())
)
)
@@ -268,15 +278,15 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
private List<WindowedSegment> getSegmentsForTable(final String dataSource, final Interval interval)
{
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline = timelines.get(dataSource);
+ final VersionedIntervalTimeline<String, DataSegment> timeline = timelines.get(dataSource);
if (timeline == null) {
return Collections.emptyList();
} else {
final List<WindowedSegment> retVal = new ArrayList<>();
- for (TimelineObjectHolder<String, ReferenceCountedSegmentProvider> holder : timeline.lookup(interval)) {
- for (PartitionChunk<ReferenceCountedSegmentProvider> chunk : holder.getObject()) {
+ for (TimelineObjectHolder<String, DataSegment> holder : timeline.lookup(interval)) {
+ for (PartitionChunk<DataSegment> chunk : holder.getObject()) {
retVal.add(new WindowedSegment(chunk.getObject(), holder.getInterval(), holder.getVersion(), chunk.getChunkNumber()));
}
}
@@ -287,7 +297,7 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
private List<WindowedSegment> getSegmentsForTable(final String dataSource, final Iterable<SegmentDescriptor> specs)
{
- final VersionedIntervalTimeline<String, ReferenceCountedSegmentProvider> timeline = timelines.get(dataSource);
+ final VersionedIntervalTimeline<String, DataSegment> timeline = timelines.get(dataSource);
if (timeline == null) {
return Collections.emptyList();
@@ -295,7 +305,7 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
final List<WindowedSegment> retVal = new ArrayList<>();
for (SegmentDescriptor spec : specs) {
- final PartitionChunk<ReferenceCountedSegmentProvider> entry = timeline.findChunk(
+ final PartitionChunk<DataSegment> entry = timeline.findChunk(
spec.getInterval(),
spec.getVersion(),
spec.getPartitionNumber()
@@ -309,18 +319,18 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
private static class WindowedSegment
{
- private final ReferenceCountedSegmentProvider segment;
+ private final DataSegment segment;
private final Interval interval;
private final String version;
private final int partitionNumber;
- public WindowedSegment(ReferenceCountedSegmentProvider segment, Interval interval, String version, int partitionNumber)
+ public WindowedSegment(DataSegment segment, Interval interval, String version, int partitionNumber)
{
- if (segment.getBaseSegment().getId() != null) {
- Preconditions.checkArgument(segment.getBaseSegment().getId().getInterval().contains(interval));
+ if (segment.getId() != null) {
+ Preconditions.checkArgument(segment.getId().getInterval().contains(interval));
} else {
Preconditions.checkArgument(
- segment.getBaseSegment().getDataInterval().contains(interval),
+ segment.getInterval().contains(interval),
"Data interval for non-table segment should default to external"
);
}
@@ -330,7 +340,7 @@ public class TestClusterQuerySegmentWalker implements QuerySegmentWalker
this.partitionNumber = partitionNumber;
}
- public ReferenceCountedSegmentProvider getSegment()
+ public DataSegment getSegment()
{
return segment;
}
diff --git a/server/src/test/java/org/apache/druid/server/coordination/SegmentBootstrapperCacheTest.java b/server/src/test/java/org/apache/druid/server/coordination/SegmentCacheBootstrapperCacheTest.java
similarity index 91%
rename from server/src/test/java/org/apache/druid/server/coordination/SegmentBootstrapperCacheTest.java
rename to server/src/test/java/org/apache/druid/server/coordination/SegmentCacheBootstrapperCacheTest.java
index 3e51cf15be4..8c870fcb757 100644
--- a/server/src/test/java/org/apache/druid/server/coordination/SegmentBootstrapperCacheTest.java
+++ b/server/src/test/java/org/apache/druid/server/coordination/SegmentCacheBootstrapperCacheTest.java
@@ -28,7 +28,6 @@ import org.apache.druid.java.util.metrics.StubServiceEmitter;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.TestIndex;
import org.apache.druid.segment.TestSegmentUtils;
-import org.apache.druid.segment.loading.DataSegmentPusher;
import org.apache.druid.segment.loading.LeastBytesUsedStorageLocationSelectorStrategy;
import org.apache.druid.segment.loading.SegmentLoaderConfig;
import org.apache.druid.segment.loading.SegmentLoadingException;
@@ -51,15 +50,18 @@ import java.util.Collections;
import java.util.List;
/**
- * Similar to {@link SegmentBootstrapperTest}. This class includes tests that cover the
+ * Similar to {@link SegmentCacheBootstrapperTest}. This class includes tests that cover the
* storage location layer as well.
*/
-public class SegmentBootstrapperCacheTest
+public class SegmentCacheBootstrapperCacheTest
{
private static final long MAX_SIZE = 1000L;
private static final long SEGMENT_SIZE = 100L;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ private File infoDir;
+ private File cacheDir;
private TestDataSegmentAnnouncer segmentAnnouncer;
private TestDataServerAnnouncer serverAnnouncer;
private SegmentManager segmentManager;
@@ -70,21 +72,23 @@ public class SegmentBootstrapperCacheTest
private ObjectMapper objectMapper;
@Before
- public void setup()
+ public void setup() throws IOException
{
+ infoDir = temporaryFolder.newFolder();
+ cacheDir = temporaryFolder.newFolder();
loaderConfig = new SegmentLoaderConfig()
{
@Override
public File getInfoDir()
{
- return temporaryFolder.getRoot();
+ return infoDir;
}
@Override
public List<StorageLocationConfig> getLocations()
{
return Collections.singletonList(
- new StorageLocationConfig(temporaryFolder.getRoot(), MAX_SIZE, null)
+ new StorageLocationConfig(cacheDir, MAX_SIZE, null)
);
}
};
@@ -130,7 +134,7 @@ public class SegmentBootstrapperCacheTest
segmentManager
);
- final SegmentBootstrapper bootstrapper = new SegmentBootstrapper(
+ final SegmentCacheBootstrapper bootstrapper = new SegmentCacheBootstrapper(
loadDropHandler,
loaderConfig,
segmentAnnouncer,
@@ -158,7 +162,7 @@ public class SegmentBootstrapperCacheTest
segmentManager
);
- final SegmentBootstrapper bootstrapper = new SegmentBootstrapper(
+ final SegmentCacheBootstrapper bootstrapper = new SegmentCacheBootstrapper(
loadDropHandler,
loaderConfig,
segmentAnnouncer,
@@ -187,8 +191,7 @@ public class SegmentBootstrapperCacheTest
String version = "segment-" + i;
DataSegment segment = TestSegmentUtils.makeSegment("test", version, SEGMENT_SIZE);
cacheManager.storeInfoFile(segment);
- String storageDir = DataSegmentPusher.getDefaultStorageDir(segment, false);
- File segmentDir = new File(temporaryFolder.getRoot(), storageDir);
+ File segmentDir = new File(cacheDir, segment.getId().toString());
new TestSegmentUtils.TestLoadSpec((int) SEGMENT_SIZE, version).loadSegment(segmentDir);
expectedSegments.add(segment);
}
@@ -199,7 +202,7 @@ public class SegmentBootstrapperCacheTest
segmentManager
);
... 555 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org