Search in sources :

Example 26 with Query

use of io.druid.query.Query in project druid by druid-io.

the class CachingQueryRunnerTest method testUseCache.

private void testUseCache(List<Result> expectedResults, Query query, QueryToolChest toolchest) throws Exception {
    DefaultObjectMapper objectMapper = new DefaultObjectMapper();
    String segmentIdentifier = "segment";
    SegmentDescriptor segmentDescriptor = new SegmentDescriptor(new Interval("2011/2012"), "version", 0);
    CacheStrategy cacheStrategy = toolchest.getCacheStrategy(query);
    Cache.NamedKey cacheKey = CacheUtil.computeSegmentCacheKey(segmentIdentifier, segmentDescriptor, cacheStrategy.computeCacheKey(query));
    Cache cache = MapCache.create(1024 * 1024);
    CacheUtil.populate(cache, objectMapper, cacheKey, Iterables.transform(expectedResults, cacheStrategy.prepareForCache()));
    CachingQueryRunner runner = new CachingQueryRunner(segmentIdentifier, segmentDescriptor, objectMapper, cache, toolchest, // return an empty sequence since results should get pulled from cache
    new QueryRunner() {

        @Override
        public Sequence run(Query query, Map responseContext) {
            return Sequences.empty();
        }
    }, backgroundExecutorService, new CacheConfig() {

        @Override
        public boolean isPopulateCache() {
            return true;
        }

        @Override
        public boolean isUseCache() {
            return true;
        }
    });
    HashMap<String, Object> context = new HashMap<String, Object>();
    List<Result> results = Sequences.toList(runner.run(query, context), new ArrayList());
    Assert.assertEquals(expectedResults.toString(), results.toString());
}
Also used : TimeseriesQuery(io.druid.query.timeseries.TimeseriesQuery) Query(io.druid.query.Query) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Sequence(io.druid.java.util.common.guava.Sequence) QueryRunner(io.druid.query.QueryRunner) Result(io.druid.query.Result) SegmentDescriptor(io.druid.query.SegmentDescriptor) DefaultObjectMapper(io.druid.jackson.DefaultObjectMapper) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CacheConfig(io.druid.client.cache.CacheConfig) CacheStrategy(io.druid.query.CacheStrategy) Interval(org.joda.time.Interval) Cache(io.druid.client.cache.Cache) MapCache(io.druid.client.cache.MapCache)

Example 27 with Query

use of io.druid.query.Query in project druid by druid-io.

the class AggregationTestHelper method makeStringSerdeQueryRunner.

public QueryRunner<Row> makeStringSerdeQueryRunner(final ObjectMapper mapper, final QueryToolChest toolChest, final Query<Row> query, final QueryRunner<Row> baseRunner) {
    return new QueryRunner<Row>() {

        @Override
        public Sequence<Row> run(Query<Row> query, Map<String, Object> map) {
            try {
                Sequence<Row> resultSeq = baseRunner.run(query, Maps.<String, Object>newHashMap());
                final Yielder yielder = resultSeq.toYielder(null, new YieldingAccumulator() {

                    @Override
                    public Object accumulate(Object accumulated, Object in) {
                        yield();
                        return in;
                    }
                });
                String resultStr = mapper.writer().writeValueAsString(yielder);
                TypeFactory typeFactory = mapper.getTypeFactory();
                JavaType baseType = typeFactory.constructType(toolChest.getResultTypeReference());
                List resultRows = Lists.transform(readQueryResultArrayFromString(resultStr), toolChest.makePreComputeManipulatorFn(query, MetricManipulatorFns.deserializing()));
                return Sequences.simple(resultRows);
            } catch (Exception ex) {
                throw Throwables.propagate(ex);
            }
        }
    };
}
Also used : Yielder(io.druid.java.util.common.guava.Yielder) Query(io.druid.query.Query) YieldingAccumulator(io.druid.java.util.common.guava.YieldingAccumulator) FinalizeResultsQueryRunner(io.druid.query.FinalizeResultsQueryRunner) QueryRunner(io.druid.query.QueryRunner) IOException(java.io.IOException) JavaType(com.fasterxml.jackson.databind.JavaType) List(java.util.List) ArrayList(java.util.ArrayList) Row(io.druid.data.input.Row) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) Map(java.util.Map)

Example 28 with Query

use of io.druid.query.Query in project druid by druid-io.

the class QueryResourceTest method testDenySecuredGetServer.

@Test(timeout = 60_000L)
public void testDenySecuredGetServer() throws Exception {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);
    EasyMock.expect(testServletRequest.getAttribute(EasyMock.anyString())).andReturn(new AuthorizationInfo() {

        @Override
        public Access isAuthorized(Resource resource, Action action) {
            // WRITE corresponds to cancellation of query
            if (action.equals(Action.READ)) {
                try {
                    waitForCancellationLatch.await();
                } catch (InterruptedException e) {
                    Throwables.propagate(e);
                }
                return new Access(true);
            } else {
                // Deny access to cancel the query
                return new Access(false);
            }
        }
    }).times(2);
    EasyMock.replay(testServletRequest);
    queryResource = new QueryResource(warehouse, serverConfig, jsonMapper, jsonMapper, testSegmentWalker, new NoopServiceEmitter(), new NoopRequestLogger(), queryManager, new AuthConfig(true));
    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"," + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query query = mapper.readValue(queryString, Query.class);
    ListenableFuture future = MoreExecutors.listeningDecorator(Execs.singleThreaded("test_query_resource_%s")).submit(new Runnable() {

        @Override
        public void run() {
            try {
                startAwaitLatch.countDown();
                Response response = queryResource.doPost(new ByteArrayInputStream(queryString.getBytes("UTF-8")), null, testServletRequest);
                Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
            } catch (IOException e) {
                Throwables.propagate(e);
            }
            waitFinishLatch.countDown();
        }
    });
    queryManager.registerQuery(query, future);
    startAwaitLatch.await();
    Executors.newSingleThreadExecutor().submit(new Runnable() {

        @Override
        public void run() {
            Response response = queryResource.getServer("id_1", testServletRequest);
            Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
            waitForCancellationLatch.countDown();
            waitFinishLatch.countDown();
        }
    });
    waitFinishLatch.await();
}
Also used : Action(io.druid.server.security.Action) Query(io.druid.query.Query) Resource(io.druid.server.security.Resource) Access(io.druid.server.security.Access) NoopRequestLogger(io.druid.server.log.NoopRequestLogger) NoopServiceEmitter(io.druid.server.metrics.NoopServiceEmitter) AuthConfig(io.druid.server.security.AuthConfig) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AuthorizationInfo(io.druid.server.security.AuthorizationInfo) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) DefaultObjectMapper(io.druid.jackson.DefaultObjectMapper) DefaultObjectMapper(io.druid.jackson.DefaultObjectMapper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 29 with Query

use of io.druid.query.Query in project druid by druid-io.

the class QueryResourceTest method testSecuredGetServer.

@Test(timeout = 60_000L)
public void testSecuredGetServer() throws Exception {
    final CountDownLatch waitForCancellationLatch = new CountDownLatch(1);
    final CountDownLatch waitFinishLatch = new CountDownLatch(2);
    final CountDownLatch startAwaitLatch = new CountDownLatch(1);
    final CountDownLatch cancelledCountDownLatch = new CountDownLatch(1);
    EasyMock.expect(testServletRequest.getAttribute(EasyMock.anyString())).andReturn(new AuthorizationInfo() {

        @Override
        public Access isAuthorized(Resource resource, Action action) {
            // WRITE corresponds to cancellation of query
            if (action.equals(Action.READ)) {
                try {
                    // Countdown startAwaitLatch as we want query cancellation to happen
                    // after we enter isAuthorized method so that we can handle the
                    // InterruptedException here because of query cancellation
                    startAwaitLatch.countDown();
                    waitForCancellationLatch.await();
                } catch (InterruptedException e) {
                    // When the query is cancelled the control will reach here,
                    // countdown the latch and rethrow the exception so that error response is returned for the query
                    cancelledCountDownLatch.countDown();
                    Throwables.propagate(e);
                }
                return new Access(true);
            } else {
                return new Access(true);
            }
        }
    }).times(2);
    EasyMock.replay(testServletRequest);
    queryResource = new QueryResource(warehouse, serverConfig, jsonMapper, jsonMapper, testSegmentWalker, new NoopServiceEmitter(), new NoopRequestLogger(), queryManager, new AuthConfig(true));
    final String queryString = "{\"queryType\":\"timeBoundary\", \"dataSource\":\"allow\"," + "\"context\":{\"queryId\":\"id_1\"}}";
    ObjectMapper mapper = new DefaultObjectMapper();
    Query query = mapper.readValue(queryString, Query.class);
    ListenableFuture future = MoreExecutors.listeningDecorator(Execs.singleThreaded("test_query_resource_%s")).submit(new Runnable() {

        @Override
        public void run() {
            try {
                Response response = queryResource.doPost(new ByteArrayInputStream(queryString.getBytes("UTF-8")), null, testServletRequest);
                Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
            } catch (IOException e) {
                Throwables.propagate(e);
            }
            waitFinishLatch.countDown();
        }
    });
    queryManager.registerQuery(query, future);
    startAwaitLatch.await();
    Executors.newSingleThreadExecutor().submit(new Runnable() {

        @Override
        public void run() {
            Response response = queryResource.getServer("id_1", testServletRequest);
            Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
            waitForCancellationLatch.countDown();
            waitFinishLatch.countDown();
        }
    });
    waitFinishLatch.await();
    cancelledCountDownLatch.await();
}
Also used : Action(io.druid.server.security.Action) Query(io.druid.query.Query) Resource(io.druid.server.security.Resource) Access(io.druid.server.security.Access) NoopRequestLogger(io.druid.server.log.NoopRequestLogger) NoopServiceEmitter(io.druid.server.metrics.NoopServiceEmitter) AuthConfig(io.druid.server.security.AuthConfig) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AuthorizationInfo(io.druid.server.security.AuthorizationInfo) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) DefaultObjectMapper(io.druid.jackson.DefaultObjectMapper) DefaultObjectMapper(io.druid.jackson.DefaultObjectMapper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 30 with Query

use of io.druid.query.Query in project druid by druid-io.

the class GroupByQueryRunnerTest method testPostAggMergedHavingSpec.

@Test
public void testPostAggMergedHavingSpec() {
    List<Row> expectedResults = Arrays.asList(GroupByQueryRunnerTestHelper.createExpectedRow("2011-04-01", "alias", "mezzanine", "rows", 6L, "index", 4420L, QueryRunnerTestHelper.addRowsIndexConstantMetric, (double) (6L + 4420L + 1L)), GroupByQueryRunnerTestHelper.createExpectedRow("2011-04-01", "alias", "premium", "rows", 6L, "index", 4416L, QueryRunnerTestHelper.addRowsIndexConstantMetric, (double) (6L + 4416L + 1L)));
    GroupByQuery.Builder builder = GroupByQuery.builder().setDataSource(QueryRunnerTestHelper.dataSource).setInterval("2011-04-02/2011-04-04").setDimensions(Lists.<DimensionSpec>newArrayList(new DefaultDimensionSpec("quality", "alias"))).setAggregatorSpecs(Arrays.asList(QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("index", "index"))).setPostAggregatorSpecs(ImmutableList.<PostAggregator>of(QueryRunnerTestHelper.addRowsIndexConstant)).setGranularity(new PeriodGranularity(new Period("P1M"), null, null)).setHavingSpec(new OrHavingSpec(ImmutableList.<HavingSpec>of(new GreaterThanHavingSpec(QueryRunnerTestHelper.addRowsIndexConstantMetric, 1000L))));
    final GroupByQuery fullQuery = builder.build();
    QueryRunner mergedRunner = factory.getToolchest().mergeResults(new QueryRunner<Row>() {

        @Override
        public Sequence<Row> run(Query<Row> query, Map<String, Object> responseContext) {
            // simulate two daily segments
            final Query query1 = query.withQuerySegmentSpec(new MultipleIntervalSegmentSpec(Lists.newArrayList(new Interval("2011-04-02/2011-04-03"))));
            final Query query2 = query.withQuerySegmentSpec(new MultipleIntervalSegmentSpec(Lists.newArrayList(new Interval("2011-04-03/2011-04-04"))));
            return new MergeSequence(query.getResultOrdering(), Sequences.simple(Arrays.asList(runner.run(query1, responseContext), runner.run(query2, responseContext))));
        }
    });
    Map<String, Object> context = Maps.newHashMap();
    TestHelper.assertExpectedObjects(expectedResults, mergedRunner.run(fullQuery, context), "merged");
}
Also used : OrHavingSpec(io.druid.query.groupby.having.OrHavingSpec) Query(io.druid.query.Query) LongSumAggregatorFactory(io.druid.query.aggregation.LongSumAggregatorFactory) PeriodGranularity(io.druid.java.util.common.granularity.PeriodGranularity) Period(org.joda.time.Period) MultipleIntervalSegmentSpec(io.druid.query.spec.MultipleIntervalSegmentSpec) Sequence(io.druid.java.util.common.guava.Sequence) MergeSequence(io.druid.java.util.common.guava.MergeSequence) DefaultDimensionSpec(io.druid.query.dimension.DefaultDimensionSpec) FinalizeResultsQueryRunner(io.druid.query.FinalizeResultsQueryRunner) QueryRunner(io.druid.query.QueryRunner) MergeSequence(io.druid.java.util.common.guava.MergeSequence) GreaterThanHavingSpec(io.druid.query.groupby.having.GreaterThanHavingSpec) HavingSpec(io.druid.query.groupby.having.HavingSpec) DimFilterHavingSpec(io.druid.query.groupby.having.DimFilterHavingSpec) BaseHavingSpec(io.druid.query.groupby.having.BaseHavingSpec) OrHavingSpec(io.druid.query.groupby.having.OrHavingSpec) DimensionSelectorHavingSpec(io.druid.query.groupby.having.DimensionSelectorHavingSpec) EqualToHavingSpec(io.druid.query.groupby.having.EqualToHavingSpec) GreaterThanHavingSpec(io.druid.query.groupby.having.GreaterThanHavingSpec) Row(io.druid.data.input.Row) Interval(org.joda.time.Interval) Test(org.junit.Test)

Aggregations

Query (io.druid.query.Query)48 QueryRunner (io.druid.query.QueryRunner)23 Test (org.junit.Test)22 Interval (org.joda.time.Interval)18 Sequence (io.druid.java.util.common.guava.Sequence)14 Map (java.util.Map)14 FinalizeResultsQueryRunner (io.druid.query.FinalizeResultsQueryRunner)11 SegmentDescriptor (io.druid.query.SegmentDescriptor)11 IOException (java.io.IOException)10 Row (io.druid.data.input.Row)9 DefaultObjectMapper (io.druid.jackson.DefaultObjectMapper)9 Result (io.druid.query.Result)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 Function (com.google.common.base.Function)8 DefaultDimensionSpec (io.druid.query.dimension.DefaultDimensionSpec)8 TimeseriesQuery (io.druid.query.timeseries.TimeseriesQuery)8 MergeSequence (io.druid.java.util.common.guava.MergeSequence)7 LongSumAggregatorFactory (io.druid.query.aggregation.LongSumAggregatorFactory)7 MultipleIntervalSegmentSpec (io.druid.query.spec.MultipleIntervalSegmentSpec)7 ImmutableMap (com.google.common.collect.ImmutableMap)6