Skip to content

Commit 3043a0b

Browse files
committed
Rework getting host info (#340)
1 parent 232cab0 commit 3043a0b

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

pkg/sysinfo/sysinfo.go

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package sysinfo
33
import (
44
"fmt"
55
"math"
6+
"os"
67
"runtime"
78
"sort"
89
"strconv"
@@ -85,12 +86,39 @@ type MointpointRequest struct {
8586
// Currently caches hostname indefinitely which isn't ideal
8687
// Potential issue with caching boot time as it may not initially get reported correctly:
8788
// https://github.com/shirou/gopsutil/issues/842#issuecomment-1908972344
88-
var cachedHostInfo = struct {
89+
type cacheableHostInfo struct {
8990
available bool
9091
hostname string
9192
platform string
9293
bootTime timestampJSON
93-
}{}
94+
}
95+
96+
var cachedHostInfo cacheableHostInfo
97+
98+
func getHostInfo() (cacheableHostInfo, error) {
99+
var err error
100+
info := cacheableHostInfo{}
101+
102+
info.hostname, err = os.Hostname()
103+
if err != nil {
104+
return info, err
105+
}
106+
107+
info.platform, _, _, err = host.PlatformInformation()
108+
if err != nil {
109+
return info, err
110+
}
111+
112+
bootTime, err := host.BootTime()
113+
if err != nil {
114+
return info, err
115+
}
116+
117+
info.bootTime = timestampJSON{time.Unix(int64(bootTime), 0)}
118+
info.available = true
119+
120+
return info, nil
121+
}
94122

95123
func Collect(req *SystemInfoRequest) (*SystemInfo, []error) {
96124
if req == nil {
@@ -117,13 +145,9 @@ func Collect(req *SystemInfoRequest) (*SystemInfo, []error) {
117145
if cachedHostInfo.available {
118146
applyCachedHostInfo()
119147
} else {
120-
hostInfo, err := host.Info()
148+
hostInfo, err := getHostInfo()
121149
if err == nil {
122-
cachedHostInfo.available = true
123-
cachedHostInfo.bootTime = timestampJSON{time.Unix(int64(hostInfo.BootTime), 0)}
124-
cachedHostInfo.hostname = hostInfo.Hostname
125-
cachedHostInfo.platform = hostInfo.Platform
126-
150+
cachedHostInfo = hostInfo
127151
applyCachedHostInfo()
128152
} else {
129153
addErr(fmt.Errorf("getting host info: %v", err))

0 commit comments

Comments
 (0)