Search in sources :

Example 6 with Exec

use of com.aws.greengrass.util.Exec in project aws-greengrass-nucleus by aws-greengrass.

the class ExecTest method GIVEN_exec_WHEN_changing_directories_THEN_success.

@Test
@SuppressWarnings("PMD.CloseResource")
void GIVEN_exec_WHEN_changing_directories_THEN_success() throws InterruptedException, IOException {
    final Exec exec = Platform.getInstance().createNewProcessRunner();
    final String getWorkingDirCmd = PlatformResolver.isWindows ? "cd" : "pwd";
    // resolve links in-case user.dir or user.home is a symlink
    // By default Exec uses home as current directory for exec
    Path expectedDir = Paths.get(readLink(System.getProperty("user.dir")));
    Path defaultDir = Paths.get(readLink(exec.withShell(getWorkingDirCmd).execAndGetStringOutput()));
    assertThat(expectedDir, is(defaultDir));
    // Now change it to some other directory
    expectedDir = Paths.get("/").toAbsolutePath();
    Path changedDir = Paths.get(exec.cd(expectedDir.toString()).withShell(getWorkingDirCmd).execAndGetStringOutput());
    assertThat(expectedDir, is(expectedDir));
    // Now use the file argument to change into another directory again
    // File argument would use the current directory ("/") as base
    expectedDir = Paths.get(readLink(System.getProperty("user.home"))).toAbsolutePath();
    changedDir = Paths.get(exec.cd(expectedDir.toString()).withShell(getWorkingDirCmd).execAndGetStringOutput());
    assertThat(changedDir, is(expectedDir));
    // Now change it to root again
    expectedDir = Paths.get("/").toAbsolutePath();
    changedDir = Paths.get(exec.cd(expectedDir.toString()).withShell(getWorkingDirCmd).execAndGetStringOutput());
    assertThat(changedDir, is(expectedDir));
    exec.close();
}
Also used : Exec(com.aws.greengrass.util.Exec) Path(java.nio.file.Path) Test(org.junit.jupiter.api.Test)

Example 7 with Exec

use of com.aws.greengrass.util.Exec in project aws-greengrass-nucleus by aws-greengrass.

the class ExecTest method GIVEN_exec_WHEN_command_outputs_THEN_output_captured.

@Test
@SuppressWarnings("PMD.CloseResource")
void GIVEN_exec_WHEN_command_outputs_THEN_output_captured() throws InterruptedException, IOException {
    Exec exec = Platform.getInstance().createNewProcessRunner();
    String expectedOutput = "HELLO";
    String command = "echo " + expectedOutput;
    StringBuilder stdout = new StringBuilder();
    StringBuilder stderr = new StringBuilder();
    Consumer<CharSequence> stdoutConsumer = stdout::append;
    Consumer<CharSequence> stderrConsumer = stderr::append;
    exec.withShell(command).withOut(stdoutConsumer).withErr(stderrConsumer);
    assertTrue(exec.successful(false));
    // new line for shell
    assertEquals(expectedOutput.length() + 1, stdout.length());
    assertEquals(0, stderr.length());
    // reinit consumers
    stdout.setLength(0);
    stderr.setLength(0);
    String stdErrCommand = command + " 1>&2";
    exec.withShell(stdErrCommand);
    assertFalse(exec.successful(false));
    assertEquals(0, stdout.length());
    // new line for shell and 1 more for windows because it actually includes the trailing space before the 1>&2
    assertEquals(expectedOutput.length() + 1 + (PlatformResolver.isWindows ? 1 : 0), stderr.length());
    exec.close();
}
Also used : Exec(com.aws.greengrass.util.Exec) Test(org.junit.jupiter.api.Test)

Example 8 with Exec

use of com.aws.greengrass.util.Exec in project aws-greengrass-nucleus by aws-greengrass.

the class ExecTest method Given_exec_WHEN_commands_executed_using_static_methods_THEN_success.

@Test
@DisabledOnOs(OS.WINDOWS)
void Given_exec_WHEN_commands_executed_using_static_methods_THEN_success() throws InterruptedException, IOException {
    try (Exec exec = Platform.getInstance().createNewProcessRunner()) {
        final String command = "pwd";
        String s = exec.cmd(command);
        assertFalse(s.contains("\n"));
        assertTrue(s.startsWith("/"));
        assertEquals(s, exec.sh(command));
        String s2 = exec.sh("ifconfig -a;echo Hello");
        assertTrue(s2.contains("Hello"));
        String expectedDir = readLink(System.getProperty("user.home"));
        assertEquals(expectedDir, exec.sh(new File(expectedDir), command));
        assertEquals(expectedDir, exec.sh(Paths.get(expectedDir), command));
        assertTrue(exec.successful(false, command));
    }
}
Also used : Exec(com.aws.greengrass.util.Exec) File(java.io.File) DisabledOnOs(org.junit.jupiter.api.condition.DisabledOnOs) Test(org.junit.jupiter.api.Test)

Example 9 with Exec

use of com.aws.greengrass.util.Exec in project aws-greengrass-nucleus by aws-greengrass.

the class DefaultDockerClient method runDockerCmd.

private CliResponse runDockerCmd(String cmd, Map<String, String> envs) {
    Throwable cause = null;
    StringBuilder output = new StringBuilder();
    StringBuilder error = new StringBuilder();
    Optional<Integer> exit = Optional.empty();
    try (Exec exec = Platform.getInstance().createNewProcessRunner()) {
        exec.withExec(cmd.split(" ")).withShell().withOut(output::append).withErr(error::append);
        for (Map.Entry<String, String> env : envs.entrySet()) {
            exec.setenv(env.getKey(), env.getValue());
        }
        exit = exec.exec();
    } catch (InterruptedException e) {
        Arrays.stream(e.getSuppressed()).forEach((t) -> {
            logger.atError().setCause(e).log("interrupted");
        });
        cause = e;
    } catch (IOException e) {
        cause = e;
    }
    return new CliResponse(exit, output.toString(), error.toString(), cause);
}
Also used : Exec(com.aws.greengrass.util.Exec) Arrays(java.util.Arrays) Getter(lombok.Getter) UserNotAuthorizedForDockerException(com.aws.greengrass.componentmanager.plugins.docker.exceptions.UserNotAuthorizedForDockerException) IOException(java.io.IOException) HashMap(java.util.HashMap) DockerServiceUnavailableException(com.aws.greengrass.componentmanager.plugins.docker.exceptions.DockerServiceUnavailableException) InvalidImageOrAccessDeniedException(com.aws.greengrass.componentmanager.plugins.docker.exceptions.InvalidImageOrAccessDeniedException) Platform(com.aws.greengrass.util.platforms.Platform) DockerLoginException(com.aws.greengrass.componentmanager.plugins.docker.exceptions.DockerLoginException) Map(java.util.Map) Optional(java.util.Optional) LogManager(com.aws.greengrass.logging.impl.LogManager) AllArgsConstructor(lombok.AllArgsConstructor) Collections(java.util.Collections) Logger(com.aws.greengrass.logging.api.Logger) NoArgsConstructor(lombok.NoArgsConstructor) IOException(java.io.IOException) Exec(com.aws.greengrass.util.Exec) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with Exec

use of com.aws.greengrass.util.Exec in project aws-greengrass-nucleus by aws-greengrass.

the class SystemServiceUtils method runCommand.

/**
 * Simply run a command with privileges.
 *
 * @param logger Logger to use
 * @param eventName logging event
 * @param command command to run
 * @param ignoreError ignore errors from this command
 * @throws IOException for command failure
 * @throws InterruptedException if interrupted while running
 */
@SuppressWarnings("PMD.CloseResource")
static void runCommand(Logger logger, String eventName, String command, boolean ignoreError) throws IOException, InterruptedException {
    logger.atDebug(eventName).log(command);
    Exec exec = Platform.getInstance().createNewProcessRunner().withShell(command);
    if (Platform.getInstance().getPrivilegedUser() != null) {
        exec.withUser(Platform.getInstance().getPrivilegedUser());
    }
    if (Platform.getInstance().getPrivilegedGroup() != null) {
        exec.withGroup(Platform.getInstance().getPrivilegedGroup());
    }
    boolean success = exec.withOut(s -> logger.atWarn(eventName).kv("command", command).kv("stdout", s.toString().trim()).log()).withErr(s -> logger.atError(eventName).kv("command", command).kv("stderr", s.toString().trim()).log()).successful(true);
    if (!success && !ignoreError) {
        throw new IOException(String.format("Command %s failed", command));
    }
}
Also used : Exec(com.aws.greengrass.util.Exec) Platform(com.aws.greengrass.util.platforms.Platform) Exec(com.aws.greengrass.util.Exec) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) IOException(java.io.IOException) Logger(com.aws.greengrass.logging.api.Logger) IOException(java.io.IOException)

Aggregations

Exec (com.aws.greengrass.util.Exec)20 Test (org.junit.jupiter.api.Test)11 IOException (java.io.IOException)10 Platform (com.aws.greengrass.util.platforms.Platform)5 Path (java.nio.file.Path)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Topic (com.aws.greengrass.config.Topic)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 Topics (com.aws.greengrass.config.Topics)2 Context (com.aws.greengrass.dependency.Context)2 DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)2 SERVICE_UNIQUE_ID_KEY (com.aws.greengrass.ipc.AuthenticationHandler.SERVICE_UNIQUE_ID_KEY)2 LogEventBuilder (com.aws.greengrass.logging.api.LogEventBuilder)2 Logger (com.aws.greengrass.logging.api.Logger)2 GGServiceTestUtil (com.aws.greengrass.testcommons.testutilities.GGServiceTestUtil)2 NucleusPaths (com.aws.greengrass.util.NucleusPaths)2 Pair (com.aws.greengrass.util.Pair)2 File (java.io.File)2 Arrays (java.util.Arrays)2 EnabledOnOs (org.junit.jupiter.api.condition.EnabledOnOs)2