Search in sources :

Example 1 with TokenMgrError

use of org.apache.asterix.lang.aql.parser.TokenMgrError in project asterixdb by apache.

the class QueryServiceServlet method handleRequest.

private void handleRequest(RequestParameters param, IServletResponse response) throws IOException {
    LOGGER.info(param.toString());
    long elapsedStart = System.nanoTime();
    final StringWriter stringWriter = new StringWriter();
    final PrintWriter resultWriter = new PrintWriter(stringWriter);
    ResultDelivery delivery = parseResultDelivery(param.mode);
    String handleUrl = getHandleUrl(param.host, param.path, delivery);
    SessionOutput sessionOutput = createSessionOutput(param, handleUrl, resultWriter);
    SessionConfig sessionConfig = sessionOutput.config();
    HttpUtil.setContentType(response, HttpUtil.ContentType.APPLICATION_JSON, HttpUtil.Encoding.UTF8);
    HttpResponseStatus status = HttpResponseStatus.OK;
    Stats stats = new Stats();
    long[] execStartEnd = new long[] { -1, -1 };
    resultWriter.print("{\n");
    printRequestId(resultWriter);
    printClientContextID(resultWriter, param);
    printSignature(resultWriter);
    printType(resultWriter, sessionConfig);
    try {
        if (param.statement == null || param.statement.isEmpty()) {
            throw new AsterixException("Empty request, no statement provided");
        }
        String statementsText = param.statement + ";";
        executeStatement(statementsText, sessionOutput, delivery, stats, param, handleUrl, execStartEnd);
        if (ResultDelivery.IMMEDIATE == delivery || ResultDelivery.DEFERRED == delivery) {
            ResultUtil.printStatus(sessionOutput, ResultStatus.SUCCESS);
        }
    } catch (AlgebricksException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.INFO, pe.getMessage(), pe);
        ResultUtil.printError(resultWriter, pe);
        ResultUtil.printStatus(sessionOutput, ResultStatus.FATAL);
        status = HttpResponseStatus.BAD_REQUEST;
    } catch (HyracksException pe) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.WARNING, pe.getMessage(), pe);
        ResultUtil.printError(resultWriter, pe);
        ResultUtil.printStatus(sessionOutput, ResultStatus.FATAL);
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, "Unexpected exception", e);
        ResultUtil.printError(resultWriter, e);
        ResultUtil.printStatus(sessionOutput, ResultStatus.FATAL);
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    } finally {
        if (execStartEnd[0] == -1) {
            execStartEnd[1] = -1;
        } else if (execStartEnd[1] == -1) {
            execStartEnd[1] = System.nanoTime();
        }
    }
    printMetrics(resultWriter, System.nanoTime() - elapsedStart, execStartEnd[1] - execStartEnd[0], stats.getCount(), stats.getSize());
    resultWriter.print("}\n");
    resultWriter.flush();
    String result = stringWriter.toString();
    GlobalConfig.ASTERIX_LOGGER.log(Level.FINE, result);
    response.setStatus(status);
    response.writer().print(result);
    if (response.writer().checkError()) {
        LOGGER.warning("Error flushing output writer");
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) AlgebricksException(org.apache.hyracks.algebricks.common.exceptions.AlgebricksException) SessionConfig(org.apache.asterix.translator.SessionConfig) TokenMgrError(org.apache.asterix.lang.aql.parser.TokenMgrError) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) ResultDelivery(org.apache.asterix.translator.IStatementExecutor.ResultDelivery) AsterixException(org.apache.asterix.common.exceptions.AsterixException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) AlgebricksException(org.apache.hyracks.algebricks.common.exceptions.AlgebricksException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) AsterixException(org.apache.asterix.common.exceptions.AsterixException) StringWriter(java.io.StringWriter) SessionOutput(org.apache.asterix.translator.SessionOutput) Stats(org.apache.asterix.translator.IStatementExecutor.Stats) PrintWriter(java.io.PrintWriter)

Example 2 with TokenMgrError

use of org.apache.asterix.lang.aql.parser.TokenMgrError in project asterixdb by apache.

the class RestApiServlet method doHandle.

private void doHandle(IServletResponse response, String query, SessionOutput sessionOutput, ResultDelivery resultDelivery) throws JsonProcessingException {
    try {
        response.setStatus(HttpResponseStatus.OK);
        IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
        IHyracksDataset hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
        if (hds == null) {
            synchronized (ctx) {
                hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
                if (hds == null) {
                    hds = new HyracksDataset(hcc, appCtx.getCompilerProperties().getFrameSize(), ResultReader.NUM_READERS);
                    ctx.put(HYRACKS_DATASET_ATTR, hds);
                }
            }
        }
        IParser parser = parserFactory.createParser(query);
        List<Statement> aqlStatements = parser.parse();
        validate(aqlStatements);
        MetadataManager.INSTANCE.init();
        IStatementExecutor translator = statementExecutorFactory.create(appCtx, aqlStatements, sessionOutput, compilationProvider, componentProvider);
        translator.compileAndExecute(hcc, hds, resultDelivery, null, new IStatementExecutor.Stats());
    } catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, pe.getMessage(), pe);
        String errorMessage = ResultUtil.buildParseExceptionMessage(pe, query);
        ObjectNode errorResp = ResultUtil.getErrorResponse(2, errorMessage, "", ResultUtil.extractFullStackTrace(pe));
        sessionOutput.out().write(new ObjectMapper().writeValueAsString(errorResp));
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        ResultUtil.apiErrorHandler(sessionOutput.out(), e);
    }
}
Also used : IHyracksClientConnection(org.apache.hyracks.api.client.IHyracksClientConnection) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Statement(org.apache.asterix.lang.common.base.Statement) TokenMgrError(org.apache.asterix.lang.aql.parser.TokenMgrError) AsterixException(org.apache.asterix.common.exceptions.AsterixException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IStatementExecutor(org.apache.asterix.translator.IStatementExecutor) AsterixException(org.apache.asterix.common.exceptions.AsterixException) HyracksDataset(org.apache.hyracks.client.dataset.HyracksDataset) IHyracksDataset(org.apache.hyracks.api.dataset.IHyracksDataset) IHyracksDataset(org.apache.hyracks.api.dataset.IHyracksDataset) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IParser(org.apache.asterix.lang.common.base.IParser)

Example 3 with TokenMgrError

use of org.apache.asterix.lang.aql.parser.TokenMgrError in project asterixdb by apache.

the class ApiServlet method post.

@Override
protected void post(IServletRequest request, IServletResponse response) {
    // Query language
    ILangCompilationProvider compilationProvider = "AQL".equals(request.getParameter("query-language")) ? aqlCompilationProvider : sqlppCompilationProvider;
    IParserFactory parserFactory = compilationProvider.getParserFactory();
    // Output format.
    PrintWriter out = response.writer();
    OutputFormat format;
    boolean csvAndHeader = false;
    String output = request.getParameter("output-format");
    try {
        format = OutputFormat.valueOf(output);
    } catch (IllegalArgumentException e) {
        LOGGER.log(Level.INFO, output + ": unsupported output-format, using " + OutputFormat.CLEAN_JSON + " instead", e);
        // Default output format
        format = OutputFormat.CLEAN_JSON;
    }
    String query = request.getParameter("query");
    String wrapperArray = request.getParameter("wrapper-array");
    String printExprParam = request.getParameter("print-expr-tree");
    String printRewrittenExprParam = request.getParameter("print-rewritten-expr-tree");
    String printLogicalPlanParam = request.getParameter("print-logical-plan");
    String printOptimizedLogicalPlanParam = request.getParameter("print-optimized-logical-plan");
    String printJob = request.getParameter("print-job");
    String executeQuery = request.getParameter("execute-query");
    try {
        response.setStatus(HttpResponseStatus.OK);
        HttpUtil.setContentType(response, ContentType.TEXT_HTML, Encoding.UTF8);
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Failure setting content type", e);
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return;
    }
    try {
        IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
        IHyracksDataset hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
        if (hds == null) {
            synchronized (ctx) {
                hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
                if (hds == null) {
                    hds = new HyracksDataset(hcc, appCtx.getCompilerProperties().getFrameSize(), ResultReader.NUM_READERS);
                    ctx.put(HYRACKS_DATASET_ATTR, hds);
                }
            }
        }
        IParser parser = parserFactory.createParser(query);
        List<Statement> aqlStatements = parser.parse();
        SessionConfig sessionConfig = new SessionConfig(format, true, isSet(executeQuery), true);
        sessionConfig.set(SessionConfig.FORMAT_HTML, true);
        sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, csvAndHeader);
        sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, isSet(wrapperArray));
        sessionConfig.setOOBData(isSet(printExprParam), isSet(printRewrittenExprParam), isSet(printLogicalPlanParam), isSet(printOptimizedLogicalPlanParam), isSet(printJob));
        SessionOutput sessionOutput = new SessionOutput(sessionConfig, out);
        MetadataManager.INSTANCE.init();
        IStatementExecutor translator = statementExectorFactory.create(appCtx, aqlStatements, sessionOutput, compilationProvider, componentProvider);
        double duration;
        long startTime = System.currentTimeMillis();
        translator.compileAndExecute(hcc, hds, IStatementExecutor.ResultDelivery.IMMEDIATE, null, new IStatementExecutor.Stats());
        long endTime = System.currentTimeMillis();
        duration = (endTime - startTime) / 1000.00;
        out.println(HTML_STATEMENT_SEPARATOR);
        out.println("<PRE>Duration of all jobs: " + duration + " sec</PRE>");
    } catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.INFO, pe.toString(), pe);
        ResultUtil.webUIParseExceptionHandler(out, pe, query);
    } catch (Exception e) {
        GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        ResultUtil.webUIErrorHandler(out, e);
    }
}
Also used : IHyracksClientConnection(org.apache.hyracks.api.client.IHyracksClientConnection) SessionConfig(org.apache.asterix.translator.SessionConfig) AsterixException(org.apache.asterix.common.exceptions.AsterixException) ILangCompilationProvider(org.apache.asterix.compiler.provider.ILangCompilationProvider) IHyracksDataset(org.apache.hyracks.api.dataset.IHyracksDataset) IParserFactory(org.apache.asterix.lang.common.base.IParserFactory) PrintWriter(java.io.PrintWriter) Statement(org.apache.asterix.lang.common.base.Statement) OutputFormat(org.apache.asterix.translator.SessionConfig.OutputFormat) TokenMgrError(org.apache.asterix.lang.aql.parser.TokenMgrError) IOException(java.io.IOException) AsterixException(org.apache.asterix.common.exceptions.AsterixException) IOException(java.io.IOException) IStatementExecutor(org.apache.asterix.translator.IStatementExecutor) HyracksDataset(org.apache.hyracks.client.dataset.HyracksDataset) IHyracksDataset(org.apache.hyracks.api.dataset.IHyracksDataset) SessionOutput(org.apache.asterix.translator.SessionOutput) IParser(org.apache.asterix.lang.common.base.IParser)

Example 4 with TokenMgrError

use of org.apache.asterix.lang.aql.parser.TokenMgrError in project asterixdb by apache.

the class ExecuteStatementRequestMessage method handle.

@Override
public void handle(ICcApplicationContext ccAppCtx) throws HyracksDataException, InterruptedException {
    ICCServiceContext ccSrvContext = ccAppCtx.getServiceContext();
    ClusterControllerService ccSrv = (ClusterControllerService) ccSrvContext.getControllerService();
    CCApplication ccApp = (CCApplication) ccSrv.getApplication();
    CCMessageBroker messageBroker = (CCMessageBroker) ccSrvContext.getMessageBroker();
    CCExtensionManager ccExtMgr = (CCExtensionManager) ccAppCtx.getExtensionManager();
    ILangCompilationProvider compilationProvider = ccExtMgr.getCompilationProvider(lang);
    IStorageComponentProvider storageComponentProvider = ccAppCtx.getStorageComponentProvider();
    IStatementExecutorFactory statementExecutorFactory = ccApp.getStatementExecutorFactory();
    IStatementExecutorContext statementExecutorContext = ccApp.getStatementExecutorContext();
    ccSrv.getExecutor().submit(() -> {
        ExecuteStatementResponseMessage responseMsg = new ExecuteStatementResponseMessage(requestMessageId);
        try {
            final IClusterManagementWork.ClusterState clusterState = ClusterStateManager.INSTANCE.getState();
            if (clusterState != IClusterManagementWork.ClusterState.ACTIVE) {
                throw new IllegalStateException("Cannot execute request, cluster is " + clusterState);
            }
            IParser parser = compilationProvider.getParserFactory().createParser(statementsText);
            List<Statement> statements = parser.parse();
            StringWriter outWriter = new StringWriter(256);
            PrintWriter outPrinter = new PrintWriter(outWriter);
            SessionOutput.ResultDecorator resultPrefix = ResultUtil.createPreResultDecorator();
            SessionOutput.ResultDecorator resultPostfix = ResultUtil.createPostResultDecorator();
            SessionOutput.ResultAppender appendHandle = ResultUtil.createResultHandleAppender(handleUrl);
            SessionOutput.ResultAppender appendStatus = ResultUtil.createResultStatusAppender();
            SessionOutput sessionOutput = new SessionOutput(sessionConfig, outPrinter, resultPrefix, resultPostfix, appendHandle, appendStatus);
            IStatementExecutor.ResultMetadata outMetadata = new IStatementExecutor.ResultMetadata();
            MetadataManager.INSTANCE.init();
            IStatementExecutor translator = statementExecutorFactory.create(ccAppCtx, statements, sessionOutput, compilationProvider, storageComponentProvider);
            translator.compileAndExecute(ccAppCtx.getHcc(), null, delivery, outMetadata, new IStatementExecutor.Stats(), clientContextID, statementExecutorContext);
            outPrinter.close();
            responseMsg.setResult(outWriter.toString());
            responseMsg.setMetadata(outMetadata);
        } catch (AlgebricksException | HyracksException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
            // we trust that "our" exceptions are serializable and have a comprehensible error message
            GlobalConfig.ASTERIX_LOGGER.log(Level.WARNING, pe.getMessage(), pe);
            responseMsg.setError(pe);
        } catch (Exception e) {
            GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, "Unexpected exception", e);
            responseMsg.setError(new Exception(e.toString()));
        }
        try {
            messageBroker.sendApplicationMessageToNC(responseMsg, requestNodeId);
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, e.toString(), e);
        }
    });
}
Also used : ICCServiceContext(org.apache.hyracks.api.application.ICCServiceContext) CCApplication(org.apache.asterix.hyracks.bootstrap.CCApplication) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) StringWriter(java.io.StringWriter) ILangCompilationProvider(org.apache.asterix.compiler.provider.ILangCompilationProvider) IStatementExecutorFactory(org.apache.asterix.translator.IStatementExecutorFactory) PrintWriter(java.io.PrintWriter) IStorageComponentProvider(org.apache.asterix.common.context.IStorageComponentProvider) IStatementExecutorContext(org.apache.asterix.translator.IStatementExecutorContext) Statement(org.apache.asterix.lang.common.base.Statement) CCMessageBroker(org.apache.asterix.messaging.CCMessageBroker) IClusterManagementWork(org.apache.asterix.common.api.IClusterManagementWork) AlgebricksException(org.apache.hyracks.algebricks.common.exceptions.AlgebricksException) TokenMgrError(org.apache.asterix.lang.aql.parser.TokenMgrError) HyracksDataException(org.apache.hyracks.api.exceptions.HyracksDataException) AlgebricksException(org.apache.hyracks.algebricks.common.exceptions.AlgebricksException) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) CCExtensionManager(org.apache.asterix.app.cc.CCExtensionManager) IStatementExecutor(org.apache.asterix.translator.IStatementExecutor) SessionOutput(org.apache.asterix.translator.SessionOutput) ClusterControllerService(org.apache.hyracks.control.cc.ClusterControllerService) IParser(org.apache.asterix.lang.common.base.IParser)

Aggregations

TokenMgrError (org.apache.asterix.lang.aql.parser.TokenMgrError)4 IOException (java.io.IOException)3 PrintWriter (java.io.PrintWriter)3 AsterixException (org.apache.asterix.common.exceptions.AsterixException)3 IParser (org.apache.asterix.lang.common.base.IParser)3 Statement (org.apache.asterix.lang.common.base.Statement)3 IStatementExecutor (org.apache.asterix.translator.IStatementExecutor)3 SessionOutput (org.apache.asterix.translator.SessionOutput)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 StringWriter (java.io.StringWriter)2 ILangCompilationProvider (org.apache.asterix.compiler.provider.ILangCompilationProvider)2 SessionConfig (org.apache.asterix.translator.SessionConfig)2 AlgebricksException (org.apache.hyracks.algebricks.common.exceptions.AlgebricksException)2 IHyracksClientConnection (org.apache.hyracks.api.client.IHyracksClientConnection)2 IHyracksDataset (org.apache.hyracks.api.dataset.IHyracksDataset)2 HyracksException (org.apache.hyracks.api.exceptions.HyracksException)2 HyracksDataset (org.apache.hyracks.client.dataset.HyracksDataset)2 JsonParseException (com.fasterxml.jackson.core.JsonParseException)1 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1