You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "zachjsh (via GitHub)" <gi...@apache.org> on 2023/11/22 22:12:02 UTC
[PR] Retreive unused segments (druid)
zachjsh opened a new pull request, #15415:
URL: https://github.com/apache/druid/pull/15415
### Description
This PR has:
- [ ] been self-reviewed.
- [ ] using the [concurrency checklist](https://github.com/apache/druid/blob/master/dev/code-review/concurrency.md) (Remove this item if the PR doesn't have any relation to concurrency.)
- [ ] added documentation for new or modified features or behaviors.
- [ ] a release note entry in the PR description.
- [ ] added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
- [ ] added or updated version, license, or notice information in [licenses.yaml](https://github.com/apache/druid/blob/master/dev/license.md)
- [ ] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
- [ ] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
- [ ] added integration tests.
- [ ] been tested in a test Druid cluster.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422163407
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
if (compareAsString) {
appendConditionForIntervalsAndMatchMode(sb, intervals, matchMode, connector);
}
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
if (compareAsString) {
appendConditionForIntervalsAndMatchMode(sb, intervals, matchMode, connector);
}
+ if (sortOrder != null) {
+ sb.append(StringUtils.format(" ORDER BY start %2$s, %1$send%1$s %2$s",
+ connector.getQuoteString(),
+ sortOrder.toString()));
+ }
final Query<Map<String, Object>> sql = handle
- .createQuery(StringUtils.format(sb.toString(), dbTables.getSegmentsTable()))
+ .createQuery(StringUtils.format(
+ sb.toString(),
+ dbTables.getSegmentsTable(),
+ lastSegmentId == null
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on PR #15415:
URL: https://github.com/apache/druid/pull/15415#issuecomment-1846431372
For performance-reasons, I think it'd be best if we don't use `OFFSET` on the segments table. Using `OFFSET` to page through results in a cluster with large number of segments will become a bottleneck. An alternative idea is to leverage the indices `id`, `start` and `end` built for the segments table along with the uniqueness of segment `id` via the primary key constraint, we can guarantee a stable sort and page through batched results from a client.
Instead of an `OFFSET` based paginated query:
```sql
SELECT "start", "end", "id"
FROM druid_segments
WHERE dataSource = 'foo' AND "start" >= '2023-01-01' AND "end" < '2024-01-01'
ORDER BY 1, 2
LIMIT 100
OFFSET 10000
```
We can do a cursor-based query:
```sql
SELECT "start", "end", "id"
FROM druid_segments
WHERE dataSource = 'foo' AND "start" >= '2023-01-01' AND "end" < '2024-01-01' AND id > 'foo_2023-02-24T07:00:00.000Z_2023-02-24T08:00:00.000Z_2023-11-20T23:04:26.856Z'
ORDER BY 1, 2, 3
LIMIT 100
```
The execution explain plans for these two queries are both `simple` from `EXPLAIN PLAN`, but the first query has to read, count and then discard results because of `OFFSET`, so it'll take longer especially for larger values of `OFFSET`. With the second query, an API caller should pass in the last segment id from a previous batch (if any); they can also narrow down the search interval as they batch through results as another optimization.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422926420
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -955,6 +956,50 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* an optionally
+ * specified interval. If the interval specified is null, this method will retrieve all unused segments.
+ *
+ * This call does not return any information about realtime segments.
+ *
+ * @param datasource The name of the datasource
+ * @param interval The intervals to search over
Review Comment:
fixed
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1206,23 +1206,86 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
markAllSegmentsUnused(new HashSet<>(segments));
- final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsLimitAndOffset(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsNoLimitNoOffset() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsLimitAndOffset(
+ ImmutableList.of(),
+ null,
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndOffset() throws IOException
Review Comment:
fixed
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1206,23 +1206,86 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
markAllSegmentsUnused(new HashSet<>(segments));
- final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsLimitAndOffset(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsNoLimitNoOffset() throws IOException
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1402833078
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
Review Comment:
nit: all these args could be `final`
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -596,6 +661,44 @@ private Response getServedSegmentsInInterval(
}
}
+ private Response getUnusedSegmentsInInterval(
+ Iterator<DataSegment> unusedDataSegments,
+ boolean full,
+ Predicate<Interval> intervalFilter,
+ final Comparator<Interval> comparator
+ )
+ {
+ if (full) {
Review Comment:
IMO, it'd be better to break these into two separate small functions:
1. `getUnusedSegmentsInInterval`
2. `getUnusedSegmentsStatsInInterval`
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
+ @QueryParam("simple") String simple,
+ @QueryParam("full") String full,
Review Comment:
Could we include the API in the public-facing docs https://github.com/apache/druid/blob/master/docs/api-reference/legacy-metadata-api.md?
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,25 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over all un-used segments of given a datasource over given interval.
Review Comment:
```suggestion
* Returns an iterable to go over un-used segments for a given datasource over an optional interval.
```
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
Review Comment:
I see we're following the same API patterns in this file written over a decade ago, but I'm wondering if it'd be better to move away from the pattern where an API doing multiple things and returning different shapes of responses depending on the parameters specified. For example, in this case, IMO it'd be cleaner to have two different sets of API endpoints each serving only one functionality:
1. `getIntervalsWithUnusedSegments()`
2. `getUnusedSegmentsInInterval()` where the interval is optional similar to other parameters
What do you think?
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
+ @QueryParam("simple") String simple,
+ @QueryParam("full") String full,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("offset") @Nullable Integer offset
+ )
+ {
+ Preconditions.checkArgument(limit == null || limit > 0, "limit must be > 0");
Review Comment:
Would suggest throwing `InvalidInput` DruidException instead of these pre-conditions
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
+ @QueryParam("simple") String simple,
Review Comment:
Do we need two `String` params for `simple` and `full`? Or would a single `Boolean simple` suffice? (Mostly curious because I see this is an existing pattern, so I don't feel strongly either way)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1414399882
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
+ @QueryParam("simple") String simple,
Review Comment:
removed
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
+ @QueryParam("simple") String simple,
+ @QueryParam("full") String full,
Review Comment:
added
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1415093465
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,51 @@
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("offset") @Nullable Integer offset
+ )
+ {
+ if (dataSource != null && dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSource name must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("limit must be > 0");
+ }
+ if (offset != null && offset < 0) {
+ throw InvalidInput.exception("offset must be > 0");
+ }
+ if (dataSource == null || dataSource.isEmpty()) {
+ return Response.status(Response.Status.OK).entity(ImmutableList.of()).build();
+ }
+
+ final Interval theInterval = interval != null ? Intervals.of(interval.replace('_', '/')) : null;
+ Iterable<DataSegment> unusedSegments = segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ dataSource,
+ theInterval,
+ limit,
+ offset
+ );
+
+ final Function<DataSegment, Iterable<ResourceAction>> raGenerator = segment -> Collections.singletonList(
+ AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSource()));
+
+ final Iterable<DataSegment> authorizedSegments =
+ AuthorizationUtils.filterAuthorizedResources(req, unusedSegments, raGenerator, authorizerMapper);
Review Comment:
## User-controlled bypass of sensitive method
Sensitive method may not be executed depending on a [this condition](1), which flows from [user-controlled value](2).
[Show more details](https://github.com/apache/druid/security/code-scanning/6026)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1402843362
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
Review Comment:
I see we're following the same API patterns in this file written over a decade ago, but I'm wondering if it'd be better to move away from the pattern where an API does multiple things and returns different shapes of responses depending on the parameters specified. For example, in this case, IMO it'd be cleaner to have two different sets of API endpoints each serving only one functionality:
1. `getIntervalsWithUnusedSegments()`
2. `getUnusedSegmentsInInterval()` where the interval is optional similar to other parameters
What do you think?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1416385345
##########
server/src/test/java/org/apache/druid/server/http/MetadataResourceTest.java:
##########
@@ -236,6 +246,117 @@ public void testGetAllSegmentsIncludingRealtime()
Assert.assertEquals(new SegmentStatusInCluster(realTimeSegments[1], false, null, 40L, true), resultList.get(5));
}
+ @Test
+ public void testGetUnusedSegmentsInDataSource()
+ {
+ Mockito.doAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .when(segmentsMetadataManager)
+ .iterateAllUnusedSegmentsForDatasource(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any());
+
+ // test with null datasource name - fails with expected bad datasource name error
+ DruidException e = Assert.assertThrows(
+ DruidException.class,
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, null, null, -1, null)
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals("dataSource name must be non-empty", e.getMessage());
+
+ // test with empty datasource name - fails with expected bad datasource name error
+ e = Assert.assertThrows(
Review Comment:
fixed
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1208,12 +1208,64 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimit() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ ImmutableList.of(),
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndOffset() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(2033, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ int offset = 10;
+ List<DataSegment> expectedSegments = segments.stream().sorted((Comparator<DataSegment>) (o1, o2) -> {
+ long o1Start = o1.getInterval().getStartMillis();
+ long o2Start = o2.getInterval().getStartMillis();
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1414401131
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
Review Comment:
updated, now there are 3 apis
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1419418889
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -956,12 +956,30 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* any interval
+ * in a particular collection of intervals. If the collection of intervals is empty, this method will retrieve all
+ * unused segments.
+ *
+ * This call does not return any information about realtime segments.
+ *
+ * @param datasource The name of the datasource
+ * @param interval The intervals to search over
+ * @param limit The limit of segments to return
+ * @param offset The offset to use when retrieving matching segments.
+ * @param orderByStartEnd Specifies the order with which to return the matching segments by start time, end time. A
Review Comment:
An enum type would be a better choice for the direction of order by? Similar to `OrderByColumnSpec#Direction`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422161587
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
+ * @param lastSegmentId the last segment id from which to search for results. All segments returned are >
+ * this segment lexigraphically if sortOrder is null or ASC, or < this segment
+ * lexigraphically if sortOrder is DESC.
+ * @param sortOrder Specifies the order with which to return the matching segments by start time, end time.
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
+ * @param lastSegmentId the last segment id from which to search for results. All segments returned are >
+ * this segment lexigraphically if sortOrder is null or ASC, or < this segment
+ * lexigraphically if sortOrder is DESC.
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SortOrder.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.metadata;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.java.util.common.StringUtils;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+/**
+ * specifies the sort order when doing metadata store queries.
+ */
+public enum SortOrder
+{
+ ASC("ASC"),
+
+ DESC("DESC");
+
+ private String value;
+
+ SortOrder(String value)
+ {
+ this.value = value;
+ }
+
+ @Override
+ @JsonValue
+ public String toString()
+ {
+ return String.valueOf(value);
+ }
+
+ @JsonCreator
+ public static SortOrder fromValue(String value)
+ {
+ for (SortOrder b : SortOrder.values()) {
+ if (String.valueOf(b.value).equalsIgnoreCase(String.valueOf(value))) {
+ return b;
+ }
+ }
+ throw InvalidInput.exception(StringUtils.format(
+ "Unexpected value [%s] for SortOrder. Possible values are: %s",
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/storage/derby/DerbyConnector.java:
##########
@@ -100,6 +100,15 @@ public String getQuoteString()
return QUOTE_STRING;
}
+ /**
+ * @return the string offset clause
+ */
+ @Override
+ public String getOffsetClause(int offset)
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422162159
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,49 @@ public Response getUsedSegmentsInDataSourceForIntervals(
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("lastSegmentId") @Nullable final String lastSegmentId,
+ @QueryParam("sortOrder") @Nullable final String sortOrder
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSourceName must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("limit must be > 0");
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -955,6 +956,49 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* any interval
+ * in a particular collection of intervals. If the collection of intervals is empty, this method will retrieve all
Review Comment:
fixed
##########
server/src/test/java/org/apache/druid/metadata/SortOrderTest.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.metadata;
+
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SortOrderTest
+{
+
+ @Test
+ public void test_asc()
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422162532
##########
server/src/test/java/org/apache/druid/metadata/SortOrderTest.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.metadata;
+
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SortOrderTest
+{
+
+ @Test
+ public void test_asc()
+ {
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("asc"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("asc").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("ASC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("ASC").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("AsC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("AsC").toString());
+ }
+
+ @Test
+ public void test_desc()
Review Comment:
fixed
##########
server/src/test/java/org/apache/druid/metadata/SortOrderTest.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.metadata;
+
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SortOrderTest
+{
+
+ @Test
+ public void test_asc()
+ {
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("asc"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("asc").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("ASC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("ASC").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("AsC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("AsC").toString());
+ }
+
+ @Test
+ public void test_desc()
+ {
+ Assert.assertEquals(SortOrder.DESC, SortOrder.fromValue("desc"));
+ Assert.assertEquals("DESC", SortOrder.fromValue("desc").toString());
+ Assert.assertEquals(SortOrder.DESC, SortOrder.fromValue("DESC"));
+ Assert.assertEquals("DESC", SortOrder.fromValue("DESC").toString());
+ Assert.assertEquals(SortOrder.DESC, SortOrder.fromValue("DesC"));
+ Assert.assertEquals("DESC", SortOrder.fromValue("DesC").toString());
+ }
+
+ @Test
+ public void test_invalid()
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1416231345
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -127,15 +127,21 @@ public CloseableIterator<DataSegment> retrieveUsedSegments(
*
* This call does not return any information about realtime segments.
*
+ * @param dataSource The name of the datasource
+ * @param intervals The intervals to search over
+ * @param limit The limit of segments to return
+ * @param offset The offset to use when retreiving matching segments. Note: This is only applied if the size of
+ * intervals is less than {@link #MAX_INTERVALS_PER_BATCH}
Review Comment:
```suggestion
* @param offset The offset to use when retrieving matching segments. Note that offset is only applied to a
* single batch - i.e., when the number of intervals is less than {@link #MAX_INTERVALS_PER_BATCH}.
* For multiple batches, the offset parameter is ignored.
```
##########
server/src/main/java/org/apache/druid/metadata/SQLMetadataConnector.java:
##########
@@ -133,6 +133,14 @@ public String getCollation()
*/
public abstract String getQuoteString();
+ /**
+ * @return the string offset clause
+ */
+ public String getOffsetClause(int offset)
+ {
+ return StringUtils.format(" OFFSET %s", offset);
Review Comment:
```suggestion
return StringUtils.format(" OFFSET %d", offset);
```
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -3050,19 +3106,20 @@ private List<DataSegment> createAndGetUsedYearSegments(final int startYear, fina
private ImmutableList<DataSegment> retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
Review Comment:
Should this method be renamed to include offset in its name, or perhaps could use a simpler name?
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1208,12 +1208,64 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimit() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ ImmutableList.of(),
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndOffset() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(2033, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ int offset = 10;
+ List<DataSegment> expectedSegments = segments.stream().sorted((Comparator<DataSegment>) (o1, o2) -> {
+ long o1Start = o1.getInterval().getStartMillis();
+ long o2Start = o2.getInterval().getStartMillis();
+ if (o1Start < o2Start) {
+ return -1;
+ } else if (o1Start > o2Start) {
+ return 1;
+ } else {
+ long o1End = o1.getInterval().getEndMillis();
+ long o2End = o2.getInterval().getEndMillis();
+ if (o1End < o2End) {
+ return -1;
+ }
+ return o1End > o2End
+ ? 1
+ : 0;
+ }
+ })
+ .skip(offset)
+ .collect(Collectors.toList());
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ ImmutableList.of(),
+ null,
+ offset
+ );
+ Assert.assertEquals(expectedSegments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(expectedSegments.containsAll(actualUnusedSegments));
+ }
+
Review Comment:
For test coverage, can we also please include new or extend existing tests for the following scenarios:
1. non-empty interval, non-null limit and non-null offset
2. multiple intervals, non-null limit and non-null offset
3. multiple intervals exceeding `MAX_INTERVALS_PER_BATCH`, non-null limit and non-null offset (the offset in this case would be ignored)
##########
server/src/main/java/org/apache/druid/metadata/storage/derby/DerbyConnector.java:
##########
@@ -100,6 +100,15 @@ public String getQuoteString()
return QUOTE_STRING;
}
+ /**
+ * @return the string offset clause
+ */
+ @Override
+ public String getOffsetClause(int offset)
+ {
+ return StringUtils.format(" OFFSET %s ROWS", offset);
Review Comment:
```suggestion
return StringUtils.format(" OFFSET %d ROWS", offset);
```
##########
server/src/test/java/org/apache/druid/server/http/MetadataResourceTest.java:
##########
@@ -236,6 +246,117 @@ public void testGetAllSegmentsIncludingRealtime()
Assert.assertEquals(new SegmentStatusInCluster(realTimeSegments[1], false, null, 40L, true), resultList.get(5));
}
+ @Test
+ public void testGetUnusedSegmentsInDataSource()
+ {
+ Mockito.doAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .when(segmentsMetadataManager)
+ .iterateAllUnusedSegmentsForDatasource(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any());
+
+ // test with null datasource name - fails with expected bad datasource name error
+ DruidException e = Assert.assertThrows(
+ DruidException.class,
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, null, null, -1, null)
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals("dataSource name must be non-empty", e.getMessage());
+
+ // test with empty datasource name - fails with expected bad datasource name error
+ e = Assert.assertThrows(
Review Comment:
Ditto here and everywhere below
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1208,12 +1208,64 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimit() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ ImmutableList.of(),
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndOffset() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(2033, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ int offset = 10;
+ List<DataSegment> expectedSegments = segments.stream().sorted((Comparator<DataSegment>) (o1, o2) -> {
+ long o1Start = o1.getInterval().getStartMillis();
+ long o2Start = o2.getInterval().getStartMillis();
Review Comment:
Do we actually need this custom comparator? `createAndGetUsedYearSegments()` already returns a list of segments sorted by start date. So I think this should suffice:
`final List<DataSegment> expectedSegments = segments.stream().skip(offset).collect(Collectors.toList());`
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1208,12 +1208,64 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimit() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ ImmutableList.of(),
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndOffset() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(2033, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ int offset = 10;
+ List<DataSegment> expectedSegments = segments.stream().sorted((Comparator<DataSegment>) (o1, o2) -> {
Review Comment:
nit: the cast is redundant
```suggestion
final List<DataSegment> expectedSegments = segments.stream().sorted((o1, o2) -> {
```
##########
server/src/test/java/org/apache/druid/server/http/MetadataResourceTest.java:
##########
@@ -236,6 +246,117 @@ public void testGetAllSegmentsIncludingRealtime()
Assert.assertEquals(new SegmentStatusInCluster(realTimeSegments[1], false, null, 40L, true), resultList.get(5));
}
+ @Test
+ public void testGetUnusedSegmentsInDataSource()
+ {
+ Mockito.doAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .when(segmentsMetadataManager)
+ .iterateAllUnusedSegmentsForDatasource(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any());
+
+ // test with null datasource name - fails with expected bad datasource name error
+ DruidException e = Assert.assertThrows(
+ DruidException.class,
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, null, null, -1, null)
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals("dataSource name must be non-empty", e.getMessage());
Review Comment:
You could replace this with the exception helper matcher:
```suggestion
DruidExceptionMatcher.invalidInput().expectMessageIs(
"dataSource name must be non-empty"
).assertThrowsAndMatches(
() -> metadataResource.getUnusedSegmentsInDataSource(request, "", null, -1, null)
);
```
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1208,12 +1208,64 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimit() throws IOException
Review Comment:
```suggestion
public void testRetrieveUnusedSegmentsUsingNoIntervalsNoLimitNoOffset() throws IOException
```
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +336,48 @@ public Response getUsedSegmentsInDataSourceForIntervals(
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("offset") @Nullable Integer offset
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSource name must be non-empty");
Review Comment:
To match the path param name as-is:
```suggestion
throw InvalidInput.exception("dataSourceName must be non-empty");
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422161060
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
Review Comment:
added
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
if (compareAsString) {
appendConditionForIntervalsAndMatchMode(sb, intervals, matchMode, connector);
}
+ if (sortOrder != null) {
+ sb.append(StringUtils.format(" ORDER BY start %2$s, %1$send%1$s %2$s",
Review Comment:
thanks, fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1414399541
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,25 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over all un-used segments of given a datasource over given interval.
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh merged PR #15415:
URL: https://github.com/apache/druid/pull/15415
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422160604
##########
docs/api-reference/legacy-metadata-api.md:
##########
@@ -248,6 +248,12 @@ Returns full segment metadata for a specific segment in the cluster.
Return the tiers that a datasource exists in.
+`GET /druid/coordinator/v1/datasources/{dataSourceName}/unusedSegments?interval={interval}&limit={limit}&lastSegmentId={lastSegmentId}&sortOrder={sortOrder}`
+
+Returns a list of unused segments for a datasource in the cluster contained within an optionally specified interval.
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SQLMetadataConnector.java:
##########
@@ -133,6 +133,14 @@ public String getCollation()
*/
public abstract String getQuoteString();
+ /**
+ * @return the string offset clause
+ */
+ public String getOffsetClause(int offset)
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422162858
##########
server/src/main/java/org/apache/druid/metadata/SortOrder.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.metadata;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.java.util.common.StringUtils;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+/**
+ * specifies the sort order when doing metadata store queries.
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on PR #15415:
URL: https://github.com/apache/druid/pull/15415#issuecomment-1848427855
> For performance-reasons, I think it'd be best if we don't use `OFFSET` on the segments table. Using `OFFSET` to page through results in a cluster with large number of segments will become a bottleneck. An alternative idea is to leverage the indices `id`, `start` and `end` built for the segments table along with the uniqueness of segment `id` via the primary key constraint, we can guarantee a stable sort and page through batched results from a client.
>
> Instead of an `OFFSET` based paginated query:
>
> ```sql
> SELECT "start", "end", "id"
> FROM druid_segments
> WHERE dataSource = 'foo' AND "start" >= '2023-01-01' AND "end" < '2024-01-01'
> ORDER BY 1, 2
> LIMIT 100
> OFFSET 10000
> ```
>
> We can do a cursor-based query:
>
> ```sql
> SELECT "start", "end", "id"
> FROM druid_segments
> WHERE dataSource = 'foo' AND "start" >= '2023-01-01' AND "end" < '2024-01-01' AND id > 'foo_2023-02-24T07:00:00.000Z_2023-02-24T08:00:00.000Z_2023-11-20T23:04:26.856Z'
> ORDER BY 1, 2, 3
> LIMIT 100
> ```
>
> The execution plans for these two queries are both `simple` from `EXPLAIN PLAN`, but the first query has to read, count and then discard results because of `OFFSET`, so it'll take longer especially for larger values of `OFFSET`. With the second query, an API caller should pass in the last segment id from a previous batch (if any); they can also narrow down the search interval as they batch through results as another optimization.
Good suggestion, updated.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422758621
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -3048,21 +3159,23 @@ private List<DataSegment> createAndGetUsedYearSegments(final int startYear, fina
return segments;
}
- private ImmutableList<DataSegment> retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ private ImmutableList<DataSegment> retrieveUnusedSegmentsUsingMultipleIntervalsLimitAndOffset(
Review Comment:
There's no offset anymore; maybe we can simply call this method `retrieveUnusedSegments`?
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1206,23 +1206,86 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
markAllSegmentsUnused(new HashSet<>(segments));
- final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsLimitAndOffset(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsNoLimitNoOffset() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsLimitAndOffset(
+ ImmutableList.of(),
+ null,
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndOffset() throws IOException
Review Comment:
Offset -> last segment id here and below
```suggestion
public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndNoLastSegmentId() throws IOException
```
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1206,23 +1206,86 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
markAllSegmentsUnused(new HashSet<>(segments));
- final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsLimitAndOffset(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsNoLimitNoOffset() throws IOException
Review Comment:
Adjust the test method names since there's no offset?
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -955,6 +956,50 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* an optionally
+ * specified interval. If the interval specified is null, this method will retrieve all unused segments.
+ *
+ * This call does not return any information about realtime segments.
+ *
+ * @param datasource The name of the datasource
+ * @param interval The intervals to search over
+ * @param limit The limit of segments to return
Review Comment:
```suggestion
* @param limit an optional maximum number of results to return. If none is specified, the results are not limited.
```
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -955,6 +956,50 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* an optionally
+ * specified interval. If the interval specified is null, this method will retrieve all unused segments.
+ *
+ * This call does not return any information about realtime segments.
+ *
+ * @param datasource The name of the datasource
+ * @param interval The intervals to search over
Review Comment:
```suggestion
* @param interval an optional interval to search over.
```
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,49 @@ public Response getUsedSegmentsInDataSourceForIntervals(
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("lastSegmentId") @Nullable final String lastSegmentId,
+ @QueryParam("sortOrder") @Nullable final String sortOrder
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSourceName must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("Invalid limit[%s] specified. Limit must be > 0", limit);
+ }
+
+ SortOrder theSortOrder = sortOrder == null ? null : SortOrder.fromValue(sortOrder);
+
Review Comment:
Could we also add a validation check for `lastSegmentId` if it's non-nul? We could use `org.apache.druid.timeline.SegmentId#tryParse` utility to validate the id and throw an invalid input exception if the result of the `tryParse` is null (the id failed to parse)
##########
server/src/test/java/org/apache/druid/server/http/MetadataResourceTest.java:
##########
@@ -236,6 +248,119 @@ public void testGetAllSegmentsIncludingRealtime()
Assert.assertEquals(new SegmentStatusInCluster(realTimeSegments[1], false, null, 40L, true), resultList.get(5));
}
+ @Test
+ public void testGetUnusedSegmentsInDataSource()
+ {
+ Mockito.doAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .when(segmentsMetadataManager)
+ .iterateAllUnusedSegmentsForDatasource(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any());
+
+ // test with null datasource name - fails with expected bad datasource name error
+ DruidExceptionMatcher.invalidInput().expectMessageIs(
+ "dataSourceName must be non-empty"
+ ).assertThrowsAndMatches(
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, null, null, null, null, null)
+ );
+
+ // test with empty datasource name - fails with expected bad datasource name error
+ DruidExceptionMatcher.invalidInput().expectMessageIs(
+ "dataSourceName must be non-empty"
+ ).assertThrowsAndMatches(
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, "", null, null, null, null)
+ );
+
+ // test invalid datasource - returns empty segments
+ Response response = metadataResource.getUnusedSegmentsInDataSource(
+ request,
+ "invalid_datasource",
+ null,
+ null,
+ null,
+ null
+ );
+ List<DataSegment> resultList = extractResponseList(response);
+ Assert.assertTrue(resultList.isEmpty());
+
+ // test valid datasource with bad limit - fails with expected bad limit message
+ DruidExceptionMatcher.invalidInput().expectMessageIs(
+ StringUtils.format("Invalid limit[%s] specified. Limit must be > 0", -1)
+ ).assertThrowsAndMatches(
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, null, -1, null, null)
+ );
+
+ // test valid datasource - returns all unused segments for that datasource
+ response = metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, null, null, null, null);
+
+ resultList = extractResponseList(response);
+ Assert.assertEquals(Arrays.asList(segments), resultList);
+
+ // test valid datasource with interval filter - returns all unused segments for that datasource within interval
+ int numDays = 2;
+ String interval = SEGMENT_START_INTERVAL + "_P" + numDays + "D";
+ response = metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, interval, null, null, null);
+
+ resultList = extractResponseList(response);
+ Assert.assertEquals(NUM_PARTITIONS * numDays, resultList.size());
+ Assert.assertEquals(Arrays.asList(segments[0], segments[1], segments[2], segments[3]), resultList);
+
+ // test valid datasource with interval filter and limit - returns unused segments for that datasource within
+ // interval upto limit
+ int limit = 3;
+ response = metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, interval, limit, null, null);
+
+ resultList = extractResponseList(response);
+ Assert.assertEquals(limit, resultList.size());
+ Assert.assertEquals(Arrays.asList(segments[0], segments[1], segments[2]), resultList);
+
+ // test valid datasource with interval filter limit and offset - returns unused segments for that datasource within
+ // interval upto limit starting at offset
Review Comment:
```suggestion
// test valid datasource with interval filter limit and last segment id - returns unused segments for that datasource within
// interval upto limit starting at last segment id
```
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,49 @@ public Response getUsedSegmentsInDataSourceForIntervals(
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("lastSegmentId") @Nullable final String lastSegmentId,
+ @QueryParam("sortOrder") @Nullable final String sortOrder
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSourceName must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("Invalid limit[%s] specified. Limit must be > 0", limit);
+ }
+
+ SortOrder theSortOrder = sortOrder == null ? null : SortOrder.fromValue(sortOrder);
+
+ final Interval theInterval = interval != null ? Intervals.of(interval.replace('_', '/')) : null;
+ Iterable<DataSegment> unusedSegments = segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ dataSource,
+ theInterval,
+ limit,
+ lastSegmentId,
+ theSortOrder
+ );
+
+ final Function<DataSegment, Iterable<ResourceAction>> raGenerator = segment -> Collections.singletonList(
+ AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSource()));
+
+ final Iterable<DataSegment> authorizedSegments =
+ AuthorizationUtils.filterAuthorizedResources(req, unusedSegments, raGenerator, authorizerMapper);
+
+ // sort by earliest start interval first, then end interval. DataSegment are sorted in this same order due to
Review Comment:
Do we need this comment here since the sorting actually happens inside `iterateAllUnusedSegmentsForDatasource`? Also, this is missing last segment id in the sort by criteria
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1414400261
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -410,7 +414,74 @@ public Response getServedSegmentsInInterval(
}
return Response.ok(segmentIds).build();
}
- return getServedSegmentsInInterval(dataSourceName, full != null, theInterval::contains);
+ return getServedSegmentsInInterval(dataSource, full != null, theInterval::contains);
+ }
+
+ @GET
+ @Path("/{dataSourceName}/unused/intervals")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ResourceFilters(DatasourceResourceFilter.class)
+ public Response getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ @PathParam("dataSourceName") String dataSourceName,
+ @QueryParam("simple") String simple,
+ @QueryParam("full") String full,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("offset") @Nullable Integer offset
+ )
+ {
+ Preconditions.checkArgument(limit == null || limit > 0, "limit must be > 0");
Review Comment:
good suggestion, fixed
##########
server/src/main/java/org/apache/druid/server/http/DataSourcesResource.java:
##########
@@ -596,6 +661,44 @@ private Response getServedSegmentsInInterval(
}
}
+ private Response getUnusedSegmentsInInterval(
+ Iterator<DataSegment> unusedDataSegments,
+ boolean full,
+ Predicate<Interval> intervalFilter,
+ final Comparator<Interval> comparator
+ )
+ {
+ if (full) {
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422989934
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,51 @@
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("lastSegmentId") @Nullable final String lastSegmentId,
+ @QueryParam("sortOrder") @Nullable final String sortOrder
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSourceName must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("Invalid limit[%s] specified. Limit must be > 0", limit);
+ }
+
+ if (lastSegmentId != null && SegmentId.tryParse(dataSource, lastSegmentId) == null) {
+ throw InvalidInput.exception("Invalid lastSegmentId[%s] specified.", lastSegmentId);
+ }
+
+ SortOrder theSortOrder = sortOrder == null ? null : SortOrder.fromValue(sortOrder);
+
+ final Interval theInterval = interval != null ? Intervals.of(interval.replace('_', '/')) : null;
+ Iterable<DataSegment> unusedSegments = segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ dataSource,
+ theInterval,
+ limit,
+ lastSegmentId,
+ theSortOrder
+ );
+
+ final Function<DataSegment, Iterable<ResourceAction>> raGenerator = segment -> Collections.singletonList(
+ AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSource()));
+
+ final Iterable<DataSegment> authorizedSegments =
+ AuthorizationUtils.filterAuthorizedResources(req, unusedSegments, raGenerator, authorizerMapper);
Review Comment:
## User-controlled bypass of sensitive method
Sensitive method may not be executed depending on a [this condition](1), which flows from [user-controlled value](2).
[Show more details](https://github.com/apache/druid/security/code-scanning/6330)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "jon-wei (via GitHub)" <gi...@apache.org>.
jon-wei commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1417891246
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,25 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
+ * @param offset the offset from which to search for results.
+ */
+ Iterable<DataSegment> iterateAllUnusedSegmentsForDatasource(
+ String datasource,
+ @Nullable Interval interval,
+ @Nullable Integer limit,
Review Comment:
I think it might be a good idea to go ahead and add a sort order now too
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "abhishekrb19 (via GitHub)" <gi...@apache.org>.
abhishekrb19 commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1421817633
##########
docs/api-reference/legacy-metadata-api.md:
##########
@@ -248,6 +248,12 @@ Returns full segment metadata for a specific segment in the cluster.
Return the tiers that a datasource exists in.
+`GET /druid/coordinator/v1/datasources/{dataSourceName}/unusedSegments?interval={interval}&limit={limit}&lastSegmentId={lastSegmentId}&sortOrder={sortOrder}`
+
+Returns a list of unused segments for a datasource in the cluster contained within an optionally specified interval.
Review Comment:
To make the API behavior clear in the absence of all the optional parameters, maybe specify what the defaults for the no interval, no limit, etc. Also, it'd be good to include an example for these params, so a user knows what to specify for params like `sortOrder` (wish we had an open API spec in Druid :)).
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,49 @@ public Response getUsedSegmentsInDataSourceForIntervals(
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("lastSegmentId") @Nullable final String lastSegmentId,
+ @QueryParam("sortOrder") @Nullable final String sortOrder
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSourceName must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("limit must be > 0");
Review Comment:
```suggestion
throw InvalidInput.exception("Invalid limit[%s] specified. Limit must be > 0", limit);
```
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
if (compareAsString) {
appendConditionForIntervalsAndMatchMode(sb, intervals, matchMode, connector);
}
+ if (sortOrder != null) {
+ sb.append(StringUtils.format(" ORDER BY start %2$s, %1$send%1$s %2$s",
Review Comment:
To guarantee stable pagination, we should also include `id` here in the `ORDER BY` clause if it's specified; otherwise, the result set can be garbled between multiple pages
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
Review Comment:
Since this is an interface method, could you specify what the default behavior should be for these other optional parameters?
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
Review Comment:
```suggestion
* @param interval an optional interval to search over. If none is specified, {@link org.apache.druid.java.util.common.Intervals#ETERNITY}
* should be used.
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
+ * @param lastSegmentId the last segment id from which to search for results. All segments returned are >
+ * this segment lexigraphically if sortOrder is null or ASC, or < this segment
+ * lexigraphically if sortOrder is DESC.
Review Comment:
```suggestion
* @param lastSegmentId the last segment id from which to search for results. All segments returned are >
* this segment lexigraphically if sortOrder is null or {@link SortOrder#ASC}, or < this segment
* lexigraphically if sortOrder is {@link SortOrder#DESC}.
```
##########
server/src/main/java/org/apache/druid/metadata/SQLMetadataConnector.java:
##########
@@ -133,6 +133,14 @@ public String getCollation()
*/
public abstract String getQuoteString();
+ /**
+ * @return the string offset clause
+ */
+ public String getOffsetClause(int offset)
Review Comment:
Unused offset method, so remove it
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -955,6 +956,49 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* any interval
+ * in a particular collection of intervals. If the collection of intervals is empty, this method will retrieve all
Review Comment:
hmm, copy-pasta here and below? This method only takes a single interval, right? (not a collection)
##########
server/src/test/java/org/apache/druid/metadata/SortOrderTest.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.metadata;
+
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SortOrderTest
+{
+
+ @Test
+ public void test_asc()
+ {
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("asc"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("asc").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("ASC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("ASC").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("AsC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("AsC").toString());
+ }
+
+ @Test
+ public void test_desc()
Review Comment:
```suggestion
public void testDesc()
```
##########
server/src/test/java/org/apache/druid/metadata/SortOrderTest.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.metadata;
+
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SortOrderTest
+{
+
+ @Test
+ public void test_asc()
Review Comment:
```suggestion
public void testAsc()
```
##########
server/src/main/java/org/apache/druid/metadata/storage/derby/DerbyConnector.java:
##########
@@ -100,6 +100,15 @@ public String getQuoteString()
return QUOTE_STRING;
}
+ /**
+ * @return the string offset clause
+ */
+ @Override
+ public String getOffsetClause(int offset)
Review Comment:
Stale offset method
##########
server/src/main/java/org/apache/druid/metadata/SortOrder.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.metadata;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.java.util.common.StringUtils;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+/**
+ * specifies the sort order when doing metadata store queries.
+ */
+public enum SortOrder
+{
+ ASC("ASC"),
+
+ DESC("DESC");
+
+ private String value;
+
+ SortOrder(String value)
+ {
+ this.value = value;
+ }
+
+ @Override
+ @JsonValue
+ public String toString()
+ {
+ return String.valueOf(value);
+ }
+
+ @JsonCreator
+ public static SortOrder fromValue(String value)
+ {
+ for (SortOrder b : SortOrder.values()) {
+ if (String.valueOf(b.value).equalsIgnoreCase(String.valueOf(value))) {
+ return b;
+ }
+ }
+ throw InvalidInput.exception(StringUtils.format(
+ "Unexpected value [%s] for SortOrder. Possible values are: %s",
Review Comment:
```suggestion
"Unexpected value[%s] for SortOrder. Possible values are: %s",
```
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,30 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
+ * @param lastSegmentId the last segment id from which to search for results. All segments returned are >
+ * this segment lexigraphically if sortOrder is null or ASC, or < this segment
+ * lexigraphically if sortOrder is DESC.
+ * @param sortOrder Specifies the order with which to return the matching segments by start time, end time.
Review Comment:
```suggestion
* @param sortOrder Specifies the order with which to return the matching segments by id, start time, end time.
```
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
if (compareAsString) {
appendConditionForIntervalsAndMatchMode(sb, intervals, matchMode, connector);
}
+ if (sortOrder != null) {
+ sb.append(StringUtils.format(" ORDER BY start %2$s, %1$send%1$s %2$s",
+ connector.getQuoteString(),
+ sortOrder.toString()));
+ }
final Query<Map<String, Object>> sql = handle
- .createQuery(StringUtils.format(sb.toString(), dbTables.getSegmentsTable()))
+ .createQuery(StringUtils.format(
+ sb.toString(),
+ dbTables.getSegmentsTable(),
+ lastSegmentId == null
Review Comment:
Please see my comment about moving this block above
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
if (compareAsString) {
appendConditionForIntervalsAndMatchMode(sb, intervals, matchMode, connector);
}
Review Comment:
I think appending the id here would make it less error-prone and keeps the sql query construction flow:
```suggestion
if (lastSegmentId != null) {
sb.append(
StringUtils.format("AND id %s :id",
(sortOrder == null || sortOrder == SortOrder.ASC)
? ">"
: "<")
);
```
##########
server/src/test/java/org/apache/druid/metadata/SortOrderTest.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.metadata;
+
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SortOrderTest
+{
+
+ @Test
+ public void test_asc()
+ {
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("asc"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("asc").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("ASC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("ASC").toString());
+ Assert.assertEquals(SortOrder.ASC, SortOrder.fromValue("AsC"));
+ Assert.assertEquals("ASC", SortOrder.fromValue("AsC").toString());
+ }
+
+ @Test
+ public void test_desc()
+ {
+ Assert.assertEquals(SortOrder.DESC, SortOrder.fromValue("desc"));
+ Assert.assertEquals("DESC", SortOrder.fromValue("desc").toString());
+ Assert.assertEquals(SortOrder.DESC, SortOrder.fromValue("DESC"));
+ Assert.assertEquals("DESC", SortOrder.fromValue("DESC").toString());
+ Assert.assertEquals(SortOrder.DESC, SortOrder.fromValue("DesC"));
+ Assert.assertEquals("DESC", SortOrder.fromValue("DesC").toString());
+ }
+
+ @Test
+ public void test_invalid()
Review Comment:
```suggestion
public void testInvalid()
```
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -394,24 +423,44 @@ private UnmodifiableIterator<DataSegment> retrieveSegmentsInIntervalsBatch(
final Collection<Interval> intervals,
final IntervalMode matchMode,
final boolean used,
- @Nullable final Integer limit
+ @Nullable final Integer limit,
+ @Nullable final String lastSegmentId,
+ @Nullable final SortOrder sortOrder
)
{
// Check if the intervals all support comparing as strings. If so, bake them into the SQL.
final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
final StringBuilder sb = new StringBuilder();
- sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
+ sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource %s");
Review Comment:
Do we need the trailing `%s`? If we add the necessary sql clauses conditionally we don't need this, right?
##########
server/src/main/java/org/apache/druid/metadata/SortOrder.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.metadata;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.java.util.common.StringUtils;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+/**
+ * specifies the sort order when doing metadata store queries.
Review Comment:
```suggestion
* Specifies the sort order when doing metadata store queries.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1416385190
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -1208,12 +1208,64 @@ public void testRetrieveUnusedSegmentsUsingMultipleIntervalsAndNoLimit() throws
final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()),
+ null,
null
);
Assert.assertEquals(segments.size(), actualUnusedSegments.size());
Assert.assertTrue(segments.containsAll(actualUnusedSegments));
}
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimit() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(1900, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ ImmutableList.of(),
+ null,
+ null
+ );
+ Assert.assertEquals(segments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(segments.containsAll(actualUnusedSegments));
+ }
+
+ @Test
+ public void testRetrieveUnusedSegmentsUsingNoIntervalsAndNoLimitAndOffset() throws IOException
+ {
+ final List<DataSegment> segments = createAndGetUsedYearSegments(2033, 2133);
+ markAllSegmentsUnused(new HashSet<>(segments));
+
+ int offset = 10;
+ List<DataSegment> expectedSegments = segments.stream().sorted((Comparator<DataSegment>) (o1, o2) -> {
+ long o1Start = o1.getInterval().getStartMillis();
+ long o2Start = o2.getInterval().getStartMillis();
+ if (o1Start < o2Start) {
+ return -1;
+ } else if (o1Start > o2Start) {
+ return 1;
+ } else {
+ long o1End = o1.getInterval().getEndMillis();
+ long o2End = o2.getInterval().getEndMillis();
+ if (o1End < o2End) {
+ return -1;
+ }
+ return o1End > o2End
+ ? 1
+ : 0;
+ }
+ })
+ .skip(offset)
+ .collect(Collectors.toList());
+ final ImmutableList<DataSegment> actualUnusedSegments = retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
+ ImmutableList.of(),
+ null,
+ offset
+ );
+ Assert.assertEquals(expectedSegments.size(), actualUnusedSegments.size());
+ Assert.assertTrue(expectedSegments.containsAll(actualUnusedSegments));
+ }
+
Review Comment:
added
##########
server/src/test/java/org/apache/druid/server/http/MetadataResourceTest.java:
##########
@@ -236,6 +246,117 @@ public void testGetAllSegmentsIncludingRealtime()
Assert.assertEquals(new SegmentStatusInCluster(realTimeSegments[1], false, null, 40L, true), resultList.get(5));
}
+ @Test
+ public void testGetUnusedSegmentsInDataSource()
+ {
+ Mockito.doAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .when(segmentsMetadataManager)
+ .iterateAllUnusedSegmentsForDatasource(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any());
+
+ // test with null datasource name - fails with expected bad datasource name error
+ DruidException e = Assert.assertThrows(
+ DruidException.class,
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, null, null, -1, null)
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals("dataSource name must be non-empty", e.getMessage());
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1416385499
##########
server/src/test/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinatorTest.java:
##########
@@ -3050,19 +3106,20 @@ private List<DataSegment> createAndGetUsedYearSegments(final int startYear, fina
private ImmutableList<DataSegment> retrieveUnusedSegmentsUsingMultipleIntervalsAndLimit(
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1421430015
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -956,12 +956,30 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* any interval
+ * in a particular collection of intervals. If the collection of intervals is empty, this method will retrieve all
+ * unused segments.
+ *
+ * This call does not return any information about realtime segments.
+ *
+ * @param datasource The name of the datasource
+ * @param interval The intervals to search over
+ * @param limit The limit of segments to return
+ * @param offset The offset to use when retrieving matching segments.
+ * @param orderByStartEnd Specifies the order with which to return the matching segments by start time, end time. A
Review Comment:
Thanks! Added new enum
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1422926083
##########
server/src/test/java/org/apache/druid/server/http/MetadataResourceTest.java:
##########
@@ -236,6 +248,119 @@ public void testGetAllSegmentsIncludingRealtime()
Assert.assertEquals(new SegmentStatusInCluster(realTimeSegments[1], false, null, 40L, true), resultList.get(5));
}
+ @Test
+ public void testGetUnusedSegmentsInDataSource()
+ {
+ Mockito.doAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .when(segmentsMetadataManager)
+ .iterateAllUnusedSegmentsForDatasource(
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any());
+
+ // test with null datasource name - fails with expected bad datasource name error
+ DruidExceptionMatcher.invalidInput().expectMessageIs(
+ "dataSourceName must be non-empty"
+ ).assertThrowsAndMatches(
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, null, null, null, null, null)
+ );
+
+ // test with empty datasource name - fails with expected bad datasource name error
+ DruidExceptionMatcher.invalidInput().expectMessageIs(
+ "dataSourceName must be non-empty"
+ ).assertThrowsAndMatches(
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, "", null, null, null, null)
+ );
+
+ // test invalid datasource - returns empty segments
+ Response response = metadataResource.getUnusedSegmentsInDataSource(
+ request,
+ "invalid_datasource",
+ null,
+ null,
+ null,
+ null
+ );
+ List<DataSegment> resultList = extractResponseList(response);
+ Assert.assertTrue(resultList.isEmpty());
+
+ // test valid datasource with bad limit - fails with expected bad limit message
+ DruidExceptionMatcher.invalidInput().expectMessageIs(
+ StringUtils.format("Invalid limit[%s] specified. Limit must be > 0", -1)
+ ).assertThrowsAndMatches(
+ () -> metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, null, -1, null, null)
+ );
+
+ // test valid datasource - returns all unused segments for that datasource
+ response = metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, null, null, null, null);
+
+ resultList = extractResponseList(response);
+ Assert.assertEquals(Arrays.asList(segments), resultList);
+
+ // test valid datasource with interval filter - returns all unused segments for that datasource within interval
+ int numDays = 2;
+ String interval = SEGMENT_START_INTERVAL + "_P" + numDays + "D";
+ response = metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, interval, null, null, null);
+
+ resultList = extractResponseList(response);
+ Assert.assertEquals(NUM_PARTITIONS * numDays, resultList.size());
+ Assert.assertEquals(Arrays.asList(segments[0], segments[1], segments[2], segments[3]), resultList);
+
+ // test valid datasource with interval filter and limit - returns unused segments for that datasource within
+ // interval upto limit
+ int limit = 3;
+ response = metadataResource.getUnusedSegmentsInDataSource(request, DATASOURCE1, interval, limit, null, null);
+
+ resultList = extractResponseList(response);
+ Assert.assertEquals(limit, resultList.size());
+ Assert.assertEquals(Arrays.asList(segments[0], segments[1], segments[2]), resultList);
+
+ // test valid datasource with interval filter limit and offset - returns unused segments for that datasource within
+ // interval upto limit starting at offset
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,49 @@ public Response getUsedSegmentsInDataSourceForIntervals(
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("lastSegmentId") @Nullable final String lastSegmentId,
+ @QueryParam("sortOrder") @Nullable final String sortOrder
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSourceName must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("Invalid limit[%s] specified. Limit must be > 0", limit);
+ }
+
+ SortOrder theSortOrder = sortOrder == null ? null : SortOrder.fromValue(sortOrder);
+
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/server/http/MetadataResource.java:
##########
@@ -334,6 +337,49 @@ public Response getUsedSegmentsInDataSourceForIntervals(
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
+ @GET
+ @Path("/datasources/{dataSourceName}/unusedSegments")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getUnusedSegmentsInDataSource(
+ @Context final HttpServletRequest req,
+ @PathParam("dataSourceName") final String dataSource,
+ @QueryParam("interval") @Nullable String interval,
+ @QueryParam("limit") @Nullable Integer limit,
+ @QueryParam("lastSegmentId") @Nullable final String lastSegmentId,
+ @QueryParam("sortOrder") @Nullable final String sortOrder
+ )
+ {
+ if (dataSource == null || dataSource.isEmpty()) {
+ throw InvalidInput.exception("dataSourceName must be non-empty");
+ }
+ if (limit != null && limit < 0) {
+ throw InvalidInput.exception("Invalid limit[%s] specified. Limit must be > 0", limit);
+ }
+
+ SortOrder theSortOrder = sortOrder == null ? null : SortOrder.fromValue(sortOrder);
+
+ final Interval theInterval = interval != null ? Intervals.of(interval.replace('_', '/')) : null;
+ Iterable<DataSegment> unusedSegments = segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ dataSource,
+ theInterval,
+ limit,
+ lastSegmentId,
+ theSortOrder
+ );
+
+ final Function<DataSegment, Iterable<ResourceAction>> raGenerator = segment -> Collections.singletonList(
+ AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSource()));
+
+ final Iterable<DataSegment> authorizedSegments =
+ AuthorizationUtils.filterAuthorizedResources(req, unusedSegments, raGenerator, authorizerMapper);
+
+ // sort by earliest start interval first, then end interval. DataSegment are sorted in this same order due to
Review Comment:
fixed
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataManager.java:
##########
@@ -955,6 +956,50 @@ public Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForD
.transform(timeline -> timeline.findNonOvershadowedObjectsInInterval(interval, Partitions.ONLY_COMPLETE));
}
+ /**
+ * Retrieves segments for a given datasource that are marked unused and that are *fully contained by* an optionally
+ * specified interval. If the interval specified is null, this method will retrieve all unused segments.
+ *
+ * This call does not return any information about realtime segments.
+ *
+ * @param datasource The name of the datasource
+ * @param interval The intervals to search over
+ * @param limit The limit of segments to return
Review Comment:
fixed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "zachjsh (via GitHub)" <gi...@apache.org>.
zachjsh commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1418577609
##########
server/src/main/java/org/apache/druid/metadata/SegmentsMetadataManager.java:
##########
@@ -125,6 +125,25 @@ Optional<Iterable<DataSegment>> iterateAllUsedNonOvershadowedSegmentsForDatasour
boolean requiresLatest
);
+ /**
+ * Returns an iterable to go over un-used segments for a given datasource over an optional interval.
+ * The order in which segments are iterated is from earliest start-time, with ties being broken with earliest end-time
+ * first. Note: the iteration may not be as trivially cheap as,
+ * for example, iteration over an ArrayList. Try (to some reasonable extent) to organize the code so that it
+ * iterates the returned iterable only once rather than several times.
+ *
+ * @param datasource the name of the datasource.
+ * @param interval the interval to search over.
+ * @param limit the maximum number of results to return.
+ * @param offset the offset from which to search for results.
+ */
+ Iterable<DataSegment> iterateAllUnusedSegmentsForDatasource(
+ String datasource,
+ @Nullable Interval interval,
+ @Nullable Integer limit,
Review Comment:
Thanks! Good suggestion. Added
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1414427674
##########
server/src/test/java/org/apache/druid/server/http/DataSourcesResourceTest.java:
##########
@@ -586,6 +591,329 @@
EasyMock.verify(inventoryView);
}
+ @Test
+ public void testGetUnusedSegmentIdsInInterval()
+ {
+ EasyMock.expect(segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ EasyMock.anyString(),
+ EasyMock.anyObject(Interval.class),
+ EasyMock.anyInt(),
+ EasyMock.anyInt()
+ ))
+ .andAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .atLeastOnce();
+ EasyMock.replay(segmentsMetadataManager);
+
+ DataSourcesResource dataSourcesResource =
+ new DataSourcesResource(null, segmentsMetadataManager, null, null, null, null);
+
+ // test invalid datasource - returns empty segmentIds
+ Response response = dataSourcesResource.getUnusedSegmentIdsInInterval(
+ "invalidDataSource",
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(response.getEntity(), ImmutableSet.of());
+
+ // test valid datasource with bad limit - fails with expected bad limit message
+ DruidException e = Assert.assertThrows(
+ DruidException.class,
+ () -> dataSourcesResource.getUnusedSegmentIdsInInterval(
+ "datasource1",
+ null,
+ -1,
+ null
+ )
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals(EXPECTED_BAD_LIMIT_MESSAGE, e.getMessage());
+
+ // test valid datasource with bad offset - fails with expected bad offset message
+ e = Assert.assertThrows(
+ DruidException.class,
+ () -> dataSourcesResource.getUnusedSegmentIdsInInterval(
+ "datasource1",
+ null,
+ null,
+ -1
+ )
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals(EXPECTED_BAD_OFFSET_MESSAGE, e.getMessage());
+
+
+ // test valid datasource - returns all unused segments for that datasource
+ response = dataSourcesResource.getUnusedSegmentIdsInInterval(
+ "datasource1",
+ null,
+ null,
+ null
+ );
+
+ TreeSet<SegmentId> actualSegmentIds = (TreeSet) response.getEntity();
+ Set<SegmentId> expectedSegmentIds = dataSegmentList.stream()
+ .filter(d -> "datasource1".equals(d.getDataSource()))
+ .map(d -> d.getId())
+ .collect(Collectors.toSet());
+ Assert.assertEquals(expectedSegmentIds, actualSegmentIds);
+
+ // test valid datasource with interval filter - returns all unused segments for that datasource within interval
+ String interval = "2010-01-01_P1D";
+ Interval theInterval = Intervals.of("2010-01-01_P1D".replace('_', '/'));
+ response = dataSourcesResource.getUnusedSegmentIdsInInterval(
+ "datasource1",
+ interval,
+ null,
+ null
+ );
+
+ actualSegmentIds = (TreeSet) response.getEntity();
+ expectedSegmentIds = dataSegmentList.stream()
+ .filter(d -> "datasource1".equals(d.getDataSource())
+ && theInterval.getStartMillis() >= d.getInterval().getStartMillis()
+ && theInterval.getEndMillis() <= d.getInterval().getEndMillis())
+ .map(d -> d.getId())
+ .collect(Collectors.toSet());
+ Assert.assertEquals(expectedSegmentIds, actualSegmentIds);
+
+ EasyMock.verify(segmentsMetadataManager);
+ }
+
+ @Test
+ public void testGetUnusedSegmentsStatsInInterval()
+ {
+ EasyMock.expect(segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ EasyMock.anyString(),
+ EasyMock.anyObject(Interval.class),
+ EasyMock.anyInt(),
+ EasyMock.anyInt()
+ ))
+ .andAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .atLeastOnce();
+ EasyMock.replay(segmentsMetadataManager);
+
+ DataSourcesResource dataSourcesResource =
+ new DataSourcesResource(null, segmentsMetadataManager, null, null, null, null);
+
+ // test invalid datasource - returns empty stats
+ Response response = dataSourcesResource.getUnusedSegmentsStatsInInterval(
+ "invalidDataSource",
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(response.getEntity(), ImmutableMap.of());
+
+ // test valid datasource with bad limit - fails with expected bad limit message
+ DruidException e = Assert.assertThrows(
+ DruidException.class,
+ () -> dataSourcesResource.getUnusedSegmentsStatsInInterval(
+ "datasource1",
+ null,
+ -1,
+ null
+ )
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals(EXPECTED_BAD_LIMIT_MESSAGE, e.getMessage());
+
+ // test valid datasource with bad offset - fails with expected bad offset message
+ e = Assert.assertThrows(
+ DruidException.class,
+ () -> dataSourcesResource.getUnusedSegmentsStatsInInterval(
+ "datasource1",
+ null,
+ null,
+ -1
+ )
+ );
+ Assert.assertEquals(DruidException.Category.INVALID_INPUT, e.getCategory());
+ Assert.assertEquals(EXPECTED_BAD_OFFSET_MESSAGE, e.getMessage());
+
+ // test valid datasource - returns stats for all intervals where unused segments are found, for that datasource
+ response = dataSourcesResource.getUnusedSegmentsStatsInInterval(
+ "datasource1",
+ null,
+ null,
+ null
+ );
+
+ List<Interval> expectedIntervals = new ArrayList<>();
+ expectedIntervals.add(Intervals.of("2010-01-22T00:00:00.000Z/2010-01-23T00:00:00.000Z"));
+ expectedIntervals.add(Intervals.of("2010-01-01T00:00:00.000Z/2010-01-02T00:00:00.000Z"));
+ TreeMap<Interval, Map<DataSourcesResource.SimpleProperties, Object>> results = (TreeMap) response.getEntity();
+ Assert.assertEquals(2, results.size());
+ List<Interval> intervalsInOrderFromEarliest = expectedIntervals.stream()
+ .sorted((o1, o2) -> Comparators.intervalsByStartThenEnd().compare(o1, o2))
+ .collect(Collectors.toList());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(0), results.firstKey());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(1), results.lastKey());
+ Assert.assertEquals(1, results.firstEntry().getValue().get(DataSourcesResource.SimpleProperties.count));
+ Assert.assertEquals(1, results.lastEntry().getValue().get(DataSourcesResource.SimpleProperties.count));
+
+ // test valid datasource with interval filter - returns stats for all intervals, within intercal specified, where
+ // unused segments are found, for that datasource
+ String interval = "2010-01-01_P1D";
+ Interval theInterval = Intervals.of("2010-01-01_P1D".replace('_', '/'));
Review Comment:
## Unread local variable
Variable 'Interval theInterval' is never read.
[Show more details](https://github.com/apache/druid/security/code-scanning/6024)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Add api for Retrieving unused segments (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #15415:
URL: https://github.com/apache/druid/pull/15415#discussion_r1402772389
##########
server/src/test/java/org/apache/druid/server/http/DataSourcesResourceTest.java:
##########
@@ -586,6 +588,203 @@
EasyMock.verify(inventoryView);
}
+ @Test
+ public void testGetUnusedSegmentDataSourceIntervals()
+ {
+ EasyMock.expect(segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ EasyMock.anyString(),
+ EasyMock.anyObject(Interval.class),
+ EasyMock.anyInt(),
+ EasyMock.anyInt()
+ ))
+ .andAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .atLeastOnce();
+ EasyMock.replay(segmentsMetadataManager);
+
+ List<Interval> expectedIntervals = new ArrayList<>();
+ expectedIntervals.add(Intervals.of("2010-01-22T00:00:00.000Z/2010-01-23T00:00:00.000Z"));
+ expectedIntervals.add(Intervals.of("2010-01-01T00:00:00.000Z/2010-01-02T00:00:00.000Z"));
+ DataSourcesResource dataSourcesResource =
+ new DataSourcesResource(null, segmentsMetadataManager, null, null, null, null);
+
+ Response response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "invalidDataSource",
+ null,
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(response.getEntity(), null);
+
+ response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "datasource1",
+ null,
+ null,
+ null,
+ null
+ );
+ TreeSet<Interval> actualIntervals = (TreeSet) response.getEntity();
+ Assert.assertEquals(2, actualIntervals.size());
+ List<Interval> intervalsInOrderFromEarliest = expectedIntervals.stream()
+ .sorted((o1, o2) -> Comparators.intervalsByStartThenEnd().compare(o1, o2))
+ .collect(Collectors.toList());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(0), actualIntervals.first());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(1), actualIntervals.last());
+
+ response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "datasource1",
+ "simple",
+ null,
+ null,
+ null
+ );
+ TreeMap<Interval, Map<DataSourcesResource.SimpleProperties, Object>> results = (TreeMap) response.getEntity();
+ Assert.assertEquals(2, results.size());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(0), results.firstKey());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(1), results.lastKey());
+ Assert.assertEquals(1, results.firstEntry().getValue().get(DataSourcesResource.SimpleProperties.count));
+ Assert.assertEquals(1, results.lastEntry().getValue().get(DataSourcesResource.SimpleProperties.count));
+
+ response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "datasource1",
+ null,
+ "full",
+ null,
+ null
+ );
+ Map<Interval, Map<SegmentId, Object>> results2 = ((Map<Interval, Map<SegmentId, Object>>) response.getEntity());
+ int i = 0;
+ List<DataSegment> segmentsInOrderFromEarliest = dataSegmentList.stream()
+ .filter(d -> d.getDataSource().equals("datasource1"))
+ .sorted((o1, o2) -> Comparators.intervalsByStartThenEnd().compare(o1.getInterval(), o2.getInterval()))
+ .collect(Collectors.toList());
+ for (Map.Entry<Interval, Map<SegmentId, Object>> entry : results2.entrySet()) {
+ for (Map.Entry<SegmentId, Object> entryInner : entry.getValue().entrySet()) {
Review Comment:
## Unread local variable
Variable 'Entry<SegmentId,Object> entryInner' is never read.
[Show more details](https://github.com/apache/druid/security/code-scanning/5994)
##########
server/src/test/java/org/apache/druid/server/http/DataSourcesResourceTest.java:
##########
@@ -586,6 +588,203 @@
EasyMock.verify(inventoryView);
}
+ @Test
+ public void testGetUnusedSegmentDataSourceIntervals()
+ {
+ EasyMock.expect(segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ EasyMock.anyString(),
+ EasyMock.anyObject(Interval.class),
+ EasyMock.anyInt(),
+ EasyMock.anyInt()
+ ))
+ .andAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .atLeastOnce();
+ EasyMock.replay(segmentsMetadataManager);
+
+ List<Interval> expectedIntervals = new ArrayList<>();
+ expectedIntervals.add(Intervals.of("2010-01-22T00:00:00.000Z/2010-01-23T00:00:00.000Z"));
+ expectedIntervals.add(Intervals.of("2010-01-01T00:00:00.000Z/2010-01-02T00:00:00.000Z"));
+ DataSourcesResource dataSourcesResource =
+ new DataSourcesResource(null, segmentsMetadataManager, null, null, null, null);
+
+ Response response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "invalidDataSource",
+ null,
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(response.getEntity(), null);
+
+ response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "datasource1",
+ null,
+ null,
+ null,
+ null
+ );
+ TreeSet<Interval> actualIntervals = (TreeSet) response.getEntity();
+ Assert.assertEquals(2, actualIntervals.size());
+ List<Interval> intervalsInOrderFromEarliest = expectedIntervals.stream()
+ .sorted((o1, o2) -> Comparators.intervalsByStartThenEnd().compare(o1, o2))
+ .collect(Collectors.toList());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(0), actualIntervals.first());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(1), actualIntervals.last());
+
+ response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "datasource1",
+ "simple",
+ null,
+ null,
+ null
+ );
+ TreeMap<Interval, Map<DataSourcesResource.SimpleProperties, Object>> results = (TreeMap) response.getEntity();
+ Assert.assertEquals(2, results.size());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(0), results.firstKey());
+ Assert.assertEquals(intervalsInOrderFromEarliest.get(1), results.lastKey());
+ Assert.assertEquals(1, results.firstEntry().getValue().get(DataSourcesResource.SimpleProperties.count));
+ Assert.assertEquals(1, results.lastEntry().getValue().get(DataSourcesResource.SimpleProperties.count));
+
+ response = dataSourcesResource.getIntervalsWithUnusedSegmentsOrAllUnusedSegmentsPerIntervals(
+ "datasource1",
+ null,
+ "full",
+ null,
+ null
+ );
+ Map<Interval, Map<SegmentId, Object>> results2 = ((Map<Interval, Map<SegmentId, Object>>) response.getEntity());
+ int i = 0;
+ List<DataSegment> segmentsInOrderFromEarliest = dataSegmentList.stream()
+ .filter(d -> d.getDataSource().equals("datasource1"))
+ .sorted((o1, o2) -> Comparators.intervalsByStartThenEnd().compare(o1.getInterval(), o2.getInterval()))
+ .collect(Collectors.toList());
+ for (Map.Entry<Interval, Map<SegmentId, Object>> entry : results2.entrySet()) {
+ for (Map.Entry<SegmentId, Object> entryInner : entry.getValue().entrySet()) {
+ Assert.assertEquals(segmentsInOrderFromEarliest.get(i).getInterval(), entry.getKey());
+ Assert.assertEquals(
+ segmentsInOrderFromEarliest.get(i),
+ ((Map<String, Object>) entry.getValue().get(segmentsInOrderFromEarliest.get(i).getId())).get("metadata")
+ );
+ i++;
+ }
+ }
+ EasyMock.verify(segmentsMetadataManager);
+ }
+
+ @Test
+ public void testGetUnusedSegmentsInIntervalInDataSource()
+ {
+ EasyMock.expect(segmentsMetadataManager.iterateAllUnusedSegmentsForDatasource(
+ EasyMock.anyString(),
+ EasyMock.anyObject(Interval.class),
+ EasyMock.anyInt(),
+ EasyMock.anyInt()
+ ))
+ .andAnswer(mockIterateAllUnusedSegmentsForDatasource())
+ .atLeastOnce();
+ EasyMock.replay(segmentsMetadataManager);
+
+ DataSourcesResource dataSourcesResource =
+ new DataSourcesResource(null, segmentsMetadataManager, null, null, null, null);
+ Response response = dataSourcesResource.getUnusedSegmentsInInterval(
+ "invalidDataSource",
+ "2010-01-01/P1D",
+ null,
+ null,
+ null,
+ null
+ );
+ Assert.assertEquals(ImmutableSet.of(), response.getEntity());
+
+ response = dataSourcesResource.getUnusedSegmentsInInterval(
+ "datasource1",
+ "2010-03-01/P1D",
+ null,
+ null,
+ null,
+ null
+ );
+ // interval not present in the datasource
+ Assert.assertEquals(ImmutableSet.of(), response.getEntity());
+
+ response = dataSourcesResource.getUnusedSegmentsInInterval("datasource1", "2010-01-01/P1D", null, null, null, null);
+ Assert.assertEquals(ImmutableSet.of(dataSegmentList.get(0).getId()), response.getEntity());
+
+ response = dataSourcesResource.getUnusedSegmentsInInterval("datasource1", "2010-01-01/P1M", null, null, null, null);
+ Assert.assertEquals(
+ ImmutableSet.of(dataSegmentList.get(1).getId(), dataSegmentList.get(0).getId()),
+ response.getEntity()
+ );
+
+ response = dataSourcesResource.getUnusedSegmentsInInterval(
+ "datasource1",
+ "2010-01-01/P1M",
+ "simple",
+ null,
+ null,
+ null
+ );
+ Map<Interval, Map<DataSourcesResource.SimpleProperties, Object>> results =
+ ((Map<Interval, Map<DataSourcesResource.SimpleProperties, Object>>) response.getEntity());
+ Assert.assertEquals(2, results.size());
+ int i;
+ for (i = 0; i < 2; i++) {
+ Assert.assertTrue(results.containsKey(dataSegmentList.get(i).getInterval()));
+ Assert.assertEquals(
+ 1,
+ (results.get(dataSegmentList.get(i).getInterval())).get(DataSourcesResource.SimpleProperties.count)
+ );
+ }
+
+ response = dataSourcesResource.getUnusedSegmentsInInterval("datasource1", "2010-01-01/P1M", null, "full", null, null);
+ Map<Interval, Map<SegmentId, Object>> results1 = ((Map<Interval, Map<SegmentId, Object>>) response.getEntity());
+ i = 0;
+ List<DataSegment> segmentsInOrderFromEarliest = dataSegmentList.stream()
+ .filter(d -> d.getDataSource().equals("datasource1"))
+ .sorted((o1, o2) -> Comparators.intervalsByStartThenEnd().compare(o1.getInterval(), o2.getInterval()))
+ .collect(Collectors.toList());
+ for (Map.Entry<Interval, Map<SegmentId, Object>> entry : results1.entrySet()) {
+ for (Map.Entry<SegmentId, Object> entryInner : entry.getValue().entrySet()) {
Review Comment:
## Unread local variable
Variable 'Entry<SegmentId,Object> entryInner' is never read.
[Show more details](https://github.com/apache/druid/security/code-scanning/5995)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org