// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT //go:build linux || darwin // +build linux darwin package cmdutil import ( "fmt" "log" "os" "path/filepath" "github.com/aws/amazon-cloudwatch-agent/translator/config" "github.com/aws/amazon-cloudwatch-agent/translator/context" ) var ( agentLogDir = "/opt/aws/amazon-cloudwatch-agent/logs" agentVarDir = "/opt/aws/amazon-cloudwatch-agent/var" agentEtcDir = "/opt/aws/amazon-cloudwatch-agent/etc" ) type ChownFunc func(name string, uid, gid int) error var chown ChownFunc = os.Chown // DetectRunAsUser get the user name from toml config. It runs on all platforms except windows. func DetectRunAsUser(mergedJsonConfigMap map[string]interface{}) (runAsUser string, err error) { fmt.Printf("I! Detecting run_as_user...\n") if agentSection, ok := mergedJsonConfigMap["agent"]; ok { agent := agentSection.(map[string]interface{}) if user, ok := agent["run_as_user"]; ok { if runasuser, ok := user.(string); ok { return runasuser, nil } log.Panicf("E! run_as_user is not string %v", user) } // agent section exists, but "runasuser" does not exist, then use "root" return "root", nil } // no agent section, it means no runasuser, use "root" return "root", nil } // changeFileOwner changes both user and group of a directory. func changeFileOwner(uid, gid int) error { dirs := []string{agentLogDir, agentEtcDir, agentVarDir} log.Printf("I! Changing ownership of %v to %v:%v", dirs, uid, gid) for _, d := range dirs { if err := chownRecursive(uid, gid, d); err != nil { return err } } return nil } // chownRecursive would recursively change the ownership of the directory // similar to `chown -R