diff --git a/README.md b/README.md index 7ace25c..3fa4c29 100644 --- a/README.md +++ b/README.md @@ -130,15 +130,7 @@ fmt.Println(v.VirtualTotal) gopsutil aims to minimize platform differences by offering common functions. However, there are many requests to obtain unique information for each platform. The Ex structs are designed to meet those requests. Additional functionalities might be added in the future. The use of these structures makes it clear that the information they provide is specific to each platform, which is why they have been designed in this way. -On Linux, `cpu.NewExLinux().TimesWithContext(ctx, percpu)` (or -`cpu.NewExLinux().Times(percpu)`) -returns `[]cpu.TimesStatEx` with the raw `uint64` CPU time counters from -`/proc/stat`, in USER_HZ ticks. This allows integer deltas to be computed before -unit conversion. No normalization is performed, so Linux counter semantics still -apply, including possible decreases in `iowait`. The existing `cpu.Times` API -continues to return `float64` seconds. See the [kernel's `/proc/stat` -documentation](https://docs.kernel.org/filesystems/proc.html#miscellaneous-kernel-statistics-in-proc-stat) -for the meaning of each counter. +On Linux, `cpu.NewExLinux().Times(percpu)` returns `[]cpu.ExTimesStat` with the raw `uint64` counters from `/proc/stat`, in USER_HZ ticks instead of the `float64` seconds of `cpu.Times`. This allows integer deltas to be computed before unit conversion. A counter can decrease, in particular `iowait`, so check that the new value is not smaller than the old one before you subtract. See the [kernel's `/proc/stat` documentation](https://docs.kernel.org/filesystems/proc.html#miscellaneous-kernel-statistics-in-proc-stat) for the meaning of each counter. ## Documentation diff --git a/cpu/cpu_linux.go b/cpu/cpu_linux.go index 4072f19..f9ab0c8 100644 --- a/cpu/cpu_linux.go +++ b/cpu/cpu_linux.go @@ -131,7 +131,7 @@ func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { if err != nil { continue } - ret = append(ret, *ct) + ret = append(ret, ct.ToTimesStat()) } return ret, nil @@ -348,83 +348,39 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { return ret, nil } -func parseStatLine(line string) (*TimesStat, error) { +// parseStatLine parses a /proc/stat CPU line for both Times and ExLinux.Times. +func parseStatLine(line string) (ExTimesStat, error) { fields := strings.Fields(line) + // The name and the seven counters present since Linux 2.6 are required. if len(fields) < 8 { - return nil, errors.New("stat does not contain cpu info") + return ExTimesStat{}, errors.New("stat does not contain cpu info") } if !strings.HasPrefix(fields[0], "cpu") { - return nil, errors.New("not contain cpu") + return ExTimesStat{}, errors.New("not contain cpu") } - cpu := fields[0] - if cpu == "cpu" { - cpu = "cpu-total" + stat := ExTimesStat{CPU: fields[0]} + if stat.CPU == "cpu" { + stat.CPU = "cpu-total" } - user, err := strconv.ParseFloat(fields[1], 64) - if err != nil { - return nil, err - } - nice, err := strconv.ParseFloat(fields[2], 64) - if err != nil { - return nil, err - } - system, err := strconv.ParseFloat(fields[3], 64) - if err != nil { - return nil, err - } - idle, err := strconv.ParseFloat(fields[4], 64) - if err != nil { - return nil, err - } - iowait, err := strconv.ParseFloat(fields[5], 64) - if err != nil { - return nil, err - } - irq, err := strconv.ParseFloat(fields[6], 64) - if err != nil { - return nil, err + // Steal, Guest and GuestNice are optional, and later columns are ignored. + counters := []*uint64{ + &stat.User, &stat.Nice, &stat.System, &stat.Idle, &stat.Iowait, + &stat.Irq, &stat.Softirq, &stat.Steal, &stat.Guest, &stat.GuestNice, } - softirq, err := strconv.ParseFloat(fields[7], 64) - if err != nil { - return nil, err - } - - ct := &TimesStat{ - CPU: cpu, - User: user / ClocksPerSec, - Nice: nice / ClocksPerSec, - System: system / ClocksPerSec, - Idle: idle / ClocksPerSec, - Iowait: iowait / ClocksPerSec, - Irq: irq / ClocksPerSec, - Softirq: softirq / ClocksPerSec, - } - if len(fields) > 8 { // Linux >= 2.6.11 - steal, err := strconv.ParseFloat(fields[8], 64) - if err != nil { - return nil, err + for i, counter := range counters { + if i+1 >= len(fields) { + break } - ct.Steal = steal / ClocksPerSec - } - if len(fields) > 9 { // Linux >= 2.6.24 - guest, err := strconv.ParseFloat(fields[9], 64) + value, err := strconv.ParseUint(fields[i+1], 10, 64) if err != nil { - return nil, err + return ExTimesStat{}, fmt.Errorf("parse CPU time field %d for %s: %w", i+1, stat.CPU, err) } - ct.Guest = guest / ClocksPerSec + *counter = value } - if len(fields) > 10 { // Linux >= 3.2.0 - guestNice, err := strconv.ParseFloat(fields[10], 64) - if err != nil { - return nil, err - } - ct.GuestNice = guestNice / ClocksPerSec - } - - return ct, nil + return stat, nil } func CountsWithContext(ctx context.Context, logical bool) (int, error) { diff --git a/cpu/ex_linux.go b/cpu/ex_linux.go index 2e5e20b..77514ef 100644 --- a/cpu/ex_linux.go +++ b/cpu/ex_linux.go @@ -8,19 +8,23 @@ import ( "context" "encoding/json" "errors" - "fmt" "io" "os" - "strconv" - "strings" "github.com/shirou/gopsutil/v4/internal/common" ) -// TimesStatEx contains the unscaled Linux CPU time counters from /proc/stat. +// ExTimesStat contains the unscaled Linux CPU time counters from /proc/stat. // Counters are in USER_HZ ticks, rather than the seconds used by TimesStat. -// They are reported as read: in particular, Iowait can decrease on Linux. -type TimesStatEx struct { +// Divide a counter by ClocksPerSec to get seconds, or use ToTimesStat. +// +// User includes Guest, and Nice includes GuestNice, because the kernel +// accounts guest time into both. Subtract Guest and GuestNice when summing +// all fields. +// +// Counters are reported as read. A counter can decrease, in particular Iowait. +// Check that the new value is not smaller than the old one before you subtract. +type ExTimesStat struct { CPU string `json:"cpu"` User uint64 `json:"user"` System uint64 `json:"system"` @@ -34,32 +38,50 @@ type TimesStatEx struct { GuestNice uint64 `json:"guestNice"` } -func (c TimesStatEx) String() string { +func (c ExTimesStat) String() string { data, _ := json.Marshal(c) return string(data) } +// ToTimesStat converts the counters to the seconds returned by the +// package-level Times function. +func (c ExTimesStat) ToTimesStat() TimesStat { + return TimesStat{ + CPU: c.CPU, + User: float64(c.User) / ClocksPerSec, + System: float64(c.System) / ClocksPerSec, + Idle: float64(c.Idle) / ClocksPerSec, + Nice: float64(c.Nice) / ClocksPerSec, + Iowait: float64(c.Iowait) / ClocksPerSec, + Irq: float64(c.Irq) / ClocksPerSec, + Softirq: float64(c.Softirq) / ClocksPerSec, + Steal: float64(c.Steal) / ClocksPerSec, + Guest: float64(c.Guest) / ClocksPerSec, + GuestNice: float64(c.GuestNice) / ClocksPerSec, + } +} + type ExLinux struct{} func NewExLinux() *ExLinux { return &ExLinux{} } -func (ex *ExLinux) Times(percpu bool) ([]TimesStatEx, error) { +func (ex *ExLinux) Times(percpu bool) ([]ExTimesStat, error) { return ex.TimesWithContext(context.Background(), percpu) } // TimesWithContext returns raw CPU tick counters without floating-point conversion. -// CPU names and selection match the package-level Times function; absent optional counters are zero. -// Unlike the legacy API, read errors and invalid selected CPU rows are returned. -func (*ExLinux) TimesWithContext(ctx context.Context, percpu bool) ([]TimesStatEx, error) { +// CPU rows are selected and parsed like the package-level Times function; absent optional counters are zero. +// Unlike the legacy API, read errors and invalid selected CPU rows are returned instead of skipped. +func (*ExLinux) TimesWithContext(ctx context.Context, percpu bool) ([]ExTimesStat, error) { file, err := os.Open(common.HostProcWithContext(ctx, "stat")) if err != nil { return nil, err } defer file.Close() reader := bufio.NewReader(file) - ret := []TimesStatEx{} + ret := []ExTimesStat{} if percpu { if _, err := reader.ReadString('\n'); err != nil { if errors.Is(err, io.EOF) { @@ -85,7 +107,7 @@ func (*ExLinux) TimesWithContext(ctx context.Context, percpu bool) ([]TimesStatE if line == "" { return ret, nil } - stat, parseErr := parseStatLineEx(line) + stat, parseErr := parseStatLine(line) if parseErr != nil { return nil, parseErr } @@ -95,32 +117,3 @@ func (*ExLinux) TimesWithContext(ctx context.Context, percpu bool) ([]TimesStatE } } } - -func parseStatLineEx(line string) (TimesStatEx, error) { - fields := strings.Fields(line) - if len(fields) < 5 { - return TimesStatEx{}, errors.New("stat does not contain cpu info") - } - if !strings.HasPrefix(fields[0], "cpu") { - return TimesStatEx{}, errors.New("not contain cpu") - } - stat := TimesStatEx{CPU: fields[0]} - if stat.CPU == "cpu" { - stat.CPU = "cpu-total" - } - counters := []*uint64{ - &stat.User, &stat.Nice, &stat.System, &stat.Idle, &stat.Iowait, - &stat.Irq, &stat.Softirq, &stat.Steal, &stat.Guest, &stat.GuestNice, - } - for i, counter := range counters { - if i+1 >= len(fields) { - break - } - value, err := strconv.ParseUint(fields[i+1], 10, 64) - if err != nil { - return TimesStatEx{}, fmt.Errorf("parse CPU time field %d for %s: %w", i+1, stat.CPU, err) - } - *counter = value - } - return stat, nil -} diff --git a/cpu/ex_linux_test.go b/cpu/ex_linux_test.go index 88f8349..ce80b1a 100644 --- a/cpu/ex_linux_test.go +++ b/cpu/ex_linux_test.go @@ -35,13 +35,13 @@ func TestExLinuxTimes(t *testing.T) { ex := NewExLinux() total, err := ex.TimesWithContext(ctx, false) require.NoError(t, err) - require.Equal(t, []TimesStatEx{{ + require.Equal(t, []ExTimesStat{{ CPU: "cpu-total", User: 101, Nice: 102, System: 103, Idle: 104, Iowait: 105, Irq: 106, Softirq: 107, Steal: 108, Guest: 109, GuestNice: 110, }}, total) cpus, err := ex.TimesWithContext(ctx, true) require.NoError(t, err) - require.Equal(t, []TimesStatEx{ + require.Equal(t, []ExTimesStat{ {CPU: "cpu0", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7, Steal: 8, Guest: 9, GuestNice: 10}, {CPU: "cpu7", User: 11, Nice: 12, System: 13, Idle: 14, Iowait: 15, Irq: 16, Softirq: 17, Steal: 18, Guest: 19, GuestNice: 20}, }, cpus) @@ -75,19 +75,18 @@ func TestExLinuxTimesColumns(t *testing.T) { for _, tc := range []struct { name string counters string - want TimesStatEx + want ExTimesStat }{ - {"four", "1 2 3 4", TimesStatEx{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4}}, - {"seven", "1 2 3 4 5 6 7", TimesStatEx{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7}}, - {"steal", "1 2 3 4 5 6 7 8", TimesStatEx{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7, Steal: 8}}, - {"guest", "1 2 3 4 5 6 7 8 9", TimesStatEx{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7, Steal: 8, Guest: 9}}, - {"extra", "1 2 3 4 5 6 7 8 9 10 11 12", TimesStatEx{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7, Steal: 8, Guest: 9, GuestNice: 10}}, + {"seven", "1 2 3 4 5 6 7", ExTimesStat{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7}}, + {"steal", "1 2 3 4 5 6 7 8", ExTimesStat{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7, Steal: 8}}, + {"guest", "1 2 3 4 5 6 7 8 9", ExTimesStat{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7, Steal: 8, Guest: 9}}, + {"extra", "1 2 3 4 5 6 7 8 9 10 11 12", ExTimesStat{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7, Steal: 8, Guest: 9, GuestNice: 10}}, } { t.Run(tc.name, func(t *testing.T) { ctx := exTimesContext(t, "cpu\t"+tc.counters+"\n") stats, err := NewExLinux().TimesWithContext(ctx, false) require.NoError(t, err) - assert.Equal(t, []TimesStatEx{tc.want}, stats) + assert.Equal(t, []ExTimesStat{tc.want}, stats) }) } } @@ -97,23 +96,27 @@ func TestExLinuxTimesErrors(t *testing.T) { name, line string cause error }{ - {"short", "cpu 1 2 3", nil}, - {"not_cpu", "btime 1 2 3 4", nil}, - {"negative", "cpu -1 2 3 4", strconv.ErrSyntax}, - {"fraction", "cpu 1.5 2 3 4", strconv.ErrSyntax}, - {"overflow", "cpu 18446744073709551616 2 3 4", strconv.ErrRange}, + {"short", "cpu 1 2 3 4 5 6", nil}, + {"not_cpu", "btime 1 2 3 4 5 6 7", nil}, + {"negative", "cpu -1 2 3 4 5 6 7", strconv.ErrSyntax}, + {"fraction", "cpu 1.5 2 3 4 5 6 7", strconv.ErrSyntax}, + {"overflow", "cpu 18446744073709551616 2 3 4 5 6 7", strconv.ErrRange}, {"optional", "cpu 1 2 3 4 5 6 7 8 9 invalid", strconv.ErrSyntax}, } { t.Run(tc.name, func(t *testing.T) { - stats, err := NewExLinux().TimesWithContext(exTimesContext(t, tc.line+"\n"), false) + ctx := exTimesContext(t, tc.line+"\n") + stats, err := NewExLinux().TimesWithContext(ctx, false) require.Error(t, err) assert.Nil(t, stats) if tc.cause != nil { require.ErrorIs(t, err, tc.cause) } + legacy, err := TimesWithContext(ctx, false) + require.NoError(t, err) + assert.Equal(t, []TimesStat{}, legacy) }) } - ctx := exTimesContext(t, "cpu 1 2 3 4 5 6 7\ncpu0 1 2 3 4\ncpu1 invalid 2 3 4\n") + ctx := exTimesContext(t, "cpu 1 2 3 4 5 6 7\ncpu0 1 2 3 4 5 6 7\ncpu1 invalid 2 3 4 5 6 7\n") stats, err := NewExLinux().TimesWithContext(ctx, true) require.ErrorIs(t, err, strconv.ErrSyntax) assert.Nil(t, stats) @@ -138,31 +141,58 @@ func TestExLinuxTimesMissingAndEmpty(t *testing.T) { stats, err = NewExLinux().TimesWithContext(empty, percpu) require.NoError(t, err) - assert.Equal(t, []TimesStatEx{}, stats) + assert.Equal(t, []ExTimesStat{}, stats) } } -func TestTimesStatExString(t *testing.T) { - want := TimesStatEx{CPU: `cpu"0`, User: math.MaxUint64, GuestNice: 1<<53 + 1} +func TestExTimesStatString(t *testing.T) { + want := ExTimesStat{CPU: `cpu"0`, User: math.MaxUint64, GuestNice: 1<<53 + 1} data := want.String() - var got TimesStatEx + var got ExTimesStat require.NoError(t, json.Unmarshal([]byte(data), &got)) assert.Equal(t, want, got) assert.Contains(t, data, `"user":18446744073709551615`) } +func TestExTimesStatToTimesStat(t *testing.T) { + clocks := ClocksPerSec + ClocksPerSec = 37 + t.Cleanup(func() { ClocksPerSec = clocks }) + seconds := func(ticks uint64) float64 { + // The float64 parsing used by Times before it shared parseStatLine. + value, err := strconv.ParseFloat(strconv.FormatUint(ticks, 10), 64) + require.NoError(t, err) + return value / ClocksPerSec + } + for _, value := range []uint64{1, 123456789, 1<<53 + 1, math.MaxUint64} { + ctx := exTimesContext(t, fmt.Sprintf("cpu %d 2 3 4 5 6 7 8 9 %d\n", value, value-1)) + want := TimesStat{ + CPU: "cpu-total", User: seconds(value), Nice: seconds(2), System: seconds(3), Idle: seconds(4), + Iowait: seconds(5), Irq: seconds(6), Softirq: seconds(7), Steal: seconds(8), Guest: seconds(9), + GuestNice: seconds(value - 1), + } + stats, err := NewExLinux().TimesWithContext(ctx, false) + require.NoError(t, err) + require.Len(t, stats, 1) + assert.Equal(t, want, stats[0].ToTimesStat()) + legacy, err := TimesWithContext(ctx, false) + require.NoError(t, err) + assert.Equal(t, []TimesStat{want}, legacy) + } +} + func TestExLinuxTimesLineBoundaries(t *testing.T) { for _, suffix := range []string{"", "\n", "\nintr " + strings.Repeat("0 ", 65536) + "\n"} { - ctx := exTimesContext(t, "cpu 1 2 3 4\ncpu0 11 12 13 14"+suffix) + ctx := exTimesContext(t, "cpu 1 2 3 4 5 6 7\ncpu0 11 12 13 14 15 16 17"+suffix) times, err := NewExLinux().TimesWithContext(ctx, true) require.NoError(t, err) - assert.Equal(t, []TimesStatEx{{CPU: "cpu0", User: 11, Nice: 12, System: 13, Idle: 14}}, times) + assert.Equal(t, []ExTimesStat{{CPU: "cpu0", User: 11, Nice: 12, System: 13, Idle: 14, Iowait: 15, Irq: 16, Softirq: 17}}, times) } - ctx := exTimesContext(t, "cpu 1 2 3 4") + ctx := exTimesContext(t, "cpu 1 2 3 4 5 6 7") stats, err := NewExLinux().TimesWithContext(ctx, false) require.NoError(t, err) - assert.Equal(t, []TimesStatEx{{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4}}, stats) + assert.Equal(t, []ExTimesStat{{CPU: "cpu-total", User: 1, Nice: 2, System: 3, Idle: 4, Iowait: 5, Irq: 6, Softirq: 7}}, stats) stats, err = NewExLinux().TimesWithContext(ctx, true) require.NoError(t, err) - assert.Equal(t, []TimesStatEx{}, stats) + assert.Equal(t, []ExTimesStat{}, stats) }