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();
}
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));
}
}
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());
}
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"));
}
}
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());
}
}
Aggregations