daemon: don't repeatedly call NumCPU if not needed

sysinfo.NumCPU returns the number of CPUs which are currently online,
which involves some syscalls and parsing on Windows.

Change the code to only retrieve this information when needed, and
memoize the result to prevent calling this function multiple times.

Ideally, we'd obtain this information from daemon.RawSysInfo(), but
that uses a sync.Once, which could return outdated information.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn
2025-01-01 18:19:59 +01:00
parent 6f6c3b9211
commit ddd885a961
2 changed files with 10 additions and 4 deletions

View File

@@ -492,8 +492,11 @@ func verifyPlatformContainerResources(resources *containertypes.Resources, sysIn
// https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
// Here we don't set the lower limit and it is up to the underlying platform (e.g., Linux) to return an error.
// The error message is 0.01 so that this is consistent with Windows
if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
return warnings, fmt.Errorf("Range of CPUs is from 0.01 to %d.00, as there are only %d CPUs available", sysinfo.NumCPU(), sysinfo.NumCPU())
if resources.NanoCPUs != 0 {
nc := sysinfo.NumCPU()
if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(nc)*1e9 {
return warnings, fmt.Errorf("range of CPUs is from 0.01 to %[1]d.00, as there are only %[1]d CPUs available", nc)
}
}
if resources.CPUShares > 0 && !sysInfo.CPUShares {

View File

@@ -109,8 +109,11 @@ func verifyPlatformContainerResources(resources *containertypes.Resources, isHyp
}
// The precision we could get is 0.01, because on Windows we have to convert to CPUPercent.
// We don't set the lower limit here and it is up to the underlying platform (e.g., Windows) to return an error.
if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
return warnings, fmt.Errorf("range of CPUs is from 0.01 to %d.00, as there are only %d CPUs available", sysinfo.NumCPU(), sysinfo.NumCPU())
if resources.NanoCPUs != 0 {
nc := sysinfo.NumCPU()
if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(nc)*1e9 {
return warnings, fmt.Errorf("range of CPUs is from 0.01 to %[1]d.00, as there are only %[1]d CPUs available", nc)
}
}
if len(resources.BlkioDeviceReadBps) > 0 {