Skip to content

Commit 0f9859e

Browse files
committed
add a sync.Once to IsContainerized()
1 parent 0e1c96a commit 0f9859e

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

cli/clistat/container_linux.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,31 @@ import (
44
"bufio"
55
"bytes"
66
"os"
7+
"sync"
78

9+
"go.uber.org/atomic"
810
"golang.org/x/xerrors"
911
)
1012

13+
var isContainerizedCacheOK atomic.Bool
14+
var isContainerizedCacheErr atomic.Error
15+
var isContainerizedCacheOnce sync.Once
16+
1117
// IsContainerized returns whether the host is containerized.
1218
// This is adapted from https://github.com/elastic/go-sysinfo/tree/main/providers/linux/container.go#L31
1319
// with modifications to support Sysbox containers.
1420
// On non-Linux platforms, it always returns false.
15-
func IsContainerized() (bool, error) {
21+
// The result is only computed once and stored for subsequent calls.
22+
func IsContainerized() (ok bool, err error) {
23+
isContainerizedCacheOnce.Do(func() {
24+
ok, err = isContainerizedOnce()
25+
isContainerizedCacheOK.Store(ok)
26+
isContainerizedCacheErr.Store(err)
27+
})
28+
return isContainerizedCacheOK.Load(), isContainerizedCacheErr.Load()
29+
}
30+
31+
func isContainerizedOnce() (bool, error) {
1632
data, err := os.ReadFile(procOneCgroup)
1733
if err != nil {
1834
if os.IsNotExist(err) { // how?

0 commit comments

Comments
 (0)