Search in sources :

Example 6 with CommandException

use of com.google.devtools.build.lib.shell.CommandException in project bazel by bazelbuild.

the class BazelBuilder method buildAndGetElapsedTime.

@Override
public double buildAndGetElapsedTime(Path buildBinary, ImmutableList<String> args) throws CommandException {
    List<String> cmdList = new ArrayList<>();
    cmdList.add(buildBinary.toString());
    cmdList.addAll(args);
    String[] cmdArr = new String[cmdList.size()];
    cmdArr = cmdList.toArray(cmdArr);
    // Run build command
    Command cmd = new Command(cmdArr, null, generatedCodeDir.toFile());
    CommandResult result = cmd.execute();
    // Get elapsed time from output
    String output = new String(result.getStderr(), UTF_8).trim();
    Matcher m = ELAPSED_TIME_PATTERN.matcher(output);
    if (m.find()) {
        try {
            return (Double.parseDouble(m.group(0)));
        } catch (NumberFormatException e) {
            // Should not be here since we look for [0-9.]+
            logger.log(Level.SEVERE, "Cannot parse " + m.group(0));
        }
    }
    throw new CommandException(cmd, "Command didn't provide parsable output.");
}
Also used : Command(com.google.devtools.build.lib.shell.Command) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) CommandException(com.google.devtools.build.lib.shell.CommandException) CommandResult(com.google.devtools.build.lib.shell.CommandResult)

Example 7 with CommandException

use of com.google.devtools.build.lib.shell.CommandException in project bazel by bazelbuild.

the class CommandUtilsTest method failingCommand.

@Test
public void failingCommand() throws Exception {
    String[] args = new String[3];
    args[0] = "/bin/sh";
    args[1] = "-c";
    args[2] = "echo Some errors 1>&2; echo Some output; exit 42";
    Map<String, String> env = Maps.newTreeMap();
    env.put("FOO", "foo");
    env.put("PATH", "/usr/bin:/bin:/sbin");
    try {
        new Command(args, env, null).execute();
        fail();
    } catch (CommandException exception) {
        String message = CommandUtils.describeCommandFailure(false, exception);
        String verboseMessage = CommandUtils.describeCommandFailure(true, exception);
        assertEquals("sh failed: error executing command " + "/bin/sh -c 'echo Some errors 1>&2; echo Some output; exit 42': " + "Process exited with status 42\n" + "Some output\n" + "Some errors\n", message);
        assertEquals("sh failed: error executing command \n" + "  (exec env - \\\n" + "    FOO=foo \\\n" + "    PATH=/usr/bin:/bin:/sbin \\\n" + "  /bin/sh -c 'echo Some errors 1>&2; echo Some output; exit 42'): " + "Process exited with status 42\n" + "Some output\n" + "Some errors\n", verboseMessage);
    }
}
Also used : Command(com.google.devtools.build.lib.shell.Command) CommandException(com.google.devtools.build.lib.shell.CommandException) Test(org.junit.Test)

Example 8 with CommandException

use of com.google.devtools.build.lib.shell.CommandException in project bazel by bazelbuild.

the class CommandUtilsTest method longCommand.

@Test
public void longCommand() throws Exception {
    String[] args = new String[40];
    args[0] = "this_command_will_not_be_found";
    for (int i = 1; i < args.length; i++) {
        args[i] = "arg" + i;
    }
    Map<String, String> env = Maps.newTreeMap();
    env.put("PATH", "/usr/bin:/bin:/sbin");
    env.put("FOO", "foo");
    File directory = new File("/tmp");
    try {
        new Command(args, env, directory).execute();
        fail();
    } catch (CommandException exception) {
        String message = CommandUtils.describeCommandError(false, exception.getCommand());
        String verboseMessage = CommandUtils.describeCommandError(true, exception.getCommand());
        assertEquals("error executing command this_command_will_not_be_found arg1 " + "arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 " + "arg11 arg12 arg13 arg14 arg15 arg16 arg17 arg18 " + "arg19 arg20 arg21 arg22 arg23 arg24 arg25 arg26 " + "arg27 arg28 arg29 arg30 " + "... (remaining 9 argument(s) skipped)", message);
        assertEquals("error executing command \n" + "  (cd /tmp && \\\n" + "  exec env - \\\n" + "    FOO=foo \\\n" + "    PATH=/usr/bin:/bin:/sbin \\\n" + "  this_command_will_not_be_found arg1 " + "arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 " + "arg11 arg12 arg13 arg14 arg15 arg16 arg17 arg18 " + "arg19 arg20 arg21 arg22 arg23 arg24 arg25 arg26 " + "arg27 arg28 arg29 arg30 arg31 arg32 arg33 arg34 " + "arg35 arg36 arg37 arg38 arg39)", verboseMessage);
    }
}
Also used : Command(com.google.devtools.build.lib.shell.Command) CommandException(com.google.devtools.build.lib.shell.CommandException) File(java.io.File) Test(org.junit.Test)

Example 9 with CommandException

use of com.google.devtools.build.lib.shell.CommandException in project bazel by bazelbuild.

the class StandaloneSpawnStrategy method actuallyExec.

/**
   * Executes the given {@code spawn}.
   */
private void actuallyExec(Spawn spawn, ActionExecutionContext actionExecutionContext) throws ExecException {
    Executor executor = actionExecutionContext.getExecutor();
    if (executor.reportsSubcommands()) {
        executor.reportSubcommand(spawn);
    }
    int timeoutSeconds = Spawns.getTimeoutSeconds(spawn);
    // We must wrap the subprocess with process-wrapper to kill the process tree.
    // All actions therefore depend on the process-wrapper file. Since it's embedded,
    // we don't bother with declaring it as an input.
    List<String> args = new ArrayList<>();
    if (OS.getCurrent() != OS.WINDOWS) {
        // TODO(bazel-team): process-wrapper seems to work on Windows, but requires
        // additional setup as it is an msys2 binary, so it needs msys2 DLLs on %PATH%.
        // Disable it for now to make the setup easier and to avoid further PATH hacks.
        // Ideally we should have a native implementation of process-wrapper for Windows.
        args.add(processWrapper.getPathString());
        args.add(Integer.toString(timeoutSeconds));
        args.add("5");
        /* kill delay: give some time to print stacktraces and whatnot. */
        // TODO(bazel-team): use process-wrapper redirection so we don't have to
        // pass test logs through the Java heap.
        args.add("-");
        /* stdout. */
        args.add("-");
    /* stderr. */
    }
    args.addAll(spawn.getArguments());
    String cwd = executor.getExecRoot().getPathString();
    Command cmd = new Command(args.toArray(new String[] {}), locallyDeterminedEnv(execRoot, productName, spawn.getEnvironment()), new File(cwd), OS.getCurrent() == OS.WINDOWS && timeoutSeconds >= 0 ? timeoutSeconds * 1000 : -1);
    FileOutErr outErr = actionExecutionContext.getFileOutErr();
    try {
        cmd.execute(/* stdin */
        new byte[] {}, Command.NO_OBSERVER, outErr.getOutputStream(), outErr.getErrorStream(), /*killSubprocessOnInterrupt*/
        true);
    } catch (AbnormalTerminationException e) {
        TerminationStatus status = e.getResult().getTerminationStatus();
        boolean timedOut = !status.exited() && (status.timedout() || status.getTerminatingSignal() == 14);
        String message = CommandFailureUtils.describeCommandFailure(verboseFailures, spawn.getArguments(), spawn.getEnvironment(), cwd);
        throw new UserExecException(String.format("%s: %s", message, e), timedOut);
    } catch (CommandException e) {
        String message = CommandFailureUtils.describeCommandFailure(verboseFailures, spawn.getArguments(), spawn.getEnvironment(), cwd);
        throw new UserExecException(message, e);
    }
}
Also used : Executor(com.google.devtools.build.lib.actions.Executor) FileOutErr(com.google.devtools.build.lib.util.io.FileOutErr) Command(com.google.devtools.build.lib.shell.Command) TerminationStatus(com.google.devtools.build.lib.shell.TerminationStatus) ArrayList(java.util.ArrayList) UserExecException(com.google.devtools.build.lib.actions.UserExecException) AbnormalTerminationException(com.google.devtools.build.lib.shell.AbnormalTerminationException) CommandException(com.google.devtools.build.lib.shell.CommandException) File(java.io.File)

Example 10 with CommandException

use of com.google.devtools.build.lib.shell.CommandException in project bazel by bazelbuild.

the class BazelBuilder method prepareFromGitRepo.

void prepareFromGitRepo(String gitRepo) throws IOException, CommandException {
    // Try to pull git repo first, delete directory if failed.
    if (builderDir.toFile().isDirectory()) {
        try {
            pullGitRepo();
        } catch (CommandException e) {
            FileSystemUtils.deleteTree(fileSystem.getPath(builderDir.toString()));
        }
    }
    if (Files.notExists(builderDir)) {
        try {
            Files.createDirectories(builderDir);
        } catch (IOException e) {
            throw new IOException("Failed to create directory for bazel", e);
        }
        String[] gitCloneCommand = { "git", "clone", gitRepo, "." };
        Command cmd = new Command(gitCloneCommand, null, builderDir.toFile());
        cmd.execute();
    }
// Assume the directory is what we need if not empty
}
Also used : Command(com.google.devtools.build.lib.shell.Command) CommandException(com.google.devtools.build.lib.shell.CommandException) IOException(java.io.IOException)

Aggregations

CommandException (com.google.devtools.build.lib.shell.CommandException)13 Command (com.google.devtools.build.lib.shell.Command)11 IOException (java.io.IOException)6 AbnormalTerminationException (com.google.devtools.build.lib.shell.AbnormalTerminationException)5 ArrayList (java.util.ArrayList)5 UserExecException (com.google.devtools.build.lib.actions.UserExecException)4 CommandResult (com.google.devtools.build.lib.shell.CommandResult)4 TerminationStatus (com.google.devtools.build.lib.shell.TerminationStatus)4 File (java.io.File)4 Path (com.google.devtools.build.lib.vfs.Path)2 PathFragment (com.google.devtools.build.lib.vfs.PathFragment)2 Test (org.junit.Test)2 ExecException (com.google.devtools.build.lib.actions.ExecException)1 Executor (com.google.devtools.build.lib.actions.Executor)1 ConfiguredTarget (com.google.devtools.build.lib.analysis.ConfiguredTarget)1 FilesToRunProvider (com.google.devtools.build.lib.analysis.FilesToRunProvider)1 NoBuildEvent (com.google.devtools.build.lib.analysis.NoBuildEvent)1 RunfilesSupport (com.google.devtools.build.lib.analysis.RunfilesSupport)1 BuildConfiguration (com.google.devtools.build.lib.analysis.config.BuildConfiguration)1 RunUnder (com.google.devtools.build.lib.analysis.config.RunUnder)1