github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/core/paths/logfile.go (about)

     1  // Copyright 2019 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  //go:build !windows
     4  
     5  package paths
     6  
     7  import (
     8  	"os"
     9  	"os/user"
    10  	"strconv"
    11  
    12  	"github.com/juju/errors"
    13  
    14  	jujuos "github.com/juju/juju/core/os"
    15  	"github.com/juju/juju/core/os/ostype"
    16  )
    17  
    18  // LogfilePermission is the file mode to use for log files.
    19  const LogfilePermission = os.FileMode(0640)
    20  
    21  // SetSyslogOwner sets the owner and group of the file to be the appropriate
    22  // syslog users as defined by the SyslogUserGroup method.
    23  func SetSyslogOwner(filename string) error {
    24  	user, group := SyslogUserGroup()
    25  	return SetOwnership(filename, user, group)
    26  }
    27  
    28  // SetOwnership sets the ownership of a given file from a path.
    29  // Searches for the corresponding id's from user, group and uses them to chown.
    30  func SetOwnership(filePath string, wantedUser string, wantedGroup string) error {
    31  	group, err := user.LookupGroup(wantedGroup)
    32  	if err != nil {
    33  		return errors.Trace(err)
    34  	}
    35  	gid, err := strconv.Atoi(group.Gid)
    36  	if err != nil {
    37  		return errors.Trace(err)
    38  	}
    39  	usr, err := user.Lookup(wantedUser)
    40  	if err != nil {
    41  		return errors.Trace(err)
    42  	}
    43  	uid, err := strconv.Atoi(usr.Uid)
    44  	if err != nil {
    45  		return errors.Trace(err)
    46  	}
    47  	return Chown(filePath, uid, gid)
    48  }
    49  
    50  // PrimeLogFile ensures that the given log file is created with the
    51  // correct mode and ownership.
    52  func PrimeLogFile(path string) error {
    53  	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, LogfilePermission)
    54  	if err != nil {
    55  		return errors.Trace(err)
    56  	}
    57  	if err := f.Close(); err != nil {
    58  		return errors.Trace(err)
    59  	}
    60  	return SetSyslogOwner(path)
    61  }
    62  
    63  // SyslogUserGroup returns the names of the user and group that own the log files.
    64  func SyslogUserGroup() (string, string) {
    65  	switch jujuos.HostOS() {
    66  	case ostype.CentOS:
    67  		return "root", "adm"
    68  	default:
    69  		return "syslog", "adm"
    70  	}
    71  }