Search in sources :

Example 1 with LogEventBuilder

use of com.aws.greengrass.logging.api.LogEventBuilder in project aws-greengrass-nucleus by aws-greengrass.

the class GenericExternalService method run.

@SuppressWarnings("PMD.CloseResource")
protected Pair<RunStatus, Exec> run(Topic t, String cmd, IntConsumer background, List<Exec> trackingList, boolean requiresPrivilege) throws InterruptedException {
    if (runWith == null) {
        Optional<RunWith> opt = computeRunWithConfiguration();
        if (!opt.isPresent()) {
            logger.atError().log("Could not determine user/group to run with. Ensure that {} is set for {}", DeviceConfiguration.RUN_WITH_TOPIC, deviceConfiguration.getNucleusComponentName());
            return new Pair<>(RunStatus.Errored, null);
        }
        runWith = opt.get();
        LogEventBuilder logEvent = logger.atDebug().kv("user", runWith.getUser());
        if (runWith.getGroup() != null) {
            logEvent.kv("group", runWith.getGroup());
        }
        if (runWith.getShell() != null) {
            logEvent.kv("shell", runWith.getShell());
        }
        logEvent.log("Saving user information for service execution");
        if (!updateComponentPathOwner()) {
            logger.atError().log("Service artifacts may not be accessible to user");
        }
    }
    final ShellRunner shellRunner = context.get(ShellRunner.class);
    Exec exec;
    try {
        exec = shellRunner.setup(t.getFullName(), cmd, this);
    } catch (IOException e) {
        logger.atError().log("Error setting up to run {}", t.getFullName(), e);
        return new Pair<>(RunStatus.Errored, null);
    }
    if (exec == null) {
        return new Pair<>(RunStatus.NothingDone, null);
    }
    exec = addUser(exec, requiresPrivilege);
    exec = addShell(exec);
    addEnv(exec, t.parent);
    logger.atDebug().setEventType("generic-service-run").log();
    // Track all running processes that we fork
    if (exec.isRunning()) {
        trackingList.add(exec);
    }
    RunStatus ret = shellRunner.successful(exec, t.getFullName(), background, this) ? RunStatus.OK : RunStatus.Errored;
    return new Pair<>(ret, exec);
}
Also used : Exec(com.aws.greengrass.util.Exec) LogEventBuilder(com.aws.greengrass.logging.api.LogEventBuilder) IOException(java.io.IOException) Pair(com.aws.greengrass.util.Pair)

Example 2 with LogEventBuilder

use of com.aws.greengrass.logging.api.LogEventBuilder 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)

Aggregations

LogEventBuilder (com.aws.greengrass.logging.api.LogEventBuilder)2 Exec (com.aws.greengrass.util.Exec)2 Pair (com.aws.greengrass.util.Pair)2 IOException (java.io.IOException)2 FileSystemPermission (com.aws.greengrass.util.FileSystemPermission)1 Permissions (com.aws.greengrass.util.Permissions)1 Utils (com.aws.greengrass.util.Utils)1 Utils.inputStreamToString (com.aws.greengrass.util.Utils.inputStreamToString)1 Platform (com.aws.greengrass.util.platforms.Platform)1 ShellDecorator (com.aws.greengrass.util.platforms.ShellDecorator)1 StubResourceController (com.aws.greengrass.util.platforms.StubResourceController)1 SystemResourceController (com.aws.greengrass.util.platforms.SystemResourceController)1 UserDecorator (com.aws.greengrass.util.platforms.UserDecorator)1 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Files (java.nio.file.Files)1 LinkOption (java.nio.file.LinkOption)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1