Merge branch 'dev' into vod

This commit is contained in:
Ingo Oppermann 2023-04-11 16:39:30 +02:00
commit 8c3fd4dc17
No known key found for this signature in database
GPG Key ID: 2AB32426E9DD229E
34 changed files with 962 additions and 253 deletions

5
go.mod
View File

@ -24,8 +24,8 @@ require (
github.com/minio/minio-go/v7 v7.0.50
github.com/prep/average v0.0.0-20200506183628-d26c465f48c3
github.com/prometheus/client_golang v1.14.0
github.com/shirou/gopsutil/v3 v3.22.11
github.com/stretchr/testify v1.8.1
github.com/shirou/gopsutil/v3 v3.23.3
github.com/stretchr/testify v1.8.2
github.com/swaggo/echo-swagger v1.3.5
github.com/swaggo/swag v1.8.7
github.com/vektah/gqlparser/v2 v2.5.1
@ -82,6 +82,7 @@ require (
github.com/rogpeppe/go-internal v1.8.1 // indirect
github.com/rs/xid v1.4.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shoenig/go-m1cpu v0.1.4 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a // indirect
github.com/tklauser/go-sysconf v0.3.11 // indirect

12
go.sum
View File

@ -213,8 +213,12 @@ github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/shirou/gopsutil/v3 v3.22.11 h1:kxsPKS+Eeo+VnEQ2XCaGJepeP6KY53QoRTETx3+1ndM=
github.com/shirou/gopsutil/v3 v3.22.11/go.mod h1:xl0EeL4vXJ+hQMAGN8B9VFpxukEMA0XdevQOe5MZ1oY=
github.com/shirou/gopsutil/v3 v3.23.3 h1:Syt5vVZXUDXPEXpIBt5ziWsJ4LdSAAxF4l/xZeQgSEE=
github.com/shirou/gopsutil/v3 v3.23.3/go.mod h1:lSBNN6t3+D6W5e5nXTxc8KIMMVxAcS+6IJlffjRRlMU=
github.com/shoenig/go-m1cpu v0.1.4 h1:SZPIgRM2sEF9NJy50mRHu9PKGwxyyTTJIWvCtgVbozs=
github.com/shoenig/go-m1cpu v0.1.4/go.mod h1:Wwvst4LR89UxjeFtLRMrpgRiyY4xPsejnVZym39dbAQ=
github.com/shoenig/test v0.6.3 h1:GVXWJFk9PiOjN0KoJ7VrJGH6uLPnqxR7/fe3HUPfE0c=
github.com/shoenig/test v0.6.3/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
@ -230,8 +234,9 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/swaggo/echo-swagger v1.3.5 h1:kCx1wvX5AKhjI6Ykt48l3PTsfL9UD40ZROOx/tYzWyY=
github.com/swaggo/echo-swagger v1.3.5/go.mod h1:3IMHd2Z8KftdWFEEjGmv6QpWj370LwMCOfovuh7vF34=
github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a h1:kAe4YSu0O0UFn1DowNo2MY5p6xzqtJ/wQ7LZynSvGaY=
@ -341,6 +346,7 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=

View File

@ -17,7 +17,7 @@ func NewFFmpegCollector(f ffmpeg.FFmpeg) metric.Collector {
ffmpeg: f,
}
c.processDescr = metric.NewDesc("ffmpeg_process", "State of the ffmpeg process", []string{"state"})
c.processDescr = metric.NewDesc("ffmpeg_process", "Accumulated state changes of all ffmpeg processes", []string{"state"})
return c
}

View File

@ -25,7 +25,7 @@ func NewRestreamCollector(r restream.Restreamer) metric.Collector {
c.restreamProcessDescr = metric.NewDesc("restream_process", "Current process values by name", []string{"processid", "state", "order", "name"})
c.restreamProcessStatesDescr = metric.NewDesc("restream_process_states", "Current process state", []string{"processid", "state"})
c.restreamProcessIODescr = metric.NewDesc("restream_io", "Current process IO values by name", []string{"processid", "type", "id", "address", "index", "stream", "media", "name"})
c.restreamStatesDescr = metric.NewDesc("restream_state", "Summarized process states", []string{"state"})
c.restreamStatesDescr = metric.NewDesc("restream_state", "Summarized current process states", []string{"state"})
return c
}

View File

@ -2,6 +2,7 @@ package psutil
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
@ -284,6 +285,10 @@ func (u *util) cpuTimes() (*cpuTimesStat, error) {
return nil, err
}
if len(times) == 0 {
return nil, errors.New("cpu.Times() returned an empty slice")
}
s := &cpuTimesStat{
total: cpuTotal(&times[0]),
system: times[0].System,

View File

@ -6,8 +6,8 @@ package cpu
import (
"context"
"regexp"
"strings"
"strconv"
"strings"
"github.com/shirou/gopsutil/v3/internal/common"
)
@ -28,19 +28,19 @@ func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) {
}
ret := TimesStat{CPU: "cpu-total"}
h := whiteSpaces.Split(lines[len(lines)-3], -1) // headers
v := whiteSpaces.Split(lines[len(lines)-2], -1) // values
h := whiteSpaces.Split(lines[len(lines)-3], -1) // headers
v := whiteSpaces.Split(lines[len(lines)-2], -1) // values
for i, header := range h {
if t, err := strconv.ParseFloat(v[i], 64); err == nil {
switch header {
case `%usr`:
ret.User = t
case `%sys`:
ret.System = t
case `%wio`:
ret.Iowait = t
case `%idle`:
ret.Idle = t
case `%usr`:
ret.User = t
case `%sys`:
ret.System = t
case `%wio`:
ret.Iowait = t
case `%idle`:
ret.Idle = t
}
}
}

View File

@ -8,6 +8,7 @@ import (
"strconv"
"strings"
"github.com/shoenig/go-m1cpu"
"github.com/tklauser/go-sysconf"
"golang.org/x/sys/unix"
)
@ -85,11 +86,15 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
c.CacheSize = int32(cacheSize)
c.VendorID, _ = unix.Sysctl("machdep.cpu.vendor")
// Use the rated frequency of the CPU. This is a static value and does not
// account for low power or Turbo Boost modes.
cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency")
if err == nil {
c.Mhz = float64(cpuFrequency) / 1000000.0
if m1cpu.IsAppleSilicon() {
c.Mhz = float64(m1cpu.PCoreHz() / 1_000_000)
} else {
// Use the rated frequency of the CPU. This is a static value and does not
// account for low power or Turbo Boost modes.
cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency")
if err == nil {
c.Mhz = float64(cpuFrequency) / 1000000.0
}
}
return append(ret, c), nil

View File

@ -190,7 +190,7 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
switch key {
case "Processor":
processorName = value
case "processor":
case "processor", "cpu number":
if c.CPU >= 0 {
finishCPUInfo(&c)
ret = append(ret, c)
@ -203,6 +203,9 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
c.CPU = int32(t)
case "vendorId", "vendor_id":
c.VendorID = value
if strings.Contains(value, "S390") {
processorName = "S390"
}
case "CPU implementer":
if v, err := strconv.ParseUint(value, 0, 8); err == nil {
switch v {
@ -242,7 +245,18 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
c.Family = value
case "model", "CPU part":
c.Model = value
case "model name", "cpu":
// if CPU is arm based, model name is found via model number. refer to: arch/arm64/kernel/cpuinfo.c
if c.VendorID == "ARM" {
if v, err := strconv.ParseUint(c.Model, 0, 16); err == nil {
modelName, exist := armModelToModelName[v]
if exist {
c.ModelName = modelName
} else {
c.ModelName = "Undefined"
}
}
}
case "Model Name", "model name", "cpu":
c.ModelName = value
if strings.Contains(value, "POWER8") ||
strings.Contains(value, "POWER7") {
@ -262,7 +276,7 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
return ret, err
}
c.Stepping = int32(t)
case "cpu MHz", "clock":
case "cpu MHz", "clock", "cpu MHz dynamic":
// treat this as the fallback value, thus we ignore error
if t, err := strconv.ParseFloat(strings.Replace(value, "MHz", "", 1), 64); err == nil {
c.Mhz = t
@ -285,16 +299,6 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
c.Microcode = value
}
}
if c.VendorID == "ARM" && c.ModelName == "" {
if v, err := strconv.ParseUint(c.Model, 0, 16); err == nil {
modelName, exist := armModelToModelName[v]
if exist {
c.ModelName = modelName
} else {
c.ModelName = "Undefined"
}
}
}
if c.CPU >= 0 {
finishCPUInfo(&c)
ret = append(ret, c)

View File

@ -14,8 +14,7 @@ import (
)
var (
procGetActiveProcessorCount = common.Modkernel32.NewProc("GetActiveProcessorCount")
procGetNativeSystemInfo = common.Modkernel32.NewProc("GetNativeSystemInfo")
procGetNativeSystemInfo = common.Modkernel32.NewProc("GetNativeSystemInfo")
)
type win32_Processor struct {
@ -204,15 +203,12 @@ type systemInfo struct {
func CountsWithContext(ctx context.Context, logical bool) (int, error) {
if logical {
// https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_psutil_windows.c#L97
err := procGetActiveProcessorCount.Find()
if err == nil { // Win7+
ret, _, _ := procGetActiveProcessorCount.Call(uintptr(0xffff)) // ALL_PROCESSOR_GROUPS is 0xffff according to Rust's winapi lib https://docs.rs/winapi/*/x86_64-pc-windows-msvc/src/winapi/shared/ntdef.rs.html#120
if ret != 0 {
return int(ret), nil
}
ret := windows.GetActiveProcessorCount(windows.ALL_PROCESSOR_GROUPS)
if ret != 0 {
return int(ret), nil
}
var systemInfo systemInfo
_, _, err = procGetNativeSystemInfo.Call(uintptr(unsafe.Pointer(&systemInfo)))
_, _, err := procGetNativeSystemInfo.Call(uintptr(unsafe.Pointer(&systemInfo)))
if systemInfo.dwNumberOfProcessors == 0 {
return 0, err
}

View File

@ -9,6 +9,8 @@ import (
var invoke common.Invoker = common.Invoke{}
type Warnings = common.Warnings
type UsageStat struct {
Path string `json:"path"`
Fstype string `json:"fstype"`

View File

@ -8,8 +8,8 @@ import (
"regexp"
"strings"
"golang.org/x/sys/unix"
"github.com/shirou/gopsutil/v3/internal/common"
"golang.org/x/sys/unix"
)
var whiteSpaces = regexp.MustCompile(`\s+`)
@ -17,11 +17,11 @@ var startBlank = regexp.MustCompile(`^\s+`)
var ignoreFSType = map[string]bool{"procfs": true}
var FSType = map[int]string{
0: "jfs2", 1: "namefs", 2: "nfs", 3: "jfs", 5: "cdrom", 6: "proc",
16: "special-fs", 17: "cache-fs", 18: "nfs3", 19: "automount-fs", 20: "pool-fs", 32: "vxfs",
33: "veritas-fs", 34: "udfs", 35: "nfs4", 36: "nfs4-pseudo", 37: "smbfs", 38: "mcr-pseudofs",
39: "ahafs", 40: "sterm-nfs", 41: "asmfs",
}
0: "jfs2", 1: "namefs", 2: "nfs", 3: "jfs", 5: "cdrom", 6: "proc",
16: "special-fs", 17: "cache-fs", 18: "nfs3", 19: "automount-fs", 20: "pool-fs", 32: "vxfs",
33: "veritas-fs", 34: "udfs", 35: "nfs4", 36: "nfs4-pseudo", 37: "smbfs", 38: "mcr-pseudofs",
39: "ahafs", 40: "sterm-nfs", 41: "asmfs",
}
func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) {
var ret []PartitionStat
@ -42,7 +42,7 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro
start := 0
finished := false
for pos, ch := range lines[1] {
if ch == ' ' && ! finished {
if ch == ' ' && !finished {
name := strings.TrimSpace(lines[0][start:pos])
colidx[name] = idx
finished = true

View File

@ -20,9 +20,15 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro
return ret, err
}
fs := make([]unix.Statfs_t, count)
if _, err = unix.Getfsstat(fs, unix.MNT_WAIT); err != nil {
count, err = unix.Getfsstat(fs, unix.MNT_WAIT)
if err != nil {
return ret, err
}
// On 10.14, and possibly other OS versions, the actual count may
// be less than from the first call. Truncate to the returned count
// to prevent accessing uninitialized entries.
// https://github.com/shirou/gopsutil/issues/1390
fs = fs[:count]
for _, stat := range fs {
opts := []string{"rw"}
if stat.Flags&unix.MNT_RDONLY != 0 {

View File

@ -12,9 +12,8 @@ import (
"strconv"
"strings"
"golang.org/x/sys/unix"
"github.com/shirou/gopsutil/v3/internal/common"
"golang.org/x/sys/unix"
)
// PartitionsWithContext returns disk partition.

View File

@ -341,7 +341,7 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro
}
if strings.HasPrefix(d.Device, "/dev/mapper/") {
devpath, err := filepath.EvalSymlinks(common.HostDev(strings.Replace(d.Device, "/dev", "", -1)))
devpath, err := filepath.EvalSymlinks(common.HostDev(strings.Replace(d.Device, "/dev", "", 1)))
if err == nil {
d.Device = devpath
}

View File

@ -6,20 +6,16 @@ package disk
import (
"bytes"
"context"
"errors"
"fmt"
"strconv"
"sync"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
"github.com/shirou/gopsutil/v3/internal/common"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
type Warnings = common.Warnings
var (
procGetDiskFreeSpaceExW = common.Modkernel32.NewProc("GetDiskFreeSpaceExW")
procGetLogicalDriveStringsW = common.Modkernel32.NewProc("GetLogicalDriveStringsW")
@ -84,44 +80,101 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return ret, nil
}
// PartitionsWithContext returns disk partitions.
// Since GetVolumeInformation doesn't have a timeout, this method uses context to set deadline by users.
func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) {
warnings := Warnings{
Verbose: true,
}
var ret []PartitionStat
retChan := make(chan []PartitionStat)
errChan := make(chan error)
lpBuffer := make([]byte, 254)
diskret, _, err := procGetLogicalDriveStringsW.Call(
uintptr(len(lpBuffer)),
uintptr(unsafe.Pointer(&lpBuffer[0])))
if diskret == 0 {
return ret, err
}
for _, v := range lpBuffer {
if v >= 65 && v <= 90 {
i, err := getVolumeInformation(string(v), &warnings)
if err != nil && !errors.Is(err, errDeviceNotReady) && !errors.Is(err, errInvalidDriveType) {
continue
}
opts := []string{"rw"}
if i.FileSystemFlags&fileReadOnlyVolume != 0 {
opts = []string{"ro"}
}
if i.FileSystemFlags&fileFileCompression != 0 {
opts = append(opts, "compress")
}
var waitgrp sync.WaitGroup
waitgrp.Add(1)
defer waitgrp.Done()
path := string(v) + ":"
d := PartitionStat{
Mountpoint: path,
Device: path,
Fstype: i.FileSystemName,
Opts: opts,
}
ret = append(ret, d)
f := func() {
defer func() {
waitgrp.Wait()
// fires when this func and the outside func finishes.
close(errChan)
close(retChan)
}()
diskret, _, err := procGetLogicalDriveStringsW.Call(
uintptr(len(lpBuffer)),
uintptr(unsafe.Pointer(&lpBuffer[0])))
if diskret == 0 {
errChan <- err
return
}
for _, v := range lpBuffer {
if v >= 65 && v <= 90 {
path := string(v) + ":"
typepath, _ := windows.UTF16PtrFromString(path)
typeret, _, _ := procGetDriveType.Call(uintptr(unsafe.Pointer(typepath)))
if typeret == 0 {
err := windows.GetLastError()
warnings.Add(err)
continue
}
// 2: DRIVE_REMOVABLE 3: DRIVE_FIXED 4: DRIVE_REMOTE 5: DRIVE_CDROM
if typeret == 2 || typeret == 3 || typeret == 4 || typeret == 5 {
lpVolumeNameBuffer := make([]byte, 256)
lpVolumeSerialNumber := int64(0)
lpMaximumComponentLength := int64(0)
lpFileSystemFlags := int64(0)
lpFileSystemNameBuffer := make([]byte, 256)
volpath, _ := windows.UTF16PtrFromString(string(v) + ":/")
driveret, _, err := procGetVolumeInformation.Call(
uintptr(unsafe.Pointer(volpath)),
uintptr(unsafe.Pointer(&lpVolumeNameBuffer[0])),
uintptr(len(lpVolumeNameBuffer)),
uintptr(unsafe.Pointer(&lpVolumeSerialNumber)),
uintptr(unsafe.Pointer(&lpMaximumComponentLength)),
uintptr(unsafe.Pointer(&lpFileSystemFlags)),
uintptr(unsafe.Pointer(&lpFileSystemNameBuffer[0])),
uintptr(len(lpFileSystemNameBuffer)))
if driveret == 0 {
if typeret == 5 || typeret == 2 {
continue // device is not ready will happen if there is no disk in the drive
}
warnings.Add(err)
continue
}
opts := []string{"rw"}
if lpFileSystemFlags&fileReadOnlyVolume != 0 {
opts = []string{"ro"}
}
if lpFileSystemFlags&fileFileCompression != 0 {
opts = append(opts, "compress")
}
d := PartitionStat{
Mountpoint: path,
Device: path,
Fstype: string(bytes.Replace(lpFileSystemNameBuffer, []byte("\x00"), []byte(""), -1)),
Opts: opts,
}
ret = append(ret, d)
}
}
}
retChan <- ret
}
go f()
select {
case err := <-errChan:
return ret, err
case ret := <-retChan:
return ret, warnings.Reference()
case <-ctx.Done():
return ret, ctx.Err()
}
return ret, warnings.Reference()
}
func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) {
@ -136,8 +189,7 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC
}
for _, v := range lpBuffer[:lpBufferLen] {
if 'A' <= v && v <= 'Z' {
vStr := string(rune(v))
path := vStr + ":"
path := string(rune(v)) + ":"
typepath, _ := windows.UTF16PtrFromString(path)
typeret := windows.GetDriveType(typepath)
if typeret == 0 {
@ -162,22 +214,14 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC
if err != nil {
return drivemap, err
}
i, err := getVolumeInformation(vStr, nil)
if err != nil {
return nil, err
}
drivemap[path] = IOCountersStat{
ReadBytes: uint64(diskPerformance.BytesRead),
WriteBytes: uint64(diskPerformance.BytesWritten),
ReadCount: uint64(diskPerformance.ReadCount),
WriteCount: uint64(diskPerformance.WriteCount),
ReadTime: uint64(diskPerformance.ReadTime / 10000 / 1000), // convert to ms: https://github.com/giampaolo/psutil/issues/1012
WriteTime: uint64(diskPerformance.WriteTime / 10000 / 1000),
Name: path,
SerialNumber: strconv.FormatInt(i.SerialNumber, 10),
Label: i.Label,
ReadBytes: uint64(diskPerformance.BytesRead),
WriteBytes: uint64(diskPerformance.BytesWritten),
ReadCount: uint64(diskPerformance.ReadCount),
WriteCount: uint64(diskPerformance.WriteCount),
ReadTime: uint64(diskPerformance.ReadTime / 10000 / 1000), // convert to ms: https://github.com/giampaolo/psutil/issues/1012
WriteTime: uint64(diskPerformance.WriteTime / 10000 / 1000),
Name: path,
}
}
}
@ -185,83 +229,9 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC
}
func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
i, err := getVolumeInformation(name, nil)
if err != nil {
return "", err
}
return strconv.FormatInt(i.SerialNumber, 10), nil
return "", common.ErrNotImplementedError
}
func LabelWithContext(ctx context.Context, name string) (string, error) {
i, err := getVolumeInformation(name, nil)
if err != nil {
return "", err
}
return i.Label, nil
}
type volumeInformation struct {
Label string
SerialNumber int64
MaximumComponentLength int64
FileSystemFlags int64
FileSystemName string
}
var (
errDeviceNotReady = errors.New("device not ready")
errInvalidDriveType = errors.New("invalid drive type specified")
)
// getVolumeInformation returns all the information gathered from GetVolumeInformationW
func getVolumeInformation(name string, warnings *common.Warnings) (*volumeInformation, error) {
path := name + ":"
typepath, _ := windows.UTF16PtrFromString(path)
typeret, _, _ := procGetDriveType.Call(uintptr(unsafe.Pointer(typepath)))
if typeret == 0 {
err := windows.GetLastError()
if warnings != nil {
warnings.Add(err)
}
return nil, err
}
if typeret == windows.DRIVE_REMOVABLE || typeret == windows.DRIVE_FIXED || typeret == windows.DRIVE_REMOTE || typeret == windows.DRIVE_CDROM {
lpVolumeNameBuffer := make([]byte, 256)
lpVolumeSerialNumber := int64(0)
lpMaximumComponentLength := int64(0)
lpFileSystemFlags := int64(0)
lpFileSystemNameBuffer := make([]byte, 256)
volpath, _ := windows.UTF16PtrFromString(name + ":/")
driveret, _, err := procGetVolumeInformation.Call(
uintptr(unsafe.Pointer(volpath)),
uintptr(unsafe.Pointer(&lpVolumeNameBuffer[0])),
uintptr(len(lpVolumeNameBuffer)),
uintptr(unsafe.Pointer(&lpVolumeSerialNumber)),
uintptr(unsafe.Pointer(&lpMaximumComponentLength)),
uintptr(unsafe.Pointer(&lpFileSystemFlags)),
uintptr(unsafe.Pointer(&lpFileSystemNameBuffer[0])),
uintptr(len(lpFileSystemNameBuffer)))
if driveret == 0 {
if typeret == 5 || typeret == 2 {
return nil, errDeviceNotReady // device is not ready will happen if there is no disk in the drive
}
if warnings != nil {
warnings.Add(err)
}
return nil, err
}
return &volumeInformation{
Label: string(bytes.Replace(lpVolumeNameBuffer, []byte("\x00"), []byte(""), -1)),
SerialNumber: lpVolumeSerialNumber,
MaximumComponentLength: lpMaximumComponentLength,
FileSystemFlags: lpFileSystemFlags,
FileSystemName: string(bytes.Replace(lpFileSystemNameBuffer, []byte("\x00"), []byte(""), -1)),
}, nil
}
return nil, errInvalidDriveType
return "", common.ErrNotImplementedError
}

View File

@ -21,6 +21,7 @@ package common
// high-performance serialization, especially for large data structures,
// should look at more advanced solutions such as the encoding/gob
// package or protocol buffers.
import (
"errors"
"io"

View File

@ -6,6 +6,7 @@ package common
// - linux (amd64, arm)
// - freebsd (amd64)
// - windows (amd64)
import (
"bufio"
"bytes"
@ -364,14 +365,8 @@ func HostDev(combineWith ...string) string {
return GetEnv("HOST_DEV", "/dev", combineWith...)
}
// MockEnv set environment variable and return revert function.
// MockEnv should be used testing only.
func MockEnv(key string, value string) func() {
original := os.Getenv(key)
os.Setenv(key, value)
return func() {
os.Setenv(key, original)
}
func HostRoot(combineWith ...string) string {
return GetEnv("HOST_ROOT", "/", combineWith...)
}
// getSysctrlEnv sets LC_ALL=C in a list of env vars for use when running

View File

@ -259,6 +259,11 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
}
}
if PathExists(HostRoot(".dockerenv")) {
system = "docker"
role = "guest"
}
// before returning for the first time, cache the system and role
cachedVirtOnce.Do(func() {
cachedVirtMutex.Lock()

View File

@ -218,9 +218,12 @@ func WMIQueryWithContext(ctx context.Context, query string, dst interface{}, con
}
// Convert paths using native DOS format like:
// "\Device\HarddiskVolume1\Windows\systemew\file.txt"
//
// "\Device\HarddiskVolume1\Windows\systemew\file.txt"
//
// into:
// "C:\Windows\systemew\file.txt"
//
// "C:\Windows\systemew\file.txt"
func ConvertDOSPath(p string) string {
rawDrive := strings.Join(strings.Split(p, `\`)[:3], `\`)

View File

@ -71,7 +71,7 @@ func callSVMon(ctx context.Context) (*VirtualMemoryStat, *SwapMemoryStat, error)
swap.Total = t * pagesize
}
if t, err := strconv.ParseUint(p[3], 10, 64); err == nil {
swap.Free = swap.Total - t * pagesize
swap.Free = swap.Total - t*pagesize
}
}
break

View File

@ -8,9 +8,8 @@ import (
"errors"
"unsafe"
"golang.org/x/sys/unix"
"github.com/shirou/gopsutil/v3/internal/common"
"golang.org/x/sys/unix"
)
func VirtualMemory() (*VirtualMemoryStat, error) {

View File

@ -9,6 +9,7 @@ import (
"encoding/binary"
"errors"
"fmt"
"github.com/shirou/gopsutil/v3/internal/common"
"golang.org/x/sys/unix"
)

View File

@ -18,14 +18,14 @@ func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat,
iocounters := make([]IOCountersStat, 0, len(ifs))
for _, netif := range ifs {
n := IOCountersStat{
Name: netif.Name,
BytesSent: uint64(netif.OBytes),
BytesRecv: uint64(netif.IBytes),
Name: netif.Name,
BytesSent: uint64(netif.OBytes),
BytesRecv: uint64(netif.IBytes),
PacketsSent: uint64(netif.OPackets),
PacketsRecv: uint64(netif.IPackets),
Errin: uint64(netif.OErrors),
Errout: uint64(netif.IErrors),
Dropout: uint64(netif.XmitDrops),
Errin: uint64(netif.OErrors),
Errout: uint64(netif.IErrors),
Dropout: uint64(netif.XmitDrops),
}
iocounters = append(iocounters, n)
}

View File

@ -211,7 +211,8 @@ func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename stri
// Return a list of network connections
// Available kind:
// reference to netConnectionKindMap
//
// reference to netConnectionKindMap
func Connections(kind string) ([]ConnectionStat, error) {
return ConnectionsWithContext(context.Background(), kind)
}

View File

@ -69,7 +69,13 @@ func (p *Process) CwdWithContext(ctx context.Context) (string, error) {
}
func (p *Process) ExeWithContext(ctx context.Context) (string, error) {
return "", common.ErrNotImplementedError
mib := []int32{CTLKern, KernProc, KernProcPathname, p.Pid}
buf, _, err := common.CallSyscall(mib)
if err != nil {
return "", err
}
return strings.Trim(string(buf), "\x00"), nil
}
func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) {

View File

@ -8,9 +8,8 @@ import (
"syscall"
"unsafe"
"golang.org/x/sys/windows"
"github.com/shirou/gopsutil/v3/internal/common"
"golang.org/x/sys/windows"
)
type PROCESS_MEMORY_COUNTERS struct {

12
vendor/github.com/shoenig/go-m1cpu/.golangci.yaml generated vendored Normal file
View File

@ -0,0 +1,12 @@
run:
timeout: 5m
linters:
enable:
- gofmt
- errcheck
- errname
- errorlint
- bodyclose
- durationcheck
- whitespace

363
vendor/github.com/shoenig/go-m1cpu/LICENSE generated vendored Normal file
View File

@ -0,0 +1,363 @@
Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0.

12
vendor/github.com/shoenig/go-m1cpu/Makefile generated vendored Normal file
View File

@ -0,0 +1,12 @@
SHELL = bash
default: test
.PHONY: test
test:
@echo "--> Running Tests ..."
@go test -v -race ./...
vet:
@echo "--> Vet Go sources ..."
@go vet ./...

66
vendor/github.com/shoenig/go-m1cpu/README.md generated vendored Normal file
View File

@ -0,0 +1,66 @@
# m1cpu
[![Go Reference](https://pkg.go.dev/badge/github.com/shoenig/go-m1cpu.svg)](https://pkg.go.dev/github.com/shoenig/go-m1cpu)
[![MPL License](https://img.shields.io/github/license/shoenig/go-m1cpu?color=g&style=flat-square)](https://github.com/shoenig/go-m1cpu/blob/main/LICENSE)
[![Run CI Tests](https://github.com/shoenig/go-m1cpu/actions/workflows/ci.yaml/badge.svg)](https://github.com/shoenig/go-m1cpu/actions/workflows/ci.yaml)
The `go-m1cpu` module is a library for inspecting Apple Silicon CPUs in Go.
Use the `m1cpu` Go package for looking up the CPU frequency for Apple M1 and M2 CPUs.
# Install
```shell
go get github.com/shoenig/go-m1cpu@latest
```
# CGO
This package requires the use of [CGO](https://go.dev/blog/cgo).
Extracting the CPU properties is done via Apple's [IOKit](https://developer.apple.com/documentation/iokit?language=objc)
framework, which is accessible only through system C libraries.
# Example
Simple Go program to print Apple Silicon M1/M2 CPU speeds.
```go
package main
import (
"fmt"
"github.com/shoenig/go-m1cpu"
)
func main() {
fmt.Println("Apple Silicon", m1cpu.IsAppleSilicon())
fmt.Println("pCore GHz", m1cpu.PCoreGHz())
fmt.Println("eCore GHz", m1cpu.ECoreGHz())
fmt.Println("pCore Hz", m1cpu.PCoreHz())
fmt.Println("eCore Hz", m1cpu.ECoreHz())
}
```
Using `go test` to print out available information.
```
➜ go test -v -run Show
=== RUN Test_Show
cpu_test.go:42: pCore Hz 3504000000
cpu_test.go:43: eCore Hz 2424000000
cpu_test.go:44: pCore GHz 3.504
cpu_test.go:45: eCore GHz 2.424
cpu_test.go:46: pCore count 8
cpu_test.go:47: eCoreCount 4
cpu_test.go:50: pCore Caches 196608 131072 16777216
cpu_test.go:53: eCore Caches 131072 65536 4194304
--- PASS: Test_Show (0.00s)
```
# License
Open source under the [MPL](LICENSE)

208
vendor/github.com/shoenig/go-m1cpu/cpu.go generated vendored Normal file
View File

@ -0,0 +1,208 @@
//go:build darwin && arm64 && cgo
package m1cpu
// #cgo LDFLAGS: -framework CoreFoundation -framework IOKit
// #include <CoreFoundation/CoreFoundation.h>
// #include <IOKit/IOKitLib.h>
// #include <sys/sysctl.h>
//
// #define HzToGHz(hz) ((hz) / 1000000000.0)
//
// UInt64 global_pCoreHz;
// UInt64 global_eCoreHz;
// int global_pCoreCount;
// int global_eCoreCount;
// int global_pCoreL1InstCacheSize;
// int global_eCoreL1InstCacheSize;
// int global_pCoreL1DataCacheSize;
// int global_eCoreL1DataCacheSize;
// int global_pCoreL2CacheSize;
// int global_eCoreL2CacheSize;
// char global_brand[32];
//
// UInt64 getFrequency(CFTypeRef typeRef) {
// CFDataRef cfData = typeRef;
//
// CFIndex size = CFDataGetLength(cfData);
// UInt8 buf[size];
// CFDataGetBytes(cfData, CFRangeMake(0, size), buf);
//
// UInt8 b1 = buf[size-5];
// UInt8 b2 = buf[size-6];
// UInt8 b3 = buf[size-7];
// UInt8 b4 = buf[size-8];
//
// UInt64 pCoreHz = 0x00000000FFFFFFFF & ((b1<<24) | (b2 << 16) | (b3 << 8) | (b4));
// return pCoreHz;
// }
//
// int sysctl_int(const char * name) {
// int value = -1;
// size_t size = 8;
// sysctlbyname(name, &value, &size, NULL, 0);
// return value;
// }
//
// void sysctl_string(const char * name, char * dest) {
// size_t size = 32;
// sysctlbyname(name, dest, &size, NULL, 0);
// }
//
// void initialize() {
// global_pCoreCount = sysctl_int("hw.perflevel0.physicalcpu");
// global_eCoreCount = sysctl_int("hw.perflevel1.physicalcpu");
// global_pCoreL1InstCacheSize = sysctl_int("hw.perflevel0.l1icachesize");
// global_eCoreL1InstCacheSize = sysctl_int("hw.perflevel1.l1icachesize");
// global_pCoreL1DataCacheSize = sysctl_int("hw.perflevel0.l1dcachesize");
// global_eCoreL1DataCacheSize = sysctl_int("hw.perflevel1.l1dcachesize");
// global_pCoreL2CacheSize = sysctl_int("hw.perflevel0.l2cachesize");
// global_eCoreL2CacheSize = sysctl_int("hw.perflevel1.l2cachesize");
// sysctl_string("machdep.cpu.brand_string", global_brand);
//
// CFMutableDictionaryRef matching = IOServiceMatching("AppleARMIODevice");
// io_iterator_t iter;
// IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iter);
//
// const size_t bufsize = 512;
// io_object_t obj;
// while ((obj = IOIteratorNext(iter))) {
// char class[bufsize];
// IOObjectGetClass(obj, class);
// char name[bufsize];
// IORegistryEntryGetName(obj, name);
//
// if (strncmp(name, "pmgr", bufsize) == 0) {
// CFTypeRef pCoreRef = IORegistryEntryCreateCFProperty(obj, CFSTR("voltage-states5-sram"), kCFAllocatorDefault, 0);
// CFTypeRef eCoreRef = IORegistryEntryCreateCFProperty(obj, CFSTR("voltage-states1-sram"), kCFAllocatorDefault, 0);
//
// long long pCoreHz = getFrequency(pCoreRef);
// long long eCoreHz = getFrequency(eCoreRef);
//
// global_pCoreHz = pCoreHz;
// global_eCoreHz = eCoreHz;
// return;
// }
// }
// }
//
// UInt64 eCoreHz() {
// return global_eCoreHz;
// }
//
// UInt64 pCoreHz() {
// return global_pCoreHz;
// }
//
// Float64 eCoreGHz() {
// return HzToGHz(global_eCoreHz);
// }
//
// Float64 pCoreGHz() {
// return HzToGHz(global_pCoreHz);
// }
//
// int pCoreCount() {
// return global_pCoreCount;
// }
//
// int eCoreCount() {
// return global_eCoreCount;
// }
//
// int pCoreL1InstCacheSize() {
// return global_pCoreL1InstCacheSize;
// }
//
// int pCoreL1DataCacheSize() {
// return global_pCoreL1DataCacheSize;
// }
//
// int pCoreL2CacheSize() {
// return global_pCoreL2CacheSize;
// }
//
// int eCoreL1InstCacheSize() {
// return global_eCoreL1InstCacheSize;
// }
//
// int eCoreL1DataCacheSize() {
// return global_eCoreL1DataCacheSize;
// }
//
// int eCoreL2CacheSize() {
// return global_eCoreL2CacheSize;
// }
//
// char * modelName() {
// return global_brand;
// }
import "C"
func init() {
C.initialize()
}
// IsAppleSilicon returns true on this platform.
func IsAppleSilicon() bool {
return true
}
// PCoreHZ returns the max frequency in Hertz of the P-Core of an Apple Silicon CPU.
func PCoreHz() uint64 {
return uint64(C.pCoreHz())
}
// ECoreHZ returns the max frequency in Hertz of the E-Core of an Apple Silicon CPU.
func ECoreHz() uint64 {
return uint64(C.eCoreHz())
}
// PCoreGHz returns the max frequency in Gigahertz of the P-Core of an Apple Silicon CPU.
func PCoreGHz() float64 {
return float64(C.pCoreGHz())
}
// ECoreGHz returns the max frequency in Gigahertz of the E-Core of an Apple Silicon CPU.
func ECoreGHz() float64 {
return float64(C.eCoreGHz())
}
// PCoreCount returns the number of physical P (performance) cores.
func PCoreCount() int {
return int(C.pCoreCount())
}
// ECoreCount returns the number of physical E (efficiency) cores.
func ECoreCount() int {
return int(C.eCoreCount())
}
// PCoreCacheSize returns the sizes of the P (performance) core cache sizes
// in the order of
//
// - L1 instruction cache
// - L1 data cache
// - L2 cache
func PCoreCache() (int, int, int) {
return int(C.pCoreL1InstCacheSize()),
int(C.pCoreL1DataCacheSize()),
int(C.pCoreL2CacheSize())
}
// ECoreCacheSize returns the sizes of the E (efficiency) core cache sizes
// in the order of
//
// - L1 instruction cache
// - L1 data cache
// - L2 cache
func ECoreCache() (int, int, int) {
return int(C.eCoreL1InstCacheSize()),
int(C.eCoreL1DataCacheSize()),
int(C.eCoreL2CacheSize())
}
// ModelName returns the model name of the CPU.
func ModelName() string {
return C.GoString(C.modelName())
}

53
vendor/github.com/shoenig/go-m1cpu/incompatible.go generated vendored Normal file
View File

@ -0,0 +1,53 @@
//go:build !darwin || !arm64 || !cgo
package m1cpu
// IsAppleSilicon return false on this platform.
func IsAppleSilicon() bool {
return false
}
// PCoreHZ requires darwin/arm64
func PCoreHz() uint64 {
panic("m1cpu: not a darwin/arm64 system")
}
// ECoreHZ requires darwin/arm64
func ECoreHz() uint64 {
panic("m1cpu: not a darwin/arm64 system")
}
// PCoreGHz requires darwin/arm64
func PCoreGHz() float64 {
panic("m1cpu: not a darwin/arm64 system")
}
// ECoreGHz requires darwin/arm64
func ECoreGHz() float64 {
panic("m1cpu: not a darwin/arm64 system")
}
// PCoreCount requires darwin/arm64
func PCoreCount() int {
panic("m1cpu: not a darwin/arm64 system")
}
// ECoreCount requires darwin/arm64
func ECoreCount() int {
panic("m1cpu: not a darwin/arm64 system")
}
// PCoreCacheSize requires darwin/arm64
func PCoreCache() (int, int, int) {
panic("m1cpu: not a darwin/arm64 system")
}
// ECoreCacheSize requires darwin/arm64
func ECoreCache() (int, int, int) {
panic("m1cpu: not a darwin/arm64 system")
}
// ModelName requires darwin/arm64
func ModelName() string {
panic("m1cpu: not a darwin/arm64 system")
}

View File

@ -8,7 +8,6 @@ import (
"fmt"
"math"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
@ -141,12 +140,11 @@ func CallerInfo() []string {
}
parts := strings.Split(file, "/")
file = parts[len(parts)-1]
if len(parts) > 1 {
filename := parts[len(parts)-1]
dir := parts[len(parts)-2]
if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
path, _ := filepath.Abs(file)
callers = append(callers, fmt.Sprintf("%s:%d", path, line))
if (dir != "assert" && dir != "mock" && dir != "require") || filename == "mock_test.go" {
callers = append(callers, fmt.Sprintf("%s:%d", file, line))
}
}
@ -530,7 +528,7 @@ func isNil(object interface{}) bool {
[]reflect.Kind{
reflect.Chan, reflect.Func,
reflect.Interface, reflect.Map,
reflect.Ptr, reflect.Slice},
reflect.Ptr, reflect.Slice, reflect.UnsafePointer},
kind)
if isNilableKind && value.IsNil() {
@ -818,49 +816,44 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
return true // we consider nil to be equal to the nil set
}
defer func() {
if e := recover(); e != nil {
ok = false
}
}()
listKind := reflect.TypeOf(list).Kind()
subsetKind := reflect.TypeOf(subset).Kind()
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
}
subsetKind := reflect.TypeOf(subset).Kind()
if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
}
subsetValue := reflect.ValueOf(subset)
if subsetKind == reflect.Map && listKind == reflect.Map {
listValue := reflect.ValueOf(list)
subsetKeys := subsetValue.MapKeys()
subsetMap := reflect.ValueOf(subset)
actualMap := reflect.ValueOf(list)
for i := 0; i < len(subsetKeys); i++ {
subsetKey := subsetKeys[i]
subsetElement := subsetValue.MapIndex(subsetKey).Interface()
listElement := listValue.MapIndex(subsetKey).Interface()
for _, k := range subsetMap.MapKeys() {
ev := subsetMap.MapIndex(k)
av := actualMap.MapIndex(k)
if !ObjectsAreEqual(subsetElement, listElement) {
return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, subsetElement), msgAndArgs...)
if !av.IsValid() {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
}
if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
}
}
return true
}
for i := 0; i < subsetValue.Len(); i++ {
element := subsetValue.Index(i).Interface()
subsetList := reflect.ValueOf(subset)
for i := 0; i < subsetList.Len(); i++ {
element := subsetList.Index(i).Interface()
ok, found := containsElement(list, element)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
}
if !found {
return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
}
}
@ -879,34 +872,28 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
}
defer func() {
if e := recover(); e != nil {
ok = false
}
}()
listKind := reflect.TypeOf(list).Kind()
subsetKind := reflect.TypeOf(subset).Kind()
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
}
subsetKind := reflect.TypeOf(subset).Kind()
if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
}
subsetValue := reflect.ValueOf(subset)
if subsetKind == reflect.Map && listKind == reflect.Map {
listValue := reflect.ValueOf(list)
subsetKeys := subsetValue.MapKeys()
subsetMap := reflect.ValueOf(subset)
actualMap := reflect.ValueOf(list)
for i := 0; i < len(subsetKeys); i++ {
subsetKey := subsetKeys[i]
subsetElement := subsetValue.MapIndex(subsetKey).Interface()
listElement := listValue.MapIndex(subsetKey).Interface()
for _, k := range subsetMap.MapKeys() {
ev := subsetMap.MapIndex(k)
av := actualMap.MapIndex(k)
if !ObjectsAreEqual(subsetElement, listElement) {
if !av.IsValid() {
return true
}
if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
return true
}
}
@ -914,8 +901,9 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
}
for i := 0; i < subsetValue.Len(); i++ {
element := subsetValue.Index(i).Interface()
subsetList := reflect.ValueOf(subset)
for i := 0; i < subsetList.Len(); i++ {
element := subsetList.Index(i).Interface()
ok, found := containsElement(list, element)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)

7
vendor/modules.txt vendored
View File

@ -286,7 +286,7 @@ github.com/rs/xid
# github.com/russross/blackfriday/v2 v2.1.0
## explicit
github.com/russross/blackfriday/v2
# github.com/shirou/gopsutil/v3 v3.22.11
# github.com/shirou/gopsutil/v3 v3.23.3
## explicit; go 1.15
github.com/shirou/gopsutil/v3/cpu
github.com/shirou/gopsutil/v3/disk
@ -294,10 +294,13 @@ github.com/shirou/gopsutil/v3/internal/common
github.com/shirou/gopsutil/v3/mem
github.com/shirou/gopsutil/v3/net
github.com/shirou/gopsutil/v3/process
# github.com/shoenig/go-m1cpu v0.1.4
## explicit; go 1.20
github.com/shoenig/go-m1cpu
# github.com/sirupsen/logrus v1.9.0
## explicit; go 1.13
github.com/sirupsen/logrus
# github.com/stretchr/testify v1.8.1
# github.com/stretchr/testify v1.8.2
## explicit; go 1.13
github.com/stretchr/testify/assert
github.com/stretchr/testify/require