File: system_cpu.go

package info (click to toggle)
golang-github-prometheus-procfs 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 4,184 kB
  • sloc: sh: 348; makefile: 20
file content (443 lines) | stat: -rw-r--r-- 12,460 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build linux
// +build linux

package sysfs

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"golang.org/x/sync/errgroup"

	"github.com/prometheus/procfs/internal/util"
)

// CPU represents a path to a CPU located in `/sys/devices/system/cpu/cpu[0-9]*`.
type CPU string

// Number returns the ID number of the given CPU.
func (c CPU) Number() string {
	return strings.TrimPrefix(filepath.Base(string(c)), "cpu")
}

// CPUTopology contains data located in `/sys/devices/system/cpu/cpu[0-9]*/topology`.
type CPUTopology struct {
	CoreID             string
	CoreSiblingsList   string
	PhysicalPackageID  string
	ThreadSiblingsList string
}

// CPUThermalThrottle contains data from `/sys/devices/system/cpu/cpu[0-9]*/thermal_throttle`.
type CPUThermalThrottle struct {
	CoreThrottleCount    uint64
	PackageThrottleCount uint64
}

// SystemCPUCpufreqStats contains stats from `/sys/devices/system/cpu/cpu[0-9]*/cpufreq/...`.
type SystemCPUCpufreqStats struct {
	Name                     string
	CpuinfoCurrentFrequency  *uint64
	CpuinfoMinimumFrequency  *uint64
	CpuinfoMaximumFrequency  *uint64
	CpuinfoTransitionLatency *uint64
	ScalingCurrentFrequency  *uint64
	ScalingMinimumFrequency  *uint64
	ScalingMaximumFrequency  *uint64
	AvailableGovernors       string
	Driver                   string
	Governor                 string
	RelatedCpus              string
	SetSpeed                 string
	// Refer `CONFIG_CPU_FREQ_STAT`: https://www.kernel.org/doc/html/latest/cpu-freq/cpufreq-stats.html#configuring-cpufreq-stats
	CpuinfoFrequencyDuration         *map[uint64]uint64
	CpuinfoFrequencyTransitionsTotal *uint64
	CpuinfoTransitionTable           *[][]uint64
}

// CPUs returns a slice of all CPUs in `/sys/devices/system/cpu`.
func (fs FS) CPUs() ([]CPU, error) {
	cpuPaths, err := filepath.Glob(fs.sys.Path("devices/system/cpu/cpu[0-9]*"))
	if err != nil {
		return nil, err
	}
	cpus := make([]CPU, len(cpuPaths))
	for i, cpu := range cpuPaths {
		cpus[i] = CPU(cpu)
	}
	return cpus, nil
}

// Topology gets the topology information for a single CPU from `/sys/devices/system/cpu/cpuN/topology`.
func (c CPU) Topology() (*CPUTopology, error) {
	cpuTopologyPath := filepath.Join(string(c), "topology")
	if _, err := os.Stat(cpuTopologyPath); err != nil {
		return nil, err
	}
	t, err := parseCPUTopology(cpuTopologyPath)
	if err != nil {
		return nil, err
	}
	return t, nil
}

func parseCPUTopology(cpuPath string) (*CPUTopology, error) {
	t := CPUTopology{}
	var err error
	t.CoreID, err = util.SysReadFile(filepath.Join(cpuPath, "core_id"))
	if err != nil {
		return nil, err
	}
	t.PhysicalPackageID, err = util.SysReadFile(filepath.Join(cpuPath, "physical_package_id"))
	if err != nil {
		return nil, err
	}
	t.CoreSiblingsList, err = util.SysReadFile(filepath.Join(cpuPath, "core_siblings_list"))
	if err != nil {
		return nil, err
	}
	t.ThreadSiblingsList, err = util.SysReadFile(filepath.Join(cpuPath, "thread_siblings_list"))
	if err != nil {
		return nil, err
	}
	return &t, nil
}

// ThermalThrottle gets the cpu throttle count information for a single CPU from `/sys/devices/system/cpu/cpuN/thermal_throttle`.
func (c CPU) ThermalThrottle() (*CPUThermalThrottle, error) {
	cpuPath := filepath.Join(string(c), "thermal_throttle")
	if _, err := os.Stat(cpuPath); err != nil {
		return nil, err
	}
	t, err := parseCPUThermalThrottle(cpuPath)
	if err != nil {
		return nil, err
	}
	return t, nil
}

// Online returns the online status of a CPU from `/sys/devices/system/cpu/cpuN/online`.
func (c CPU) Online() (bool, error) {
	cpuPath := filepath.Join(string(c), "online")
	str, err := util.SysReadFile(cpuPath)
	if err != nil {
		return false, err
	}
	return str == "1", nil
}

func parseCPUThermalThrottle(cpuPath string) (*CPUThermalThrottle, error) {
	t := CPUThermalThrottle{}
	var err error
	t.PackageThrottleCount, err = util.ReadUintFromFile(filepath.Join(cpuPath, "package_throttle_count"))
	if err != nil {
		return nil, err
	}
	t.CoreThrottleCount, err = util.ReadUintFromFile(filepath.Join(cpuPath, "core_throttle_count"))
	if err != nil {
		return nil, err
	}
	return &t, nil
}

func binSearch(elem uint16, elemSlice *[]uint16) bool {
	if len(*elemSlice) == 0 {
		return false
	}

	if len(*elemSlice) == 1 {
		return elem == (*elemSlice)[0]
	}

	start := 0
	end := len(*elemSlice) - 1

	var mid int

	for start <= end {
		mid = (start + end) / 2
		if (*elemSlice)[mid] == elem {
			return true
		} else if (*elemSlice)[mid] > elem {
			end = mid - 1
		} else if (*elemSlice)[mid] < elem {
			start = mid + 1
		}
	}

	return false
}

func filterOfflineCPUs(offlineCpus *[]uint16, cpus *[]string) ([]string, error) {
	var filteredCPUs []string
	for _, cpu := range *cpus {
		cpuName := strings.TrimPrefix(filepath.Base(cpu), "cpu")
		cpuNameUint16, err := strconv.Atoi(cpuName)
		if err != nil {
			return nil, err
		}
		if !binSearch(uint16(cpuNameUint16), offlineCpus) {
			filteredCPUs = append(filteredCPUs, cpu)
		}
	}

	return filteredCPUs, nil
}

// SystemCpufreq returns CPU frequency metrics for all CPUs.
func (fs FS) SystemCpufreq() ([]SystemCPUCpufreqStats, error) {
	var g errgroup.Group

	cpus, err := filepath.Glob(fs.sys.Path("devices/system/cpu/cpu[0-9]*"))
	if err != nil {
		return nil, err
	}

	line, err := util.ReadFileNoStat(fs.sys.Path("devices/system/cpu/offline"))
	if err != nil {
		return nil, err
	}

	if strings.TrimSpace(string(line)) != "" {
		offlineCPUs, err := parseCPURange(line)
		if err != nil {
			return nil, err
		}

		if len(offlineCPUs) > 0 {
			cpus, err = filterOfflineCPUs(&offlineCPUs, &cpus)
			if err != nil {
				return nil, err
			}
		}
	}

	systemCpufreq := make([]SystemCPUCpufreqStats, len(cpus))
	for i, cpu := range cpus {
		cpuName := strings.TrimPrefix(filepath.Base(cpu), "cpu")

		cpuCpufreqPath := filepath.Join(cpu, "cpufreq")
		_, err = os.Stat(cpuCpufreqPath)
		if os.IsNotExist(err) {
			continue
		} else if err != nil {
			return nil, err
		}

		// Execute the parsing of each CPU in parallel.
		// This is done because the kernel intentionally delays access to each CPU by
		// 50 milliseconds to avoid DDoSing possibly expensive functions.
		i := i // https://golang.org/doc/faq#closures_and_goroutines
		g.Go(func() error {
			cpufreq, err := parseCpufreqCpuinfo(cpuCpufreqPath)
			if err == nil {
				cpufreq.Name = cpuName
				systemCpufreq[i] = *cpufreq
			}
			return err
		})
	}

	if err = g.Wait(); err != nil {
		return nil, err
	}

	if len(systemCpufreq) == 0 {
		return nil, fmt.Errorf("could not find any cpufreq files: %w", os.ErrNotExist)
	}

	return systemCpufreq, nil
}

func parseCpufreqCpuinfo(cpuPath string) (*SystemCPUCpufreqStats, error) {
	uintFiles := []string{
		"cpuinfo_cur_freq",
		"cpuinfo_max_freq",
		"cpuinfo_min_freq",
		"cpuinfo_transition_latency",
		"scaling_cur_freq",
		"scaling_max_freq",
		"scaling_min_freq",
	}
	uintOut := make([]*uint64, len(uintFiles))

	for i, f := range uintFiles {
		v, err := util.ReadUintFromFile(filepath.Join(cpuPath, f))
		if err != nil {
			if os.IsNotExist(err) || os.IsPermission(err) {
				continue
			}
			return &SystemCPUCpufreqStats{}, err
		}

		uintOut[i] = &v
	}

	stringFiles := []string{
		"scaling_available_governors",
		"scaling_driver",
		"scaling_governor",
		"related_cpus",
		"scaling_setspeed",
	}
	stringOut := make([]string, len(stringFiles))
	var err error

	for i, f := range stringFiles {
		stringOut[i], err = util.SysReadFile(filepath.Join(cpuPath, f))
		if err != nil {
			return &SystemCPUCpufreqStats{}, err
		}
	}

	// "total_trans" is the total number of times the CPU has changed frequency.
	var cpuinfoFrequencyTransitionsTotal *uint64
	cpuinfoFrequencyTransitionsTotalUint, err := util.ReadUintFromFile(filepath.Join(cpuPath, "stats", "total_trans"))
	if err != nil {
		if !(os.IsNotExist(err) || os.IsPermission(err)) {
			return &SystemCPUCpufreqStats{}, err
		}
	} else {
		cpuinfoFrequencyTransitionsTotal = &cpuinfoFrequencyTransitionsTotalUint
	}

	// "time_in_state" is the total time spent at each frequency.
	var cpuinfoFrequencyDuration *map[uint64]uint64
	cpuinfoFrequencyDurationString, err := util.ReadFileNoStat(filepath.Join(cpuPath, "stats", "time_in_state"))
	if err != nil {
		if !(os.IsNotExist(err) || os.IsPermission(err)) {
			return &SystemCPUCpufreqStats{}, err
		}
	} else {
		cpuinfoFrequencyDuration = &map[uint64]uint64{}
		for _, line := range strings.Split(string(cpuinfoFrequencyDurationString), "\n") {
			if line == "" {
				continue
			}
			fields := strings.Fields(line)
			if len(fields) != 2 {
				return &SystemCPUCpufreqStats{}, fmt.Errorf("unexpected number of fields in time_in_state: %v", fields)
			}
			freq, err := strconv.ParseUint(fields[0], 10, 64)
			if err != nil {
				return &SystemCPUCpufreqStats{}, err
			}
			duration, err := strconv.ParseUint(fields[1], 10, 64)
			if err != nil {
				return &SystemCPUCpufreqStats{}, err
			}
			(*cpuinfoFrequencyDuration)[freq] = duration
		}
	}

	// "trans_table" contains information about all the CPU frequency transitions.
	var cpuinfoTransitionTable *[][]uint64
	cpuinfoTransitionTableString, err := util.ReadFileNoStat(filepath.Join(cpuPath, "stats", "trans_table"))
	if err != nil {
		if !(os.IsNotExist(err) || os.IsPermission(err)) {
			return &SystemCPUCpufreqStats{}, err
		}
	} else {
		cpuinfoTransitionTable = &[][]uint64{}
		for i, line := range strings.Split(string(cpuinfoTransitionTableString), "\n") {
			// Skip the "From: To" header.
			if i == 0 || line == "" {
				continue
			}
			fields := strings.Fields(line)
			fields[0] = strings.TrimSuffix(fields[0], ":")
			cpuinfoTransitionTableRow := make([]uint64, len(fields))
			for i := range fields {
				if len(fields[i]) == 0 {
					continue
				}
				f, err := strconv.ParseUint(fields[i], 10, 64)
				if err != nil {
					return &SystemCPUCpufreqStats{}, err
				}
				cpuinfoTransitionTableRow[i] = f
			}
			*cpuinfoTransitionTable = append(*cpuinfoTransitionTable, cpuinfoTransitionTableRow)
		}
	}

	return &SystemCPUCpufreqStats{
		CpuinfoCurrentFrequency:          uintOut[0],
		CpuinfoMaximumFrequency:          uintOut[1],
		CpuinfoMinimumFrequency:          uintOut[2],
		CpuinfoTransitionLatency:         uintOut[3],
		ScalingCurrentFrequency:          uintOut[4],
		ScalingMaximumFrequency:          uintOut[5],
		ScalingMinimumFrequency:          uintOut[6],
		AvailableGovernors:               stringOut[0],
		Driver:                           stringOut[1],
		Governor:                         stringOut[2],
		RelatedCpus:                      stringOut[3],
		SetSpeed:                         stringOut[4],
		CpuinfoFrequencyDuration:         cpuinfoFrequencyDuration,
		CpuinfoFrequencyTransitionsTotal: cpuinfoFrequencyTransitionsTotal,
		CpuinfoTransitionTable:           cpuinfoTransitionTable,
	}, nil
}

func (fs FS) IsolatedCPUs() ([]uint16, error) {
	isolcpus, err := os.ReadFile(fs.sys.Path("devices/system/cpu/isolated"))
	if err != nil {
		return nil, err
	}

	return parseCPURange(isolcpus)
}

func parseCPURange(data []byte) ([]uint16, error) {

	var cpusInt = []uint16{}

	for _, cpu := range strings.Split(strings.TrimSuffix(string(data), "\n"), ",") {
		if cpu == "" {
			continue
		}
		if strings.Contains(cpu, "-") {
			ranges := strings.Split(cpu, "-")
			if len(ranges) != 2 {
				return nil, fmt.Errorf("invalid cpu range: %s", cpu)
			}
			startRange, err := strconv.Atoi(ranges[0])
			if err != nil {
				return nil, fmt.Errorf("invalid cpu start range: %w", err)
			}
			endRange, err := strconv.Atoi(ranges[1])
			if err != nil {
				return nil, fmt.Errorf("invalid cpu end range: %w", err)
			}

			for i := startRange; i <= endRange; i++ {
				cpusInt = append(cpusInt, uint16(i))
			}
			continue
		}

		cpuN, err := strconv.Atoi(cpu)
		if err != nil {
			return nil, err
		}
		cpusInt = append(cpusInt, uint16(cpuN))
	}
	return cpusInt, nil
}