Something went wrong. Try again.
forked from shirou/gopsutil
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508// SPDX-License-Identifier: BSD-3-Clause//go:build linux
package host
import ( "bytes" "context" "encoding/binary" "fmt" "io" "os" "regexp" "strings" "time"
"golang.org/x/sys/unix"
"github.com/shirou/gopsutil/v4/internal/common")
type lsbStruct struct { ID string Release string Codename string Description string}
// from utmp.hconst ( user_PROCESS = 7 //nolint:revive //FIXME)
func HostIDWithContext(ctx context.Context) (string, error) { sysProductUUID := common.HostSysWithContext(ctx, "class/dmi/id/product_uuid") machineID := common.HostEtcWithContext(ctx, "machine-id") procSysKernelRandomBootID := common.HostProcWithContext(ctx, "sys/kernel/random/boot_id") switch { // In order to read this file, needs to be supported by kernel/arch and run as root // so having fallback is important case common.PathExists(sysProductUUID): lines, err := common.ReadLines(sysProductUUID) if err == nil && len(lines) > 0 && lines[0] != "" { return strings.ToLower(lines[0]), nil } fallthrough // Fallback on GNU Linux systems with systemd, readable by everyone case common.PathExists(machineID): lines, err := common.ReadLines(machineID) if err == nil && len(lines) > 0 && len(lines[0]) == 32 { st := lines[0] return fmt.Sprintf("%s-%s-%s-%s-%s", st[0:8], st[8:12], st[12:16], st[16:20], st[20:32]), nil } fallthrough // Not stable between reboot, but better than nothing default: lines, err := common.ReadLines(procSysKernelRandomBootID) if err == nil && len(lines) > 0 && lines[0] != "" { return strings.ToLower(lines[0]), nil } }
return "", nil}
func numProcs(ctx context.Context) (uint64, error) { return common.NumProcsWithContext(ctx)}
func BootTimeWithContext(ctx context.Context) (uint64, error) { return common.BootTimeWithContext(ctx, enableBootTimeCache)}
func UptimeWithContext(_ context.Context) (uint64, error) { sysinfo := &unix.Sysinfo_t{} if err := unix.Sysinfo(sysinfo); err != nil { return 0, err } return uint64(sysinfo.Uptime), nil}
func UsersWithContext(ctx context.Context) ([]UserStat, error) { utmpfile := common.HostVarWithContext(ctx, "run/utmp")
file, err := os.Open(utmpfile) if err != nil { if os.IsNotExist(err) { // utmp is no longer populated on some newer distributions // (e.g. Debian 13), which track sessions via systemd-logind // instead. Fall back to loginctl in that case. If it fails too, // return the original utmp error so callers can still rely on // os.IsNotExist. if users, lerr := usersFromLoginctlWithContext(ctx); lerr == nil { return users, nil } } return nil, err } defer file.Close()
buf, err := io.ReadAll(file) if err != nil { return nil, err }
count := len(buf) / sizeOfUtmp
ret := make([]UserStat, 0, count)
for i := 0; i < count; i++ { b := buf[i*sizeOfUtmp : (i+1)*sizeOfUtmp]
var u utmp br := bytes.NewReader(b) err := binary.Read(br, binary.LittleEndian, &u) if err != nil { continue } if u.Type != user_PROCESS { continue } user := UserStat{ User: common.IntToString(u.User[:]), Terminal: common.IntToString(u.Line[:]), Host: common.IntToString(u.Host[:]), Started: int(u.Tv.Sec), } ret = append(ret, user) }
return ret, nil}
// usersFromLoginctlWithContext lists logged-in users through systemd-logind.// It is used when utmp is not available. The plain column output of// list-sessions is parsed on purpose: -o json is ignored since systemd 256 and// --json only exists from 256 on, while the first column has been the session// id in every version. loginctl always queries the local systemd-logind, so// HOST_VAR / HOST_ROOT are ignored here.func usersFromLoginctlWithContext(ctx context.Context) ([]UserStat, error) { ctx, cancel := context.WithTimeout(ctx, common.Timeout) defer cancel()
out, err := invoke.CommandWithContext(ctx, "loginctl", "list-sessions", "--no-legend", "--no-pager") if err != nil { return nil, err }
var ids []string for _, line := range strings.Split(string(out), "\n") { // The session column is right-aligned, so use Fields to drop padding. fields := strings.Fields(line) if len(fields) == 0 { continue } ids = append(ids, fields[0]) }
ret := make([]UserStat, 0, len(ids)) var lastErr error failed := 0 for _, id := range ids { stat, ok, err := loginctlShowSessionWithContext(ctx, id) if err != nil { // Sessions can close between list-sessions and show-session. lastErr = err failed++ continue } if ok { ret = append(ret, stat) } } if len(ids) > 0 && failed == len(ids) { return nil, lastErr }
return ret, nil}
// loginctlShowSessionWithContext returns the session as a UserStat. The bool is// false for sessions that utmp would not have listed as USER_PROCESS: those whose// class does not start with "user" (e.g. "manager", "greeter") or that have// neither a seat nor a tty.func loginctlShowSessionWithContext(ctx context.Context, id string) (UserStat, bool, error) { out, err := invoke.CommandWithContext(ctx, "loginctl", "show-session", id, "-p", "Name", "-p", "TTY", "-p", "RemoteHost", "-p", "Timestamp", "-p", "Class", "-p", "Seat") if err != nil { return UserStat{}, false, err }
var stat UserStat var class, seat string for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { key, value, found := strings.Cut(line, "=") if !found { continue } switch key { case "Name": stat.User = value case "TTY": stat.Terminal = value case "RemoteHost": stat.Host = value case "Class": class = value case "Seat": seat = value case "Timestamp": // Format: "Mon 2026-01-22 14:51:57 CET". The zone abbreviation can be // numeric (e.g. +0330), which time.Parse rejects, so only read the wall // clock and interpret it in the local zone. if f := strings.Fields(value); len(f) >= 3 { if t, err := time.ParseInLocation("2006-01-02 15:04:05", f[1]+" "+f[2], time.Local); err == nil { stat.Started = int(t.Unix()) } } } }
if !strings.HasPrefix(class, "user") || (seat == "" && stat.Terminal == "") { return UserStat{}, false, nil }
if stat.Terminal == "" { // Graphical logins have no tty; utmp-based tools such as who show the seat. stat.Terminal = seat }
return stat, true, nil}
func getlsbStruct(ctx context.Context) (*lsbStruct, error) { ret := &lsbStruct{} if common.PathExists(common.HostEtcWithContext(ctx, "lsb-release")) { contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "lsb-release")) if err != nil { return ret, err // return empty } for _, line := range contents { field := strings.Split(line, "=") if len(field) < 2 { continue } switch field[0] { case "DISTRIB_ID": ret.ID = strings.ReplaceAll(field[1], `"`, ``) case "DISTRIB_RELEASE": ret.Release = strings.ReplaceAll(field[1], `"`, ``) case "DISTRIB_CODENAME": ret.Codename = strings.ReplaceAll(field[1], `"`, ``) case "DISTRIB_DESCRIPTION": ret.Description = strings.ReplaceAll(field[1], `"`, ``) } } } else if common.PathExists("/usr/bin/lsb_release") { out, err := invoke.Command("/usr/bin/lsb_release") if err != nil { return ret, err } for _, line := range strings.Split(string(out), "\n") { field := strings.Split(line, ":") if len(field) < 2 { continue } switch field[0] { case "Distributor ID": ret.ID = strings.ReplaceAll(field[1], `"`, ``) case "Release": ret.Release = strings.ReplaceAll(field[1], `"`, ``) case "Codename": ret.Codename = strings.ReplaceAll(field[1], `"`, ``) case "Description": ret.Description = strings.ReplaceAll(field[1], `"`, ``) } }
}
return ret, nil}
func PlatformInformationWithContext(ctx context.Context) (platform, family, version string, err error) { lsb, err := getlsbStruct(ctx) if err != nil { lsb = &lsbStruct{} }
switch { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "oracle-release")): platform = "oracle" contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "oracle-release")) if err == nil { version = getRedhatishVersion(contents) }
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "enterprise-release")): platform = "oracle" contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "enterprise-release")) if err == nil { version = getRedhatishVersion(contents) } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "slackware-version")): platform = "slackware" contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "slackware-version")) if err == nil { version = getSlackwareVersion(contents) } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "debian_version")): switch lsb.ID { case "Ubuntu": platform = "ubuntu" version = lsb.Release case "LinuxMint": platform = "linuxmint" version = lsb.Release case "Kylin": platform = "Kylin" version = lsb.Release case `"Cumulus Linux"`: platform = "cumuluslinux" version = lsb.Release case "uos": platform = "uos" version = lsb.Release case "Deepin": platform = "Deepin" version = lsb.Release default: if common.PathExistsWithContents("/usr/bin/raspi-config") { platform = "raspbian" } else { platform = "debian" } contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "debian_version")) if err == nil && len(contents) > 0 && contents[0] != "" { version = contents[0] } } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "neokylin-release")): contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "neokylin-release")) if err == nil { version = getRedhatishVersion(contents) platform = getRedhatishPlatform(contents) } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "redhat-release")): contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "redhat-release")) if err == nil { version = getRedhatishVersion(contents) platform = getRedhatishPlatform(contents) } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "system-release")): contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "system-release")) if err == nil { version = getRedhatishVersion(contents) platform = getRedhatishPlatform(contents) } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "gentoo-release")): platform = "gentoo" contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "gentoo-release")) if err == nil { version = getRedhatishVersion(contents) } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "SuSE-release")): contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "SuSE-release")) if err == nil { version = getSuseVersion(contents) platform = getSusePlatform(contents) } // TODO: slackware detection case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "arch-release")): platform = "arch" version = lsb.Release case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "alpine-release")): platform = "alpine" contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "alpine-release")) if err == nil && len(contents) > 0 && contents[0] != "" { version = contents[0] } case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "os-release")): p, v, err := common.GetOSReleaseWithContext(ctx) if err == nil { platform = p version = v } case lsb.ID == "RedHat": platform = "redhat" version = lsb.Release case lsb.ID == "Amazon": platform = "amazon" version = lsb.Release case lsb.ID == "ScientificSL": platform = "scientific" version = lsb.Release case lsb.ID == "XenServer": platform = "xenserver" version = lsb.Release case lsb.ID != "": platform = strings.ToLower(lsb.ID) version = lsb.Release }
platform = strings.Trim(platform, `"`)
switch platform { case "debian", "ubuntu", "linuxmint", "raspbian", "Kylin", "cumuluslinux", "uos", "Deepin": family = "debian" case "fedora": family = "fedora" case "oracle", "centos", "redhat", "scientific", "enterpriseenterprise", "amazon", "xenserver", "cloudlinux", "ibm_powerkvm", "rocky", "almalinux": family = "rhel" case "suse", "opensuse", "opensuse-leap", "opensuse-tumbleweed", "opensuse-tumbleweed-kubic", "sles", "sled", "caasp": family = "suse" case "gentoo": family = "gentoo" case "slackware": family = "slackware" case "arch": family = "arch" case "exherbo": family = "exherbo" case "alpine": family = "alpine" case "coreos": family = "coreos" case "solus": family = "solus" case "neokylin": family = "neokylin" case "anolis": family = "anolis" case "nixos": family = "nixos" }
return platform, family, version, nil}
func KernelVersionWithContext(_ context.Context) (version string, err error) { var utsname unix.Utsname err = unix.Uname(&utsname) if err != nil { return "", err } return unix.ByteSliceToString(utsname.Release[:]), nil}
func getSlackwareVersion(contents []string) string { c := strings.ToLower(strings.Join(contents, "")) c = strings.Replace(c, "slackware ", "", 1) return c}
var redhatishReleaseMatch = regexp.MustCompile(`release (\w[\d.]*)`)
func getRedhatishVersion(contents []string) string { c := strings.ToLower(strings.Join(contents, ""))
if strings.Contains(c, "rawhide") { return "rawhide" } if matches := redhatishReleaseMatch.FindStringSubmatch(c); matches != nil { return matches[1] } return ""}
func getRedhatishPlatform(contents []string) string { c := strings.ToLower(strings.Join(contents, ""))
if strings.Contains(c, "red hat") { return "redhat" } f := strings.Split(c, " ")
return f[0]}
var ( suseVersionMatch = regexp.MustCompile(`VERSION = ([\d.]+)`) susePatchLevelMatch = regexp.MustCompile(`PATCHLEVEL = (\d+)`))
func getSuseVersion(contents []string) string { version := "" for _, line := range contents { if matches := suseVersionMatch.FindStringSubmatch(line); matches != nil { version = matches[1] } else if matches = susePatchLevelMatch.FindStringSubmatch(line); matches != nil { version = version + "." + matches[1] } } return version}
func getSusePlatform(contents []string) string { c := strings.ToLower(strings.Join(contents, "")) if strings.Contains(c, "opensuse") { return "opensuse" } return "suse"}
func VirtualizationWithContext(ctx context.Context) (string, string, error) { return common.VirtualizationWithContext(ctx)}