|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package securitycontext |
| 18 | + |
| 19 | +import ( |
| 20 | + "os" |
| 21 | + "runtime" |
| 22 | + "strconv" |
| 23 | + "strings" |
| 24 | + "sync" |
| 25 | +) |
| 26 | + |
| 27 | +// possibleCPUs returns the number of possible CPUs on this host. |
| 28 | +func possibleCPUs() (cpus []int) { |
| 29 | + if ncpu := possibleCPUsParsed(); ncpu != nil { |
| 30 | + return ncpu |
| 31 | + } |
| 32 | + |
| 33 | + for i := range runtime.NumCPU() { |
| 34 | + cpus = append(cpus, i) |
| 35 | + } |
| 36 | + |
| 37 | + return cpus |
| 38 | +} |
| 39 | + |
| 40 | +// possibleCPUsParsed is parsing the amount of possible CPUs on this host from |
| 41 | +// /sys/devices. |
| 42 | +var possibleCPUsParsed = sync.OnceValue(func() (cpus []int) { |
| 43 | + data, err := os.ReadFile("/sys/devices/system/cpu/possible") |
| 44 | + if err != nil { |
| 45 | + return nil |
| 46 | + } |
| 47 | + |
| 48 | + ranges := strings.Split(strings.TrimSpace(string(data)), ",") |
| 49 | + |
| 50 | + for _, r := range ranges { |
| 51 | + if rStart, rEnd, ok := strings.Cut(r, "-"); !ok { |
| 52 | + cpu, err := strconv.Atoi(rStart) |
| 53 | + if err != nil { |
| 54 | + return nil |
| 55 | + } |
| 56 | + cpus = append(cpus, cpu) |
| 57 | + } else { |
| 58 | + var start, end int |
| 59 | + start, err := strconv.Atoi(rStart) |
| 60 | + if err != nil { |
| 61 | + return nil |
| 62 | + } |
| 63 | + end, err = strconv.Atoi(rEnd) |
| 64 | + if err != nil { |
| 65 | + return nil |
| 66 | + } |
| 67 | + for i := start; i <= end; i++ { |
| 68 | + cpus = append(cpus, i) |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return cpus |
| 74 | +}) |
0 commit comments