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