Search in sources :

Example 1 with AbruptExitException

use of com.google.devtools.build.lib.util.AbruptExitException 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 2 with AbruptExitException

use of com.google.devtools.build.lib.util.AbruptExitException in project bazel by bazelbuild.

the class CommandInterruptionTest method callingExitOnceInterruptsAndOverridesExitCode.

@Test
public void callingExitOnceInterruptsAndOverridesExitCode() throws Exception {
    CommandState command = snooze.runIn(executor, dispatcher, /*expectInterruption=*/
    false);
    command.getModuleEnvironment().exit(new AbruptExitException(ExitCode.NO_TESTS_FOUND));
    command.assertFinishedWith(ExitCode.NO_TESTS_FOUND);
}
Also used : AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException) Test(org.junit.Test)

Example 3 with AbruptExitException

use of com.google.devtools.build.lib.util.AbruptExitException in project bazel by bazelbuild.

the class CommandInterruptionTest method abruptExitCodesDontOverrideInfrastructureFailures.

@Test
public void abruptExitCodesDontOverrideInfrastructureFailures() throws Exception {
    CommandState command = snooze.runIn(executor, dispatcher, /*expectInterruption=*/
    true);
    command.getModuleEnvironment().exit(new AbruptExitException(ExitCode.NO_TESTS_FOUND));
    command.assertNotFinishedYet();
    command.requestExitWith(ExitCode.BLAZE_INTERNAL_ERROR);
    command.assertFinishedWith(ExitCode.BLAZE_INTERNAL_ERROR);
}
Also used : AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException) Test(org.junit.Test)

Example 4 with AbruptExitException

use of com.google.devtools.build.lib.util.AbruptExitException in project bazel by bazelbuild.

the class CommandInterruptionTest method callingExitAfterCommandCompletesDoesNothing.

@Test
public void callingExitAfterCommandCompletesDoesNothing() throws Exception {
    CommandState firstCommand = snooze.runIn(executor, dispatcher, /*expectInterruption=*/
    false);
    firstCommand.requestExitWith(ExitCode.SUCCESS);
    firstCommand.assertFinishedWith(ExitCode.SUCCESS);
    CommandState newCommandOnSameThread = snooze.runIn(executor, dispatcher, /*expectInterruption=*/
    false);
    firstCommand.assertOnSameThreadAs(newCommandOnSameThread);
    firstCommand.getModuleEnvironment().exit(new AbruptExitException(ExitCode.RUN_FAILURE));
    newCommandOnSameThread.assertNotFinishedYet();
    newCommandOnSameThread.requestExitWith(ExitCode.SUCCESS);
}
Also used : AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException) Test(org.junit.Test)

Example 5 with AbruptExitException

use of com.google.devtools.build.lib.util.AbruptExitException in project bazel by bazelbuild.

the class SkyframeExecutor method maybeInjectEmbeddedArtifacts.

@VisibleForTesting
void maybeInjectEmbeddedArtifacts() throws AbruptExitException {
    if (!needToInjectEmbeddedArtifacts) {
        return;
    }
    Preconditions.checkNotNull(artifactFactory.get());
    Preconditions.checkNotNull(binTools);
    Map<SkyKey, SkyValue> values = Maps.newHashMap();
    // Blaze separately handles the symlinks that target these binaries. See BinTools#setupTool.
    for (Artifact artifact : binTools.getAllEmbeddedArtifacts(artifactFactory.get())) {
        FileArtifactValue fileArtifactValue;
        try {
            fileArtifactValue = FileArtifactValue.create(artifact);
        } catch (IOException e) {
            // See ExtractData in blaze.cc.
            String message = "Error: corrupt installation: file " + artifact.getPath() + " missing. " + "Please remove '" + directories.getInstallBase() + "' and try again.";
            throw new AbruptExitException(message, ExitCode.LOCAL_ENVIRONMENTAL_ERROR, e);
        }
        values.put(ArtifactSkyKey.key(artifact, /*isMandatory=*/
        true), fileArtifactValue);
    }
    injectable().inject(values);
    needToInjectEmbeddedArtifacts = false;
}
Also used : SkyKey(com.google.devtools.build.skyframe.SkyKey) SkyValue(com.google.devtools.build.skyframe.SkyValue) IOException(java.io.IOException) AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException) Artifact(com.google.devtools.build.lib.actions.Artifact) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

AbruptExitException (com.google.devtools.build.lib.util.AbruptExitException)15 IOException (java.io.IOException)8 Test (org.junit.Test)5 Path (com.google.devtools.build.lib.vfs.Path)4 BlazeRuntime (com.google.devtools.build.lib.runtime.BlazeRuntime)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 NoBuildEvent (com.google.devtools.build.lib.analysis.NoBuildEvent)2 InvalidConfigurationException (com.google.devtools.build.lib.analysis.config.InvalidConfigurationException)2 Target (com.google.devtools.build.lib.packages.Target)2 QueryException (com.google.devtools.build.lib.query2.engine.QueryException)2 QueryExpression (com.google.devtools.build.lib.query2.engine.QueryExpression)2 RPCServer (com.google.devtools.build.lib.server.RPCServer)2 ExitCode (com.google.devtools.build.lib.util.ExitCode)2 OutErr (com.google.devtools.build.lib.util.io.OutErr)2 OptionsParsingException (com.google.devtools.common.options.OptionsParsingException)2 Supplier (com.google.common.base.Supplier)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Artifact (com.google.devtools.build.lib.actions.Artifact)1 BuildFailedException (com.google.devtools.build.lib.actions.BuildFailedException)1