Search in sources :

Example 1 with ThreadSafeOutputFormatterCallback

use of com.google.devtools.build.lib.query2.engine.ThreadSafeOutputFormatterCallback in project bazel by bazelbuild.

the class BlazeQueryEnvironment method evaluateQuery.

@Override
public DigraphQueryEvalResult<Target> evaluateQuery(QueryExpression expr, ThreadSafeOutputFormatterCallback<Target> callback) throws QueryException, InterruptedException, IOException {
    eventHandler.resetErrors();
    resolvedTargetPatterns.clear();
    QueryEvalResult queryEvalResult = super.evaluateQuery(expr, callback);
    return new DigraphQueryEvalResult<>(queryEvalResult.getSuccess(), queryEvalResult.isEmpty(), graph);
}
Also used : DigraphQueryEvalResult(com.google.devtools.build.lib.query2.engine.DigraphQueryEvalResult) QueryEvalResult(com.google.devtools.build.lib.query2.engine.QueryEvalResult) DigraphQueryEvalResult(com.google.devtools.build.lib.query2.engine.DigraphQueryEvalResult)

Example 2 with ThreadSafeOutputFormatterCallback

use of com.google.devtools.build.lib.query2.engine.ThreadSafeOutputFormatterCallback in project bazel by bazelbuild.

the class QueryCommand method exec.

/**
   * Exit codes:
   *   0   on successful evaluation.
   *   1   if query evaluation did not complete.
   *   2   if query parsing failed.
   *   3   if errors were reported but evaluation produced a partial result
   *        (only when --keep_going is in effect.)
   */
@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) {
    BlazeRuntime runtime = env.getRuntime();
    QueryOptions queryOptions = options.getOptions(QueryOptions.class);
    try {
        env.setupPackageCache(options, runtime.getDefaultsPackageContent());
    } catch (InterruptedException e) {
        env.getReporter().handle(Event.error("query interrupted"));
        return ExitCode.INTERRUPTED;
    } catch (AbruptExitException e) {
        env.getReporter().handle(Event.error(null, "Unknown error: " + e.getMessage()));
        return e.getExitCode();
    }
    String query;
    if (!options.getResidue().isEmpty()) {
        if (!queryOptions.queryFile.isEmpty()) {
            env.getReporter().handle(Event.error("Command-line query and --query_file cannot both be specified"));
            return ExitCode.COMMAND_LINE_ERROR;
        }
        query = Joiner.on(' ').join(options.getResidue());
    } else if (!queryOptions.queryFile.isEmpty()) {
        // Works for absolute or relative query file.
        Path residuePath = env.getWorkingDirectory().getRelative(queryOptions.queryFile);
        try {
            query = new String(FileSystemUtils.readContent(residuePath), StandardCharsets.UTF_8);
        } catch (IOException e) {
            env.getReporter().handle(Event.error("I/O error reading from " + residuePath.getPathString()));
            return ExitCode.COMMAND_LINE_ERROR;
        }
    } else {
        env.getReporter().handle(Event.error(String.format("missing query expression. Type '%s help query' for syntax and help", runtime.getProductName())));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    Iterable<OutputFormatter> formatters = runtime.getQueryOutputFormatters();
    OutputFormatter formatter = OutputFormatter.getFormatter(formatters, queryOptions.outputFormat);
    if (formatter == null) {
        env.getReporter().handle(Event.error(String.format("Invalid output format '%s'. Valid values are: %s", queryOptions.outputFormat, OutputFormatter.formatterNames(formatters))));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    Set<Setting> settings = queryOptions.toSettings();
    boolean streamResults = QueryOutputUtils.shouldStreamResults(queryOptions, formatter);
    QueryEvalResult result;
    AbstractBlazeQueryEnvironment<Target> queryEnv = newQueryEnvironment(env, queryOptions.keepGoing, !streamResults, queryOptions.universeScope, queryOptions.loadingPhaseThreads, settings);
    // 1. Parse and transform query:
    QueryExpression expr;
    try {
        expr = QueryExpression.parse(query, queryEnv);
    } catch (QueryException e) {
        env.getReporter().handle(Event.error(null, "Error while parsing '" + query + "': " + e.getMessage()));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    expr = queryEnv.transformParsedQuery(expr);
    OutputStream out = env.getReporter().getOutErr().getOutputStream();
    ThreadSafeOutputFormatterCallback<Target> callback;
    if (streamResults) {
        disableAnsiCharactersFiltering(env);
        // 2. Evaluate expression:
        StreamedFormatter streamedFormatter = ((StreamedFormatter) formatter);
        streamedFormatter.setOptions(queryOptions, queryOptions.aspectDeps.createResolver(env.getPackageManager(), env.getReporter()));
        callback = streamedFormatter.createStreamCallback(out, queryOptions, queryEnv);
    } else {
        callback = QueryUtil.newOrderedAggregateAllOutputFormatterCallback();
    }
    boolean catastrophe = true;
    try {
        result = queryEnv.evaluateQuery(expr, callback);
        catastrophe = false;
    } catch (QueryException e) {
        catastrophe = false;
        // Keep consistent with reportBuildFileError()
        env.getReporter().handle(Event.error(e.getMessage() == null ? e.toString() : e.getMessage()));
        return ExitCode.ANALYSIS_FAILURE;
    } catch (InterruptedException e) {
        catastrophe = false;
        IOException ioException = callback.getIoException();
        if (ioException == null || ioException instanceof ClosedByInterruptException) {
            env.getReporter().handle(Event.error("query interrupted"));
            return ExitCode.INTERRUPTED;
        } else {
            env.getReporter().handle(Event.error("I/O error: " + e.getMessage()));
            return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
        }
    } catch (IOException e) {
        catastrophe = false;
        env.getReporter().handle(Event.error("I/O error: " + e.getMessage()));
        return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    } finally {
        if (!catastrophe) {
            try {
                out.flush();
            } catch (IOException e) {
                env.getReporter().handle(Event.error("Failed to flush query results: " + e.getMessage()));
                return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
            }
        }
    }
    env.getEventBus().post(new NoBuildEvent());
    if (!streamResults) {
        disableAnsiCharactersFiltering(env);
        // 3. Output results:
        try {
            Set<Target> targets = ((AggregateAllOutputFormatterCallback<Target>) callback).getResult();
            QueryOutputUtils.output(queryOptions, result, targets, formatter, env.getReporter().getOutErr().getOutputStream(), queryOptions.aspectDeps.createResolver(env.getPackageManager(), env.getReporter()));
        } catch (ClosedByInterruptException | InterruptedException e) {
            env.getReporter().handle(Event.error("query interrupted"));
            return ExitCode.INTERRUPTED;
        } catch (IOException e) {
            env.getReporter().handle(Event.error("I/O error: " + e.getMessage()));
            return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
        } finally {
            try {
                out.flush();
            } catch (IOException e) {
                env.getReporter().handle(Event.error("Failed to flush query results: " + e.getMessage()));
                return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
            }
        }
    }
    if (result.isEmpty()) {
        env.getReporter().handle(Event.info("Empty results"));
    }
    return result.getSuccess() ? ExitCode.SUCCESS : ExitCode.PARTIAL_ANALYSIS_FAILURE;
}
Also used : OutputStream(java.io.OutputStream) QueryEvalResult(com.google.devtools.build.lib.query2.engine.QueryEvalResult) StreamedFormatter(com.google.devtools.build.lib.query2.output.OutputFormatter.StreamedFormatter) AggregateAllOutputFormatterCallback(com.google.devtools.build.lib.query2.engine.QueryUtil.AggregateAllOutputFormatterCallback) QueryOptions(com.google.devtools.build.lib.query2.output.QueryOptions) OutputFormatter(com.google.devtools.build.lib.query2.output.OutputFormatter) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) Target(com.google.devtools.build.lib.packages.Target) QueryExpression(com.google.devtools.build.lib.query2.engine.QueryExpression) Path(com.google.devtools.build.lib.vfs.Path) Setting(com.google.devtools.build.lib.query2.engine.QueryEnvironment.Setting) NoBuildEvent(com.google.devtools.build.lib.analysis.NoBuildEvent) IOException(java.io.IOException) BlazeRuntime(com.google.devtools.build.lib.runtime.BlazeRuntime) QueryException(com.google.devtools.build.lib.query2.engine.QueryException) AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException)

Example 3 with ThreadSafeOutputFormatterCallback

use of com.google.devtools.build.lib.query2.engine.ThreadSafeOutputFormatterCallback in project bazel by bazelbuild.

the class FetchCommand method exec.

@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) {
    BlazeRuntime runtime = env.getRuntime();
    if (options.getResidue().isEmpty()) {
        env.getReporter().handle(Event.error(String.format("missing fetch expression. Type '%s help fetch' for syntax and help", env.getRuntime().getProductName())));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    try {
        env.setupPackageCache(options, runtime.getDefaultsPackageContent());
    } catch (InterruptedException e) {
        env.getReporter().handle(Event.error("fetch interrupted"));
        return ExitCode.INTERRUPTED;
    } catch (AbruptExitException e) {
        env.getReporter().handle(Event.error(null, "Unknown error: " + e.getMessage()));
        return e.getExitCode();
    }
    PackageCacheOptions pkgOptions = options.getOptions(PackageCacheOptions.class);
    if (!pkgOptions.fetch) {
        env.getReporter().handle(Event.error(null, "You cannot run fetch with --fetch=false"));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    // Querying for all of the dependencies of the targets has the side-effect of populating the
    // Skyframe graph for external targets, which requires downloading them. The JDK is required to
    // build everything but isn't counted as a dep in the build graph so we add it manually.
    ImmutableList.Builder<String> labelsToLoad = new ImmutableList.Builder<String>().addAll(options.getResidue());
    String query = Joiner.on(" union ").join(labelsToLoad.build());
    query = "deps(" + query + ")";
    AbstractBlazeQueryEnvironment<Target> queryEnv = QueryCommand.newQueryEnvironment(env, options.getOptions(FetchOptions.class).keepGoing, false, Lists.<String>newArrayList(), 200, Sets.<Setting>newHashSet());
    // 1. Parse query:
    QueryExpression expr;
    try {
        expr = QueryExpression.parse(query, queryEnv);
    } catch (QueryException e) {
        env.getReporter().handle(Event.error(null, "Error while parsing '" + query + "': " + e.getMessage()));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    // 2. Evaluate expression:
    try {
        queryEnv.evaluateQuery(expr, new ThreadSafeOutputFormatterCallback<Target>() {

            @Override
            public void processOutput(Iterable<Target> partialResult) {
            // Throw away the result.
            }
        });
    } catch (InterruptedException e) {
        return ExitCode.COMMAND_LINE_ERROR;
    } catch (QueryException e) {
        // Keep consistent with reportBuildFileError()
        env.getReporter().handle(Event.error(e.getMessage()));
        return ExitCode.COMMAND_LINE_ERROR;
    } catch (IOException e) {
        // Should be impossible since our OutputFormatterCallback doesn't throw IOException.
        throw new IllegalStateException(e);
    }
    env.getReporter().handle(Event.progress("All external dependencies fetched successfully."));
    return ExitCode.SUCCESS;
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) IOException(java.io.IOException) PackageCacheOptions(com.google.devtools.build.lib.pkgcache.PackageCacheOptions) BlazeRuntime(com.google.devtools.build.lib.runtime.BlazeRuntime) Target(com.google.devtools.build.lib.packages.Target) QueryException(com.google.devtools.build.lib.query2.engine.QueryException) AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException) QueryExpression(com.google.devtools.build.lib.query2.engine.QueryExpression)

Example 4 with ThreadSafeOutputFormatterCallback

use of com.google.devtools.build.lib.query2.engine.ThreadSafeOutputFormatterCallback in project bazel by bazelbuild.

the class AbstractBlazeQueryEnvironment method evaluateQuery.

/**
   * Evaluate the specified query expression in this environment, streaming results to the given
   * {@code callback}. {@code callback.start()} will be called before query evaluation and
   * {@code callback.close()} will be unconditionally called at the end of query evaluation
   * (i.e. regardless of whether it was successful).
   *
   * @return a {@link QueryEvalResult} object that contains the resulting set of targets and a bit
   *   to indicate whether errors occurred during evaluation; note that the
   *   success status can only be false if {@code --keep_going} was in effect
   * @throws QueryException if the evaluation failed and {@code --nokeep_going} was in
   *   effect
   */
public QueryEvalResult evaluateQuery(QueryExpression expr, ThreadSafeOutputFormatterCallback<T> callback) throws QueryException, InterruptedException, IOException {
    EmptinessSensingCallback<T> emptySensingCallback = new EmptinessSensingCallback<>(callback);
    long startTime = System.currentTimeMillis();
    // In the --nokeep_going case, errors are reported in the order in which the patterns are
    // specified; using a linked hash set here makes sure that the left-most error is reported.
    Set<String> targetPatternSet = new LinkedHashSet<>();
    expr.collectTargetPatterns(targetPatternSet);
    try {
        preloadOrThrow(expr, targetPatternSet);
    } catch (TargetParsingException e) {
        // Unfortunately, by evaluating the patterns in parallel, we lose some location information.
        throw new QueryException(expr, e.getMessage());
    }
    IOException ioExn = null;
    boolean failFast = true;
    try {
        callback.start();
        evalTopLevelInternal(expr, emptySensingCallback);
        failFast = false;
    } catch (QueryException e) {
        throw new QueryException(e, expr);
    } catch (InterruptedException e) {
        throw e;
    } finally {
        try {
            callback.close(failFast);
        } catch (IOException e) {
            // Only throw this IOException if we weren't about to throw a different exception.
            ioExn = e;
        }
    }
    if (ioExn != null) {
        throw ioExn;
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    if (elapsedTime > 1) {
        logger.info("Spent " + elapsedTime + " milliseconds evaluating query");
    }
    if (eventHandler.hasErrors()) {
        if (!keepGoing) {
            // of target patterns that don't cause evaluation to fail per se.
            throw new QueryException("Evaluation of query \"" + expr + "\" failed due to BUILD file errors");
        } else {
            eventHandler.handle(Event.warn("--keep_going specified, ignoring errors.  " + "Results may be inaccurate"));
        }
    }
    return new QueryEvalResult(!eventHandler.hasErrors(), emptySensingCallback.isEmpty());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) QueryEvalResult(com.google.devtools.build.lib.query2.engine.QueryEvalResult) IOException(java.io.IOException) QueryException(com.google.devtools.build.lib.query2.engine.QueryException) TargetParsingException(com.google.devtools.build.lib.cmdline.TargetParsingException)

Aggregations

QueryEvalResult (com.google.devtools.build.lib.query2.engine.QueryEvalResult)3 QueryException (com.google.devtools.build.lib.query2.engine.QueryException)3 IOException (java.io.IOException)3 Target (com.google.devtools.build.lib.packages.Target)2 QueryExpression (com.google.devtools.build.lib.query2.engine.QueryExpression)2 BlazeRuntime (com.google.devtools.build.lib.runtime.BlazeRuntime)2 AbruptExitException (com.google.devtools.build.lib.util.AbruptExitException)2 ImmutableList (com.google.common.collect.ImmutableList)1 NoBuildEvent (com.google.devtools.build.lib.analysis.NoBuildEvent)1 TargetParsingException (com.google.devtools.build.lib.cmdline.TargetParsingException)1 PackageCacheOptions (com.google.devtools.build.lib.pkgcache.PackageCacheOptions)1 DigraphQueryEvalResult (com.google.devtools.build.lib.query2.engine.DigraphQueryEvalResult)1 Setting (com.google.devtools.build.lib.query2.engine.QueryEnvironment.Setting)1 AggregateAllOutputFormatterCallback (com.google.devtools.build.lib.query2.engine.QueryUtil.AggregateAllOutputFormatterCallback)1 OutputFormatter (com.google.devtools.build.lib.query2.output.OutputFormatter)1 StreamedFormatter (com.google.devtools.build.lib.query2.output.OutputFormatter.StreamedFormatter)1 QueryOptions (com.google.devtools.build.lib.query2.output.QueryOptions)1 Path (com.google.devtools.build.lib.vfs.Path)1 OutputStream (java.io.OutputStream)1 ClosedByInterruptException (java.nio.channels.ClosedByInterruptException)1