Search in sources :

Example 16 with Exec

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

the class UnixPlatform method id.

/**
 * Run the `id` program which returns user and group information about a particular user.
 *
 * @param id       the identifier (numeric or name). If empty, then the current user is looked up.
 * @param option   whether to load group or user information.
 * @param loadName whether a name should or id should be returned.
 * @return the output of id (either an integer string or name of the user/group) or empty if an error occurs.
 */
private static Optional<String> id(String id, IdOption option, boolean loadName) {
    boolean loadSelf = Utils.isEmpty(id);
    String[] cmd = new String[2 + (loadName ? 1 : 0) + (loadSelf ? 0 : 1)];
    int i = 0;
    cmd[i] = "id";
    switch(option) {
        case Group:
            cmd[++i] = "-g";
            break;
        case User:
            cmd[++i] = "-u";
            break;
        default:
            logger.atDebug().setEventType("id-lookup").addKeyValue("option", option).log("invalid option provided for id");
            return Optional.empty();
    }
    if (loadName) {
        cmd[++i] = "-n";
    }
    if (!loadSelf) {
        cmd[++i] = id;
    }
    logger.atTrace().setEventType("id-lookup").kv("command", String.join(" ", cmd)).log();
    StringBuilder out = new StringBuilder();
    StringBuilder err = new StringBuilder();
    Throwable cause = null;
    try (Exec exec = getInstance().createNewProcessRunner()) {
        Optional<Integer> exit = exec.withExec(cmd).withShell().withOut(out::append).withErr(err::append).exec();
        if (exit.isPresent() && exit.get() == 0) {
            return Optional.of(out.toString().trim());
        }
    } catch (InterruptedException e) {
        Arrays.stream(e.getSuppressed()).forEach((t) -> {
            logger.atError().setCause(e).log("interrupted");
        });
        cause = e;
    } catch (IOException e) {
        cause = e;
    }
    LogEventBuilder logEvent = logger.atError().setEventType("id-lookup");
    if (option == IdOption.Group) {
        logEvent.kv("group", id);
    } else if (option == IdOption.User && !loadSelf) {
        logEvent.kv("user", id);
    }
    logEvent.kv(STDOUT, out).kv(STDERR, err).setCause(cause).log("Error while looking up id" + (loadSelf ? " for current user" : ""));
    return Optional.empty();
}
Also used : UserDecorator(com.aws.greengrass.util.platforms.UserDecorator) Arrays(java.util.Arrays) Getter(lombok.Getter) LogEventBuilder(com.aws.greengrass.logging.api.LogEventBuilder) ShellDecorator(com.aws.greengrass.util.platforms.ShellDecorator) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView) GroupPrincipal(java.nio.file.attribute.GroupPrincipal) ArrayList(java.util.ArrayList) Platform(com.aws.greengrass.util.platforms.Platform) LinkOption(java.nio.file.LinkOption) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) UserPrincipal(java.nio.file.attribute.UserPrincipal) Matcher(java.util.regex.Matcher) StubResourceController(com.aws.greengrass.util.platforms.StubResourceController) Utils.inputStreamToString(com.aws.greengrass.util.Utils.inputStreamToString) Map(java.util.Map) SystemResourceController(com.aws.greengrass.util.platforms.SystemResourceController) Processes(org.zeroturnaround.process.Processes) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) FileSystemPermission(com.aws.greengrass.util.FileSystemPermission) Exec(com.aws.greengrass.util.Exec) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) Files(java.nio.file.Files) Permissions(com.aws.greengrass.util.Permissions) Set(java.util.Set) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) Pair(com.aws.greengrass.util.Pair) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) Consumer(java.util.function.Consumer) List(java.util.List) Utils(com.aws.greengrass.util.Utils) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) Optional(java.util.Optional) PidProcess(org.zeroturnaround.process.PidProcess) BufferedReader(java.io.BufferedReader) Pattern(java.util.regex.Pattern) NoArgsConstructor(lombok.NoArgsConstructor) Utils.inputStreamToString(com.aws.greengrass.util.Utils.inputStreamToString) IOException(java.io.IOException) Exec(com.aws.greengrass.util.Exec) LogEventBuilder(com.aws.greengrass.logging.api.LogEventBuilder)

Example 17 with Exec

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

the class ExecTest method Given_windows_exec_WHEN_commands_executed_using_static_methods_THEN_success.

@Test
@EnabledOnOs(OS.WINDOWS)
void Given_windows_exec_WHEN_commands_executed_using_static_methods_THEN_success() throws InterruptedException, IOException {
    try (Exec exec = Platform.getInstance().createNewProcessRunner()) {
        String command = "cd";
        // "cd" is not a program so shell is required
        String s = exec.cmd("cmd", "/c", "cd");
        // Expect to print out an absolute path
        assertTrue(new File(s).isAbsolute());
        assertEquals(s, exec.sh(command));
        // test changing the shell
        s = exec.usingShell("powershell").cmd("pwd");
        assertTrue(s.contains("Path"));
        String s2 = exec.cmd("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) EnabledOnOs(org.junit.jupiter.api.condition.EnabledOnOs) Test(org.junit.jupiter.api.Test)

Example 18 with Exec

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

the class ExecTest method GIVEN_exec_WHEN_running_command_closed_THEN_success.

@Test
@SuppressWarnings("PMD.CloseResource")
void GIVEN_exec_WHEN_running_command_closed_THEN_success() throws IOException, InterruptedException {
    // close waits for atmost 7 seconds before close
    String command = "sleep 10";
    CountDownLatch done = new CountDownLatch(1);
    Exec exec = Platform.getInstance().createNewProcessRunner();
    if (PlatformResolver.isWindows) {
        exec.withShell(command).usingShell("powershell").background(exc -> done.countDown());
    } else {
        exec.withShell(command).background(exc -> done.countDown());
    }
    assertTrue(exec.isRunning());
    exec.close();
    assertFalse(exec.isRunning());
    // closing again should be no op, it should not throw
    exec.close();
    assertFalse(exec.isRunning());
}
Also used : Exec(com.aws.greengrass.util.Exec) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 19 with Exec

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

the class ExecTest method GIVEN_windows_exec_WHEN_lookup_common_command_THEN_returns_correct_path.

@Test
@EnabledOnOs(OS.WINDOWS)
void GIVEN_windows_exec_WHEN_lookup_common_command_THEN_returns_correct_path() throws IOException {
    String expectedCmdPathStr = "C:\\Windows\\System32\\cmd.exe";
    try (Exec exec = Platform.getInstance().createNewProcessRunner()) {
        // absolute path
        assertThat(Objects.requireNonNull(exec.which("C:\\Windows\\System32\\cmd.exe")).toString(), equalToIgnoringCase(expectedCmdPathStr));
        // absolute path without extension
        assertThat(Objects.requireNonNull(exec.which("C:\\Windows\\System32\\cmd")).toString(), equalToIgnoringCase(expectedCmdPathStr));
        // forward slash
        assertThat(Objects.requireNonNull(exec.which("C:/Windows/System32/cmd.exe")).toString(), equalToIgnoringCase(expectedCmdPathStr));
        // command only
        assertThat(Objects.requireNonNull(exec.which("cmd")).toString(), equalToIgnoringCase(expectedCmdPathStr));
        assertNull(exec.which("nonexist_program"));
    }
}
Also used : Exec(com.aws.greengrass.util.Exec) EnabledOnOs(org.junit.jupiter.api.condition.EnabledOnOs) Test(org.junit.jupiter.api.Test)

Example 20 with Exec

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

the class GenericExternalService method startup.

// Synchronize startup() and shutdown() as both are non-blocking, but need to have coordination
// to operate properly
@Override
protected synchronized void startup() throws InterruptedException {
    stopAllLifecycleProcesses();
    long startingStateGeneration = getStateGeneration();
    Pair<RunStatus, Exec> result = run(Lifecycle.LIFECYCLE_STARTUP_NAMESPACE_TOPIC, exit -> {
        // the reportStates outside of the callback
        synchronized (this) {
            logger.atInfo().kv(EXIT_CODE, exit).log("Startup script exited");
            separateLogger.atInfo().kv(EXIT_CODE, exit).log("Startup script exited");
            State state = getState();
            if (startingStateGeneration == getStateGeneration() && State.STARTING.equals(state) || State.RUNNING.equals(state)) {
                if (exit == 0 && State.STARTING.equals(state)) {
                    reportState(State.RUNNING);
                } else if (exit != 0) {
                    serviceErrored("Non-zero exit code in startup");
                }
            }
        }
    }, lifecycleProcesses);
    if (result.getLeft() == RunStatus.Errored) {
        serviceErrored("Script errored in startup");
    } else if (result.getLeft() == RunStatus.NothingDone && startingStateGeneration == getStateGeneration() && State.STARTING.equals(getState())) {
        handleRunScript();
    } else if (result.getRight() != null) {
        updateSystemResourceLimits();
        systemResourceController.addComponentProcess(this, result.getRight().getProcess());
    }
}
Also used : Exec(com.aws.greengrass.util.Exec) State(com.aws.greengrass.dependency.State)

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