Derive cpuinfo as needed, instead of at init-time

This changes platforms.Parse to hit /proc to look up CPU info only when
it's needed, instead of in init(). This makes the package a bit easier
for other packages to consume, especially clients that don't call
platforms.Parse or need to lookup CPU info.

Signed-off-by: Jason Hall <jasonhall@redhat.com>
This commit is contained in:
Jason Hall 2021-01-19 13:50:14 -05:00
parent 66fec3bbbf
commit 363f2c392c
5 changed files with 18 additions and 13 deletions

View File

@ -21,6 +21,7 @@ import (
"os" "os"
"runtime" "runtime"
"strings" "strings"
"sync"
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/log" "github.com/containerd/containerd/log"
@ -28,14 +29,18 @@ import (
) )
// Present the ARM instruction set architecture, eg: v7, v8 // Present the ARM instruction set architecture, eg: v7, v8
var cpuVariant string // Don't use this value directly; call cpuVariant() instead.
var cpuVariantValue string
func init() { var cpuVariantOnce sync.Once
if isArmArch(runtime.GOARCH) {
cpuVariant = getCPUVariant() func cpuVariant() string {
} else { cpuVariantOnce.Do(func() {
cpuVariant = "" if isArmArch(runtime.GOARCH) {
} cpuVariantValue = getCPUVariant()
}
})
return cpuVariantValue
} }
// For Linux, the kernel has already detected the ABI, ISA and Features. // For Linux, the kernel has already detected the ABI, ISA and Features.

View File

@ -33,6 +33,6 @@ func DefaultSpec() specs.Platform {
OS: runtime.GOOS, OS: runtime.GOOS,
Architecture: runtime.GOARCH, Architecture: runtime.GOARCH,
// The Variant field will be empty if arch != ARM. // The Variant field will be empty if arch != ARM.
Variant: cpuVariant, Variant: cpuVariant(),
} }
} }

View File

@ -28,7 +28,7 @@ func TestDefault(t *testing.T) {
expected := specs.Platform{ expected := specs.Platform{
OS: runtime.GOOS, OS: runtime.GOOS,
Architecture: runtime.GOARCH, Architecture: runtime.GOARCH,
Variant: cpuVariant, Variant: cpuVariant(),
} }
p := DefaultSpec() p := DefaultSpec()
if !reflect.DeepEqual(p, expected) { if !reflect.DeepEqual(p, expected) {

View File

@ -189,8 +189,8 @@ func Parse(specifier string) (specs.Platform, error) {
if isKnownOS(p.OS) { if isKnownOS(p.OS) {
// picks a default architecture // picks a default architecture
p.Architecture = runtime.GOARCH p.Architecture = runtime.GOARCH
if p.Architecture == "arm" && cpuVariant != "v7" { if p.Architecture == "arm" && cpuVariant() != "v7" {
p.Variant = cpuVariant p.Variant = cpuVariant()
} }
return p, nil return p, nil

View File

@ -31,8 +31,8 @@ func TestParseSelector(t *testing.T) {
defaultVariant = "" defaultVariant = ""
) )
if defaultArch == "arm" && cpuVariant != "v7" { if defaultArch == "arm" && cpuVariant() != "v7" {
defaultVariant = cpuVariant defaultVariant = cpuVariant()
} }
for _, testcase := range []struct { for _, testcase := range []struct {