Skip to content

Commit 0569072

Browse files
authored
Merge pull request #3003 from alexandear/refactor/sync-once-values
sysprof,osutil: simplify with sync.OnceValues
2 parents 8826909 + 4f9dfe3 commit 0569072

File tree

2 files changed

+23
-37
lines changed

2 files changed

+23
-37
lines changed

pkg/osutil/machineid.go

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,27 +14,18 @@ import (
1414
"github.com/sirupsen/logrus"
1515
)
1616

17-
var (
18-
machineIDCached string
19-
machineIDOnce sync.Once
20-
)
21-
22-
func MachineID() string {
23-
machineIDOnce.Do(func() {
24-
x, err := machineID()
25-
if err == nil && x != "" {
26-
machineIDCached = x
27-
return
28-
}
29-
logrus.WithError(err).Debug("failed to get machine ID, falling back to use hostname instead")
30-
hostname, err := os.Hostname()
31-
if err != nil {
32-
panic(err)
33-
}
34-
machineIDCached = hostname
35-
})
36-
return machineIDCached
37-
}
17+
var MachineID = sync.OnceValue(func() string {
18+
x, err := machineID()
19+
if err == nil && x != "" {
20+
return x
21+
}
22+
logrus.WithError(err).Debug("failed to get machine ID, falling back to use hostname instead")
23+
hostname, err := os.Hostname()
24+
if err != nil {
25+
panic(fmt.Errorf("failed to get hostname: %w", err))
26+
}
27+
return hostname
28+
})
3829

3930
func machineID() (string, error) {
4031
if runtime.GOOS == "darwin" {

pkg/sysprof/sysprof_darwin.go

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,17 @@ import (
1111
"github.com/sirupsen/logrus"
1212
)
1313

14-
var (
15-
networkDataOnce sync.Once
16-
networkDataCached SPNetworkDataType
17-
networkDataError error
18-
)
19-
20-
func NetworkData() ([]NetworkDataType, error) {
21-
networkDataOnce.Do(func() {
22-
var jsonBytes []byte
23-
jsonBytes, networkDataError = SystemProfiler("SPNetworkDataType")
24-
if networkDataError == nil {
25-
networkDataError = json.Unmarshal(jsonBytes, &networkDataCached)
26-
}
27-
})
28-
return networkDataCached.SPNetworkDataType, networkDataError
29-
}
14+
var NetworkData = sync.OnceValues(func() ([]NetworkDataType, error) {
15+
b, err := SystemProfiler("SPNetworkDataType")
16+
if err != nil {
17+
return nil, err
18+
}
19+
var networkData SPNetworkDataType
20+
if err := json.Unmarshal(b, &networkData); err != nil {
21+
return nil, err
22+
}
23+
return networkData.SPNetworkDataType, nil
24+
})
3025

3126
func SystemProfiler(dataType string) ([]byte, error) {
3227
exe, err := exec.LookPath("system_profiler")

0 commit comments

Comments
 (0)