Java Code Examples for org.apache.kylin.rest.request.SQLRequest

The following examples show how to use org.apache.kylin.rest.request.SQLRequest. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: kylin-on-parquet-v2   Source File: QueryServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws JobException, IOException, SQLException {
    Assert.assertNotNull(queryService.getConfig());
    Assert.assertNotNull(queryService.getConfig());
    Assert.assertNotNull(queryService.getDataModelManager());
    Assert.assertNotNull(QueryConnection.getConnection(ProjectInstance.DEFAULT_PROJECT_NAME));

    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 0);
    //
    //        queryService.saveQuery("test", "test", "select * from test_table", "test");
    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 1);
    //
    //        queryService.removeQuery(queryService.getQueries("ADMIN").get(0).getProperty("id"));
    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 0);

    SQLRequest request = new SQLRequest();
    request.setSql("select * from test_table");
    request.setAcceptPartial(true);
    QueryContext queryContext = QueryContextFacade.current();
    SQLResponse response = new SQLResponse();
    response.setHitExceptionCache(true);
    queryService.logQuery(queryContext.getQueryId(), request, response);
}
 
Example 2
Source Project: kylin-on-parquet-v2   Source File: QueryServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTableToWith() {
    String create_table1 = " create table tableId as select * from some_table1;";
    String create_table2 = "CREATE TABLE tableId2 AS select * FROM some_table2;";
    String select_table = "select * from tableId join tableId2 on tableId.a = tableId2.b;";

    KylinConfig config = KylinConfig.getInstanceFromEnv();
    config.setProperty("kylin.query.convert-create-table-to-with", "true");
    try (SetAndUnsetThreadLocalConfig autoUnset = KylinConfig.setAndUnsetThreadLocalConfig(config)) {

        SQLRequest request = new SQLRequest();
        request.setProject("default");
        request.setSql(create_table1);
        queryService.doQueryWithCache(request);

        request.setSql(create_table2);
        queryService.doQueryWithCache(request);

        request.setSql(select_table);
        SQLResponse response = queryService.doQueryWithCache(request, true);

        Assert.assertEquals(
                "WITH tableId as (select * from some_table1) , tableId2 AS (select * FROM some_table2) select * from tableId join tableId2 on tableId.a = tableId2.b;",
                response.getExceptionMessage());
    }
}
 
Example 3
Source Project: kylin-on-parquet-v2   Source File: QueryMetrics2Facade.java    License: Apache License 2.0 6 votes vote down vote up
public static void updateMetrics(SQLRequest sqlRequest, SQLResponse sqlResponse) {
    if (!enabled) {
        return;
    }
    if (metrics == null) {
        metrics = MetricsFactory.getInstance();
    }
    String projectName = sqlRequest.getProject();
    String cube = sqlResponse.getCube();
    if (cube == null) {
        return;
    }
    String cubeName = cube.replace("=", "->");

    //        update(getQueryMetrics("Server_Total"), sqlResponse);
    update(buildCubeMetricPrefix(TOTAL), sqlResponse);
    update(buildCubeMetricPrefix(projectName), sqlResponse);
    String cubeMetricName = buildCubeMetricPrefix(projectName, cubeName);
    update(cubeMetricName, sqlResponse);
}
 
Example 4
Source Project: kylin-on-parquet-v2   Source File: QueryService.java    License: Apache License 2.0 6 votes vote down vote up
public SQLResponse update(SQLRequest sqlRequest) throws Exception {
    // non select operations, only supported when enable pushdown
    logger.debug("Query pushdown enabled, redirect the non-select query to pushdown engine.");
    Connection conn = null;
    try {
        conn = QueryConnection.getConnection(sqlRequest.getProject());
        Pair<List<List<String>>, List<SelectedColumnMeta>> r = PushDownUtil.tryPushDownNonSelectQuery(
                sqlRequest.getProject(), sqlRequest.getSql(), conn.getSchema(), BackdoorToggles.getPrepareOnly());

        List<SelectedColumnMeta> columnMetas = Lists.newArrayList();
        columnMetas.add(new SelectedColumnMeta(false, false, false, false, 1, false, Integer.MAX_VALUE, "c0", "c0",
                null, null, null, Integer.MAX_VALUE, 128, 1, "char", false, false, false));

        return buildSqlResponse(sqlRequest.getProject(), true, r.getFirst(), columnMetas);

    } catch (Exception e) {
        logger.info("pushdown engine failed to finish current non-select query");
        throw e;
    } finally {
        close(null, null, conn);
    }
}
 
Example 5
Source Project: kylin-on-parquet-v2   Source File: QueryService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param correctedSql
 * @param sqlRequest
 * @return
 * @throws Exception
 */
private SQLResponse executeRequest(String correctedSql, SQLRequest sqlRequest, Connection conn) throws Exception {
    Statement stat = null;
    ResultSet resultSet = null;
    boolean isPushDown = false;

    Pair<List<List<String>>, List<SelectedColumnMeta>> r = null;
    try {
        stat = conn.createStatement();
        processStatementAttr(stat, sqlRequest);
        resultSet = stat.executeQuery(correctedSql);

        r = createResponseFromResultSet(resultSet);

    } catch (SQLException sqlException) {
        r = pushDownQuery(sqlRequest, correctedSql, conn, sqlException);
        if (r == null)
            throw sqlException;

        isPushDown = true;
    } finally {
        close(resultSet, stat, null); //conn is passed in, not my duty to close
    }

    return buildSqlResponse(sqlRequest.getProject(), isPushDown, r.getFirst(), r.getSecond());
}
 
Example 6
Source Project: kylin   Source File: KylinQueryTimeoutTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryTimeout() throws SQLException {
    thrown.expectCause(CoreMatchers.isA(KylinTimeoutException.class));
    thrown.expectMessage(CoreMatchers.containsString("Kylin query timeout"));
    StorageFactory.clearCache();
    BadQueryDetector detector = new BadQueryDetector(100, BadQueryDetector.getSystemAvailMB() * 2, 100, 1);
    detector.start();
    SQLRequest request = new SQLRequest();
    request.setProject("default");
    request.setSql("select count(*) from STREAMING_TABLE");
    detector.queryStart(Thread.currentThread(), request, "ADMIN", RandomUtil.randomUUID().toString());
    try {
        QueryACLTestUtil.mockQuery("default", "select * from STREAMING_TABLE");
    } finally{
        detector.queryEnd(Thread.currentThread(), "timeout");
        detector.interrupt();
    }
    // every place that thrown KylinTimeoutException should reset the interrupt.
    Assert.assertEquals(false, Thread.currentThread().isInterrupted());
}
 
Example 7
Source Project: kylin   Source File: QueryServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws JobException, IOException, SQLException {
    Assert.assertNotNull(queryService.getConfig());
    Assert.assertNotNull(queryService.getConfig());
    Assert.assertNotNull(queryService.getDataModelManager());
    Assert.assertNotNull(QueryConnection.getConnection(ProjectInstance.DEFAULT_PROJECT_NAME));

    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 0);
    //
    //        queryService.saveQuery("test", "test", "select * from test_table", "test");
    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 1);
    //
    //        queryService.removeQuery(queryService.getQueries("ADMIN").get(0).getProperty("id"));
    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 0);

    SQLRequest request = new SQLRequest();
    request.setSql("select * from test_table");
    request.setAcceptPartial(true);
    QueryContext queryContext = QueryContextFacade.current();
    SQLResponse response = new SQLResponse();
    response.setHitExceptionCache(true);
    queryService.logQuery(queryContext.getQueryId(), request, response);
}
 
Example 8
Source Project: kylin   Source File: QueryServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTableToWith() {
    String create_table1 = " create table tableId as select * from some_table1;";
    String create_table2 = "CREATE TABLE tableId2 AS select * FROM some_table2;";
    String select_table = "select * from tableId join tableId2 on tableId.a = tableId2.b;";

    KylinConfig config = KylinConfig.getInstanceFromEnv();
    config.setProperty("kylin.query.convert-create-table-to-with", "true");
    try (SetAndUnsetThreadLocalConfig autoUnset = KylinConfig.setAndUnsetThreadLocalConfig(config)) {

        SQLRequest request = new SQLRequest();
        request.setProject("default");
        request.setSql(create_table1);
        queryService.doQueryWithCache(request);

        request.setSql(create_table2);
        queryService.doQueryWithCache(request);

        request.setSql(select_table);
        SQLResponse response = queryService.doQueryWithCache(request, true);

        Assert.assertEquals(
                "WITH tableId as (select * from some_table1) , tableId2 AS (select * FROM some_table2) select * from tableId join tableId2 on tableId.a = tableId2.b;",
                response.getExceptionMessage());
    }
}
 
Example 9
Source Project: kylin   Source File: QueryServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSyntaxError() {
    KylinConfig config = KylinConfig.getInstanceFromEnv();
    config.setProperty("kylin.query.cache-enabled", "true");
    config.setProperty("kylin.query.lazy-query-enabled", "true");

    String badSql = "select with syntax error";

    SQLRequest request = new SQLRequest();
    request.setProject("default");
    request.setSql(badSql);

    try (SetAndUnsetThreadLocalConfig autoUnset = KylinConfig.setAndUnsetThreadLocalConfig(config)) {
        queryService.doQueryWithCache(request, false);
    } catch (Exception e) {
        // expected error
        Cache.ValueWrapper wrapper = cacheManager.getCache(QueryService.QUERY_CACHE).get(request.getCacheKey());
        Assert.assertTrue(wrapper == null || wrapper.get() == null);
    }
}
 
Example 10
Source Project: kylin   Source File: QueryMetrics2Facade.java    License: Apache License 2.0 6 votes vote down vote up
public static void updateMetrics(SQLRequest sqlRequest, SQLResponse sqlResponse) {
    if (!enabled) {
        return;
    }
    if (metrics == null) {
        metrics = MetricsFactory.getInstance();
    }
    String projectName = sqlRequest.getProject();
    String cube = sqlResponse.getCube();
    if (cube == null) {
        return;
    }
    String cubeName = cube.replace("=", "->");

    //        update(getQueryMetrics("Server_Total"), sqlResponse);
    update(buildCubeMetricPrefix(TOTAL), sqlResponse);
    update(buildCubeMetricPrefix(projectName), sqlResponse);
    String cubeMetricName = buildCubeMetricPrefix(projectName, cubeName);
    update(cubeMetricName, sqlResponse);
}
 
Example 11
Source Project: kylin   Source File: QueryService.java    License: Apache License 2.0 6 votes vote down vote up
public SQLResponse update(SQLRequest sqlRequest) throws Exception {
    // non select operations, only supported when enable pushdown
    logger.debug("Query pushdown enabled, redirect the non-select query to pushdown engine.");
    Connection conn = null;
    try {
        conn = QueryConnection.getConnection(sqlRequest.getProject());
        Pair<List<List<String>>, List<SelectedColumnMeta>> r = PushDownUtil.tryPushDownNonSelectQuery(
                sqlRequest.getProject(), sqlRequest.getSql(), conn.getSchema(), BackdoorToggles.getPrepareOnly());

        List<SelectedColumnMeta> columnMetas = Lists.newArrayList();
        columnMetas.add(new SelectedColumnMeta(false, false, false, false, 1, false, Integer.MAX_VALUE, "c0", "c0",
                null, null, null, Integer.MAX_VALUE, 128, 1, "char", false, false, false));

        return buildSqlResponse(sqlRequest.getProject(), true, r.getFirst(), columnMetas);

    } catch (Exception e) {
        logger.info("pushdown engine failed to finish current non-select query");
        throw e;
    } finally {
        close(null, null, conn);
    }
}
 
Example 12
Source Project: kylin   Source File: QueryService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param correctedSql
 * @param sqlRequest
 * @return
 * @throws Exception
 */
private SQLResponse executeRequest(String correctedSql, SQLRequest sqlRequest, Connection conn) throws Exception {
    Statement stat = null;
    ResultSet resultSet = null;
    boolean isPushDown = false;

    Pair<List<List<String>>, List<SelectedColumnMeta>> r = null;
    try {
        stat = conn.createStatement();
        processStatementAttr(stat, sqlRequest);
        resultSet = stat.executeQuery(correctedSql);

        r = createResponseFromResultSet(resultSet);

    } catch (SQLException sqlException) {
        r = pushDownQuery(sqlRequest, correctedSql, conn, sqlException);
        if (r == null)
            throw sqlException;

        isPushDown = true;
    } finally {
        close(resultSet, stat, null); //conn is passed in, not my duty to close
    }

    return buildSqlResponse(sqlRequest.getProject(), isPushDown, r.getFirst(), r.getSecond());
}
 
Example 13
Source Project: Kylin   Source File: QueryService.java    License: Apache License 2.0 6 votes vote down vote up
protected SQLResponse executeQuery(String sql, SQLRequest sqlRequest) throws Exception {
    sql = sql.trim().replace(";", "");

    int limit = sqlRequest.getLimit();
    if (limit > 0 && !sql.toLowerCase().contains("limit")) {
        sql += (" LIMIT " + limit);
    }

    int offset = sqlRequest.getOffset();
    if (offset > 0 && !sql.toLowerCase().contains("offset")) {
        sql += (" OFFSET " + offset);
    }

    // add extra parameters into olap context, like acceptPartial
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put(OLAPContext.PRM_ACCEPT_PARTIAL_RESULT, String.valueOf(sqlRequest.isAcceptPartial()));
    OLAPContext.setParameters(parameters);

    return execute(sql, sqlRequest);
}
 
Example 14
Source Project: Kylin   Source File: QueryServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws JobException, IOException, SQLException {
    Assert.assertNotNull(queryService.getConfig());
    Assert.assertNotNull(queryService.getKylinConfig());
    Assert.assertNotNull(queryService.getMetadataManager());
    Assert.assertNotNull(queryService.getOLAPDataSource(ProjectInstance.DEFAULT_PROJECT_NAME));

    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 0);
    //
    //        queryService.saveQuery("test", "test", "select * from test_table", "test");
    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 1);
    //
    //        queryService.removeQuery(queryService.getQueries("ADMIN").get(0).getProperty("id"));
    //        Assert.assertTrue(queryService.getQueries("ADMIN").size() == 0);

    SQLRequest request = new SQLRequest();
    request.setSql("select * from test_table");
    request.setAcceptPartial(true);
    SQLResponse response = new SQLResponse();
    response.setHitCache(true);
    queryService.logQuery(request, response, new Date(), new Date());
}
 
Example 15
Source Project: kylin-on-parquet-v2   Source File: BadQueryDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void test() throws InterruptedException {
    int alertMB = BadQueryDetector.getSystemAvailMB() * 2;
    int alertRunningSec = 5;
    String mockSql = "select * from just_a_test";
    final ArrayList<String[]> alerts = new ArrayList<>();

    BadQueryDetector badQueryDetector = new BadQueryDetector(alertRunningSec * 1000, alertMB, alertRunningSec, 1000);
    badQueryDetector.registerNotifier(new BadQueryDetector.Notifier() {
        @Override
        public void badQueryFound(String adj, float runningSec, long startTime, String project, String sql,
                String user, Thread t, String queryId, QueryInfoCollector collect) {
            alerts.add(new String[] { adj, sql });
        }
    });
    badQueryDetector.start();

    {
        Thread.sleep(1000);

        SQLRequest sqlRequest = new SQLRequest();
        sqlRequest.setSql(mockSql);
        badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, "user", RandomUtil.randomUUID().toString());

        // make sure bad query check happens twice
        Thread.sleep((alertRunningSec * 2 + 1) * 1000);

        badQueryDetector.queryEnd(Thread.currentThread(), BadQueryEntry.ADJ_PUSHDOWN);
    }

    badQueryDetector.interrupt();

    assertEquals(2, alerts.size());
    // second check founds a Slow
    assertArrayEquals(new String[] { BadQueryEntry.ADJ_SLOW, mockSql }, alerts.get(0));
    // end notifies a Pushdown
    assertArrayEquals(new String[] { BadQueryEntry.ADJ_PUSHDOWN, mockSql }, alerts.get(1));
}
 
Example 16
Source Project: kylin-on-parquet-v2   Source File: BadQueryDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSlowQuery() throws InterruptedException, IOException {
    int alertMB = BadQueryDetector.getSystemAvailMB() * 2;
    int alertRunningSec = 2;
    String mockSql = "select * from just_a_test";

    BadQueryDetector badQueryDetector = new BadQueryDetector(alertRunningSec * 1000, alertMB, alertRunningSec, 1000);
    badQueryDetector.start();

    SQLRequest sqlRequest = new SQLRequest();
    sqlRequest.setProject("test_project");
    sqlRequest.setSql(mockSql);
    badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, "user", RandomUtil.randomUUID().toString());

    try {
        Thread.sleep(1000);

        QueryInfoCollector.current().setCubeNames(Lists.newArrayList("[CUBE[name=TEST_CUBE]]"));

        Thread.sleep((alertRunningSec * 2 + 1) * 1000);

        BadQueryHistory badQueryHistory = BadQueryHistoryManager.getInstance(KylinConfig.getInstanceFromEnv()).getBadQueriesForProject("test_project");
        Set entries = badQueryHistory.getEntries();

        assertEquals(1, entries.size());

        BadQueryEntry entry = (BadQueryEntry) ((NavigableSet) entries).pollFirst();

        assertNotNull(entry);
        assertEquals(BadQueryEntry.ADJ_SLOW, entry.getAdj());
        assertEquals("[CUBE[name=TEST_CUBE]]", entry.getCube());
    } finally {
        badQueryDetector.queryEnd(Thread.currentThread(), BadQueryEntry.ADJ_SLOW);
        badQueryDetector.interrupt();
        QueryInfoCollector.reset();
    }
}
 
Example 17
Source Project: kylin-on-parquet-v2   Source File: QueryMetricsFacade.java    License: Apache License 2.0 5 votes vote down vote up
private static void updateMetricsToLocal(SQLRequest sqlRequest, SQLResponse sqlResponse) {
    if (!enabled)
        return;

    String projectName = sqlRequest.getProject();
    update(getQueryMetrics("Server_Total"), sqlResponse);
    update(getQueryMetrics(projectName), sqlResponse);

    String cube = sqlResponse.getCube();
    String cubeName = cube.replace("=", "->");
    String cubeMetricName = projectName + ",sub=" + cubeName;
    update(getQueryMetrics(cubeMetricName), sqlResponse);
}
 
Example 18
Source Project: kylin-on-parquet-v2   Source File: BadQueryDetector.java    License: Apache License 2.0 5 votes vote down vote up
Entry(SQLRequest sqlRequest, String user, Thread thread, String queryId, QueryInfoCollector collector) {
    this.sqlRequest = sqlRequest;
    this.startTime = System.currentTimeMillis();
    this.thread = thread;
    this.user = user;
    this.queryId = queryId;
    this.collector = collector;
}
 
Example 19
Source Project: kylin-on-parquet-v2   Source File: QueryService.java    License: Apache License 2.0 5 votes vote down vote up
public SQLResponse query(SQLRequest sqlRequest, String queryId) throws Exception {
    SQLResponse ret = null;
    try {
        final String user = SecurityContextHolder.getContext().getAuthentication().getName();
        badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, user, queryId);

        ret = queryWithSqlMassage(sqlRequest);
        return ret;

    } finally {
        String badReason = (ret != null && ret.isPushDown()) ? BadQueryEntry.ADJ_PUSHDOWN : null;
        badQueryDetector.queryEnd(Thread.currentThread(), badReason);
        Thread.interrupted(); //reset if interrupted
    }
}
 
Example 20
Source Project: kylin-on-parquet-v2   Source File: QueryService.java    License: Apache License 2.0 5 votes vote down vote up
protected void processStatementAttr(Statement s, SQLRequest sqlRequest) throws SQLException {
    Integer statementMaxRows = BackdoorToggles.getStatementMaxRows();
    if (statementMaxRows != null) {
        logger.info("Setting current statement's max rows to {}", statementMaxRows);
        s.setMaxRows(statementMaxRows);
    }
}
 
Example 21
Source Project: kylin-on-parquet-v2   Source File: QueryService.java    License: Apache License 2.0 5 votes vote down vote up
private Pair<List<List<String>>, List<SelectedColumnMeta>> pushDownQuery(SQLRequest sqlRequest, String correctedSql,
        Connection conn, SQLException sqlException) throws Exception {
    try {
        return PushDownUtil.tryPushDownSelectQuery(sqlRequest.getProject(), correctedSql, conn.getSchema(),
                sqlException, BackdoorToggles.getPrepareOnly());
    } catch (Exception e2) {
        logger.error("pushdown engine failed current query too", e2);
        //exception in pushdown, throw it instead of exception in calcite
        throw e2;
    }
}
 
Example 22
Source Project: kylin-on-parquet-v2   Source File: BeanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        BeanValidator.validateAccssor(ColumnMeta.class, new String[0]);
        BeanValidator.validateAccssor(TableMeta.class, new String[0]);
        BeanValidator.validateAccssor(SelectedColumnMeta.class, new String[0]);
        BeanValidator.validateAccssor(AccessRequest.class, new String[0]);
        BeanValidator.validateAccssor(CubeRequest.class, new String[0]);
        BeanValidator.validateAccssor(JobListRequest.class, new String[0]);
        BeanValidator.validateAccssor(SQLRequest.class, new String[0]);
        BeanValidator.validateAccssor(AccessEntryResponse.class, new String[0]);
        BeanValidator.validateAccssor(SQLResponse.class, new String[0]);
    } catch (IntrospectionException e) {
    }

    new SQLResponse(null, null, 0, true, null);

    SelectedColumnMeta coulmnMeta = new SelectedColumnMeta(false, false, false, false, 0, false, 0, null, null,
            null, null, null, 0, 0, 0, null, false, false, false);
    Assert.assertTrue(!coulmnMeta.isAutoIncrement());
    Assert.assertTrue(!coulmnMeta.isCaseSensitive());
    Assert.assertTrue(!coulmnMeta.isSearchable());
    Assert.assertTrue(!coulmnMeta.isCurrency());
    Assert.assertTrue(coulmnMeta.getIsNullable() == 0);
    Assert.assertTrue(!coulmnMeta.isSigned());

    Assert.assertEquals(Constant.ACCESS_HAS_ROLE_ADMIN, "hasRole('ROLE_ADMIN')");
    Assert.assertEquals(Constant.ACCESS_POST_FILTER_READ,
            "hasRole('ROLE_ADMIN') " + " or hasPermission(filterObject, 'ADMINISTRATION')"
                    + " or hasPermission(filterObject, 'MANAGEMENT')"
                    + " or hasPermission(filterObject, 'OPERATION')" + " or hasPermission(filterObject, 'READ')");
    Assert.assertEquals(Constant.FakeCatalogName, "defaultCatalog");
    Assert.assertEquals(Constant.FakeSchemaName, "defaultSchema");
    Assert.assertEquals(Constant.IDENTITY_ROLE, "role");
    Assert.assertEquals(Constant.IDENTITY_USER, "user");
}
 
Example 23
Source Project: kylin   Source File: BadQueryDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void test() throws InterruptedException {
    int alertMB = BadQueryDetector.getSystemAvailMB() * 2;
    int alertRunningSec = 5;
    String mockSql = "select * from just_a_test";
    final ArrayList<String[]> alerts = new ArrayList<>();

    BadQueryDetector badQueryDetector = new BadQueryDetector(alertRunningSec * 1000, alertMB, alertRunningSec, 1000);
    badQueryDetector.registerNotifier(new BadQueryDetector.Notifier() {
        @Override
        public void badQueryFound(String adj, float runningSec, long startTime, String project, String sql,
                String user, Thread t, String queryId, QueryInfoCollector collect) {
            alerts.add(new String[] { adj, sql });
        }
    });
    badQueryDetector.start();

    {
        Thread.sleep(1000);

        SQLRequest sqlRequest = new SQLRequest();
        sqlRequest.setSql(mockSql);
        badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, "user", RandomUtil.randomUUID().toString());

        // make sure bad query check happens twice
        Thread.sleep((alertRunningSec * 2 + 1) * 1000);

        badQueryDetector.queryEnd(Thread.currentThread(), BadQueryEntry.ADJ_PUSHDOWN);
    }

    badQueryDetector.interrupt();

    assertEquals(2, alerts.size());
    // second check founds a Slow
    assertArrayEquals(new String[] { BadQueryEntry.ADJ_SLOW, mockSql }, alerts.get(0));
    // end notifies a Pushdown
    assertArrayEquals(new String[] { BadQueryEntry.ADJ_PUSHDOWN, mockSql }, alerts.get(1));
}
 
Example 24
Source Project: kylin   Source File: BadQueryDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSlowQuery() throws InterruptedException, IOException {
    int alertMB = BadQueryDetector.getSystemAvailMB() * 2;
    int alertRunningSec = 2;
    String mockSql = "select * from just_a_test";

    BadQueryDetector badQueryDetector = new BadQueryDetector(alertRunningSec * 1000, alertMB, alertRunningSec, 1000);
    badQueryDetector.start();

    SQLRequest sqlRequest = new SQLRequest();
    sqlRequest.setProject("test_project");
    sqlRequest.setSql(mockSql);
    badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, "user", RandomUtil.randomUUID().toString());

    try {
        Thread.sleep(1000);

        QueryInfoCollector.current().setCubeNames(Lists.newArrayList("[CUBE[name=TEST_CUBE]]"));

        Thread.sleep((alertRunningSec * 2 + 1) * 1000);

        BadQueryHistory badQueryHistory = BadQueryHistoryManager.getInstance(KylinConfig.getInstanceFromEnv()).getBadQueriesForProject("test_project");
        Set entries = badQueryHistory.getEntries();

        assertEquals(1, entries.size());

        BadQueryEntry entry = (BadQueryEntry) ((NavigableSet) entries).pollFirst();

        assertNotNull(entry);
        assertEquals(BadQueryEntry.ADJ_SLOW, entry.getAdj());
        assertEquals("[CUBE[name=TEST_CUBE]]", entry.getCube());
    } finally {
        badQueryDetector.queryEnd(Thread.currentThread(), BadQueryEntry.ADJ_SLOW);
        badQueryDetector.interrupt();
        QueryInfoCollector.reset();
    }
}
 
Example 25
Source Project: kylin   Source File: MigrationRuleSet.java    License: Apache License 2.0 5 votes vote down vote up
private long executeQueries(final List<String> queries, final Context ctx) throws Exception {
    int maxThreads = KylinConfig.getInstanceFromEnv().getMigrationRuleQueryLatencyMaxThreads();
    int threadNum = Math.min(maxThreads, queries.size());
    ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
    CompletionService<Long> completionService = new ExecutorCompletionService<Long>(threadPool);
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    long start = System.currentTimeMillis();
    for (final String query : queries) {
        completionService.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                SecurityContextHolder.getContext().setAuthentication(auth);
                SQLRequest sqlRequest = new SQLRequest();
                sqlRequest.setProject(ctx.getSrcProjectName());
                sqlRequest.setSql(query);
                SQLResponse sqlResponse = ctx.getQueryService().doQueryWithCache(sqlRequest, false);
                if (sqlResponse.getIsException()) {
                    throw new RuleValidationException(sqlResponse.getExceptionMessage());
                }
                return sqlResponse.getDuration();
            }

        });
    }
    long timeCostSum = 0L;
    for (int i = 0; i < queries.size(); ++i) {
        try {
            timeCostSum += completionService.take().get();
        } catch (InterruptedException | ExecutionException e) {
            threadPool.shutdownNow();
            throw e;
        }
    }
    long end = System.currentTimeMillis();
    logger.info("Execute" + queries.size() + " queries took " + (end - start) + " ms, query time cost sum "
            + timeCostSum + " ms.");
    return timeCostSum / queries.size();
}
 
Example 26
Source Project: kylin   Source File: QueryMetricsFacade.java    License: Apache License 2.0 5 votes vote down vote up
private static void updateMetricsToLocal(SQLRequest sqlRequest, SQLResponse sqlResponse) {
    if (!enabled)
        return;

    String projectName = sqlRequest.getProject();
    update(getQueryMetrics("Server_Total"), sqlResponse);
    update(getQueryMetrics(projectName), sqlResponse);

    String cube = sqlResponse.getCube();
    String cubeName = cube.replace("=", "->");
    String cubeMetricName = projectName + ",sub=" + cubeName;
    update(getQueryMetrics(cubeMetricName), sqlResponse);
}
 
Example 27
Source Project: kylin   Source File: BadQueryDetector.java    License: Apache License 2.0 5 votes vote down vote up
Entry(SQLRequest sqlRequest, String user, Thread thread, String queryId, QueryInfoCollector collector) {
    this.sqlRequest = sqlRequest;
    this.startTime = System.currentTimeMillis();
    this.thread = thread;
    this.user = user;
    this.queryId = queryId;
    this.collector = collector;
}
 
Example 28
Source Project: kylin   Source File: QueryService.java    License: Apache License 2.0 5 votes vote down vote up
public SQLResponse query(SQLRequest sqlRequest, String queryId) throws Exception {
    SQLResponse ret = null;
    try {
        final String user = SecurityContextHolder.getContext().getAuthentication().getName();
        badQueryDetector.queryStart(Thread.currentThread(), sqlRequest, user, queryId);

        ret = queryWithSqlMassage(sqlRequest);
        return ret;

    } finally {
        String badReason = (ret != null && ret.isPushDown()) ? BadQueryEntry.ADJ_PUSHDOWN : null;
        badQueryDetector.queryEnd(Thread.currentThread(), badReason);
        Thread.interrupted(); //reset if interrupted
    }
}
 
Example 29
Source Project: kylin   Source File: QueryService.java    License: Apache License 2.0 5 votes vote down vote up
protected void processStatementAttr(Statement s, SQLRequest sqlRequest) throws SQLException {
    Integer statementMaxRows = BackdoorToggles.getStatementMaxRows();
    if (statementMaxRows != null) {
        logger.info("Setting current statement's max rows to {}", statementMaxRows);
        s.setMaxRows(statementMaxRows);
    }
}
 
Example 30
Source Project: kylin   Source File: QueryService.java    License: Apache License 2.0 5 votes vote down vote up
private Pair<List<List<String>>, List<SelectedColumnMeta>> pushDownQuery(SQLRequest sqlRequest, String correctedSql,
        Connection conn, SQLException sqlException) throws Exception {
    ProjectInstance projectInstance = getProjectManager().getProject(sqlRequest.getProject());
    try {
        return PushDownUtil.tryPushDownSelectQuery(sqlRequest.getProject(), correctedSql, conn.getSchema(),
                sqlException, BackdoorToggles.getPrepareOnly(), projectInstance != null ? projectInstance.getConfig() : null);
    } catch (Exception e2) {
        logger.error("pushdown engine failed current query too", e2);
        //exception in pushdown, throw it instead of exception in calcite
        throw e2;
    }
}