├── pkg └── gopsutil │ ├── doc.go │ ├── cpu │ ├── testdata │ │ ├── linux │ │ │ ├── 424 │ │ │ │ └── proc │ │ │ │ │ └── stat │ │ │ ├── 1037 │ │ │ │ └── proc │ │ │ │ │ └── cpuinfo │ │ │ └── times_empty │ │ │ │ └── proc │ │ │ │ └── stat │ │ ├── solaris │ │ │ ├── 2cpu_8core_isainfo.txt │ │ │ ├── 2cpu_12core_isainfo.txt │ │ │ ├── 1cpu_1core_psrinfo.txt │ │ │ ├── 1cpu_1core_isainfo.txt │ │ │ ├── 2cpu_1core_isainfo.txt │ │ │ ├── 2cpu_1core_psrinfo.txt │ │ │ ├── 2cpu_12core_psrinfo.txt │ │ │ └── 2cpu_8core_psrinfo.txt │ │ └── freebsd │ │ │ ├── 1cpu_4core.txt │ │ │ ├── 2cpu_4core.txt │ │ │ └── 1cpu_2core.txt │ ├── cpu_dragonfly_amd64.go │ ├── cpu_freebsd_386.go │ ├── cpu_freebsd_amd64.go │ ├── cpu_freebsd_arm.go │ ├── cpu_freebsd_arm64.go │ ├── cpu_darwin_nocgo.go │ ├── cpu_fallback.go │ ├── cpu_freebsd_test.go │ ├── cpu_darwin.go │ ├── cpu_linux_test.go │ └── cpu_darwin_cgo.go │ ├── go.mod │ ├── .gitignore │ ├── .github │ ├── FUNDING.yml │ ├── dependabot.yml │ ├── workflows │ │ ├── labeler.yml │ │ ├── shellcheck.yml │ │ ├── lint.yml │ │ ├── build_test.yml │ │ └── test.yml │ ├── ISSUE_TEMPLATE │ │ ├── feature_request.md │ │ └── bug_report.md │ └── labeler.yml │ ├── load │ ├── load_freebsd.go │ ├── load_openbsd.go │ ├── load_fallback.go │ ├── load.go │ ├── load_solaris.go │ ├── load_darwin.go │ ├── load_bsd.go │ ├── load_test.go │ ├── load_windows.go │ └── load_linux.go │ ├── process │ ├── testdata │ │ ├── darwin │ │ │ └── ps-ax-opid_fail │ │ ├── lx_brandz │ │ │ └── 1 │ │ │ │ └── stat │ │ └── linux │ │ │ ├── 1 │ │ │ └── status │ │ │ ├── 1060 │ │ │ └── status │ │ │ └── 68927 │ │ │ └── stat │ ├── process_posix_test.go │ ├── process_race_test.go │ ├── process_darwin_cgo.go │ ├── process_darwin_nocgo.go │ ├── process_windows_amd64.go │ ├── types_freebsd.go │ ├── process_bsd.go │ ├── types_openbsd.go │ └── process_windows_arm64.go │ ├── .golangci.yml │ ├── host │ ├── types_darwin.go │ ├── host_darwin_nocgo.go │ ├── host_posix.go │ ├── host_darwin_386.go │ ├── host_darwin_amd64.go │ ├── types.go │ ├── host_darwin_arm64.go │ ├── host_openbsd_amd64.go │ ├── host_openbsd_386.go │ ├── host_openbsd_arm64.go │ ├── host_freebsd_386.go │ ├── host_freebsd_arm.go │ ├── host_freebsd_amd64.go │ ├── host_freebsd_arm64.go │ ├── types_linux.go │ ├── types_openbsd.go │ ├── host_bsd.go │ ├── host_linux_mips.go │ ├── host_linux_mips64.go │ ├── host_linux_mips64le.go │ ├── host_linux_mipsle.go │ ├── types_freebsd.go │ ├── host_linux_arm64.go │ ├── host_linux_386.go │ ├── host_linux_arm.go │ ├── host_linux_s390x.go │ ├── host_linux_ppc64le.go │ ├── host_linux_riscv64.go │ ├── host_linux_amd64.go │ ├── smc_darwin.h │ ├── host_darwin_cgo.go │ ├── host_fallback.go │ ├── host_linux_test.go │ ├── freebsd_headers │ │ └── utxdb.h │ └── host_openbsd.go │ ├── disk │ ├── disk_darwin_nocgo.go │ ├── types_openbsd.go │ ├── disk_fallback.go │ ├── disk_openbsd_amd64.go │ ├── iostat_darwin.h │ ├── disk_openbsd_386.go │ ├── disk_openbsd_arm64.go │ ├── disk_darwin_cgo.go │ ├── disk_freebsd_386.go │ ├── disk_freebsd_arm.go │ ├── types_freebsd.go │ ├── disk_freebsd_amd64.go │ ├── disk_freebsd_arm64.go │ ├── disk_unix.go │ ├── disk_darwin.go │ └── disk.go │ ├── internal │ └── common │ │ ├── sleep.go │ │ ├── sleep_test.go │ │ ├── common_openbsd.go │ │ ├── common_unix.go │ │ ├── common_darwin.go │ │ └── common_freebsd.go │ ├── mem │ ├── types_openbsd.go │ ├── mem_openbsd_amd64.go │ ├── mem_openbsd_386.go │ ├── mem_openbsd_arm64.go │ ├── mem_fallback.go │ ├── mem_darwin_test.go │ ├── mem_solaris_test.go │ ├── testdata │ │ └── linux │ │ │ └── virtualmemory │ │ │ ├── issue1002 │ │ │ └── proc │ │ │ │ └── meminfo │ │ │ └── intelcorei5 │ │ │ └── proc │ │ │ └── meminfo │ ├── mem_bsd_test.go │ ├── mem_darwin_cgo.go │ ├── mem_darwin.go │ ├── mem_darwin_nocgo.go │ ├── mem_openbsd.go │ └── mem_bsd.go │ ├── mktypes.sh │ ├── winservices │ └── manager.go │ ├── coverall.sh │ ├── windows_memo.rst │ ├── Gopkg.toml │ ├── _tools │ └── v3migration │ │ ├── v3Changes.md │ │ └── v3migration.go │ ├── docker │ ├── docker_linux_test.go │ ├── docker_notlinux.go │ └── docker.go │ ├── Makefile │ └── LICENSE ├── ss ├── error.go ├── tcp.go ├── udp.go └── ss.go ├── bridge ├── error.go └── bridge.go ├── .gitignore ├── go.mod ├── ip ├── ip.go └── neighbour.go ├── cmd ├── ip │ ├── main.go │ ├── neighbour.go │ └── route.go ├── bridge │ ├── main.go │ ├── monitor.go │ └── fdb.go └── ss │ ├── process.go │ ├── tcp.go │ ├── udp.go │ ├── summary.go │ └── main.go ├── README.md └── internal └── etc └── etc.go /pkg/gopsutil/doc.go: -------------------------------------------------------------------------------- 1 | package gopsutil 2 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/linux/times_empty/proc/stat: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pkg/gopsutil/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/shirou/gopsutil 2 | -------------------------------------------------------------------------------- /pkg/gopsutil/.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | #* 3 | _obj 4 | *.tmp 5 | .idea 6 | vendor 7 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: shirou 4 | -------------------------------------------------------------------------------- /ss/error.go: -------------------------------------------------------------------------------- 1 | package ss 2 | 3 | import "errors" 4 | 5 | // errors about ss 6 | var ( 7 | ErrNotImplemented = errors.New("ss: not implemented") 8 | ) 9 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_freebsd.go: -------------------------------------------------------------------------------- 1 | // +build freebsd 2 | 3 | package load 4 | 5 | func getForkStat() (forkstat, error) { 6 | return forkstat{}, nil 7 | } 8 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/testdata/darwin/ps-ax-opid_fail: -------------------------------------------------------------------------------- 1 | PID 2 | 245 3 | 247 4 | 248 5 | 249 6 | 254 7 | 262 8 | 264 9 | 265 10 | 267 11 | -------------------------------------------------------------------------------- /bridge/error.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | import "errors" 4 | 5 | // errors about bridge 6 | var ( 7 | ErrNotImplemented = errors.New("bridge: not implemented") 8 | ) 9 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_dragonfly_amd64.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | type cpuTimes struct { 4 | User uint64 5 | Nice uint64 6 | Sys uint64 7 | Intr uint64 8 | Idle uint64 9 | } 10 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_freebsd_386.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | type cpuTimes struct { 4 | User uint32 5 | Nice uint32 6 | Sys uint32 7 | Intr uint32 8 | Idle uint32 9 | } 10 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_freebsd_amd64.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | type cpuTimes struct { 4 | User uint64 5 | Nice uint64 6 | Sys uint64 7 | Intr uint64 8 | Idle uint64 9 | } 10 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_freebsd_arm.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | type cpuTimes struct { 4 | User uint32 5 | Nice uint32 6 | Sys uint32 7 | Intr uint32 8 | Idle uint32 9 | } 10 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_freebsd_arm64.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | type cpuTimes struct { 4 | User uint64 5 | Nice uint64 6 | Sys uint64 7 | Intr uint64 8 | Idle uint64 9 | } 10 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/testdata/lx_brandz/1/stat: -------------------------------------------------------------------------------- 1 | 1 (systemd) S 0 0 0 0 -1 0 0 0 0 0 8 15 48 52 1 0 0 0 25 31883264 1413 18446744073709551615 0 0 140737487261696 0 0 0 0 0 0 18446741901776689794 0 0 17 0 2 | -------------------------------------------------------------------------------- /pkg/gopsutil/.golangci.yml: -------------------------------------------------------------------------------- 1 | linters: 2 | disable: 3 | - deadcode 4 | - errcheck 5 | - govet 6 | - ineffassign 7 | - staticcheck 8 | - structcheck 9 | - unused 10 | - varcheck 11 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/2cpu_8core_isainfo.txt: -------------------------------------------------------------------------------- 1 | 64-bit amd64 applications 2 | vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 3 | sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/2cpu_12core_isainfo.txt: -------------------------------------------------------------------------------- 1 | 64-bit amd64 applications 2 | amd_svm amd_lzcnt popcnt amd_sse4a tscp ahf cx16 sse3 sse2 sse fxsr 3 | amd_3dnowx amd_3dnow amd_mmx mmx cmov amd_sysc cx8 tsc fpu 4 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/1cpu_1core_psrinfo.txt: -------------------------------------------------------------------------------- 1 | The physical processor has 1 virtual processor (0) 2 | x86 (GenuineIntel 406E3 family 6 model 78 step 3 clock 3312 MHz) 3 | Intel(r) Core(tm) i7-6567U CPU @ 3.30GHz -------------------------------------------------------------------------------- /pkg/gopsutil/.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gomod 4 | directory: /v3 5 | schedule: 6 | interval: daily 7 | - package-ecosystem: github-actions 8 | directory: / 9 | schedule: 10 | interval: daily 11 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/1cpu_1core_isainfo.txt: -------------------------------------------------------------------------------- 1 | 64-bit amd64 applications 2 | rdseed adx avx2 fma bmi2 bmi1 rdrand f16c vmx avx xsave pclmulqdq 3 | aes movbe sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr 4 | mmx cmov amd_sysc cx8 tsc fpu -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/2cpu_1core_isainfo.txt: -------------------------------------------------------------------------------- 1 | 64-bit amd64 applications 2 | rdseed adx avx2 fma bmi2 bmi1 rdrand f16c vmx avx xsave pclmulqdq 3 | aes movbe sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr 4 | mmx cmov amd_sysc cx8 tsc fpu -------------------------------------------------------------------------------- /pkg/gopsutil/.github/workflows/labeler.yml: -------------------------------------------------------------------------------- 1 | name: "Pull Request Labeler" 2 | on: 3 | - pull_request_target 4 | 5 | jobs: 6 | triage: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/labeler@v3.0.2 10 | with: 11 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 12 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/workflows/shellcheck.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: Shellcheck 3 | jobs: 4 | shellcheck: 5 | name: Shellcheck 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - name: Run ShellCheck 10 | uses: ludeeus/action-shellcheck@master -------------------------------------------------------------------------------- /pkg/gopsutil/host/types_darwin.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | // plus hand editing about timeval 3 | 4 | /* 5 | Input to cgo -godefs. 6 | */ 7 | 8 | package host 9 | 10 | /* 11 | #include 12 | #include 13 | */ 14 | import "C" 15 | 16 | type Utmpx C.struct_utmpx 17 | type Timeval C.struct_timeval 18 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_darwin_nocgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build !cgo 3 | 4 | package disk 5 | 6 | import ( 7 | "context" 8 | 9 | "github.com/shirou/gopsutil/internal/common" 10 | ) 11 | 12 | func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { 13 | return nil, common.ErrNotImplementedError 14 | } 15 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_darwin_nocgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build !cgo 3 | 4 | package host 5 | 6 | import ( 7 | "context" 8 | 9 | "github.com/shirou/gopsutil/internal/common" 10 | ) 11 | 12 | func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, error) { 13 | return []TemperatureStat{}, common.ErrNotImplementedError 14 | } 15 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/testdata/linux/68927/stat: -------------------------------------------------------------------------------- 1 | 68927 (test(cmd).sh) S 68044 68927 68044 34818 68927 4194304 165 0 0 0 0 0 0 0 20 0 1 0 114413973 9961472 868 18446744073709551615 94388826710016 94388827626021 140725039102800 0 0 0 2 4 65536 1 0 0 17 1 0 0 0 0 0 94388827875984 94388827924080 94388835627008 140725039105503 140725039105528 140725039105528 140725039108073 0 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | nlmon/ 18 | 19 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | 3 | package load 4 | 5 | import ( 6 | "unsafe" 7 | 8 | "golang.org/x/sys/unix" 9 | ) 10 | 11 | func getForkStat() (forkstat, error) { 12 | b, err := unix.SysctlRaw("kern.forkstat") 13 | if err != nil { 14 | return forkstat{}, err 15 | } 16 | return *(*forkstat)(unsafe.Pointer((&b[0]))), nil 17 | } 18 | -------------------------------------------------------------------------------- /bridge/bridge.go: -------------------------------------------------------------------------------- 1 | package bridge 2 | 3 | import "github.com/mdlayher/netlink" 4 | 5 | // A Client can manipulate the bridge netlink interface. 6 | type Client struct { 7 | conn *netlink.Conn 8 | } 9 | 10 | // New creates a Client which can issue bridger commands. 11 | func New(conn *netlink.Conn) *Client { 12 | var c Client 13 | c.conn = conn 14 | return &c 15 | } 16 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_posix.go: -------------------------------------------------------------------------------- 1 | // +build linux freebsd openbsd darwin solaris 2 | 3 | package host 4 | 5 | import ( 6 | "bytes" 7 | 8 | "golang.org/x/sys/unix" 9 | ) 10 | 11 | func KernelArch() (string, error) { 12 | var utsname unix.Utsname 13 | err := unix.Uname(&utsname) 14 | return string(utsname.Machine[:bytes.IndexByte(utsname.Machine[:], 0)]), err 15 | } 16 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_darwin_nocgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build !cgo 3 | 4 | package cpu 5 | 6 | import "github.com/shirou/gopsutil/internal/common" 7 | 8 | func perCPUTimes() ([]TimesStat, error) { 9 | return []TimesStat{}, common.ErrNotImplementedError 10 | } 11 | 12 | func allCPUTimes() ([]TimesStat, error) { 13 | return []TimesStat{}, common.ErrNotImplementedError 14 | } 15 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/2cpu_1core_psrinfo.txt: -------------------------------------------------------------------------------- 1 | The physical processor has 1 virtual processor (0) 2 | x86 (GenuineIntel 406E3 family 6 model 78 step 3 clock 3312 MHz) 3 | Intel(r) Core(tm) i7-6567U CPU @ 3.30GHz 4 | The physical processor has 1 virtual processor (1) 5 | x86 (GenuineIntel 406E3 family 6 model 78 step 3 clock 3312 MHz) 6 | Intel(r) Core(tm) i7-6567U CPU @ 3.30GHz -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/2cpu_12core_psrinfo.txt: -------------------------------------------------------------------------------- 1 | The physical processor has 12 virtual processors (0-11) 2 | x86 (AuthenticAMD 100F91 family 16 model 9 step 1 clock 2300 MHz) 3 | AMD Opteron(tm) Processor 6176 [ Socket: G34 ] 4 | The physical processor has 12 virtual processors (12-23) 5 | x86 (AuthenticAMD 100F91 family 16 model 9 step 1 clock 2300 MHz) 6 | AMD Opteron(tm) Processor 6176 [ Socket: G34 ] 7 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/process_posix_test.go: -------------------------------------------------------------------------------- 1 | // +build linux freebsd 2 | 3 | package process 4 | 5 | import ( 6 | "os" 7 | "testing" 8 | 9 | "golang.org/x/sys/unix" 10 | ) 11 | 12 | func Test_SendSignal(t *testing.T) { 13 | checkPid := os.Getpid() 14 | 15 | p, _ := NewProcess(int32(checkPid)) 16 | err := p.SendSignal(unix.SIGCONT) 17 | if err != nil { 18 | t.Errorf("send signal %v", err) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /pkg/gopsutil/internal/common/sleep.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "context" 5 | "time" 6 | ) 7 | 8 | // Sleep awaits for provided interval. 9 | // Can be interrupted by context cancelation. 10 | func Sleep(ctx context.Context, interval time.Duration) error { 11 | var timer = time.NewTimer(interval) 12 | select { 13 | case <-ctx.Done(): 14 | return ctx.Err() 15 | case <-timer.C: 16 | return nil 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_darwin_386.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_darwin.go 3 | 4 | package host 5 | 6 | type Utmpx struct { 7 | User [256]int8 8 | ID [4]int8 9 | Line [32]int8 10 | Pid int32 11 | Type int16 12 | Pad_cgo_0 [6]byte 13 | Tv Timeval 14 | Host [256]int8 15 | Pad [16]uint32 16 | } 17 | type Timeval struct { 18 | Sec int32 19 | } 20 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_darwin_amd64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_darwin.go 3 | 4 | package host 5 | 6 | type Utmpx struct { 7 | User [256]int8 8 | ID [4]int8 9 | Line [32]int8 10 | Pid int32 11 | Type int16 12 | Pad_cgo_0 [6]byte 13 | Tv Timeval 14 | Host [256]int8 15 | Pad [16]uint32 16 | } 17 | type Timeval struct { 18 | Sec int32 19 | } 20 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Asphaltt/go-iproute2 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/mdlayher/netlink v1.4.0 7 | github.com/shirou/gopsutil v3.21.11+incompatible 8 | github.com/spf13/cobra v1.1.3 9 | github.com/tklauser/go-sysconf v0.3.10 // indirect 10 | github.com/yusufpapurcu/wmi v1.2.2 // indirect 11 | golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27 12 | ) 13 | 14 | replace github.com/shirou/gopsutil => ./pkg/gopsutil 15 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/types.go: -------------------------------------------------------------------------------- 1 | package host 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Warnings struct { 8 | List []error 9 | } 10 | 11 | func (w *Warnings) Add(err error) { 12 | w.List = append(w.List, err) 13 | } 14 | 15 | func (w *Warnings) Reference() error { 16 | if len(w.List) > 0 { 17 | return w 18 | } else { 19 | return nil 20 | } 21 | } 22 | 23 | func (w *Warnings) Error() string { 24 | return fmt.Sprintf("Number of warnings: %v", len(w.List)) 25 | } 26 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_darwin_arm64.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build arm64 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs host/types_darwin.go 5 | 6 | package host 7 | 8 | type Utmpx struct { 9 | User [256]int8 10 | Id [4]int8 11 | Line [32]int8 12 | Pid int32 13 | Type int16 14 | Tv Timeval 15 | Host [256]int8 16 | Pad [16]uint32 17 | } 18 | type Timeval struct { 19 | Sec int64 20 | Usec int32 21 | Pad_cgo_0 [4]byte 22 | } 23 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/types_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | 3 | /* 4 | Input to cgo -godefs. 5 | */ 6 | 7 | package mem 8 | 9 | /* 10 | #include 11 | #include 12 | #include 13 | */ 14 | import "C" 15 | 16 | // Machine characteristics; for internal use. 17 | 18 | const ( 19 | CTLVfs = 10 20 | VfsGeneric = 0 21 | VfsBcacheStat = 3 22 | ) 23 | 24 | const ( 25 | sizeOfBcachestats = C.sizeof_struct_bcachestats 26 | ) 27 | 28 | type Bcachestats C.struct_bcachestats 29 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Golangci-lint 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | golangci: 9 | name: lint 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Setup go 13 | uses: actions/setup-go@v2 14 | with: 15 | go-version: 1.17 16 | - name: Checkout repository 17 | uses: actions/checkout@v2 18 | - name: Setup golangci-lint 19 | uses: golangci/golangci-lint-action@v2 20 | with: 21 | args: --verbose 22 | version: latest 23 | working-directory: v3 24 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_openbsd_amd64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_openbsd.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x8 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x8 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x130 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int64 19 | _C_long_long int64 20 | ) 21 | 22 | type Utmp struct { 23 | Line [8]int8 24 | Name [32]int8 25 | Host [256]int8 26 | Time int64 27 | } 28 | type Timeval struct { 29 | Sec int64 30 | Usec int64 31 | } 32 | -------------------------------------------------------------------------------- /pkg/gopsutil/mktypes.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | PKGS="cpu disk docker host load mem net process" 4 | 5 | GOOS=$(go env GOOS) 6 | GOARCH=$(go env GOARCH) 7 | GOARCH=$(go env GOARCH) 8 | 9 | for DIR in . v3 10 | do 11 | (cd "$DIR" || exit 12 | for PKG in $PKGS 13 | do 14 | if [ -e "${PKG}/types_${GOOS}.go" ]; then 15 | (echo "// +build $GOOS" 16 | echo "// +build $GOARCH" 17 | go tool cgo -godefs "${PKG}/types_${GOOS}.go") | gofmt > "${PKG}/${PKG}_${GOOS}_${GOARCH}.go" 18 | fi 19 | done) 20 | done 21 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/process_race_test.go: -------------------------------------------------------------------------------- 1 | // +build race 2 | 3 | package process 4 | 5 | import ( 6 | "sync" 7 | "testing" 8 | ) 9 | 10 | func Test_Process_Ppid_Race(t *testing.T) { 11 | wg := sync.WaitGroup{} 12 | testCount := 10 13 | p := testGetProcess() 14 | wg.Add(testCount) 15 | for i := 0; i < testCount; i++ { 16 | go func(j int) { 17 | ppid, err := p.Ppid() 18 | wg.Done() 19 | skipIfNotImplementedErr(t, err) 20 | if err != nil { 21 | t.Errorf("Ppid() failed, %v", err) 22 | } 23 | 24 | if j == 9 { 25 | t.Logf("Ppid(): %d", ppid) 26 | } 27 | }(i) 28 | } 29 | wg.Wait() 30 | } 31 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/types_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | // Hand writing: _Ctype_struct___0 3 | 4 | /* 5 | Input to cgo -godefs. 6 | */ 7 | 8 | package disk 9 | 10 | /* 11 | #include 12 | #include 13 | #include 14 | */ 15 | import "C" 16 | 17 | const ( 18 | DEVSTAT_NO_DATA = 0x00 19 | DEVSTAT_READ = 0x01 20 | DEVSTAT_WRITE = 0x02 21 | DEVSTAT_FREE = 0x03 22 | ) 23 | 24 | const ( 25 | sizeOfDiskstats = C.sizeof_struct_diskstats 26 | ) 27 | 28 | type Diskstats C.struct_diskstats 29 | type Timeval C.struct_timeval 30 | 31 | type Diskstat C.struct_diskstat 32 | type Bintime C.struct_bintime 33 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_fallback.go: -------------------------------------------------------------------------------- 1 | // +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris 2 | 3 | package load 4 | 5 | import ( 6 | "context" 7 | 8 | "github.com/shirou/gopsutil/internal/common" 9 | ) 10 | 11 | func Avg() (*AvgStat, error) { 12 | return AvgWithContext(context.Background()) 13 | } 14 | 15 | func AvgWithContext(ctx context.Context) (*AvgStat, error) { 16 | return nil, common.ErrNotImplementedError 17 | } 18 | 19 | func Misc() (*MiscStat, error) { 20 | return MiscWithContext(context.Background()) 21 | } 22 | 23 | func MiscWithContext(ctx context.Context) (*MiscStat, error) { 24 | return nil, common.ErrNotImplementedError 25 | } 26 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_fallback.go: -------------------------------------------------------------------------------- 1 | // +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris 2 | 3 | package disk 4 | 5 | import ( 6 | "context" 7 | 8 | "github.com/shirou/gopsutil/internal/common" 9 | ) 10 | 11 | func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { 12 | return nil, common.ErrNotImplementedError 13 | } 14 | 15 | func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { 16 | return []PartitionStat{}, common.ErrNotImplementedError 17 | } 18 | 19 | func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { 20 | return nil, common.ErrNotImplementedError 21 | } 22 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_openbsd_386.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | // +build 386 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs host/types_openbsd.go 5 | 6 | package host 7 | 8 | const ( 9 | sizeofPtr = 0x4 10 | sizeofShort = 0x2 11 | sizeofInt = 0x4 12 | sizeofLong = 0x4 13 | sizeofLongLong = 0x8 14 | sizeOfUtmp = 0x130 15 | ) 16 | 17 | type ( 18 | _C_short int16 19 | _C_int int32 20 | _C_long int32 21 | _C_long_long int64 22 | ) 23 | 24 | type Utmp struct { 25 | Line [8]int8 26 | Name [32]int8 27 | Host [256]int8 28 | Time int64 29 | } 30 | type Timeval struct { 31 | Sec int64 32 | Usec int32 33 | } 34 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_openbsd_arm64.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | // +build arm64 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs host/types_openbsd.go 5 | 6 | package host 7 | 8 | const ( 9 | sizeofPtr = 0x8 10 | sizeofShort = 0x2 11 | sizeofInt = 0x4 12 | sizeofLong = 0x8 13 | sizeofLongLong = 0x8 14 | sizeOfUtmp = 0x130 15 | ) 16 | 17 | type ( 18 | _C_short int16 19 | _C_int int32 20 | _C_long int64 21 | _C_long_long int64 22 | ) 23 | 24 | type Utmp struct { 25 | Line [8]int8 26 | Name [32]int8 27 | Host [256]int8 28 | Time int64 29 | } 30 | type Timeval struct { 31 | Sec int64 32 | Usec int64 33 | } 34 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for gopsutil 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | [A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]] 9 | 10 | **Describe the solution you'd like** 11 | [A clear and concise description of what you want to happen.] 12 | 13 | **Describe alternatives you've considered** 14 | [A clear and concise description of any alternative solutions or features you've considered.] 15 | 16 | **Additional context** 17 | [Add any other context or screenshots about the feature request here.] 18 | -------------------------------------------------------------------------------- /pkg/gopsutil/winservices/manager.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package winservices 4 | 5 | import ( 6 | "golang.org/x/sys/windows/svc/mgr" 7 | ) 8 | 9 | type scmanager struct { 10 | mgr *mgr.Mgr 11 | } 12 | 13 | func openSCManager() (*scmanager, error) { 14 | m, err := mgr.Connect() 15 | if err != nil { 16 | return nil, err 17 | } 18 | return &scmanager{m}, nil 19 | } 20 | 21 | func (sc *scmanager) close() error { 22 | return sc.mgr.Disconnect() 23 | } 24 | 25 | func getService(serviceName string) (*mgr.Service, error) { 26 | m, err := openSCManager() 27 | if err != nil { 28 | return nil, err 29 | } 30 | defer m.close() 31 | return m.mgr.OpenService(serviceName) 32 | } 33 | -------------------------------------------------------------------------------- /pkg/gopsutil/coverall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # see http://www.songmu.jp/riji/entry/2015-01-15-goveralls-multi-package.html 4 | 5 | set -e 6 | # cleanup 7 | cleanup() { 8 | if [ "$tmpprof" != "" ] && [ -f "$tmpprof" ]; then 9 | rm -f "$tmpprof" 10 | fi 11 | exit 12 | } 13 | trap cleanup INT QUIT TERM EXIT 14 | 15 | # メインの処理 16 | prof=${1:-".profile.cov"} 17 | echo "mode: count" > "$prof" 18 | gopath1=$(echo "$GOPATH" | cut -d: -f1) 19 | for pkg in $(go list ./...); do 20 | tmpprof="$gopath1/src/$pkg/profile.tmp" 21 | go test -covermode=count -coverprofile="$tmpprof" "$pkg" 22 | if [ -f "$tmpprof" ]; then 23 | tail -n +2 "$tmpprof" >> "$prof" 24 | rm "$tmpprof" 25 | fi 26 | done 27 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_openbsd_amd64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_openbsd.go 3 | 4 | package mem 5 | 6 | const ( 7 | CTLVfs = 10 8 | VfsGeneric = 0 9 | VfsBcacheStat = 3 10 | ) 11 | 12 | const ( 13 | sizeOfBcachestats = 0x78 14 | ) 15 | 16 | type Bcachestats struct { 17 | Numbufs int64 18 | Numbufpages int64 19 | Numdirtypages int64 20 | Numcleanpages int64 21 | Pendingwrites int64 22 | Pendingreads int64 23 | Numwrites int64 24 | Numreads int64 25 | Cachehits int64 26 | Busymapped int64 27 | Dmapages int64 28 | Highpages int64 29 | Delwribufs int64 30 | Kvaslots int64 31 | Avail int64 32 | } 33 | -------------------------------------------------------------------------------- /ip/ip.go: -------------------------------------------------------------------------------- 1 | package ip 2 | 3 | import ( 4 | "github.com/Asphaltt/go-iproute2" 5 | "github.com/mdlayher/netlink" 6 | ) 7 | 8 | // A Client can manipulate ip netlink interface. 9 | type Client struct { 10 | conn *netlink.Conn 11 | } 12 | 13 | // New creates a Client which can issue ip commands. 14 | func New() (*Client, error) { 15 | conn, err := netlink.Dial(iproute2.NETLINK_ROUTE, nil) 16 | if err != nil { 17 | return nil, err 18 | } 19 | 20 | return NewWithConn(conn), nil 21 | } 22 | 23 | // NewWithConn creates a Client which can issue ip commands with the given 24 | // netlink connection. 25 | func NewWithConn(conn *netlink.Conn) *Client { 26 | var c Client 27 | c.conn = conn 28 | return &c 29 | } 30 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_freebsd_386.go: -------------------------------------------------------------------------------- 1 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 2 | // cgo -godefs types_freebsd.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeOfUtmpx = 0xc5 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int32 19 | _C_long_long int64 20 | ) 21 | 22 | type Utmp struct { 23 | Line [8]int8 24 | Name [16]int8 25 | Host [16]int8 26 | Time int32 27 | } 28 | 29 | type Utmpx struct { 30 | Type uint8 31 | Tv uint64 32 | Id [8]int8 33 | Pid uint32 34 | User [32]int8 35 | Line [16]int8 36 | Host [128]int8 37 | } 38 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_freebsd_arm.go: -------------------------------------------------------------------------------- 1 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 2 | // cgo -godefs types_freebsd.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x8 11 | sizeofLongLong = 0x8 12 | sizeOfUtmpx = 0xc5 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int32 19 | _C_long_long int64 20 | ) 21 | 22 | type Utmp struct { 23 | Line [8]int8 24 | Name [16]int8 25 | Host [16]int8 26 | Time int32 27 | } 28 | 29 | type Utmpx struct { 30 | Type uint8 31 | Tv uint64 32 | Id [8]int8 33 | Pid uint32 34 | User [32]int8 35 | Line [16]int8 36 | Host [128]int8 37 | } 38 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_freebsd_amd64.go: -------------------------------------------------------------------------------- 1 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 2 | // cgo -godefs types_freebsd.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x8 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x8 11 | sizeofLongLong = 0x8 12 | sizeOfUtmpx = 0xc5 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int64 19 | _C_long_long int64 20 | ) 21 | 22 | type Utmp struct { 23 | Line [8]int8 24 | Name [16]int8 25 | Host [16]int8 26 | Time int32 27 | } 28 | 29 | type Utmpx struct { 30 | Type uint8 31 | Tv uint64 32 | Id [8]int8 33 | Pid uint32 34 | User [32]int8 35 | Line [16]int8 36 | Host [128]int8 37 | } 38 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_freebsd_arm64.go: -------------------------------------------------------------------------------- 1 | // +build freebsd 2 | // +build arm64 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs host/types_freebsd.go 5 | 6 | package host 7 | 8 | const ( 9 | sizeofPtr = 0x8 10 | sizeofShort = 0x2 11 | sizeofInt = 0x4 12 | sizeofLong = 0x8 13 | sizeofLongLong = 0x8 14 | sizeOfUtmpx = 0xc5 15 | ) 16 | 17 | type ( 18 | _C_short int16 19 | _C_int int32 20 | _C_long int64 21 | _C_long_long int64 22 | ) 23 | 24 | type Utmp struct { 25 | Line [8]int8 26 | Name [16]int8 27 | Host [16]int8 28 | Time int32 29 | } 30 | 31 | type Utmpx struct { 32 | Type uint8 33 | Tv uint64 34 | Id [8]int8 35 | Pid uint32 36 | User [32]int8 37 | Line [16]int8 38 | Host [128]int8 39 | } 40 | -------------------------------------------------------------------------------- /cmd/ip/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/Asphaltt/go-iproute2" 7 | "github.com/mdlayher/netlink" 8 | "github.com/spf13/cobra" 9 | ) 10 | 11 | var cli client 12 | 13 | type client struct { 14 | conn *netlink.Conn 15 | } 16 | 17 | func (c *client) dialNetlink() error { 18 | var err error 19 | c.conn, err = netlink.Dial(iproute2.NETLINK_ROUTE, nil) 20 | return err 21 | } 22 | 23 | func (c *client) runCmd(fn func()) { 24 | err := c.dialNetlink() 25 | if err != nil { 26 | fmt.Println("failed to create netlink socket, err:", err) 27 | return 28 | } 29 | defer c.conn.Close() 30 | 31 | fn() 32 | } 33 | 34 | var rootCmd = cobra.Command{ 35 | Use: "ip", 36 | } 37 | 38 | func main() { 39 | rootCmd.Execute() 40 | } 41 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_openbsd_amd64.go: -------------------------------------------------------------------------------- 1 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 2 | // cgo -godefs types_openbsd.go 3 | 4 | package disk 5 | 6 | const ( 7 | DEVSTAT_NO_DATA = 0x00 8 | DEVSTAT_READ = 0x01 9 | DEVSTAT_WRITE = 0x02 10 | DEVSTAT_FREE = 0x03 11 | ) 12 | 13 | const ( 14 | sizeOfDiskstats = 0x70 15 | ) 16 | 17 | type Diskstats struct { 18 | Name [16]int8 19 | Busy int32 20 | Pad_cgo_0 [4]byte 21 | Rxfer uint64 22 | Wxfer uint64 23 | Seek uint64 24 | Rbytes uint64 25 | Wbytes uint64 26 | Attachtime Timeval 27 | Timestamp Timeval 28 | Time Timeval 29 | } 30 | type Timeval struct { 31 | Sec int64 32 | Usec int64 33 | } 34 | 35 | type Diskstat struct{} 36 | type Bintime struct{} 37 | -------------------------------------------------------------------------------- /pkg/gopsutil/internal/common/sleep_test.go: -------------------------------------------------------------------------------- 1 | package common_test 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "testing" 7 | "time" 8 | 9 | "github.com/shirou/gopsutil/internal/common" 10 | ) 11 | 12 | func TestSleep(test *testing.T) { 13 | const dt = 50 * time.Millisecond 14 | var t = func(name string, ctx context.Context, expected error) { 15 | test.Run(name, func(test *testing.T) { 16 | var err = common.Sleep(ctx, dt) 17 | if !errors.Is(err, expected) { 18 | test.Errorf("expected %v, got %v", expected, err) 19 | } 20 | }) 21 | } 22 | 23 | var ctx = context.Background() 24 | var canceled, cancel = context.WithCancel(ctx) 25 | cancel() 26 | 27 | t("background context", ctx, nil) 28 | t("canceled context", canceled, context.Canceled) 29 | } 30 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/iostat_darwin.h: -------------------------------------------------------------------------------- 1 | // https://github.com/lufia/iostat/blob/9f7362b77ad333b26c01c99de52a11bdb650ded2/iostat_darwin.h 2 | typedef struct DriveStats DriveStats; 3 | typedef struct CPUStats CPUStats; 4 | 5 | enum { 6 | NDRIVE = 16, 7 | NAMELEN = 31 8 | }; 9 | 10 | struct DriveStats { 11 | char name[NAMELEN+1]; 12 | int64_t size; 13 | int64_t blocksize; 14 | 15 | int64_t read; 16 | int64_t written; 17 | int64_t nread; 18 | int64_t nwrite; 19 | int64_t readtime; 20 | int64_t writetime; 21 | int64_t readlat; 22 | int64_t writelat; 23 | }; 24 | 25 | struct CPUStats { 26 | natural_t user; 27 | natural_t nice; 28 | natural_t sys; 29 | natural_t idle; 30 | }; 31 | 32 | extern int readdrivestat(DriveStats a[], int n); 33 | extern int readcpustat(CPUStats *cpu); 34 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_openbsd_386.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | // +build 386 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs disk/types_openbsd.go 5 | 6 | package disk 7 | 8 | const ( 9 | DEVSTAT_NO_DATA = 0x00 10 | DEVSTAT_READ = 0x01 11 | DEVSTAT_WRITE = 0x02 12 | DEVSTAT_FREE = 0x03 13 | ) 14 | 15 | const ( 16 | sizeOfDiskstats = 0x60 17 | ) 18 | 19 | type Diskstats struct { 20 | Name [16]int8 21 | Busy int32 22 | Rxfer uint64 23 | Wxfer uint64 24 | Seek uint64 25 | Rbytes uint64 26 | Wbytes uint64 27 | Attachtime Timeval 28 | Timestamp Timeval 29 | Time Timeval 30 | } 31 | type Timeval struct { 32 | Sec int64 33 | Usec int32 34 | } 35 | 36 | type Diskstat struct{} 37 | type Bintime struct{} 38 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_openbsd_arm64.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | // +build arm64 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs disk/types_openbsd.go 5 | 6 | package disk 7 | 8 | const ( 9 | DEVSTAT_NO_DATA = 0x00 10 | DEVSTAT_READ = 0x01 11 | DEVSTAT_WRITE = 0x02 12 | DEVSTAT_FREE = 0x03 13 | ) 14 | 15 | const ( 16 | sizeOfDiskstats = 0x70 17 | ) 18 | 19 | type Diskstats struct { 20 | Name [16]int8 21 | Busy int32 22 | Rxfer uint64 23 | Wxfer uint64 24 | Seek uint64 25 | Rbytes uint64 26 | Wbytes uint64 27 | Attachtime Timeval 28 | Timestamp Timeval 29 | Time Timeval 30 | } 31 | type Timeval struct { 32 | Sec int64 33 | Usec int64 34 | } 35 | 36 | type Diskstat struct{} 37 | type Bintime struct{} 38 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load.go: -------------------------------------------------------------------------------- 1 | package load 2 | 3 | import ( 4 | "encoding/json" 5 | 6 | "github.com/shirou/gopsutil/internal/common" 7 | ) 8 | 9 | var invoke common.Invoker = common.Invoke{} 10 | 11 | type AvgStat struct { 12 | Load1 float64 `json:"load1"` 13 | Load5 float64 `json:"load5"` 14 | Load15 float64 `json:"load15"` 15 | } 16 | 17 | func (l AvgStat) String() string { 18 | s, _ := json.Marshal(l) 19 | return string(s) 20 | } 21 | 22 | type MiscStat struct { 23 | ProcsTotal int `json:"procsTotal"` 24 | ProcsCreated int `json:"procsCreated"` 25 | ProcsRunning int `json:"procsRunning"` 26 | ProcsBlocked int `json:"procsBlocked"` 27 | Ctxt int `json:"ctxt"` 28 | } 29 | 30 | func (m MiscStat) String() string { 31 | s, _ := json.Marshal(m) 32 | return string(s) 33 | } 34 | -------------------------------------------------------------------------------- /pkg/gopsutil/windows_memo.rst: -------------------------------------------------------------------------------- 1 | Windows memo 2 | ===================== 3 | 4 | Size 5 | ---------- 6 | 7 | DWORD 8 | 32-bit unsigned integer 9 | DWORDLONG 10 | 64-bit unsigned integer 11 | DWORD_PTR 12 | unsigned long type for pointer precision 13 | DWORD32 14 | 32-bit unsigned integer 15 | DWORD64 16 | 64-bit unsigned integer 17 | HALF_PTR 18 | _WIN64 = int, else short 19 | INT 20 | 32-bit signed integer 21 | INT_PTR 22 | _WIN64 = __int64 else int 23 | LONG 24 | 32-bit signed integer 25 | LONGLONG 26 | 64-bit signed integer 27 | LONG_PTR 28 | _WIN64 = __int64 else long 29 | SHORT 30 | 16-bit integer 31 | SIZE_T 32 | maximum number of bytes to which a pointer can point. typedef ULONG_PTR SIZE_T; 33 | SSIZE_T 34 | signed version of SIZE_T. typedef LONG_PTR SSIZE_T; 35 | WORD 36 | 16-bit unsigned integer -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_openbsd_386.go: -------------------------------------------------------------------------------- 1 | // +build openbsd,386 2 | 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs mem/types_openbsd.go 5 | 6 | package mem 7 | 8 | const ( 9 | CTLVfs = 10 10 | VfsGeneric = 0 11 | VfsBcacheStat = 3 12 | ) 13 | 14 | const ( 15 | sizeOfBcachestats = 0x90 16 | ) 17 | 18 | type Bcachestats struct { 19 | Numbufs int64 20 | Numbufpages int64 21 | Numdirtypages int64 22 | Numcleanpages int64 23 | Pendingwrites int64 24 | Pendingreads int64 25 | Numwrites int64 26 | Numreads int64 27 | Cachehits int64 28 | Busymapped int64 29 | Dmapages int64 30 | Highpages int64 31 | Delwribufs int64 32 | Kvaslots int64 33 | Avail int64 34 | Highflips int64 35 | Highflops int64 36 | Dmaflips int64 37 | } 38 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_openbsd_arm64.go: -------------------------------------------------------------------------------- 1 | // +build openbsd,arm64 2 | 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs mem/types_openbsd.go 5 | 6 | package mem 7 | 8 | const ( 9 | CTLVfs = 10 10 | VfsGeneric = 0 11 | VfsBcacheStat = 3 12 | ) 13 | 14 | const ( 15 | sizeOfBcachestats = 0x90 16 | ) 17 | 18 | type Bcachestats struct { 19 | Numbufs int64 20 | Numbufpages int64 21 | Numdirtypages int64 22 | Numcleanpages int64 23 | Pendingwrites int64 24 | Pendingreads int64 25 | Numwrites int64 26 | Numreads int64 27 | Cachehits int64 28 | Busymapped int64 29 | Dmapages int64 30 | Highpages int64 31 | Delwribufs int64 32 | Kvaslots int64 33 | Avail int64 34 | Highflips int64 35 | Highflops int64 36 | Dmaflips int64 37 | } 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-iproute2 2 | 3 | Some net tools of iproute2 implement with Go. 4 | 5 | ## Completions 6 | 7 | ### ip 8 | 9 | 1. ip neigh list 10 | 2. ip link list 11 | 3. ip addr list 12 | 4. ip rourte list 13 | 14 | ### bridge 15 | 16 | 1. bridge monitor fdb 17 | 2. bridge fdb list 18 | 19 | ### ss 20 | 21 | 1. ss -s: print summary of socket stat 22 | 2. ss -l: list all udp and tcp listening sockets 23 | 3. ss -t: list all tcp connections 24 | 4. ss -lt: list all tcp listeners 25 | 5. ss -u: list all udp sockets, excluding the listening ones 26 | 6. ss -lu: list all udp listening sockets 27 | 28 | All the above listings support IPv4 and IPv6 version. 29 | 30 | ## TO-DO 31 | 32 | - [ ] ip 33 | - [ ] bridge 34 | - [x] ss (basically complete) 35 | 36 | Maybe more tools, like dcb, devlink, nstat, tc, will be implemented in some day. 37 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/process_darwin_cgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build cgo 3 | 4 | package process 5 | 6 | // #include 7 | // #include 8 | import "C" 9 | import ( 10 | "context" 11 | "fmt" 12 | "unsafe" 13 | ) 14 | 15 | func (p *Process) ExeWithContext(ctx context.Context) (string, error) { 16 | var c C.char // need a var for unsafe.Sizeof need a var 17 | const bufsize = C.PROC_PIDPATHINFO_MAXSIZE * unsafe.Sizeof(c) 18 | buffer := (*C.char)(C.malloc(C.size_t(bufsize))) 19 | defer C.free(unsafe.Pointer(buffer)) 20 | 21 | ret, err := C.proc_pidpath(C.int(p.Pid), unsafe.Pointer(buffer), C.uint32_t(bufsize)) 22 | if err != nil { 23 | return "", err 24 | } 25 | if ret <= 0 { 26 | return "", fmt.Errorf("unknown error: proc_pidpath returned %d", ret) 27 | } 28 | 29 | return C.GoString(buffer), nil 30 | } 31 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/types_linux.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | 3 | /* 4 | Input to cgo -godefs. 5 | */ 6 | 7 | package host 8 | 9 | /* 10 | #include 11 | #include 12 | 13 | enum { 14 | sizeofPtr = sizeof(void*), 15 | }; 16 | 17 | */ 18 | import "C" 19 | 20 | // Machine characteristics; for internal use. 21 | 22 | const ( 23 | sizeofPtr = C.sizeofPtr 24 | sizeofShort = C.sizeof_short 25 | sizeofInt = C.sizeof_int 26 | sizeofLong = C.sizeof_long 27 | sizeofLongLong = C.sizeof_longlong 28 | sizeOfUtmp = C.sizeof_struct_utmp 29 | ) 30 | 31 | // Basic types 32 | 33 | type ( 34 | _C_short C.short 35 | _C_int C.int 36 | _C_long C.long 37 | _C_long_long C.longlong 38 | ) 39 | 40 | type utmp C.struct_utmp 41 | type exit_status C.struct_exit_status 42 | type timeval C.struct_timeval 43 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/types_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | 3 | /* 4 | Input to cgo -godefs. 5 | */ 6 | 7 | package host 8 | 9 | /* 10 | #define KERNEL 11 | #include 12 | #include 13 | #include 14 | 15 | enum { 16 | sizeofPtr = sizeof(void*), 17 | }; 18 | 19 | */ 20 | import "C" 21 | 22 | // Machine characteristics; for internal use. 23 | 24 | const ( 25 | sizeofPtr = C.sizeofPtr 26 | sizeofShort = C.sizeof_short 27 | sizeofInt = C.sizeof_int 28 | sizeofLong = C.sizeof_long 29 | sizeofLongLong = C.sizeof_longlong 30 | sizeOfUtmp = C.sizeof_struct_utmp 31 | ) 32 | 33 | // Basic types 34 | 35 | type ( 36 | _C_short C.short 37 | _C_int C.int 38 | _C_long C.long 39 | _C_long_long C.longlong 40 | ) 41 | 42 | type Utmp C.struct_utmp 43 | type Timeval C.struct_timeval 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_bsd.go: -------------------------------------------------------------------------------- 1 | // +build darwin freebsd openbsd 2 | 3 | package host 4 | 5 | import ( 6 | "context" 7 | "sync/atomic" 8 | 9 | "golang.org/x/sys/unix" 10 | ) 11 | 12 | // cachedBootTime must be accessed via atomic.Load/StoreUint64 13 | var cachedBootTime uint64 14 | 15 | func BootTimeWithContext(ctx context.Context) (uint64, error) { 16 | t := atomic.LoadUint64(&cachedBootTime) 17 | if t != 0 { 18 | return t, nil 19 | } 20 | tv, err := unix.SysctlTimeval("kern.boottime") 21 | if err != nil { 22 | return 0, err 23 | } 24 | 25 | atomic.StoreUint64(&cachedBootTime, uint64(tv.Sec)) 26 | 27 | return uint64(tv.Sec), nil 28 | } 29 | 30 | func UptimeWithContext(ctx context.Context) (uint64, error) { 31 | boot, err := BootTimeWithContext(ctx) 32 | if err != nil { 33 | return 0, err 34 | } 35 | return timeSince(boot), nil 36 | } 37 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_fallback.go: -------------------------------------------------------------------------------- 1 | // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!dragonfly 2 | 3 | package cpu 4 | 5 | import ( 6 | "context" 7 | "runtime" 8 | 9 | "github.com/shirou/gopsutil/internal/common" 10 | ) 11 | 12 | func Times(percpu bool) ([]TimesStat, error) { 13 | return TimesWithContext(context.Background(), percpu) 14 | } 15 | 16 | func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { 17 | return []TimesStat{}, common.ErrNotImplementedError 18 | } 19 | 20 | func Info() ([]InfoStat, error) { 21 | return InfoWithContext(context.Background()) 22 | } 23 | 24 | func InfoWithContext(ctx context.Context) ([]InfoStat, error) { 25 | return []InfoStat{}, common.ErrNotImplementedError 26 | } 27 | 28 | func CountsWithContext(ctx context.Context, logical bool) (int, error) { 29 | return runtime.NumCPU(), nil 30 | } 31 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/process_darwin_nocgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build !cgo 3 | 4 | package process 5 | 6 | import ( 7 | "context" 8 | "fmt" 9 | "os/exec" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | func (p *Process) ExeWithContext(ctx context.Context) (string, error) { 15 | lsof_bin, err := exec.LookPath("lsof") 16 | if err != nil { 17 | return "", err 18 | } 19 | out, err := invoke.CommandWithContext(ctx, lsof_bin, "-p", strconv.Itoa(int(p.Pid)), "-Fpfn") 20 | if err != nil { 21 | return "", fmt.Errorf("bad call to lsof: %s", err) 22 | } 23 | txtFound := 0 24 | lines := strings.Split(string(out), "\n") 25 | for i := 1; i < len(lines); i++ { 26 | if lines[i] == "ftxt" { 27 | txtFound++ 28 | if txtFound == 2 { 29 | return lines[i-1][1:], nil 30 | } 31 | } 32 | } 33 | return "", fmt.Errorf("missing txt data returned by lsof") 34 | } 35 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_mips.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int32 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pad_cgo_0 [2]byte 25 | Pid int32 26 | Line [32]int8 27 | Id [4]int8 28 | User [32]int8 29 | Host [256]int8 30 | Exit exit_status 31 | Session int32 32 | Tv timeval 33 | Addr_v6 [4]int32 34 | X__unused [20]int8 35 | } 36 | type exit_status struct { 37 | Termination int16 38 | Exit int16 39 | } 40 | type timeval struct { 41 | Sec int32 42 | Usec int32 43 | } 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_mips64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int32 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pad_cgo_0 [2]byte 25 | Pid int32 26 | Line [32]int8 27 | Id [4]int8 28 | User [32]int8 29 | Host [256]int8 30 | Exit exit_status 31 | Session int32 32 | Tv timeval 33 | Addr_v6 [4]int32 34 | X__unused [20]int8 35 | } 36 | type exit_status struct { 37 | Termination int16 38 | Exit int16 39 | } 40 | type timeval struct { 41 | Sec int32 42 | Usec int32 43 | } 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_mips64le.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int32 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pad_cgo_0 [2]byte 25 | Pid int32 26 | Line [32]int8 27 | Id [4]int8 28 | User [32]int8 29 | Host [256]int8 30 | Exit exit_status 31 | Session int32 32 | Tv timeval 33 | Addr_v6 [4]int32 34 | X__unused [20]int8 35 | } 36 | type exit_status struct { 37 | Termination int16 38 | Exit int16 39 | } 40 | type timeval struct { 41 | Sec int32 42 | Usec int32 43 | } 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_mipsle.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int32 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pad_cgo_0 [2]byte 25 | Pid int32 26 | Line [32]int8 27 | Id [4]int8 28 | User [32]int8 29 | Host [256]int8 30 | Exit exit_status 31 | Session int32 32 | Tv timeval 33 | Addr_v6 [4]int32 34 | X__unused [20]int8 35 | } 36 | type exit_status struct { 37 | Termination int16 38 | Exit int16 39 | } 40 | type timeval struct { 41 | Sec int32 42 | Usec int32 43 | } 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/types_freebsd.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | 3 | /* 4 | Input to cgo -godefs. 5 | */ 6 | 7 | package host 8 | 9 | /* 10 | #define KERNEL 11 | #include 12 | #include 13 | #include 14 | #include "freebsd_headers/utxdb.h" 15 | 16 | enum { 17 | sizeofPtr = sizeof(void*), 18 | }; 19 | 20 | */ 21 | import "C" 22 | 23 | // Machine characteristics; for internal use. 24 | 25 | const ( 26 | sizeofPtr = C.sizeofPtr 27 | sizeofShort = C.sizeof_short 28 | sizeofInt = C.sizeof_int 29 | sizeofLong = C.sizeof_long 30 | sizeofLongLong = C.sizeof_longlong 31 | sizeOfUtmpx = C.sizeof_struct_futx 32 | ) 33 | 34 | // Basic types 35 | 36 | type ( 37 | _C_short C.short 38 | _C_int C.int 39 | _C_long C.long 40 | _C_long_long C.longlong 41 | ) 42 | 43 | type Utmp C.struct_utmp // for FreeBSD 9.0 compatibility 44 | type Utmpx C.struct_futx 45 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_fallback.go: -------------------------------------------------------------------------------- 1 | // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows 2 | 3 | package mem 4 | 5 | import ( 6 | "context" 7 | 8 | "github.com/shirou/gopsutil/internal/common" 9 | ) 10 | 11 | func VirtualMemory() (*VirtualMemoryStat, error) { 12 | return VirtualMemoryWithContext(context.Background()) 13 | } 14 | 15 | func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { 16 | return nil, common.ErrNotImplementedError 17 | } 18 | 19 | func SwapMemory() (*SwapMemoryStat, error) { 20 | return SwapMemoryWithContext(context.Background()) 21 | } 22 | 23 | func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { 24 | return nil, common.ErrNotImplementedError 25 | } 26 | 27 | func SwapDevices() ([]*SwapDevice, error) { 28 | return SwapDevicesWithContext(context.Background()) 29 | } 30 | 31 | func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { 32 | return nil, common.ErrNotImplementedError 33 | } 34 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve gopsutil 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | [A clear and concise description of what the bug is.] 9 | 10 | **To Reproduce** 11 | ```go 12 | // paste example code reproducing the bug you are reporting 13 | ``` 14 | 15 | **Expected behavior** 16 | [A clear and concise description of what you expected to happen.] 17 | 18 | **Environment (please complete the following information):** 19 | - [ ] Windows: [paste the result of `ver`] 20 | - [ ] Linux: [paste contents of `/etc/os-release` and the result of `uname -a`] 21 | - [ ] Mac OS: [paste the result of `sw_vers` and `uname -a` 22 | - [ ] FreeBSD: [paste the result of `freebsd-version -k -r -u` and `uname -a`] 23 | - [ ] OpenBSD: [paste the result of `uname -a`] 24 | 25 | **Additional context** 26 | [Cross-compiling? Paste the command you are using to cross-compile and the result of the corresponding `go env`] 27 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_arm64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x8 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x8 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int64 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pad_cgo_0 [2]byte 25 | Pid int32 26 | Line [32]int8 27 | Id [4]int8 28 | User [32]int8 29 | Host [256]int8 30 | Exit exit_status 31 | Session int32 32 | Tv timeval 33 | Addr_v6 [4]int32 34 | X__glibc_reserved [20]int8 35 | } 36 | type exit_status struct { 37 | Termination int16 38 | Exit int16 39 | } 40 | type timeval struct { 41 | Sec int64 42 | Usec int64 43 | } 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_solaris.go: -------------------------------------------------------------------------------- 1 | // +build solaris 2 | 3 | package load 4 | 5 | import ( 6 | "context" 7 | "os/exec" 8 | "strings" 9 | 10 | "github.com/shirou/gopsutil/internal/common" 11 | ) 12 | 13 | func Avg() (*AvgStat, error) { 14 | return AvgWithContext(context.Background()) 15 | } 16 | 17 | func AvgWithContext(ctx context.Context) (*AvgStat, error) { 18 | return nil, common.ErrNotImplementedError 19 | } 20 | 21 | func Misc() (*MiscStat, error) { 22 | return MiscWithContext(context.Background()) 23 | } 24 | 25 | func MiscWithContext(ctx context.Context) (*MiscStat, error) { 26 | bin, err := exec.LookPath("ps") 27 | if err != nil { 28 | return nil, err 29 | } 30 | out, err := invoke.CommandWithContext(ctx, bin, "-efo", "s") 31 | if err != nil { 32 | return nil, err 33 | } 34 | lines := strings.Split(string(out), "\n") 35 | 36 | ret := MiscStat{} 37 | for _, l := range lines { 38 | if l == "O" { 39 | ret.ProcsRunning++ 40 | } 41 | } 42 | 43 | return &ret, nil 44 | } 45 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_386.go: -------------------------------------------------------------------------------- 1 | // ATTENTION - FILE MANUAL FIXED AFTER CGO. 2 | // Fixed line: Tv _Ctype_struct_timeval -> Tv UtTv 3 | // Created by cgo -godefs, MANUAL FIXED 4 | // cgo -godefs types_linux.go 5 | 6 | package host 7 | 8 | const ( 9 | sizeofPtr = 0x4 10 | sizeofShort = 0x2 11 | sizeofInt = 0x4 12 | sizeofLong = 0x4 13 | sizeofLongLong = 0x8 14 | sizeOfUtmp = 0x180 15 | ) 16 | 17 | type ( 18 | _C_short int16 19 | _C_int int32 20 | _C_long int32 21 | _C_long_long int64 22 | ) 23 | 24 | type utmp struct { 25 | Type int16 26 | Pad_cgo_0 [2]byte 27 | Pid int32 28 | Line [32]int8 29 | ID [4]int8 30 | User [32]int8 31 | Host [256]int8 32 | Exit exit_status 33 | Session int32 34 | Tv UtTv 35 | Addr_v6 [4]int32 36 | X__unused [20]int8 37 | } 38 | type exit_status struct { 39 | Termination int16 40 | Exit int16 41 | } 42 | type UtTv struct { 43 | Sec int32 44 | Usec int32 45 | } 46 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_arm.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go | sed "s/uint8/int8/g" 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int32 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pad_cgo_0 [2]byte 25 | Pid int32 26 | Line [32]int8 27 | Id [4]int8 28 | User [32]int8 29 | Host [256]int8 30 | Exit exit_status 31 | Session int32 32 | Tv timeval 33 | Addr_v6 [4]int32 34 | X__glibc_reserved [20]int8 35 | } 36 | type exit_status struct { 37 | Termination int16 38 | Exit int16 39 | } 40 | type timeval struct { 41 | Sec int32 42 | Usec int32 43 | } 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_s390x.go: -------------------------------------------------------------------------------- 1 | // +build linux 2 | // +build s390x 3 | // Created by cgo -godefs - DO NOT EDIT 4 | // cgo -godefs types_linux.go 5 | 6 | package host 7 | 8 | const ( 9 | sizeofPtr = 0x8 10 | sizeofShort = 0x2 11 | sizeofInt = 0x4 12 | sizeofLong = 0x8 13 | sizeofLongLong = 0x8 14 | sizeOfUtmp = 0x180 15 | ) 16 | 17 | type ( 18 | _C_short int16 19 | _C_int int32 20 | _C_long int64 21 | _C_long_long int64 22 | ) 23 | 24 | type utmp struct { 25 | Type int16 26 | Pad_cgo_0 [2]byte 27 | Pid int32 28 | Line [32]int8 29 | Id [4]int8 30 | User [32]int8 31 | Host [256]int8 32 | Exit exit_status 33 | Session int32 34 | Tv timeval 35 | Addr_v6 [4]int32 36 | X__glibc_reserved [20]int8 37 | } 38 | type exit_status struct { 39 | Termination int16 40 | Exit int16 41 | } 42 | type timeval struct { 43 | Sec int64 44 | Usec int64 45 | } 46 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_ppc64le.go: -------------------------------------------------------------------------------- 1 | // +build linux 2 | // +build ppc64le 3 | // Created by cgo -godefs - DO NOT EDIT 4 | // cgo -godefs types_linux.go 5 | 6 | package host 7 | 8 | const ( 9 | sizeofPtr = 0x8 10 | sizeofShort = 0x2 11 | sizeofInt = 0x4 12 | sizeofLong = 0x8 13 | sizeofLongLong = 0x8 14 | sizeOfUtmp = 0x180 15 | ) 16 | 17 | type ( 18 | _C_short int16 19 | _C_int int32 20 | _C_long int64 21 | _C_long_long int64 22 | ) 23 | 24 | type utmp struct { 25 | Type int16 26 | Pad_cgo_0 [2]byte 27 | Pid int32 28 | Line [32]int8 29 | Id [4]int8 30 | User [32]int8 31 | Host [256]int8 32 | Exit exit_status 33 | Session int32 34 | Tv timeval 35 | Addr_v6 [4]int32 36 | X__glibc_reserved [20]int8 37 | } 38 | type exit_status struct { 39 | Termination int16 40 | Exit int16 41 | } 42 | type timeval struct { 43 | Sec int64 44 | Usec int64 45 | } 46 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_riscv64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x8 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x8 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int64 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pid int32 25 | Line [32]int8 26 | Id [4]int8 27 | User [32]int8 28 | Host [256]int8 29 | Exit exit_status 30 | Session int32 31 | Tv _Ctype_struct___0 32 | Addr_v6 [4]int32 33 | X__glibc_reserved [20]uint8 34 | } 35 | type exit_status struct { 36 | Termination int16 37 | Exit int16 38 | } 39 | type timeval struct { 40 | Sec int64 41 | Usec int64 42 | } 43 | 44 | type _Ctype_struct___0 struct { 45 | Sec int32 46 | Usec int32 47 | } 48 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_freebsd_test.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | import ( 4 | "path/filepath" 5 | "runtime" 6 | "testing" 7 | 8 | "github.com/shirou/gopsutil/internal/common" 9 | ) 10 | 11 | func TestParseDmesgBoot(t *testing.T) { 12 | if runtime.GOOS != "freebsd" { 13 | t.SkipNow() 14 | } 15 | 16 | var cpuTests = []struct { 17 | file string 18 | cpuNum int 19 | cores int32 20 | }{ 21 | {"1cpu_2core.txt", 1, 2}, 22 | {"1cpu_4core.txt", 1, 4}, 23 | {"2cpu_4core.txt", 2, 4}, 24 | } 25 | for _, tt := range cpuTests { 26 | v, num, err := parseDmesgBoot(filepath.Join("testdata", "freebsd", tt.file)) 27 | if err != nil { 28 | t.Errorf("parseDmesgBoot failed(%s), %v", tt.file, err) 29 | } 30 | if num != tt.cpuNum { 31 | t.Errorf("parseDmesgBoot wrong length(%s), %v", tt.file, err) 32 | } 33 | if v.Cores != tt.cores { 34 | t.Errorf("parseDmesgBoot wrong core(%s), %v", tt.file, err) 35 | } 36 | if !common.StringsContains(v.Flags, "fpu") { 37 | t.Errorf("parseDmesgBoot fail to parse features(%s), %v", tt.file, err) 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_amd64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_linux.go 3 | 4 | package host 5 | 6 | const ( 7 | sizeofPtr = 0x8 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x8 11 | sizeofLongLong = 0x8 12 | sizeOfUtmp = 0x180 13 | ) 14 | 15 | type ( 16 | _C_short int16 17 | _C_int int32 18 | _C_long int64 19 | _C_long_long int64 20 | ) 21 | 22 | type utmp struct { 23 | Type int16 24 | Pad_cgo_0 [2]byte 25 | Pid int32 26 | Line [32]int8 27 | Id [4]int8 28 | User [32]int8 29 | Host [256]int8 30 | Exit exit_status 31 | Session int32 32 | Tv _Ctype_struct___0 33 | Addr_v6 [4]int32 34 | X__glibc_reserved [20]int8 35 | } 36 | type exit_status struct { 37 | Termination int16 38 | Exit int16 39 | } 40 | type timeval struct { 41 | Sec int64 42 | Usec int64 43 | } 44 | 45 | type _Ctype_struct___0 struct { 46 | Sec int32 47 | Usec int32 48 | } 49 | -------------------------------------------------------------------------------- /cmd/bridge/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/Asphaltt/go-iproute2" 7 | "github.com/Asphaltt/go-iproute2/bridge" 8 | "github.com/mdlayher/netlink" 9 | "github.com/spf13/cobra" 10 | ) 11 | 12 | var cli client 13 | 14 | type client struct { 15 | conn *netlink.Conn 16 | } 17 | 18 | func (c *client) dialNetlink() error { 19 | var err error 20 | c.conn, err = netlink.Dial(iproute2.NETLINK_ROUTE, nil) 21 | return err 22 | } 23 | 24 | func (c *client) dialFdbMonitor() error { 25 | var err error 26 | c.conn, err = bridge.DialFdbMonitor() 27 | return err 28 | } 29 | 30 | func (c *client) runCmd(fn func()) { c.run(c.dialNetlink, fn) } 31 | func (c *client) runFdbMonitor(fn func()) { c.run(c.dialFdbMonitor, fn) } 32 | func (c *client) run(dial func() error, fn func()) { 33 | err := dial() 34 | if err != nil { 35 | fmt.Println("failed to create netlink socket, err:", err) 36 | return 37 | } 38 | defer c.conn.Close() 39 | 40 | fn() 41 | } 42 | 43 | var rootCmd = cobra.Command{ 44 | Use: "bridge", 45 | } 46 | 47 | func main() { 48 | rootCmd.Execute() 49 | } 50 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/smc_darwin.h: -------------------------------------------------------------------------------- 1 | #ifndef __SMC_H__ 2 | #define __SMC_H__ 1 3 | 4 | #include 5 | 6 | #define AMBIENT_AIR_0 "TA0P" 7 | #define AMBIENT_AIR_1 "TA1P" 8 | #define CPU_0_DIODE "TC0D" 9 | #define CPU_0_HEATSINK "TC0H" 10 | #define CPU_0_PROXIMITY "TC0P" 11 | #define ENCLOSURE_BASE_0 "TB0T" 12 | #define ENCLOSURE_BASE_1 "TB1T" 13 | #define ENCLOSURE_BASE_2 "TB2T" 14 | #define ENCLOSURE_BASE_3 "TB3T" 15 | #define GPU_0_DIODE "TG0D" 16 | #define GPU_0_HEATSINK "TG0H" 17 | #define GPU_0_PROXIMITY "TG0P" 18 | #define HARD_DRIVE_BAY "TH0P" 19 | #define MEMORY_SLOT_0 "TM0S" 20 | #define MEMORY_SLOTS_PROXIMITY "TM0P" 21 | #define NORTHBRIDGE "TN0H" 22 | #define NORTHBRIDGE_DIODE "TN0D" 23 | #define NORTHBRIDGE_PROXIMITY "TN0P" 24 | #define THUNDERBOLT_0 "TI0P" 25 | #define THUNDERBOLT_1 "TI1P" 26 | #define WIRELESS_MODULE "TW0P" 27 | 28 | kern_return_t open_smc(void); 29 | kern_return_t close_smc(void); 30 | double get_temperature(char *); 31 | 32 | #endif // __SMC_H__ 33 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/testdata/linux/1/status: -------------------------------------------------------------------------------- 1 | Name: ksoftirqd/0 2 | Umask: 0000 3 | State: S (sleeping) 4 | Tgid: 10 5 | Ngid: 0 6 | Pid: 10 7 | PPid: 2 8 | TracerPid: 0 9 | Uid: 0 0 0 0 10 | Gid: 0 0 0 0 11 | FDSize: 64 12 | Groups: 13 | NStgid: 10 14 | NSpid: 10 15 | NSpgid: 0 16 | NSsid: 0 17 | Threads: 1 18 | SigQ: 0/27700 19 | SigPnd: 0000000000000000 20 | ShdPnd: 0000000000000000 21 | SigBlk: 0000000000000000 22 | SigIgn: ffffffffffffffff 23 | SigCgt: 0000000000000000 24 | CapInh: 0000000000000000 25 | CapPrm: 0000003fffffffff 26 | CapEff: 0000003fffffffff 27 | CapBnd: 0000003fffffffff 28 | CapAmb: 0000000000000000 29 | NoNewPrivs: 0 30 | Seccomp: 0 31 | Speculation_Store_Bypass: vulnerable 32 | Cpus_allowed: 1 33 | Cpus_allowed_list: 0 34 | Mems_allowed: 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001 35 | Mems_allowed_list: 0 36 | voluntary_ctxt_switches: 76887 37 | nonvoluntary_ctxt_switches: 1771 38 | -------------------------------------------------------------------------------- /pkg/gopsutil/Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://golang.github.io/dep/docs/Gopkg.toml.html 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | name = "github.com/yusufpapurcu/wmi" 30 | version = "1.2.2" 31 | 32 | [[constraint]] 33 | name = "github.com/stretchr/testify" 34 | version = "1.2.2" 35 | 36 | [[constraint]] 37 | name = "github.com/tklauser/go-sysconf" 38 | version = "0.3.9" 39 | 40 | [[constraint]] 41 | branch = "master" 42 | name = "golang.org/x/sys" 43 | 44 | [prune] 45 | go-tests = true 46 | unused-packages = true 47 | -------------------------------------------------------------------------------- /cmd/ss/process.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/shirou/gopsutil/process" 8 | ) 9 | 10 | type processInfo struct { 11 | name string 12 | pid int32 13 | fd uint32 14 | } 15 | 16 | func (p *processInfo) String() string { 17 | return fmt.Sprintf(`("%s",pid=%d,fd=%d)`, p.name, p.pid, p.fd) 18 | } 19 | 20 | type processesInfo []*processInfo 21 | 22 | func (ps processesInfo) String() string { 23 | s := make([]string, 0, len(ps)) 24 | for _, p := range ps { 25 | s = append(s, p.String()) 26 | } 27 | return strings.Join(s, ",") 28 | } 29 | 30 | var procs = make(map[int]processesInfo) 31 | 32 | func prepareProcs() error { 33 | processes, err := process.Processes() 34 | if err != nil { 35 | return err 36 | } 37 | 38 | for _, p := range processes { 39 | conns, err := p.Connections() 40 | if err != nil { 41 | return err 42 | } 43 | 44 | pname, err := p.Name() 45 | if err != nil { 46 | return err 47 | } 48 | for _, c := range conns { 49 | procs[c.Inode] = append(procs[c.Inode], &processInfo{ 50 | name: pname, 51 | pid: p.Pid, 52 | fd: c.Fd, 53 | }) 54 | } 55 | } 56 | 57 | return nil 58 | } 59 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/solaris/2cpu_8core_psrinfo.txt: -------------------------------------------------------------------------------- 1 | The physical processor has 8 cores and 16 virtual processors (0-7 16-23) 2 | The core has 2 virtual processors (0 16) 3 | The core has 2 virtual processors (1 17) 4 | The core has 2 virtual processors (2 18) 5 | The core has 2 virtual processors (3 19) 6 | The core has 2 virtual processors (4 20) 7 | The core has 2 virtual processors (5 21) 8 | The core has 2 virtual processors (6 22) 9 | The core has 2 virtual processors (7 23) 10 | x86 (GenuineIntel 206D7 family 6 model 45 step 7 clock 2600 MHz) 11 | Intel(r) Xeon(r) CPU E5-2670 0 @ 2.60GHz 12 | The physical processor has 8 cores and 16 virtual processors (8-15 24-31) 13 | The core has 2 virtual processors (8 24) 14 | The core has 2 virtual processors (9 25) 15 | The core has 2 virtual processors (10 26) 16 | The core has 2 virtual processors (11 27) 17 | The core has 2 virtual processors (12 28) 18 | The core has 2 virtual processors (13 29) 19 | The core has 2 virtual processors (14 30) 20 | The core has 2 virtual processors (15 31) 21 | x86 (GenuineIntel 206D7 family 6 model 45 step 7 clock 2600 MHz) 22 | Intel(r) Xeon(r) CPU E5-2670 0 @ 2.60GHz -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_darwin_cgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build cgo 3 | 4 | package host 5 | 6 | // #cgo LDFLAGS: -framework IOKit 7 | // #include "smc_darwin.h" 8 | import "C" 9 | import "context" 10 | 11 | func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, error) { 12 | temperatureKeys := []string{ 13 | C.AMBIENT_AIR_0, 14 | C.AMBIENT_AIR_1, 15 | C.CPU_0_DIODE, 16 | C.CPU_0_HEATSINK, 17 | C.CPU_0_PROXIMITY, 18 | C.ENCLOSURE_BASE_0, 19 | C.ENCLOSURE_BASE_1, 20 | C.ENCLOSURE_BASE_2, 21 | C.ENCLOSURE_BASE_3, 22 | C.GPU_0_DIODE, 23 | C.GPU_0_HEATSINK, 24 | C.GPU_0_PROXIMITY, 25 | C.HARD_DRIVE_BAY, 26 | C.MEMORY_SLOT_0, 27 | C.MEMORY_SLOTS_PROXIMITY, 28 | C.NORTHBRIDGE, 29 | C.NORTHBRIDGE_DIODE, 30 | C.NORTHBRIDGE_PROXIMITY, 31 | C.THUNDERBOLT_0, 32 | C.THUNDERBOLT_1, 33 | C.WIRELESS_MODULE, 34 | } 35 | var temperatures []TemperatureStat 36 | 37 | C.open_smc() 38 | defer C.close_smc() 39 | 40 | for _, key := range temperatureKeys { 41 | temperatures = append(temperatures, TemperatureStat{ 42 | SensorKey: key, 43 | Temperature: float64(C.get_temperature(C.CString(key))), 44 | }) 45 | } 46 | return temperatures, nil 47 | } 48 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/testdata/linux/1060/status: -------------------------------------------------------------------------------- 1 | Name: server 2 | Umask: 0022 3 | State: S (sleeping) 4 | Tgid: 2549 5 | Ngid: 0 6 | Pid: 2549 7 | PPid: 1 8 | TracerPid: 0 9 | Uid: 107 107 107 107 10 | Gid: 113 113 113 113 11 | FDSize: 64 12 | Groups: 113 13 | VmPeak: 664744 kB 14 | VmSize: 664744 kB 15 | VmLck: 0 kB 16 | VmPin: 0 kB 17 | VmHWM: 2892 kB 18 | VmRSS: 2892 kB 19 | RssAnon: 524 kB 20 | RssFile: 2368 kB 21 | RssShmem: 0 kB 22 | VmData: 5932 kB 23 | VmStk: 132 kB 24 | VmExe: 1304 kB 25 | VmLib: 1180 kB 26 | VmPTE: 44 kB 27 | VmSwap: 0 kB 28 | CoreDumping: 0 29 | THP_enabled: 1 30 | Threads: 5 31 | SigQ: 0/1823 32 | SigPnd: 00000000000000000000000000000000 33 | ShdPnd: 00000000000000000000000000000000 34 | SigBlk: 00000000000000000000000000000000 35 | SigIgn: 00000000000000000000000000000000 36 | SigCgt: fffffffffffffffffffffffe783ffeff 37 | CapInh: 0000000000000000 38 | CapPrm: 0000000000000000 39 | CapEff: 0000000000000000 40 | CapBnd: 0000003fffffffff 41 | CapAmb: 0000000000000000 42 | NoNewPrivs: 0 43 | Speculation_Store_Bypass: unknown 44 | Cpus_allowed: 3 45 | Cpus_allowed_list: 0-1 46 | voluntary_ctxt_switches: 3 47 | nonvoluntary_ctxt_switches: 146 -------------------------------------------------------------------------------- /cmd/bridge/monitor.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | 7 | "github.com/Asphaltt/go-iproute2/bridge" 8 | "github.com/spf13/cobra" 9 | ) 10 | 11 | func init() { 12 | rootCmd.AddCommand(monitorCmd()) 13 | } 14 | 15 | func monitorCmd() *cobra.Command { 16 | monitorCmd := &cobra.Command{ 17 | Use: "monitor", 18 | } 19 | monitorCmd.AddCommand(&cobra.Command{ 20 | Use: "fdb", 21 | Run: func(cmd *cobra.Command, args []string) { 22 | cli.runFdbMonitor(cli.monitorFdb) 23 | }, 24 | }) 25 | return monitorCmd 26 | } 27 | 28 | func (c *client) monitorFdb() { 29 | bcli := bridge.New(c.conn) 30 | err := bcli.MonitorFdb(printFdbEntry) 31 | if err != nil { 32 | fmt.Println("failed to bridge monitor fdb, err:", err) 33 | } 34 | } 35 | 36 | func printFdbEntry(entry *bridge.FdbEntry) { 37 | var action string 38 | switch entry.Action { 39 | case bridge.FdbActionAdd: 40 | action = "Added" 41 | case bridge.FdbActionDel: 42 | action = "Deleted" 43 | default: 44 | action = "Unkowned" 45 | } 46 | devInfo, _ := net.InterfaceByIndex(entry.Ifindex) 47 | masterInfo, _ := net.InterfaceByIndex(entry.Master) 48 | fmt.Printf("%s %s dev %s master %s\n", action, entry.Lladdr, devInfo.Name, masterInfo.Name) 49 | } 50 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_darwin_test.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | 3 | package mem 4 | 5 | import ( 6 | "strconv" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func TestVirtualMemoryDarwin(t *testing.T) { 14 | v, err := VirtualMemory() 15 | assert.Nil(t, err) 16 | 17 | outBytes, err := invoke.Command("/usr/sbin/sysctl", "hw.memsize") 18 | assert.Nil(t, err) 19 | outString := string(outBytes) 20 | outString = strings.TrimSpace(outString) 21 | outParts := strings.Split(outString, " ") 22 | actualTotal, err := strconv.ParseInt(outParts[1], 10, 64) 23 | assert.Nil(t, err) 24 | assert.Equal(t, uint64(actualTotal), v.Total) 25 | 26 | assert.True(t, v.Available > 0) 27 | assert.Equal(t, v.Available, v.Free+v.Inactive, "%v", v) 28 | 29 | assert.True(t, v.Used > 0) 30 | assert.True(t, v.Used < v.Total) 31 | 32 | assert.True(t, v.UsedPercent > 0) 33 | assert.True(t, v.UsedPercent < 100) 34 | 35 | assert.True(t, v.Free > 0) 36 | assert.True(t, v.Free < v.Available) 37 | 38 | assert.True(t, v.Active > 0) 39 | assert.True(t, v.Active < v.Total) 40 | 41 | assert.True(t, v.Inactive > 0) 42 | assert.True(t, v.Inactive < v.Total) 43 | 44 | assert.True(t, v.Wired > 0) 45 | assert.True(t, v.Wired < v.Total) 46 | } 47 | -------------------------------------------------------------------------------- /internal/etc/etc.go: -------------------------------------------------------------------------------- 1 | package etc 2 | 3 | import ( 4 | "bufio" 5 | "os" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | const ( 11 | routeTableConf = "/etc/iproute2/rt_tables" 12 | routeProtocolConf = "/etc/iproute2/rt_protos" 13 | routeScopeConf = "/etc/iproute2/rt_scopes" 14 | groupConf = "/etc/iproute2/group" 15 | ) 16 | 17 | func ReadRouteTables() (map[int]string, error) { return read(routeTableConf) } 18 | func ReadRouteProtos() (map[int]string, error) { return read(routeProtocolConf) } 19 | func ReadRouteScopes() (map[int]string, error) { return read(routeScopeConf) } 20 | func ReadGroup() (map[int]string, error) { return read(groupConf) } 21 | 22 | func read(conf string) (map[int]string, error) { 23 | m := make(map[int]string) 24 | fd, err := os.Open(conf) 25 | if err != nil { 26 | return m, err 27 | } 28 | defer fd.Close() 29 | 30 | scanner := bufio.NewScanner(fd) 31 | for scanner.Scan() { 32 | line := scanner.Text() 33 | line = strings.TrimSpace(line) 34 | if line == "" || line[0] == '#' { 35 | continue 36 | } 37 | 38 | items := strings.Split(line, "\t") 39 | if len(items) != 2 { 40 | continue 41 | } 42 | n, err := strconv.Atoi(items[0]) 43 | if err == nil { 44 | m[n] = items[1] 45 | } 46 | } 47 | return m, nil 48 | } 49 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_solaris_test.go: -------------------------------------------------------------------------------- 1 | // +build solaris 2 | 3 | package mem 4 | 5 | import ( 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | const validFile = `swapfile dev swaplo blocks free 12 | /dev/zvol/dsk/rpool/swap 256,1 16 1058800 1058800 13 | /dev/dsk/c0t0d0s1 136,1 16 1638608 1600528` 14 | 15 | const invalidFile = `swapfile dev swaplo INVALID free 16 | /dev/zvol/dsk/rpool/swap 256,1 16 1058800 1058800 17 | /dev/dsk/c0t0d0s1 136,1 16 1638608 1600528` 18 | 19 | func TestParseSwapsCommandOutput_Valid(t *testing.T) { 20 | assert := assert.New(t) 21 | stats, err := parseSwapsCommandOutput(validFile) 22 | assert.NoError(err) 23 | 24 | assert.Equal(*stats[0], SwapDevice{ 25 | Name: "/dev/zvol/dsk/rpool/swap", 26 | UsedBytes: 0, 27 | FreeBytes: 1058800 * 512, 28 | }) 29 | 30 | assert.Equal(*stats[1], SwapDevice{ 31 | Name: "/dev/dsk/c0t0d0s1", 32 | UsedBytes: 38080 * 512, 33 | FreeBytes: 1600528 * 512, 34 | }) 35 | } 36 | 37 | func TestParseSwapsCommandOutput_Invalid(t *testing.T) { 38 | _, err := parseSwapsCommandOutput(invalidFile) 39 | assert.Error(t, err) 40 | } 41 | 42 | func TestParseSwapsCommandOutput_Empty(t *testing.T) { 43 | _, err := parseSwapsCommandOutput("") 44 | assert.Error(t, err) 45 | } 46 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_darwin_cgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build cgo 3 | 4 | package disk 5 | 6 | /* 7 | #cgo LDFLAGS: -framework CoreFoundation -framework IOKit 8 | #include 9 | #include 10 | #include "iostat_darwin.h" 11 | */ 12 | import "C" 13 | 14 | import ( 15 | "context" 16 | 17 | "github.com/shirou/gopsutil/internal/common" 18 | ) 19 | 20 | func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { 21 | var buf [C.NDRIVE]C.DriveStats 22 | n, err := C.readdrivestat(&buf[0], C.int(len(buf))) 23 | if err != nil { 24 | return nil, err 25 | } 26 | ret := make(map[string]IOCountersStat, 0) 27 | for i := 0; i < int(n); i++ { 28 | d := IOCountersStat{ 29 | ReadBytes: uint64(buf[i].read), 30 | WriteBytes: uint64(buf[i].written), 31 | ReadCount: uint64(buf[i].nread), 32 | WriteCount: uint64(buf[i].nwrite), 33 | ReadTime: uint64(buf[i].readtime / 1000 / 1000), // note: read/write time are in ns, but we want ms. 34 | WriteTime: uint64(buf[i].writetime / 1000 / 1000), 35 | IoTime: uint64((buf[i].readtime + buf[i].writetime) / 1000 / 1000), 36 | Name: C.GoString(&buf[i].name[0]), 37 | } 38 | if len(names) > 0 && !common.StringsHas(names, d.Name) { 39 | continue 40 | } 41 | 42 | ret[d.Name] = d 43 | } 44 | return ret, nil 45 | } 46 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_freebsd_386.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_freebsd.go 3 | 4 | package disk 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeofLongDouble = 0x8 13 | 14 | DEVSTAT_NO_DATA = 0x00 15 | DEVSTAT_READ = 0x01 16 | DEVSTAT_WRITE = 0x02 17 | DEVSTAT_FREE = 0x03 18 | ) 19 | 20 | const ( 21 | sizeOfDevstat = 0xf0 22 | ) 23 | 24 | type ( 25 | _C_short int16 26 | _C_int int32 27 | _C_long int32 28 | _C_long_long int64 29 | _C_long_double int64 30 | ) 31 | 32 | type Devstat struct { 33 | Sequence0 uint32 34 | Allocated int32 35 | Start_count uint32 36 | End_count uint32 37 | Busy_from Bintime 38 | Dev_links _Ctype_struct___0 39 | Device_number uint32 40 | Device_name [16]int8 41 | Unit_number int32 42 | Bytes [4]uint64 43 | Operations [4]uint64 44 | Duration [4]Bintime 45 | Busy_time Bintime 46 | Creation_time Bintime 47 | Block_size uint32 48 | Tag_types [3]uint64 49 | Flags uint32 50 | Device_type uint32 51 | Priority uint32 52 | Id *byte 53 | Sequence1 uint32 54 | } 55 | type Bintime struct { 56 | Sec int32 57 | Frac uint64 58 | } 59 | 60 | type _Ctype_struct___0 struct { 61 | Empty uint32 62 | } 63 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_freebsd_arm.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_freebsd.go 3 | 4 | package disk 5 | 6 | const ( 7 | sizeofPtr = 0x4 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x4 11 | sizeofLongLong = 0x8 12 | sizeofLongDouble = 0x8 13 | 14 | DEVSTAT_NO_DATA = 0x00 15 | DEVSTAT_READ = 0x01 16 | DEVSTAT_WRITE = 0x02 17 | DEVSTAT_FREE = 0x03 18 | ) 19 | 20 | const ( 21 | sizeOfDevstat = 0xf0 22 | ) 23 | 24 | type ( 25 | _C_short int16 26 | _C_int int32 27 | _C_long int32 28 | _C_long_long int64 29 | _C_long_double int64 30 | ) 31 | 32 | type Devstat struct { 33 | Sequence0 uint32 34 | Allocated int32 35 | Start_count uint32 36 | End_count uint32 37 | Busy_from Bintime 38 | Dev_links _Ctype_struct___0 39 | Device_number uint32 40 | Device_name [16]int8 41 | Unit_number int32 42 | Bytes [4]uint64 43 | Operations [4]uint64 44 | Duration [4]Bintime 45 | Busy_time Bintime 46 | Creation_time Bintime 47 | Block_size uint32 48 | Tag_types [3]uint64 49 | Flags uint32 50 | Device_type uint32 51 | Priority uint32 52 | Id *byte 53 | Sequence1 uint32 54 | } 55 | type Bintime struct { 56 | Sec int32 57 | Frac uint64 58 | } 59 | 60 | type _Ctype_struct___0 struct { 61 | Empty uint32 62 | } 63 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/types_freebsd.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | // Hand writing: _Ctype_struct___0 3 | 4 | /* 5 | Input to cgo -godefs. 6 | 7 | */ 8 | 9 | package disk 10 | 11 | /* 12 | #include 13 | #include 14 | #include 15 | 16 | enum { 17 | sizeofPtr = sizeof(void*), 18 | }; 19 | 20 | // because statinfo has long double snap_time, redefine with changing long long 21 | struct statinfo2 { 22 | long cp_time[CPUSTATES]; 23 | long tk_nin; 24 | long tk_nout; 25 | struct devinfo *dinfo; 26 | long long snap_time; 27 | }; 28 | */ 29 | import "C" 30 | 31 | // Machine characteristics; for internal use. 32 | 33 | const ( 34 | sizeofPtr = C.sizeofPtr 35 | sizeofShort = C.sizeof_short 36 | sizeofInt = C.sizeof_int 37 | sizeofLong = C.sizeof_long 38 | sizeofLongLong = C.sizeof_longlong 39 | sizeofLongDouble = C.sizeof_longlong 40 | 41 | DEVSTAT_NO_DATA = 0x00 42 | DEVSTAT_READ = 0x01 43 | DEVSTAT_WRITE = 0x02 44 | DEVSTAT_FREE = 0x03 45 | ) 46 | 47 | const ( 48 | sizeOfDevstat = C.sizeof_struct_devstat 49 | ) 50 | 51 | // Basic types 52 | 53 | type ( 54 | _C_short C.short 55 | _C_int C.int 56 | _C_long C.long 57 | _C_long_long C.longlong 58 | _C_long_double C.longlong 59 | ) 60 | 61 | type Devstat C.struct_devstat 62 | type Bintime C.struct_bintime 63 | -------------------------------------------------------------------------------- /ss/tcp.go: -------------------------------------------------------------------------------- 1 | package ss 2 | 3 | import ( 4 | "syscall" 5 | 6 | "github.com/Asphaltt/go-iproute2" 7 | ) 8 | 9 | // ListTcp4Conns retrieves all tcp connections from kernel. 10 | func (c *Client) ListTcp4Conns() ([]*Entry, error) { 11 | var req iproute2.InetDiagReq 12 | req.Family = syscall.AF_INET 13 | req.Protocol = syscall.IPPROTO_TCP 14 | req.States = uint32(iproute2.Conn) 15 | return c.listSockets(&req) 16 | } 17 | 18 | // ListTcp6Conns retrieves all tcp connections from kernel. 19 | func (c *Client) ListTcp6Conns() ([]*Entry, error) { 20 | var req iproute2.InetDiagReq 21 | req.Family = syscall.AF_INET6 22 | req.Protocol = syscall.IPPROTO_TCP 23 | req.States = uint32(iproute2.Conn) 24 | return c.listSockets(&req) 25 | } 26 | 27 | // ListTcp4Listeners retreives all IPv4 tcp listeners from kernel. 28 | func (c *Client) ListTcp4Listeners() ([]*Entry, error) { 29 | var req iproute2.InetDiagReq 30 | req.Family = syscall.AF_INET 31 | req.Protocol = syscall.IPPROTO_TCP 32 | req.States = uint32((1 << iproute2.Listen) | (1 << iproute2.Close)) 33 | return c.listSockets(&req) 34 | } 35 | 36 | // ListTcp6Listeners retreives all IPv6 tcp listeners from kernel. 37 | func (c *Client) ListTcp6Listeners() ([]*Entry, error) { 38 | var req iproute2.InetDiagReq 39 | req.Family = syscall.AF_INET6 40 | req.Protocol = syscall.IPPROTO_TCP 41 | req.States = uint32((1 << iproute2.Listen) | (1 << iproute2.Close)) 42 | return c.listSockets(&req) 43 | } 44 | -------------------------------------------------------------------------------- /ss/udp.go: -------------------------------------------------------------------------------- 1 | package ss 2 | 3 | import ( 4 | "syscall" 5 | 6 | "github.com/Asphaltt/go-iproute2" 7 | ) 8 | 9 | // ListUdp4Conns retrieves all Udp sockets from kernel. 10 | func (c *Client) ListUdp4Sockets() ([]*Entry, error) { 11 | var req iproute2.InetDiagReq 12 | req.Family = syscall.AF_INET 13 | req.Protocol = syscall.IPPROTO_UDP 14 | req.States = uint32(1 << iproute2.Established) 15 | return c.listSockets(&req) 16 | } 17 | 18 | // ListUdp6Conns retrieves all Udp sockets from kernel. 19 | func (c *Client) ListUdp6Sockets() ([]*Entry, error) { 20 | var req iproute2.InetDiagReq 21 | req.Family = syscall.AF_INET6 22 | req.Protocol = syscall.IPPROTO_UDP 23 | req.States = uint32(1 << iproute2.Established) 24 | return c.listSockets(&req) 25 | } 26 | 27 | // ListUdp4Listeners retreives all IPv4 Udp listeners from kernel. 28 | func (c *Client) ListUdp4Listeners() ([]*Entry, error) { 29 | var req iproute2.InetDiagReq 30 | req.Family = syscall.AF_INET 31 | req.Protocol = syscall.IPPROTO_UDP 32 | req.States = uint32((1 << iproute2.Listen) | (1 << iproute2.Close)) 33 | return c.listSockets(&req) 34 | } 35 | 36 | // ListUdp6Listeners retreives all IPv6 Udp listeners from kernel. 37 | func (c *Client) ListUdp6Listeners() ([]*Entry, error) { 38 | var req iproute2.InetDiagReq 39 | req.Family = syscall.AF_INET6 40 | req.Protocol = syscall.IPPROTO_UDP 41 | req.States = uint32((1 << iproute2.Listen) | (1 << iproute2.Close)) 42 | return c.listSockets(&req) 43 | } 44 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/testdata/linux/virtualmemory/issue1002/proc/meminfo: -------------------------------------------------------------------------------- 1 | total: used: free: shared: buffers: cached: 2 | Mem: 260579328 136073216 124506112 0 4915200 94064640 3 | Swap: 0 0 0 4 | MemTotal: 254472 kB 5 | MemFree: 121588 kB 6 | MemShared: 0 kB 7 | Buffers: 4800 kB 8 | Cached: 91860 kB 9 | SwapCached: 0 kB 10 | Active: 106236 kB 11 | Inactive: 8380 kB 12 | MemAvailable: 210156 kB 13 | Active(anon): 17956 kB 14 | Inactive(anon): 0 kB 15 | Active(file): 88280 kB 16 | Inactive(file): 8380 kB 17 | Unevictable: 0 kB 18 | Mlocked: 0 kB 19 | HighTotal: 131072 kB 20 | HighFree: 66196 kB 21 | LowTotal: 123400 kB 22 | LowFree: 55392 kB 23 | SwapTotal: 0 kB 24 | SwapFree: 0 kB 25 | Dirty: 0 kB 26 | Writeback: 0 kB 27 | AnonPages: 17992 kB 28 | Mapped: 37884 kB 29 | Shmem: 0 kB 30 | Slab: 9076 kB 31 | SReclaimable: 2700 kB 32 | SUnreclaim: 6376 kB 33 | KernelStack: 624 kB 34 | PageTables: 396 kB 35 | NFS_Unstable: 0 kB 36 | Bounce: 0 kB 37 | WritebackTmp: 0 kB 38 | CommitLimit: 127236 kB 39 | Committed_AS: 24968 kB 40 | VmallocTotal: 1949696 kB 41 | VmallocUsed: 0 kB 42 | VmallocChunk: 0 kB 43 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/labeler.yml: -------------------------------------------------------------------------------- 1 | v3: 2 | - v3/**/*.go 3 | package:cpu: 4 | - cpu/* 5 | - v3/cpu/* 6 | package:disk: 7 | - disk/* 8 | - v3/disk/* 9 | package:docker: 10 | - docker/* 11 | - v3/docker/* 12 | package:host: 13 | - host/* 14 | - v3/host/* 15 | package:load: 16 | - load/* 17 | - v3/load/* 18 | package:mem: 19 | - mem/* 20 | - v3/mem/* 21 | package:net: 22 | - net/* 23 | - v3/net/* 24 | package:process: 25 | - process/* 26 | - v3/process/* 27 | package:winservices: 28 | - winservices/* 29 | - v3/winservices/* 30 | os:linux: 31 | - ./**/*_linux.go 32 | - ./**/*_linux_mips64.go 33 | - ./**/*_linux_386.go 34 | - ./**/*_linux_test.go 35 | - ./**/*_linux_s390x.go 36 | - ./**/*_linux_amd64.go 37 | - ./**/*_posix.go 38 | os:freebsd: 39 | - ./**/*_freebsd.go 40 | - ./**/*_freebsd_386.go 41 | - ./**/*_freebsd_test.go 42 | - ./**/*_freebsd_amd64.go 43 | - ./**/*_bsd.go 44 | - ./**/*_posix.go 45 | os:darwin: 46 | - ./**/*_darwin.go 47 | - ./**/*_darwin_386.go 48 | - ./**/*_darwin_test.go 49 | - ./**/*_darwin_amd64.go 50 | - ./**/*_posix.go 51 | os:openbsd: 52 | - ./**/*_openbsd.go 53 | - ./**/*_openbsd_386.go 54 | - ./**/*_openbsd_test.go 55 | - ./**/*_openbsd_amd64.go 56 | - ./**/*_bsd.go 57 | - ./**/*_posix.go 58 | os:windows: 59 | - ./**/*_windows.go 60 | - ./**/*_windows_386.go 61 | - ./**/*_windows_test.go 62 | - ./**/*_windows_amd64.go 63 | os:solaris: 64 | - ./**/*_solaris.go 65 | - ./**/*_posix.go 66 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_freebsd_amd64.go: -------------------------------------------------------------------------------- 1 | // Created by cgo -godefs - DO NOT EDIT 2 | // cgo -godefs types_freebsd.go 3 | 4 | package disk 5 | 6 | const ( 7 | sizeofPtr = 0x8 8 | sizeofShort = 0x2 9 | sizeofInt = 0x4 10 | sizeofLong = 0x8 11 | sizeofLongLong = 0x8 12 | sizeofLongDouble = 0x8 13 | 14 | DEVSTAT_NO_DATA = 0x00 15 | DEVSTAT_READ = 0x01 16 | DEVSTAT_WRITE = 0x02 17 | DEVSTAT_FREE = 0x03 18 | ) 19 | 20 | const ( 21 | sizeOfDevstat = 0x120 22 | ) 23 | 24 | type ( 25 | _C_short int16 26 | _C_int int32 27 | _C_long int64 28 | _C_long_long int64 29 | _C_long_double int64 30 | ) 31 | 32 | type Devstat struct { 33 | Sequence0 uint32 34 | Allocated int32 35 | Start_count uint32 36 | End_count uint32 37 | Busy_from Bintime 38 | Dev_links _Ctype_struct___0 39 | Device_number uint32 40 | Device_name [16]int8 41 | Unit_number int32 42 | Bytes [4]uint64 43 | Operations [4]uint64 44 | Duration [4]Bintime 45 | Busy_time Bintime 46 | Creation_time Bintime 47 | Block_size uint32 48 | Pad_cgo_0 [4]byte 49 | Tag_types [3]uint64 50 | Flags uint32 51 | Device_type uint32 52 | Priority uint32 53 | Pad_cgo_1 [4]byte 54 | ID *byte 55 | Sequence1 uint32 56 | Pad_cgo_2 [4]byte 57 | } 58 | type Bintime struct { 59 | Sec int64 60 | Frac uint64 61 | } 62 | 63 | type _Ctype_struct___0 struct { 64 | Empty uint64 65 | } 66 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_freebsd_arm64.go: -------------------------------------------------------------------------------- 1 | // +build freebsd 2 | // +build arm64 3 | // Code generated by cmd/cgo -godefs; DO NOT EDIT. 4 | // cgo -godefs disk/types_freebsd.go 5 | 6 | package disk 7 | 8 | const ( 9 | sizeofPtr = 0x8 10 | sizeofShort = 0x2 11 | sizeofInt = 0x4 12 | sizeofLong = 0x8 13 | sizeofLongLong = 0x8 14 | sizeofLongDouble = 0x8 15 | 16 | DEVSTAT_NO_DATA = 0x00 17 | DEVSTAT_READ = 0x01 18 | DEVSTAT_WRITE = 0x02 19 | DEVSTAT_FREE = 0x03 20 | ) 21 | 22 | const ( 23 | sizeOfDevstat = 0x120 24 | ) 25 | 26 | type ( 27 | _C_short int16 28 | _C_int int32 29 | _C_long int64 30 | _C_long_long int64 31 | _C_long_double int64 32 | ) 33 | 34 | type Devstat struct { 35 | Sequence0 uint32 36 | Allocated int32 37 | Start_count uint32 38 | End_count uint32 39 | Busy_from Bintime 40 | Dev_links _Ctype_struct___0 41 | Device_number uint32 42 | Device_name [16]int8 43 | Unit_number int32 44 | Bytes [4]uint64 45 | Operations [4]uint64 46 | Duration [4]Bintime 47 | Busy_time Bintime 48 | Creation_time Bintime 49 | Block_size uint32 50 | Tag_types [3]uint64 51 | Flags uint32 52 | Device_type uint32 53 | Priority uint32 54 | Id *byte 55 | Sequence1 uint32 56 | Pad_cgo_0 [4]byte 57 | } 58 | type Bintime struct { 59 | Sec int64 60 | Frac uint64 61 | } 62 | 63 | type _Ctype_struct___0 struct { 64 | Empty uint64 65 | } 66 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_fallback.go: -------------------------------------------------------------------------------- 1 | // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows 2 | 3 | package host 4 | 5 | import ( 6 | "context" 7 | 8 | "github.com/shirou/gopsutil/internal/common" 9 | ) 10 | 11 | func HostIDWithContext(ctx context.Context) (string, error) { 12 | return "", common.ErrNotImplementedError 13 | } 14 | 15 | func numProcs(ctx context.Context) (uint64, error) { 16 | return 0, common.ErrNotImplementedError 17 | } 18 | 19 | func BootTimeWithContext(ctx context.Context) (uint64, error) { 20 | return 0, common.ErrNotImplementedError 21 | } 22 | 23 | func UptimeWithContext(ctx context.Context) (uint64, error) { 24 | return 0, common.ErrNotImplementedError 25 | } 26 | 27 | func UsersWithContext(ctx context.Context) ([]UserStat, error) { 28 | return []UserStat{}, common.ErrNotImplementedError 29 | } 30 | 31 | func VirtualizationWithContext(ctx context.Context) (string, string, error) { 32 | return "", "", common.ErrNotImplementedError 33 | } 34 | 35 | func KernelVersionWithContext(ctx context.Context) (string, error) { 36 | return "", common.ErrNotImplementedError 37 | } 38 | 39 | func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) { 40 | return "", "", "", common.ErrNotImplementedError 41 | } 42 | 43 | func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, error) { 44 | return []TemperatureStat{}, common.ErrNotImplementedError 45 | } 46 | 47 | func KernelArch() (string, error) { 48 | return "", common.ErrNotImplementedError 49 | } 50 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/testdata/linux/virtualmemory/intelcorei5/proc/meminfo: -------------------------------------------------------------------------------- 1 | MemTotal: 16115528 kB 2 | MemFree: 8577628 kB 3 | MemAvailable: 11225936 kB 4 | Buffers: 207516 kB 5 | Cached: 3791568 kB 6 | SwapCached: 0 kB 7 | Active: 4245500 kB 8 | Inactive: 2869956 kB 9 | Active(anon): 3123508 kB 10 | Inactive(anon): 1186612 kB 11 | Active(file): 1121992 kB 12 | Inactive(file): 1683344 kB 13 | Unevictable: 32 kB 14 | Mlocked: 32 kB 15 | SwapTotal: 8065020 kB 16 | SwapFree: 8065020 kB 17 | Dirty: 172 kB 18 | Writeback: 0 kB 19 | AnonPages: 3116472 kB 20 | Mapped: 1145144 kB 21 | Shmem: 1193752 kB 22 | Slab: 247824 kB 23 | SReclaimable: 182100 kB 24 | SUnreclaim: 65724 kB 25 | KernelStack: 14224 kB 26 | PageTables: 63712 kB 27 | NFS_Unstable: 0 kB 28 | Bounce: 0 kB 29 | WritebackTmp: 0 kB 30 | CommitLimit: 16122784 kB 31 | Committed_AS: 12071112 kB 32 | VmallocTotal: 34359738367 kB 33 | VmallocUsed: 0 kB 34 | VmallocChunk: 0 kB 35 | HardwareCorrupted: 0 kB 36 | AnonHugePages: 0 kB 37 | ShmemHugePages: 0 kB 38 | ShmemPmdMapped: 0 kB 39 | HugePages_Total: 0 40 | HugePages_Free: 0 41 | HugePages_Rsvd: 0 42 | HugePages_Surp: 0 43 | Hugepagesize: 2048 kB 44 | DirectMap4k: 143564 kB 45 | DirectMap2M: 6871040 kB 46 | DirectMap1G: 10485760 kB 47 | -------------------------------------------------------------------------------- /cmd/ss/tcp.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/Asphaltt/go-iproute2/ss" 7 | ) 8 | 9 | func (c *client) showTCP(listen, tcp4, tcp6 bool) { 10 | if listen { 11 | c.showTCPListeners(tcp4, tcp6) 12 | } else { 13 | c.showTCPConns(tcp4, tcp6) 14 | } 15 | } 16 | 17 | func (c *client) showTCPConns(tcp4, tcp6 bool) { 18 | sc := ss.NewWithConn(c.conn) 19 | if tcp4 { 20 | c.showTCP4Conns(sc) 21 | } 22 | if tcp6 { 23 | c.showTCP6Conns(sc) 24 | } 25 | } 26 | 27 | func (c *client) showTCP4Conns(sc *ss.Client) { 28 | if err := c.showTcpEntries(sc.ListTcp4Conns, config.process); err != nil { 29 | fmt.Println("failed to list IPv4 tcp connections, err:", err) 30 | } 31 | } 32 | 33 | func (c *client) showTCP6Conns(sc *ss.Client) { 34 | if err := c.showTcpEntries(sc.ListTcp6Conns, config.process); err != nil { 35 | fmt.Println("failed to list IPv6 tcp connections, err:", err) 36 | } 37 | } 38 | 39 | func (c *client) showTCPListeners(tcp4, tcp6 bool) { 40 | sc := ss.NewWithConn(c.conn) 41 | if tcp4 { 42 | c.showTCP4Listeners(sc) 43 | } 44 | if tcp6 { 45 | c.showTCP6Listeners(sc) 46 | } 47 | } 48 | 49 | func (c *client) showTCP4Listeners(sc *ss.Client) { 50 | if err := c.showTcpEntries(sc.ListTcp4Listeners, config.process); err != nil { 51 | fmt.Println("failed to list IPv4 tcp listeners, err:", err) 52 | } 53 | } 54 | 55 | func (c *client) showTCP6Listeners(sc *ss.Client) { 56 | if err := c.showTcpEntries(sc.ListTcp6Listeners, config.process); err != nil { 57 | fmt.Println("failed to list IPv6 tcp listeners, err:", err) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /cmd/ss/udp.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/Asphaltt/go-iproute2/ss" 7 | ) 8 | 9 | func (c *client) showUDP(listen, udp4, udp6 bool) { 10 | if listen { 11 | c.showUDPListeners(udp4, udp6) 12 | } else { 13 | c.showUDPSockets(udp4, udp6) 14 | } 15 | } 16 | 17 | func (c *client) showUDPSockets(udp4, udp6 bool) { 18 | sc := ss.NewWithConn(c.conn) 19 | if udp4 { 20 | c.showUDP4Sockets(sc) 21 | } 22 | if udp6 { 23 | c.showUDP6Sockets(sc) 24 | } 25 | } 26 | 27 | func (c *client) showUDP4Sockets(sc *ss.Client) { 28 | if err := c.showUdpEntries(sc.ListUdp4Sockets, config.process); err != nil { 29 | fmt.Println("failed to list IPv4 udp sockets, err:", err) 30 | } 31 | } 32 | 33 | func (c *client) showUDP6Sockets(sc *ss.Client) { 34 | if err := c.showUdpEntries(sc.ListUdp6Sockets, config.process); err != nil { 35 | fmt.Println("failed to list IPv6 udp sockets, err:", err) 36 | } 37 | } 38 | 39 | func (c *client) showUDPListeners(udp4, udp6 bool) { 40 | sc := ss.NewWithConn(c.conn) 41 | if udp4 { 42 | c.showUDP4Listeners(sc) 43 | } 44 | if udp6 { 45 | c.showUDP6Listeners(sc) 46 | } 47 | } 48 | 49 | func (c *client) showUDP4Listeners(sc *ss.Client) { 50 | if err := c.showUdpEntries(sc.ListUdp4Listeners, config.process); err != nil { 51 | fmt.Println("failed to list IPv4 udp listeners, err:", err) 52 | } 53 | } 54 | 55 | func (c *client) showUDP6Listeners(sc *ss.Client) { 56 | if err := c.showUdpEntries(sc.ListUdp6Listeners, config.process); err != nil { 57 | fmt.Println("failed to list IPv6 udp listeners, err:", err) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /pkg/gopsutil/internal/common/common_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | 3 | package common 4 | 5 | import ( 6 | "os" 7 | "os/exec" 8 | "strings" 9 | "unsafe" 10 | 11 | "golang.org/x/sys/unix" 12 | ) 13 | 14 | func DoSysctrl(mib string) ([]string, error) { 15 | sysctl, err := exec.LookPath("sysctl") 16 | if err != nil { 17 | return []string{}, err 18 | } 19 | cmd := exec.Command(sysctl, "-n", mib) 20 | cmd.Env = getSysctrlEnv(os.Environ()) 21 | out, err := cmd.Output() 22 | if err != nil { 23 | return []string{}, err 24 | } 25 | v := strings.Replace(string(out), "{ ", "", 1) 26 | v = strings.Replace(string(v), " }", "", 1) 27 | values := strings.Fields(string(v)) 28 | 29 | return values, nil 30 | } 31 | 32 | func CallSyscall(mib []int32) ([]byte, uint64, error) { 33 | mibptr := unsafe.Pointer(&mib[0]) 34 | miblen := uint64(len(mib)) 35 | 36 | // get required buffer size 37 | length := uint64(0) 38 | _, _, err := unix.Syscall6( 39 | unix.SYS___SYSCTL, 40 | uintptr(mibptr), 41 | uintptr(miblen), 42 | 0, 43 | uintptr(unsafe.Pointer(&length)), 44 | 0, 45 | 0) 46 | if err != 0 { 47 | var b []byte 48 | return b, length, err 49 | } 50 | if length == 0 { 51 | var b []byte 52 | return b, length, err 53 | } 54 | // get proc info itself 55 | buf := make([]byte, length) 56 | _, _, err = unix.Syscall6( 57 | unix.SYS___SYSCTL, 58 | uintptr(mibptr), 59 | uintptr(miblen), 60 | uintptr(unsafe.Pointer(&buf[0])), 61 | uintptr(unsafe.Pointer(&length)), 62 | 0, 63 | 0) 64 | if err != 0 { 65 | return buf, length, err 66 | } 67 | 68 | return buf, length, nil 69 | } 70 | -------------------------------------------------------------------------------- /pkg/gopsutil/_tools/v3migration/v3Changes.md: -------------------------------------------------------------------------------- 1 | # v2 to v3 changes 2 | 3 | - v3 is in the `v3` directory 4 | 5 | - [process] RLimit is now uint64 ([#364](https://github.com/shirou/gopsutil/issues/364)) 6 | - [process] Remove process.NetIOCounters ([#429](https://github.com/shirou/gopsutil/issues/429)) 7 | - [docker] fix typo of memoryLimitInBbytes ([#464](https://github.com/shirou/gopsutil/issues/464)) 8 | - [mem] VirtualMemoryStat JSON fields capitalization ([#545](https://github.com/shirou/gopsutil/issues/545)) 9 | - various JSON field name and some of Variable name have been changed. see v3migration.sh 10 | - [all] various kind of platform dependent values/constants such as process.GetWin32Proc is now private. see v3migration.sh 11 | - [process] process.Status() now returns []string. and status string is "Running", not just "R". defined in process.go. ([#596](https://github.com/shirou/gopsutil/issues/596)) 12 | - [docker] `CgroupCPU()` now returns `*CgroupCPUStat` with Usage ([#590](https://github.com/shirou/gopsutil/issues/590) and [#581](https://github.com/shirou/gopsutil/issues/581)) 13 | - [disk] `disk.Opts` is now string[], not string. (related to [#955](https://github.com/shirou/gopsutil/issues/955)) 14 | - [host] Fixed temperature sensors detection in Linux ([#905](https://github.com/shirou/gopsutil/issues/905)) 15 | - [disk] `GetDiskSerialNumber()` is now `SerialNumber()` and spread to all platforms 16 | - [disk] `GetLabel ()` is now `Label()` and spread to all platform 17 | - [net] Change net.InterfaceStat.Addrs to InterfaceAddrList ([#226](https://github.com/shirou/gopsutil/issues/226)) 18 | - [cpu] Removed windows-specific `ProcInfo()` 19 | -------------------------------------------------------------------------------- /cmd/ip/neighbour.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "strings" 7 | 8 | "github.com/Asphaltt/go-iproute2" 9 | "github.com/Asphaltt/go-iproute2/ip" 10 | "github.com/spf13/cobra" 11 | ) 12 | 13 | func init() { 14 | rootCmd.AddCommand(neighCmd()) 15 | } 16 | 17 | func neighCmd() *cobra.Command { 18 | neighCmd := &cobra.Command{ 19 | Use: "neighbour", 20 | Aliases: []string{"n", "ne", "nei", "neig", "neigh"}, 21 | Run: func(cmd *cobra.Command, args []string) { 22 | cli.runCmd(cli.listNeighbours) 23 | }, 24 | } 25 | neighCmd.AddCommand(&cobra.Command{ 26 | Use: "list", 27 | Aliases: []string{"l", "li", "lis", "lst", "s", "sh", "sho", "show"}, 28 | Run: func(cmd *cobra.Command, args []string) { 29 | cli.runCmd(cli.listNeighbours) 30 | }, 31 | }) 32 | return neighCmd 33 | } 34 | 35 | func (c *client) listNeighbours() { 36 | ipcli := ip.NewWithConn(c.conn) 37 | entries, err := ipcli.ListNeighbours() 38 | if err != nil { 39 | fmt.Println("failed to list neighbour entries, err:", err) 40 | return 41 | } 42 | 43 | for _, e := range entries { 44 | if e.State != iproute2.NudNoArp { 45 | printNeighEntry(e) 46 | } 47 | } 48 | } 49 | 50 | func printNeighEntry(e *ip.NeighEntry) { 51 | var b strings.Builder 52 | b.WriteString(e.Addr.String()) 53 | 54 | if e.Ifindex != 0 { 55 | ifc, _ := net.InterfaceByIndex(e.Ifindex) 56 | b.WriteString(fmt.Sprintf(" dev %s", ifc.Name)) 57 | } 58 | 59 | if e.State != iproute2.NudFailed { 60 | b.WriteString(fmt.Sprintf(" lladdr %s", e.Lladdr)) 61 | } 62 | b.WriteString(fmt.Sprintf(" %s", strings.ToUpper(e.State.String()))) 63 | fmt.Println(b.String()) 64 | } 65 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/workflows/build_test.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: Build Test 3 | jobs: 4 | build_test_v2: 5 | env: 6 | GOPATH: ${{ github.workspace }} 7 | GO111MODULE: off 8 | strategy: 9 | matrix: 10 | go-version: [1.16.x, 1.17.x] 11 | runs-on: ubuntu-20.04 12 | steps: 13 | - name: Install Go 14 | uses: actions/setup-go@v2 15 | with: 16 | go-version: ${{ matrix.go-version }} 17 | - name: Checkout code 18 | uses: actions/checkout@v2 19 | with: 20 | path: ${{ github.workspace }}/src/github.com/shirou/gopsutil 21 | - name: Get dependencies 22 | if: runner.os != 'Windows' 23 | run: | 24 | if ! command -v dep &>/dev/null; then 25 | mkdir -p $GOPATH/bin 26 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 27 | echo "PATH=$GOPATH/bin:$PATH" >> $GITHUB_PATH 28 | fi 29 | cd $GOPATH/src/github.com/shirou/gopsutil 30 | dep ensure 31 | # exclude v3 from being run with ./... 32 | rm -rf $GOPATH/src/github.com/shirou/gopsutil/v3 33 | - name: Build Test v2 34 | run: | 35 | cd $GOPATH/src/github.com/shirou/gopsutil && make build_test 36 | build_test_v3: 37 | strategy: 38 | matrix: 39 | go-version: [1.16.x, 1.17.x] 40 | runs-on: ubuntu-20.04 41 | steps: 42 | - name: Install Go 43 | uses: actions/setup-go@v2 44 | with: 45 | go-version: ${{ matrix.go-version }} 46 | - name: Checkout code 47 | uses: actions/checkout@v2 48 | - name: Build Test v3 49 | run: | 50 | cd v3 && make build_test -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_linux_test.go: -------------------------------------------------------------------------------- 1 | // +build linux 2 | 3 | package host 4 | 5 | import ( 6 | "testing" 7 | ) 8 | 9 | func TestGetRedhatishVersion(t *testing.T) { 10 | var ret string 11 | c := []string{"Rawhide"} 12 | ret = getRedhatishVersion(c) 13 | if ret != "rawhide" { 14 | t.Errorf("Could not get version rawhide: %v", ret) 15 | } 16 | 17 | c = []string{"Fedora release 15 (Lovelock)"} 18 | ret = getRedhatishVersion(c) 19 | if ret != "15" { 20 | t.Errorf("Could not get version fedora: %v", ret) 21 | } 22 | 23 | c = []string{"Enterprise Linux Server release 5.5 (Carthage)"} 24 | ret = getRedhatishVersion(c) 25 | if ret != "5.5" { 26 | t.Errorf("Could not get version redhat enterprise: %v", ret) 27 | } 28 | 29 | c = []string{""} 30 | ret = getRedhatishVersion(c) 31 | if ret != "" { 32 | t.Errorf("Could not get version with no value: %v", ret) 33 | } 34 | } 35 | 36 | func TestGetRedhatishPlatform(t *testing.T) { 37 | var ret string 38 | c := []string{"red hat"} 39 | ret = getRedhatishPlatform(c) 40 | if ret != "redhat" { 41 | t.Errorf("Could not get platform redhat: %v", ret) 42 | } 43 | 44 | c = []string{"Fedora release 15 (Lovelock)"} 45 | ret = getRedhatishPlatform(c) 46 | if ret != "fedora" { 47 | t.Errorf("Could not get platform fedora: %v", ret) 48 | } 49 | 50 | c = []string{"Enterprise Linux Server release 5.5 (Carthage)"} 51 | ret = getRedhatishPlatform(c) 52 | if ret != "enterprise" { 53 | t.Errorf("Could not get platform redhat enterprise: %v", ret) 54 | } 55 | 56 | c = []string{""} 57 | ret = getRedhatishPlatform(c) 58 | if ret != "" { 59 | t.Errorf("Could not get platform with no value: %v", ret) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_bsd_test.go: -------------------------------------------------------------------------------- 1 | // +build freebsd openbsd 2 | 3 | package mem 4 | 5 | import ( 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | const validFreeBSD = `Device: 1kB-blocks Used: 12 | /dev/gpt/swapfs 1048576 1234 13 | /dev/md0 1048576 666 14 | ` 15 | 16 | const validOpenBSD = `Device 1K-blocks Used Avail Capacity Priority 17 | /dev/wd0b 655025 1234 653791 1% 0 18 | ` 19 | 20 | const invalid = `Device: 512-blocks Used: 21 | /dev/gpt/swapfs 1048576 1234 22 | /dev/md0 1048576 666 23 | ` 24 | 25 | func TestParseSwapctlOutput_FreeBSD(t *testing.T) { 26 | assert := assert.New(t) 27 | stats, err := parseSwapctlOutput(validFreeBSD) 28 | assert.NoError(err) 29 | 30 | assert.Equal(*stats[0], SwapDevice{ 31 | Name: "/dev/gpt/swapfs", 32 | UsedBytes: 1263616, 33 | FreeBytes: 1072478208, 34 | }) 35 | 36 | assert.Equal(*stats[1], SwapDevice{ 37 | Name: "/dev/md0", 38 | UsedBytes: 681984, 39 | FreeBytes: 1073059840, 40 | }) 41 | } 42 | 43 | func TestParseSwapctlOutput_OpenBSD(t *testing.T) { 44 | assert := assert.New(t) 45 | stats, err := parseSwapctlOutput(validOpenBSD) 46 | assert.NoError(err) 47 | 48 | assert.Equal(*stats[0], SwapDevice{ 49 | Name: "/dev/wd0b", 50 | UsedBytes: 1234 * 1024, 51 | FreeBytes: 653791 * 1024, 52 | }) 53 | } 54 | 55 | func TestParseSwapctlOutput_Invalid(t *testing.T) { 56 | _, err := parseSwapctlOutput(invalid) 57 | assert.Error(t, err) 58 | } 59 | 60 | func TestParseSwapctlOutput_Empty(t *testing.T) { 61 | _, err := parseSwapctlOutput("") 62 | assert.Error(t, err) 63 | } 64 | -------------------------------------------------------------------------------- /cmd/bridge/fdb.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "strings" 7 | 8 | "github.com/Asphaltt/go-iproute2/bridge" 9 | "github.com/spf13/cobra" 10 | ) 11 | 12 | func init() { 13 | rootCmd.AddCommand(fdbCmd()) 14 | } 15 | 16 | func fdbCmd() *cobra.Command { 17 | fdbCmd := &cobra.Command{ 18 | Use: "fdb", 19 | Run: func(cmd *cobra.Command, args []string) { 20 | cli.runCmd(cli.listFdb) 21 | }, 22 | } 23 | fdbCmd.AddCommand(&cobra.Command{ 24 | Use: "list", 25 | Aliases: []string{"l", "ls", "lis", "lst", "s", "sh", "sho", "show"}, 26 | Run: func(cmd *cobra.Command, args []string) { 27 | cli.runCmd(cli.listFdb) 28 | }, 29 | }) 30 | return fdbCmd 31 | } 32 | 33 | func (c *client) listFdb() { 34 | bcli := bridge.New(c.conn) 35 | entries, err := bcli.ListFdb() 36 | if err != nil { 37 | fmt.Println("failed to list fdb entries, err:", err) 38 | return 39 | } 40 | 41 | for _, e := range entries { 42 | printListFdb(e) 43 | } 44 | } 45 | 46 | func printListFdb(e *bridge.FdbEntry) { 47 | var devName string 48 | if ifi, err := net.InterfaceByIndex(e.Ifindex); err == nil { 49 | devName = ifi.Name 50 | } 51 | 52 | var b strings.Builder 53 | b.WriteString(fmt.Sprintf("%s dev %s ", e.Lladdr, devName)) 54 | 55 | if e.Vlan != 0 { 56 | b.WriteString(fmt.Sprintf("vlan %d ", e.Vlan)) 57 | } 58 | 59 | if e.Flag != 0 { 60 | b.WriteString(fmt.Sprintf("%s ", e.Flag)) 61 | } 62 | 63 | if e.Master != 0 { 64 | ifi, err := net.InterfaceByIndex(e.Master) 65 | if err == nil { 66 | b.WriteString(fmt.Sprintf("master %s ", ifi.Name)) 67 | } 68 | } 69 | 70 | b.WriteString(e.State.String()) 71 | 72 | fmt.Println(b.String()) 73 | } 74 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_darwin_cgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin,cgo 2 | 3 | package mem 4 | 5 | /* 6 | #include 7 | */ 8 | import "C" 9 | 10 | import ( 11 | "context" 12 | "fmt" 13 | "unsafe" 14 | 15 | "golang.org/x/sys/unix" 16 | ) 17 | 18 | // VirtualMemory returns VirtualmemoryStat. 19 | func VirtualMemory() (*VirtualMemoryStat, error) { 20 | return VirtualMemoryWithContext(context.Background()) 21 | } 22 | 23 | func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { 24 | count := C.mach_msg_type_number_t(C.HOST_VM_INFO_COUNT) 25 | var vmstat C.vm_statistics_data_t 26 | 27 | status := C.host_statistics(C.host_t(C.mach_host_self()), 28 | C.HOST_VM_INFO, 29 | C.host_info_t(unsafe.Pointer(&vmstat)), 30 | &count) 31 | 32 | if status != C.KERN_SUCCESS { 33 | return nil, fmt.Errorf("host_statistics error=%d", status) 34 | } 35 | 36 | pageSize := uint64(unix.Getpagesize()) 37 | total, err := getHwMemsize() 38 | if err != nil { 39 | return nil, err 40 | } 41 | totalCount := C.natural_t(total / pageSize) 42 | 43 | availableCount := vmstat.inactive_count + vmstat.free_count 44 | usedPercent := 100 * float64(totalCount-availableCount) / float64(totalCount) 45 | 46 | usedCount := totalCount - availableCount 47 | 48 | return &VirtualMemoryStat{ 49 | Total: total, 50 | Available: pageSize * uint64(availableCount), 51 | Used: pageSize * uint64(usedCount), 52 | UsedPercent: usedPercent, 53 | Free: pageSize * uint64(vmstat.free_count), 54 | Active: pageSize * uint64(vmstat.active_count), 55 | Inactive: pageSize * uint64(vmstat.inactive_count), 56 | Wired: pageSize * uint64(vmstat.wire_count), 57 | }, nil 58 | } 59 | -------------------------------------------------------------------------------- /pkg/gopsutil/internal/common/common_unix.go: -------------------------------------------------------------------------------- 1 | // +build linux freebsd darwin openbsd 2 | 3 | package common 4 | 5 | import ( 6 | "context" 7 | "os/exec" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ...string) ([]string, error) { 13 | var cmd []string 14 | if pid == 0 { // will get from all processes. 15 | cmd = []string{"-a", "-n", "-P"} 16 | } else { 17 | cmd = []string{"-a", "-n", "-P", "-p", strconv.Itoa(int(pid))} 18 | } 19 | cmd = append(cmd, args...) 20 | lsof, err := exec.LookPath("lsof") 21 | if err != nil { 22 | return []string{}, err 23 | } 24 | out, err := invoke.CommandWithContext(ctx, lsof, cmd...) 25 | if err != nil { 26 | // if no pid found, lsof returns code 1. 27 | if err.Error() == "exit status 1" && len(out) == 0 { 28 | return []string{}, nil 29 | } 30 | } 31 | lines := strings.Split(string(out), "\n") 32 | 33 | var ret []string 34 | for _, l := range lines[1:] { 35 | if len(l) == 0 { 36 | continue 37 | } 38 | ret = append(ret, l) 39 | } 40 | return ret, nil 41 | } 42 | 43 | func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) { 44 | cmd := []string{"-P", strconv.Itoa(int(pid))} 45 | pgrep, err := exec.LookPath("pgrep") 46 | if err != nil { 47 | return []int32{}, err 48 | } 49 | out, err := invoke.CommandWithContext(ctx, pgrep, cmd...) 50 | if err != nil { 51 | return []int32{}, err 52 | } 53 | lines := strings.Split(string(out), "\n") 54 | ret := make([]int32, 0, len(lines)) 55 | for _, l := range lines { 56 | if len(l) == 0 { 57 | continue 58 | } 59 | i, err := strconv.Atoi(l) 60 | if err != nil { 61 | continue 62 | } 63 | ret = append(ret, int32(i)) 64 | } 65 | return ret, nil 66 | } 67 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_unix.go: -------------------------------------------------------------------------------- 1 | // +build freebsd linux darwin 2 | 3 | package disk 4 | 5 | import ( 6 | "context" 7 | "strconv" 8 | 9 | "golang.org/x/sys/unix" 10 | ) 11 | 12 | func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { 13 | stat := unix.Statfs_t{} 14 | err := unix.Statfs(path, &stat) 15 | if err != nil { 16 | return nil, err 17 | } 18 | bsize := stat.Bsize 19 | 20 | ret := &UsageStat{ 21 | Path: unescapeFstab(path), 22 | Fstype: getFsType(stat), 23 | Total: (uint64(stat.Blocks) * uint64(bsize)), 24 | Free: (uint64(stat.Bavail) * uint64(bsize)), 25 | InodesTotal: (uint64(stat.Files)), 26 | InodesFree: (uint64(stat.Ffree)), 27 | } 28 | 29 | // if could not get InodesTotal, return empty 30 | if ret.InodesTotal < ret.InodesFree { 31 | return ret, nil 32 | } 33 | 34 | ret.InodesUsed = (ret.InodesTotal - ret.InodesFree) 35 | ret.Used = (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(bsize) 36 | 37 | if ret.InodesTotal == 0 { 38 | ret.InodesUsedPercent = 0 39 | } else { 40 | ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0 41 | } 42 | 43 | if (ret.Used + ret.Free) == 0 { 44 | ret.UsedPercent = 0 45 | } else { 46 | // We don't use ret.Total to calculate percent. 47 | // see https://github.com/shirou/gopsutil/issues/562 48 | ret.UsedPercent = (float64(ret.Used) / float64(ret.Used+ret.Free)) * 100.0 49 | } 50 | 51 | return ret, nil 52 | } 53 | 54 | // Unescape escaped octal chars (like space 040, ampersand 046 and backslash 134) to their real value in fstab fields issue#555 55 | func unescapeFstab(path string) string { 56 | escaped, err := strconv.Unquote(`"` + path + `"`) 57 | if err != nil { 58 | return path 59 | } 60 | return escaped 61 | } 62 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_darwin.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | 3 | package mem 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "unsafe" 9 | 10 | "github.com/shirou/gopsutil/internal/common" 11 | "golang.org/x/sys/unix" 12 | ) 13 | 14 | func getHwMemsize() (uint64, error) { 15 | total, err := unix.SysctlUint64("hw.memsize") 16 | if err != nil { 17 | return 0, err 18 | } 19 | return total, nil 20 | } 21 | 22 | // xsw_usage in sys/sysctl.h 23 | type swapUsage struct { 24 | Total uint64 25 | Avail uint64 26 | Used uint64 27 | Pagesize int32 28 | Encrypted bool 29 | } 30 | 31 | // SwapMemory returns swapinfo. 32 | func SwapMemory() (*SwapMemoryStat, error) { 33 | return SwapMemoryWithContext(context.Background()) 34 | } 35 | 36 | func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { 37 | // https://github.com/yanllearnn/go-osstat/blob/ae8a279d26f52ec946a03698c7f50a26cfb427e3/memory/memory_darwin.go 38 | var ret *SwapMemoryStat 39 | 40 | value, err := unix.SysctlRaw("vm.swapusage") 41 | if err != nil { 42 | return ret, err 43 | } 44 | if len(value) != 32 { 45 | return ret, fmt.Errorf("unexpected output of sysctl vm.swapusage: %v (len: %d)", value, len(value)) 46 | } 47 | swap := (*swapUsage)(unsafe.Pointer(&value[0])) 48 | 49 | u := float64(0) 50 | if swap.Total != 0 { 51 | u = ((float64(swap.Total) - float64(swap.Avail)) / float64(swap.Total)) * 100.0 52 | } 53 | 54 | ret = &SwapMemoryStat{ 55 | Total: swap.Total, 56 | Used: swap.Used, 57 | Free: swap.Avail, 58 | UsedPercent: u, 59 | } 60 | 61 | return ret, nil 62 | } 63 | 64 | func SwapDevices() ([]*SwapDevice, error) { 65 | return SwapDevicesWithContext(context.Background()) 66 | } 67 | 68 | func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { 69 | return nil, common.ErrNotImplementedError 70 | } 71 | -------------------------------------------------------------------------------- /pkg/gopsutil/internal/common/common_darwin.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | 3 | package common 4 | 5 | import ( 6 | "context" 7 | "os" 8 | "os/exec" 9 | "strings" 10 | "unsafe" 11 | 12 | "golang.org/x/sys/unix" 13 | ) 14 | 15 | func DoSysctrlWithContext(ctx context.Context, mib string) ([]string, error) { 16 | sysctl, err := exec.LookPath("sysctl") 17 | if err != nil { 18 | return []string{}, err 19 | } 20 | cmd := exec.CommandContext(ctx, sysctl, "-n", mib) 21 | cmd.Env = getSysctrlEnv(os.Environ()) 22 | out, err := cmd.Output() 23 | if err != nil { 24 | return []string{}, err 25 | } 26 | v := strings.Replace(string(out), "{ ", "", 1) 27 | v = strings.Replace(string(v), " }", "", 1) 28 | values := strings.Fields(string(v)) 29 | 30 | return values, nil 31 | } 32 | 33 | func CallSyscall(mib []int32) ([]byte, uint64, error) { 34 | miblen := uint64(len(mib)) 35 | 36 | // get required buffer size 37 | length := uint64(0) 38 | _, _, err := unix.Syscall6( 39 | 202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146 40 | uintptr(unsafe.Pointer(&mib[0])), 41 | uintptr(miblen), 42 | 0, 43 | uintptr(unsafe.Pointer(&length)), 44 | 0, 45 | 0) 46 | if err != 0 { 47 | var b []byte 48 | return b, length, err 49 | } 50 | if length == 0 { 51 | var b []byte 52 | return b, length, err 53 | } 54 | // get proc info itself 55 | buf := make([]byte, length) 56 | _, _, err = unix.Syscall6( 57 | 202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146 58 | uintptr(unsafe.Pointer(&mib[0])), 59 | uintptr(miblen), 60 | uintptr(unsafe.Pointer(&buf[0])), 61 | uintptr(unsafe.Pointer(&length)), 62 | 0, 63 | 0) 64 | if err != 0 { 65 | return buf, length, err 66 | } 67 | 68 | return buf, length, nil 69 | } 70 | -------------------------------------------------------------------------------- /cmd/ss/summary.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/Asphaltt/go-iproute2/ss" 7 | ) 8 | 9 | func showSummary() { 10 | var s ss.Summary 11 | if err := s.GetSockStat(); err != nil { 12 | fmt.Println("failed to get sock stat, err:", err) 13 | return 14 | } 15 | if err := s.GetSockStat6(); err != nil { 16 | fmt.Println("failed to get sock6 stat, err:", err) 17 | return 18 | } 19 | if err := s.GetTcpEstablished(); err != nil { 20 | fmt.Println("failed to get number of established tcp connections, err:", err) 21 | return 22 | } 23 | printSummary(&s) 24 | } 25 | 26 | /* 27 | * summary example: 28 | * 29 | * Total: 182 30 | * TCP: 16 (estab 3, closed 1, orphaned 0, synrecv 0, timewait 0/0), ports 0 31 | * 32 | * Transport Total IP IPv6 33 | * RAW 0 0 0 34 | * UDP 11 8 3 35 | * TCP 15 12 3 36 | * INET 26 20 6 37 | * FRAG 0 0 0 38 | * 39 | */ 40 | func printSummary(s *ss.Summary) { 41 | fmt.Printf("Total: %d\n", s.Sockets) 42 | fmt.Printf("TCP: %d (estab %d, closed %d, orphaned %d, timewait %d)\n", 43 | s.TcpTotal+s.TcpTws, s.TcpEstablished, 44 | s.TcpTotal-(s.Tcp4Hashed+s.Tcp6Hashed-s.TcpTws), 45 | s.TcpOrphans, s.TcpTws) 46 | fmt.Println() 47 | 48 | fmt.Println("Transport Total IP IPv6") 49 | fmt.Printf("RAW %-9d %-9d %-9d\n", s.Raw4+s.Raw6, s.Raw4, s.Raw6) 50 | fmt.Printf("UDP %-9d %-9d %-9d\n", s.Udp4+s.Udp6, s.Udp4, s.Udp6) 51 | fmt.Printf("TCP %-9d %-9d %-9d\n", 52 | s.Tcp4Hashed+s.Tcp6Hashed, s.Tcp4Hashed, s.Tcp6Hashed) 53 | fmt.Printf("INET %-9d %-9d %-9d\n", 54 | s.Raw4+s.Udp4+s.Tcp4Hashed+s.Raw6+s.Udp6+s.Tcp6Hashed, 55 | s.Raw4+s.Udp4+s.Tcp4Hashed, 56 | s.Raw6+s.Udp6+s.Tcp6Hashed) 57 | fmt.Printf("FRAG %-9d %-9d %-9d\n", s.Frag4+s.Frag6, s.Frag4, s.Frag6) 58 | fmt.Println() 59 | } 60 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_darwin.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | 3 | package load 4 | 5 | import ( 6 | "context" 7 | "os/exec" 8 | "strings" 9 | "unsafe" 10 | 11 | "golang.org/x/sys/unix" 12 | ) 13 | 14 | func Avg() (*AvgStat, error) { 15 | return AvgWithContext(context.Background()) 16 | } 17 | 18 | func AvgWithContext(ctx context.Context) (*AvgStat, error) { 19 | // This SysctlRaw method borrowed from 20 | // https://github.com/prometheus/node_exporter/blob/master/collector/loadavg_freebsd.go 21 | // this implementation is common with BSDs 22 | type loadavg struct { 23 | load [3]uint32 24 | scale int 25 | } 26 | b, err := unix.SysctlRaw("vm.loadavg") 27 | if err != nil { 28 | return nil, err 29 | } 30 | load := *(*loadavg)(unsafe.Pointer((&b[0]))) 31 | scale := float64(load.scale) 32 | ret := &AvgStat{ 33 | Load1: float64(load.load[0]) / scale, 34 | Load5: float64(load.load[1]) / scale, 35 | Load15: float64(load.load[2]) / scale, 36 | } 37 | 38 | return ret, nil 39 | } 40 | 41 | // Misc returnes miscellaneous host-wide statistics. 42 | // darwin use ps command to get process running/blocked count. 43 | // Almost same as FreeBSD implementation, but state is different. 44 | // U means 'Uninterruptible Sleep'. 45 | func Misc() (*MiscStat, error) { 46 | return MiscWithContext(context.Background()) 47 | } 48 | 49 | func MiscWithContext(ctx context.Context) (*MiscStat, error) { 50 | bin, err := exec.LookPath("ps") 51 | if err != nil { 52 | return nil, err 53 | } 54 | out, err := invoke.CommandWithContext(ctx, bin, "axo", "state") 55 | if err != nil { 56 | return nil, err 57 | } 58 | lines := strings.Split(string(out), "\n") 59 | 60 | ret := MiscStat{} 61 | for _, l := range lines { 62 | if strings.Contains(l, "R") { 63 | ret.ProcsRunning++ 64 | } else if strings.Contains(l, "U") { 65 | // uninterruptible sleep == blocked 66 | ret.ProcsBlocked++ 67 | } 68 | } 69 | 70 | return &ret, nil 71 | } 72 | -------------------------------------------------------------------------------- /pkg/gopsutil/docker/docker_linux_test.go: -------------------------------------------------------------------------------- 1 | // +build linux 2 | 3 | package docker 4 | 5 | import "testing" 6 | 7 | func TestGetDockerIDList(t *testing.T) { 8 | // If there is not docker environment, this test always fail. 9 | // not tested here 10 | /* 11 | _, err := GetDockerIDList() 12 | if err != nil { 13 | t.Errorf("error %v", err) 14 | } 15 | */ 16 | } 17 | 18 | func TestGetDockerStat(t *testing.T) { 19 | // If there is not docker environment, this test always fail. 20 | // not tested here 21 | 22 | /* 23 | ret, err := GetDockerStat() 24 | if err != nil { 25 | t.Errorf("error %v", err) 26 | } 27 | if len(ret) == 0 { 28 | t.Errorf("ret is empty") 29 | } 30 | empty := CgroupDockerStat{} 31 | for _, v := range ret { 32 | if empty == v { 33 | t.Errorf("empty CgroupDockerStat") 34 | } 35 | if v.ContainerID == "" { 36 | t.Errorf("Could not get container id") 37 | } 38 | } 39 | */ 40 | } 41 | 42 | func TestCgroupCPU(t *testing.T) { 43 | v, _ := GetDockerIDList() 44 | for _, id := range v { 45 | v, err := CgroupCPUDocker(id) 46 | if err != nil { 47 | t.Errorf("error %v", err) 48 | } 49 | if v.CPU == "" { 50 | t.Errorf("could not get CgroupCPU %v", v) 51 | } 52 | 53 | } 54 | } 55 | 56 | func TestCgroupCPUInvalidId(t *testing.T) { 57 | _, err := CgroupCPUDocker("bad id") 58 | if err == nil { 59 | t.Error("Expected path does not exist error") 60 | } 61 | } 62 | 63 | func TestCgroupMem(t *testing.T) { 64 | v, _ := GetDockerIDList() 65 | for _, id := range v { 66 | v, err := CgroupMemDocker(id) 67 | if err != nil { 68 | t.Errorf("error %v", err) 69 | } 70 | empty := &CgroupMemStat{} 71 | if v == empty { 72 | t.Errorf("Could not CgroupMemStat %v", v) 73 | } 74 | } 75 | } 76 | 77 | func TestCgroupMemInvalidId(t *testing.T) { 78 | _, err := CgroupMemDocker("bad id") 79 | if err == nil { 80 | t.Error("Expected path does not exist error") 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_bsd.go: -------------------------------------------------------------------------------- 1 | // +build freebsd openbsd 2 | 3 | package load 4 | 5 | import ( 6 | "context" 7 | "os/exec" 8 | "strings" 9 | "unsafe" 10 | 11 | "golang.org/x/sys/unix" 12 | ) 13 | 14 | func Avg() (*AvgStat, error) { 15 | return AvgWithContext(context.Background()) 16 | } 17 | 18 | func AvgWithContext(ctx context.Context) (*AvgStat, error) { 19 | // This SysctlRaw method borrowed from 20 | // https://github.com/prometheus/node_exporter/blob/master/collector/loadavg_freebsd.go 21 | type loadavg struct { 22 | load [3]uint32 23 | scale int 24 | } 25 | b, err := unix.SysctlRaw("vm.loadavg") 26 | if err != nil { 27 | return nil, err 28 | } 29 | load := *(*loadavg)(unsafe.Pointer((&b[0]))) 30 | scale := float64(load.scale) 31 | ret := &AvgStat{ 32 | Load1: float64(load.load[0]) / scale, 33 | Load5: float64(load.load[1]) / scale, 34 | Load15: float64(load.load[2]) / scale, 35 | } 36 | 37 | return ret, nil 38 | } 39 | 40 | type forkstat struct { 41 | forks int 42 | vforks int 43 | __tforks int 44 | } 45 | 46 | // Misc returns miscellaneous host-wide statistics. 47 | // darwin use ps command to get process running/blocked count. 48 | // Almost same as Darwin implementation, but state is different. 49 | func Misc() (*MiscStat, error) { 50 | return MiscWithContext(context.Background()) 51 | } 52 | 53 | func MiscWithContext(ctx context.Context) (*MiscStat, error) { 54 | bin, err := exec.LookPath("ps") 55 | if err != nil { 56 | return nil, err 57 | } 58 | out, err := invoke.CommandWithContext(ctx, bin, "axo", "state") 59 | if err != nil { 60 | return nil, err 61 | } 62 | lines := strings.Split(string(out), "\n") 63 | 64 | ret := MiscStat{} 65 | for _, l := range lines { 66 | if strings.Contains(l, "R") { 67 | ret.ProcsRunning++ 68 | } else if strings.Contains(l, "D") { 69 | ret.ProcsBlocked++ 70 | } 71 | } 72 | 73 | f, err := getForkStat() 74 | if err != nil { 75 | return nil, err 76 | } 77 | ret.ProcsCreated = f.forks 78 | 79 | return &ret, nil 80 | } 81 | -------------------------------------------------------------------------------- /pkg/gopsutil/internal/common/common_freebsd.go: -------------------------------------------------------------------------------- 1 | // +build freebsd openbsd 2 | 3 | package common 4 | 5 | import ( 6 | "fmt" 7 | "os" 8 | "os/exec" 9 | "strings" 10 | "unsafe" 11 | 12 | "golang.org/x/sys/unix" 13 | ) 14 | 15 | func SysctlUint(mib string) (uint64, error) { 16 | buf, err := unix.SysctlRaw(mib) 17 | if err != nil { 18 | return 0, err 19 | } 20 | if len(buf) == 8 { // 64 bit 21 | return *(*uint64)(unsafe.Pointer(&buf[0])), nil 22 | } 23 | if len(buf) == 4 { // 32bit 24 | t := *(*uint32)(unsafe.Pointer(&buf[0])) 25 | return uint64(t), nil 26 | } 27 | return 0, fmt.Errorf("unexpected size: %s, %d", mib, len(buf)) 28 | } 29 | 30 | func DoSysctrl(mib string) ([]string, error) { 31 | sysctl, err := exec.LookPath("sysctl") 32 | if err != nil { 33 | return []string{}, err 34 | } 35 | cmd := exec.Command(sysctl, "-n", mib) 36 | cmd.Env = getSysctrlEnv(os.Environ()) 37 | out, err := cmd.Output() 38 | if err != nil { 39 | return []string{}, err 40 | } 41 | v := strings.Replace(string(out), "{ ", "", 1) 42 | v = strings.Replace(string(v), " }", "", 1) 43 | values := strings.Fields(string(v)) 44 | 45 | return values, nil 46 | } 47 | 48 | func CallSyscall(mib []int32) ([]byte, uint64, error) { 49 | mibptr := unsafe.Pointer(&mib[0]) 50 | miblen := uint64(len(mib)) 51 | 52 | // get required buffer size 53 | length := uint64(0) 54 | _, _, err := unix.Syscall6( 55 | unix.SYS___SYSCTL, 56 | uintptr(mibptr), 57 | uintptr(miblen), 58 | 0, 59 | uintptr(unsafe.Pointer(&length)), 60 | 0, 61 | 0) 62 | if err != 0 { 63 | var b []byte 64 | return b, length, err 65 | } 66 | if length == 0 { 67 | var b []byte 68 | return b, length, err 69 | } 70 | // get proc info itself 71 | buf := make([]byte, length) 72 | _, _, err = unix.Syscall6( 73 | unix.SYS___SYSCTL, 74 | uintptr(mibptr), 75 | uintptr(miblen), 76 | uintptr(unsafe.Pointer(&buf[0])), 77 | uintptr(unsafe.Pointer(&length)), 78 | 0, 79 | 0) 80 | if err != 0 { 81 | return buf, length, err 82 | } 83 | 84 | return buf, length, nil 85 | } 86 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/freebsd/1cpu_4core.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 1992-2016 The FreeBSD Project. 2 | Copyright (c) 1979, 1980, 1983, 1986, 1988, 1989, 1991, 1992, 1993, 1994 3 | The Regents of the University of California. All rights reserved. 4 | FreeBSD is a registered trademark of The FreeBSD Foundation. 5 | FreeBSD 10.3-RELEASE-p4 #0: Sat May 28 12:23:44 UTC 2016 6 | root@amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC amd64 7 | FreeBSD clang version 3.4.1 (tags/RELEASE_34/dot1-final 208032) 20140512 8 | CPU: Intel(R) Xeon(R) CPU E5-1620 v2 @ 3.70GHz (3700.09-MHz K8-class CPU) 9 | Origin="GenuineIntel" Id=0x306e4 Family=0x6 Model=0x3e Stepping=4 10 | Features=0xbfebfbff 11 | Features2=0x7fbee3ff 12 | AMD Features=0x2c100800 13 | AMD Features2=0x1 14 | Structured Extended Features=0x281 15 | XSAVE Features=0x1 16 | VT-x: PAT,HLT,MTF,PAUSE,EPT,UG,VPID,VID,PostIntr 17 | TSC: P-state invariant, performance statistics 18 | real memory = 34368126976 (32776 MB) 19 | avail memory = 33228333056 (31689 MB) 20 | Event timer "LAPIC" quality 600 21 | ACPI APIC Table: < > 22 | FreeBSD/SMP: Multiprocessor System Detected: 8 CPUs 23 | FreeBSD/SMP: 1 package(s) x 4 core(s) x 2 SMT threads 24 | cpu0 (BSP): APIC ID: 0 25 | cpu1 (AP): APIC ID: 1 26 | cpu2 (AP): APIC ID: 2 27 | cpu3 (AP): APIC ID: 3 28 | cpu4 (AP): APIC ID: 4 29 | cpu5 (AP): APIC ID: 5 30 | cpu6 (AP): APIC ID: 6 31 | cpu7 (AP): APIC ID: 7 32 | random: initialized 33 | ioapic0 irqs 0-23 on motherboard 34 | ioapic1 irqs 24-47 on motherboard 35 | kbd1 at kbdmux0 36 | cryptosoft0: on motherboard 37 | aesni0: on motherboard 38 | acpi0: on motherboard -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/freebsd/2cpu_4core.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 1992-2011 The FreeBSD Project. 2 | Copyright (c) 1979, 1980, 1983, 1986, 1988, 1989, 1991, 1992, 1993, 1994 3 | The Regents of the University of California. All rights reserved. 4 | FreeBSD is a registered trademark of The FreeBSD Foundation. 5 | FreeBSD 8.2-RELEASE #1: Sat Mar 5 23:03:14 CET 2011 6 | root@host1:/usr/obj/usr/src/sys/MYKERNEL amd64 7 | Timecounter "i8254" frequency 1193182 Hz quality 0 8 | CPU: Intel(R) Xeon(R) CPU E5420 @ 2.50GHz (2500.11-MHz K8-class CPU) 9 | Origin = "GenuineIntel" Id = 0x10676 Family = 6 Model = 17 Stepping = 6 10 | Features=0xbfebfbff 11 | Features2=0xce3bd 12 | AMD Features=0x20100800 13 | AMD Features2=0x1 14 | TSC: P-state invariant 15 | real memory = 17179869184 (16384 MB) 16 | avail memory = 16531587072 (15765 MB) 17 | ACPI APIC Table: 18 | FreeBSD/SMP: Multiprocessor System Detected: 8 CPUs 19 | FreeBSD/SMP: 2 package(s) x 4 core(s) 20 | cpu0 (BSP): APIC ID: 0 21 | cpu1 (AP): APIC ID: 1 22 | cpu2 (AP): APIC ID: 2 23 | cpu3 (AP): APIC ID: 3 24 | cpu4 (AP): APIC ID: 4 25 | cpu5 (AP): APIC ID: 5 26 | cpu6 (AP): APIC ID: 6 27 | cpu7 (AP): APIC ID: 7 28 | ioapic0 irqs 0-23 on motherboard 29 | ioapic1 irqs 24-47 on motherboard 30 | kbd1 at kbdmux0 31 | acpi0: on motherboard 32 | acpi0: [ITHREAD] 33 | acpi0: Power Button (fixed) 34 | unknown: I/O range not supported 35 | Timecounter "ACPI-fast" frequency 3579545 Hz quality 1000 36 | acpi_timer0: <24-bit timer at 3.579545MHz> port 0x1008-0x100b on acpi0 37 | cpu0: on acpi0 38 | cpu1: on acpi0 39 | cpu2: on acpi0 40 | cpu3: on acpi0 41 | cpu4: on acpi0 42 | cpu5: on acpi0 43 | cpu6: on acpi0 44 | cpu7: on acpi0 45 | pcib0: port 0xcf8-0xcff on acpi0 -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk_darwin.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | 3 | package disk 4 | 5 | import ( 6 | "context" 7 | 8 | "github.com/shirou/gopsutil/internal/common" 9 | "golang.org/x/sys/unix" 10 | ) 11 | 12 | // PartitionsWithContext returns disk partition. 13 | // 'all' argument is ignored, see: https://github.com/giampaolo/psutil/issues/906 14 | func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { 15 | var ret []PartitionStat 16 | 17 | count, err := unix.Getfsstat(nil, unix.MNT_WAIT) 18 | if err != nil { 19 | return ret, err 20 | } 21 | fs := make([]unix.Statfs_t, count) 22 | if _, err = unix.Getfsstat(fs, unix.MNT_WAIT); err != nil { 23 | return ret, err 24 | } 25 | for _, stat := range fs { 26 | opts := "rw" 27 | if stat.Flags&unix.MNT_RDONLY != 0 { 28 | opts = "ro" 29 | } 30 | if stat.Flags&unix.MNT_SYNCHRONOUS != 0 { 31 | opts += ",sync" 32 | } 33 | if stat.Flags&unix.MNT_NOEXEC != 0 { 34 | opts += ",noexec" 35 | } 36 | if stat.Flags&unix.MNT_NOSUID != 0 { 37 | opts += ",nosuid" 38 | } 39 | if stat.Flags&unix.MNT_UNION != 0 { 40 | opts += ",union" 41 | } 42 | if stat.Flags&unix.MNT_ASYNC != 0 { 43 | opts += ",async" 44 | } 45 | if stat.Flags&unix.MNT_DONTBROWSE != 0 { 46 | opts += ",nobrowse" 47 | } 48 | if stat.Flags&unix.MNT_AUTOMOUNTED != 0 { 49 | opts += ",automounted" 50 | } 51 | if stat.Flags&unix.MNT_JOURNALED != 0 { 52 | opts += ",journaled" 53 | } 54 | if stat.Flags&unix.MNT_MULTILABEL != 0 { 55 | opts += ",multilabel" 56 | } 57 | if stat.Flags&unix.MNT_NOATIME != 0 { 58 | opts += ",noatime" 59 | } 60 | if stat.Flags&unix.MNT_NODEV != 0 { 61 | opts += ",nodev" 62 | } 63 | d := PartitionStat{ 64 | Device: common.ByteToString(stat.Mntfromname[:]), 65 | Mountpoint: common.ByteToString(stat.Mntonname[:]), 66 | Fstype: common.ByteToString(stat.Fstypename[:]), 67 | Opts: opts, 68 | } 69 | 70 | ret = append(ret, d) 71 | } 72 | 73 | return ret, nil 74 | } 75 | 76 | func getFsType(stat unix.Statfs_t) string { 77 | return common.ByteToString(stat.Fstypename[:]) 78 | } 79 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_test.go: -------------------------------------------------------------------------------- 1 | package load 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "testing" 7 | 8 | "github.com/shirou/gopsutil/internal/common" 9 | ) 10 | 11 | func skipIfNotImplementedErr(t testing.TB, err error) { 12 | if errors.Is(err, common.ErrNotImplementedError) { 13 | t.Skip("not implemented") 14 | } 15 | } 16 | 17 | func TestLoad(t *testing.T) { 18 | v, err := Avg() 19 | skipIfNotImplementedErr(t, err) 20 | if err != nil { 21 | t.Errorf("error %v", err) 22 | } 23 | 24 | empty := &AvgStat{} 25 | if v == empty { 26 | t.Errorf("error load: %v", v) 27 | } 28 | t.Log(v) 29 | } 30 | 31 | func TestLoadAvgStat_String(t *testing.T) { 32 | v := AvgStat{ 33 | Load1: 10.1, 34 | Load5: 20.1, 35 | Load15: 30.1, 36 | } 37 | e := `{"load1":10.1,"load5":20.1,"load15":30.1}` 38 | if e != fmt.Sprintf("%v", v) { 39 | t.Errorf("LoadAvgStat string is invalid: %v", v) 40 | } 41 | t.Log(e) 42 | } 43 | 44 | func TestMisc(t *testing.T) { 45 | v, err := Misc() 46 | skipIfNotImplementedErr(t, err) 47 | if err != nil { 48 | t.Errorf("error %v", err) 49 | } 50 | 51 | empty := &MiscStat{} 52 | if v == empty { 53 | t.Errorf("error load: %v", v) 54 | } 55 | t.Log(v) 56 | } 57 | 58 | func TestMiscStatString(t *testing.T) { 59 | v := MiscStat{ 60 | ProcsTotal: 4, 61 | ProcsCreated: 5, 62 | ProcsRunning: 1, 63 | ProcsBlocked: 2, 64 | Ctxt: 3, 65 | } 66 | e := `{"procsTotal":4,"procsCreated":5,"procsRunning":1,"procsBlocked":2,"ctxt":3}` 67 | if e != fmt.Sprintf("%v", v) { 68 | t.Errorf("TestMiscString string is invalid: %v", v) 69 | } 70 | t.Log(e) 71 | } 72 | 73 | func BenchmarkLoad(b *testing.B) { 74 | loadAvg := func(t testing.TB) { 75 | v, err := Avg() 76 | skipIfNotImplementedErr(t, err) 77 | if err != nil { 78 | t.Errorf("error %v", err) 79 | } 80 | empty := &AvgStat{} 81 | if v == empty { 82 | t.Errorf("error load: %v", v) 83 | } 84 | } 85 | 86 | b.Run("FirstCall", func(b *testing.B) { 87 | loadAvg(b) 88 | }) 89 | 90 | b.Run("SubsequentCalls", func(b *testing.B) { 91 | for i := 0; i < b.N; i++ { 92 | loadAvg(b) 93 | } 94 | }) 95 | } 96 | -------------------------------------------------------------------------------- /ip/neighbour.go: -------------------------------------------------------------------------------- 1 | package ip 2 | 3 | import ( 4 | "net" 5 | "syscall" 6 | "unsafe" 7 | 8 | "github.com/Asphaltt/go-iproute2" 9 | "github.com/mdlayher/netlink" 10 | ) 11 | 12 | // A NeighEntry contains information for the arp records from kernel. 13 | type NeighEntry struct { 14 | Ifindex int 15 | Addr net.IP 16 | Lladdr net.HardwareAddr 17 | State iproute2.NudState 18 | } 19 | 20 | // ListNeighbours dumps arp table from kernel. 21 | // Firstly, send a getting neighbour request, and receive all netlink 22 | // response messages. Secondly, parse neighbour information from every 23 | // netlink response messages one by one. 24 | func (c *Client) ListNeighbours() ([]*NeighEntry, error) { 25 | var ndmsg iproute2.NdMsg 26 | ndmsg.Family = syscall.AF_UNSPEC 27 | // ndmsg.State = uint16(0xFF & ^iproute2.NudNoArp) 28 | 29 | var msg netlink.Message 30 | msg.Header.Type = iproute2.RTM_GETNEIGH 31 | msg.Header.Flags = netlink.Dump | netlink.Request 32 | msg.Data, _ = ndmsg.MarshalBinary() 33 | 34 | msgs, err := c.conn.Execute(msg) 35 | if err != nil { 36 | return nil, err 37 | } 38 | 39 | entries := make([]*NeighEntry, 0, len(msgs)) 40 | for _, msg := range msgs { 41 | if msg.Header.Type != iproute2.RTM_NEWNEIGH { 42 | continue 43 | } 44 | if msg.Header.Length < uint32(iproute2.SizeofNdMsg) { 45 | continue 46 | } 47 | 48 | ndmsg := (*iproute2.NdMsg)(unsafe.Pointer(&msg.Data[0])) 49 | if ndmsg.Family != syscall.AF_INET && 50 | ndmsg.Family != syscall.AF_INET6 { 51 | continue 52 | } 53 | 54 | ad, err := netlink.NewAttributeDecoder(msg.Data[iproute2.SizeofNdMsg:]) 55 | if err != nil { 56 | return entries, err 57 | } 58 | 59 | var e NeighEntry 60 | e.Ifindex = int(ndmsg.Ifindex) 61 | e.State = iproute2.NudState(ndmsg.State) 62 | 63 | for ad.Next() { 64 | switch iproute2.NdAttrType(ad.Type()) { 65 | case iproute2.NdaDst: 66 | e.Addr = net.IP(ad.Bytes()) 67 | case iproute2.NdaLladdr: 68 | e.Lladdr = net.HardwareAddr(ad.Bytes()) 69 | } 70 | } 71 | if err := ad.Err(); err != nil { 72 | return entries, err 73 | } 74 | 75 | entries = append(entries, &e) 76 | } 77 | return entries, nil 78 | } 79 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_darwin_nocgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin,!cgo 2 | 3 | package mem 4 | 5 | import ( 6 | "context" 7 | "os/exec" 8 | "strconv" 9 | "strings" 10 | 11 | "golang.org/x/sys/unix" 12 | ) 13 | 14 | // Runs vm_stat and returns Free and inactive pages 15 | func getVMStat(vms *VirtualMemoryStat) error { 16 | vm_stat, err := exec.LookPath("vm_stat") 17 | if err != nil { 18 | return err 19 | } 20 | out, err := invoke.Command(vm_stat) 21 | if err != nil { 22 | return err 23 | } 24 | return parseVMStat(string(out), vms) 25 | } 26 | 27 | func parseVMStat(out string, vms *VirtualMemoryStat) error { 28 | var err error 29 | 30 | lines := strings.Split(out, "\n") 31 | pagesize := uint64(unix.Getpagesize()) 32 | for _, line := range lines { 33 | fields := strings.Split(line, ":") 34 | if len(fields) < 2 { 35 | continue 36 | } 37 | key := strings.TrimSpace(fields[0]) 38 | value := strings.Trim(fields[1], " .") 39 | switch key { 40 | case "Pages free": 41 | free, e := strconv.ParseUint(value, 10, 64) 42 | if e != nil { 43 | err = e 44 | } 45 | vms.Free = free * pagesize 46 | case "Pages inactive": 47 | inactive, e := strconv.ParseUint(value, 10, 64) 48 | if e != nil { 49 | err = e 50 | } 51 | vms.Inactive = inactive * pagesize 52 | case "Pages active": 53 | active, e := strconv.ParseUint(value, 10, 64) 54 | if e != nil { 55 | err = e 56 | } 57 | vms.Active = active * pagesize 58 | case "Pages wired down": 59 | wired, e := strconv.ParseUint(value, 10, 64) 60 | if e != nil { 61 | err = e 62 | } 63 | vms.Wired = wired * pagesize 64 | } 65 | } 66 | return err 67 | } 68 | 69 | // VirtualMemory returns VirtualmemoryStat. 70 | func VirtualMemory() (*VirtualMemoryStat, error) { 71 | return VirtualMemoryWithContext(context.Background()) 72 | } 73 | 74 | func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { 75 | ret := &VirtualMemoryStat{} 76 | 77 | total, err := getHwMemsize() 78 | if err != nil { 79 | return nil, err 80 | } 81 | err = getVMStat(ret) 82 | if err != nil { 83 | return nil, err 84 | } 85 | 86 | ret.Available = ret.Free + ret.Inactive 87 | ret.Total = total 88 | 89 | ret.Used = ret.Total - ret.Available 90 | ret.UsedPercent = 100 * float64(ret.Used) / float64(ret.Total) 91 | 92 | return ret, nil 93 | } 94 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/process_windows_amd64.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package process 4 | 5 | import ( 6 | "syscall" 7 | "unsafe" 8 | 9 | "github.com/shirou/gopsutil/internal/common" 10 | "golang.org/x/sys/windows" 11 | ) 12 | 13 | type PROCESS_MEMORY_COUNTERS struct { 14 | CB uint32 15 | PageFaultCount uint32 16 | PeakWorkingSetSize uint64 17 | WorkingSetSize uint64 18 | QuotaPeakPagedPoolUsage uint64 19 | QuotaPagedPoolUsage uint64 20 | QuotaPeakNonPagedPoolUsage uint64 21 | QuotaNonPagedPoolUsage uint64 22 | PagefileUsage uint64 23 | PeakPagefileUsage uint64 24 | } 25 | 26 | func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { 27 | if is32BitProcess { 28 | //we are on a 64-bit process reading an external 32-bit process 29 | var wow64 uint 30 | 31 | ret, _, _ := common.ProcNtQueryInformationProcess.Call( 32 | uintptr(procHandle), 33 | uintptr(common.ProcessWow64Information), 34 | uintptr(unsafe.Pointer(&wow64)), 35 | uintptr(unsafe.Sizeof(wow64)), 36 | uintptr(0), 37 | ) 38 | if status := windows.NTStatus(ret); status == windows.STATUS_SUCCESS { 39 | return uint64(wow64), nil 40 | } else { 41 | return 0, windows.NTStatus(ret) 42 | } 43 | } else { 44 | //we are on a 64-bit process reading an external 64-bit process 45 | var info processBasicInformation64 46 | 47 | ret, _, _ := common.ProcNtQueryInformationProcess.Call( 48 | uintptr(procHandle), 49 | uintptr(common.ProcessBasicInformation), 50 | uintptr(unsafe.Pointer(&info)), 51 | uintptr(unsafe.Sizeof(info)), 52 | uintptr(0), 53 | ) 54 | if status := windows.NTStatus(ret); status == windows.STATUS_SUCCESS { 55 | return info.PebBaseAddress, nil 56 | } else { 57 | return 0, windows.NTStatus(ret) 58 | } 59 | } 60 | } 61 | 62 | func readProcessMemory(procHandle syscall.Handle, _ bool, address uint64, size uint) []byte { 63 | var read uint 64 | 65 | buffer := make([]byte, size) 66 | 67 | ret, _, _ := common.ProcNtReadVirtualMemory.Call( 68 | uintptr(procHandle), 69 | uintptr(address), 70 | uintptr(unsafe.Pointer(&buffer[0])), 71 | uintptr(size), 72 | uintptr(unsafe.Pointer(&read)), 73 | ) 74 | if int(ret) >= 0 && read > 0 { 75 | return buffer[:read] 76 | } 77 | return nil 78 | } 79 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/freebsd/1cpu_2core.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 1992-2016 The FreeBSD Project. 2 | Copyright (c) 1979, 1980, 1983, 1986, 1988, 1989, 1991, 1992, 1993, 1994 3 | The Regents of the University of California. All rights reserved. 4 | FreeBSD is a registered trademark of The FreeBSD Foundation. 5 | FreeBSD 11.0-RELEASE-p2 #0: Mon Oct 24 06:55:27 UTC 2016 6 | root@amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC amd64 7 | FreeBSD clang version 3.8.0 (tags/RELEASE_380/final 262564) (based on LLVM 3.8.0) 8 | VT(vga): resolution 640x480 9 | CPU: Intel(R) Core(TM) i3 CPU 550 @ 3.20GHz (3192.07-MHz K8-class CPU) 10 | Origin="GenuineIntel" Id=0x20655 Family=0x6 Model=0x25 Stepping=5 11 | Features=0xbfebfbff 12 | Features2=0x9ae3bd 13 | AMD Features=0x28100800 14 | AMD Features2=0x1 15 | VT-x: PAT,HLT,MTF,PAUSE,EPT,UG,VPID 16 | TSC: P-state invariant, performance statistics 17 | real memory = 8589934592 (8192 MB) 18 | avail memory = 8046452736 (7673 MB) 19 | Event timer "LAPIC" quality 600 20 | ACPI APIC Table: 21 | FreeBSD/SMP: Multiprocessor System Detected: 4 CPUs 22 | FreeBSD/SMP: 1 package(s) x 2 core(s) x 2 hardware threads 23 | random: unblocking device. 24 | ioapic0 irqs 0-23 on motherboard 25 | random: entropy device external interface 26 | kbd1 at kbdmux0 27 | netmap: loaded module 28 | module_register_init: MOD_LOAD (vesa, 0xffffffff8101c970, 0) error 19 29 | vtvga0: on motherboard 30 | cryptosoft0: on motherboard 31 | aesni0: No AESNI support. 32 | acpi0: on motherboard 33 | acpi0: Power Button (fixed) 34 | cpu0: on acpi0 35 | ACPI BIOS Warning (bug): Incorrect checksum in table [SSDT] - 0x3F, should be 0x1F (20160527/tbprint-229) 36 | cpu1: on acpi0 37 | cpu2: on acpi0 38 | cpu3: on acpi0 39 | attimer0: port 0x40-0x43 irq 0 on acpi0 40 | Timecounter "i8254" frequency 1193182 Hz quality 0 41 | Event timer "i8254" frequency 1193182 Hz quality 100 42 | atrtc0: port 0x70-0x71 irq 8 on acpi0 43 | Event timer "RTC" frequency 32768 Hz quality 0 -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/linux/424/proc/stat: -------------------------------------------------------------------------------- 1 | cpu 23644 6695 4764 134931750 22115 0 473 5892 0 0 2 | cpu0 6418 888 1230 33730755 5043 0 4 1046 0 0 3 | cpu1 6858 4870 1632 33716510 12327 0 235 1765 0 0 4 | cpu2 4859 622 915 33742072 2312 0 25 1546 0 0 5 | cpu3 5507 314 986 33742411 2432 0 208 1534 0 0 6 | intr 32552791 35 9 0 0 2335 0 3 0 2 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3107077 2985327 15704 0 6672 0 3218027 3063711 11558 0 6151 0 2160633 2194945 15838 0 6565 0 1595129 2134446 15337 0 5715 0 157 112837 717318 710764 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 | ctxt 41317767 8 | btime 1505515383 9 | processes 41562 10 | procs_running 1 11 | procs_blocked 0 12 | softirq 5433315 0 1644387 67542 1428221 0 0 12270 1573783 0 707112 -------------------------------------------------------------------------------- /pkg/gopsutil/docker/docker_notlinux.go: -------------------------------------------------------------------------------- 1 | // +build !linux 2 | 3 | package docker 4 | 5 | import ( 6 | "context" 7 | 8 | cpu "github.com/shirou/gopsutil/cpu" 9 | "github.com/shirou/gopsutil/internal/common" 10 | ) 11 | 12 | // GetDockerStat returns a list of Docker basic stats. 13 | // This requires certain permission. 14 | func GetDockerStat() ([]CgroupDockerStat, error) { 15 | return GetDockerStatWithContext(context.Background()) 16 | } 17 | 18 | func GetDockerStatWithContext(ctx context.Context) ([]CgroupDockerStat, error) { 19 | return nil, ErrDockerNotAvailable 20 | } 21 | 22 | // GetDockerIDList returnes a list of DockerID. 23 | // This requires certain permission. 24 | func GetDockerIDList() ([]string, error) { 25 | return GetDockerIDListWithContext(context.Background()) 26 | } 27 | 28 | func GetDockerIDListWithContext(ctx context.Context) ([]string, error) { 29 | return nil, ErrDockerNotAvailable 30 | } 31 | 32 | // CgroupCPU returnes specified cgroup id CPU status. 33 | // containerid is same as docker id if you use docker. 34 | // If you use container via systemd.slice, you could use 35 | // containerid = docker-.scope and base=/sys/fs/cgroup/cpuacct/system.slice/ 36 | func CgroupCPU(containerid string, base string) (*cpu.TimesStat, error) { 37 | return CgroupCPUWithContext(context.Background(), containerid, base) 38 | } 39 | 40 | func CgroupCPUWithContext(ctx context.Context, containerid string, base string) (*cpu.TimesStat, error) { 41 | return nil, ErrCgroupNotAvailable 42 | } 43 | 44 | func CgroupCPUDocker(containerid string) (*cpu.TimesStat, error) { 45 | return CgroupCPUDockerWithContext(context.Background(), containerid) 46 | } 47 | 48 | func CgroupCPUDockerWithContext(ctx context.Context, containerid string) (*cpu.TimesStat, error) { 49 | return CgroupCPU(containerid, common.HostSys("fs/cgroup/cpuacct/docker")) 50 | } 51 | 52 | func CgroupMem(containerid string, base string) (*CgroupMemStat, error) { 53 | return CgroupMemWithContext(context.Background(), containerid, base) 54 | } 55 | 56 | func CgroupMemWithContext(ctx context.Context, containerid string, base string) (*CgroupMemStat, error) { 57 | return nil, ErrCgroupNotAvailable 58 | } 59 | 60 | func CgroupMemDocker(containerid string) (*CgroupMemStat, error) { 61 | return CgroupMemDockerWithContext(context.Background(), containerid) 62 | } 63 | 64 | func CgroupMemDockerWithContext(ctx context.Context, containerid string) (*CgroupMemStat, error) { 65 | return CgroupMem(containerid, common.HostSys("fs/cgroup/memory/docker")) 66 | } 67 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/freebsd_headers/utxdb.h: -------------------------------------------------------------------------------- 1 | /*- 2 | * SPDX-License-Identifier: BSD-2-Clause-FreeBSD 3 | * 4 | * Copyright (c) 2010 Ed Schouten 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions 9 | * are met: 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 17 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 20 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 22 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 23 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 24 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 25 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 26 | * SUCH DAMAGE. 27 | * 28 | * $FreeBSD$ 29 | */ 30 | 31 | #ifndef _UTXDB_H_ 32 | #define _UTXDB_H_ 33 | 34 | #include 35 | 36 | #define _PATH_UTX_ACTIVE "/var/run/utx.active" 37 | #define _PATH_UTX_LASTLOGIN "/var/log/utx.lastlogin" 38 | #define _PATH_UTX_LOG "/var/log/utx.log" 39 | 40 | /* 41 | * Entries in struct futx are ordered by how often they are used. In 42 | * utx.log only entries will be written until the last non-zero byte, 43 | * which means we want to put the hostname at the end. Most primitive 44 | * records only store a ut_type and ut_tv, which means we want to store 45 | * those at the front. 46 | */ 47 | 48 | struct utmpx; 49 | 50 | struct futx { 51 | uint8_t fu_type; 52 | uint64_t fu_tv; 53 | char fu_id[8]; 54 | uint32_t fu_pid; 55 | char fu_user[32]; 56 | char fu_line[16]; 57 | char fu_host[128]; 58 | } __packed; 59 | 60 | void utx_to_futx(const struct utmpx *, struct futx *); 61 | struct utmpx *futx_to_utx(const struct futx *); 62 | 63 | #endif /* !_UTXDB_H_ */ 64 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/types_freebsd.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | 3 | // We still need editing by hands. 4 | // go tool cgo -godefs types_freebsd.go | sed 's/\*int64/int64/' | sed 's/\*byte/int64/' > process_freebsd_amd64.go 5 | 6 | /* 7 | Input to cgo -godefs. 8 | */ 9 | 10 | // +godefs map struct_pargs int64 /* pargs */ 11 | // +godefs map struct_proc int64 /* proc */ 12 | // +godefs map struct_user int64 /* user */ 13 | // +godefs map struct_vnode int64 /* vnode */ 14 | // +godefs map struct_vnode int64 /* vnode */ 15 | // +godefs map struct_filedesc int64 /* filedesc */ 16 | // +godefs map struct_vmspace int64 /* vmspace */ 17 | // +godefs map struct_pcb int64 /* pcb */ 18 | // +godefs map struct_thread int64 /* thread */ 19 | // +godefs map struct___sigset [16]byte /* sigset */ 20 | 21 | package process 22 | 23 | /* 24 | #include 25 | #include 26 | 27 | enum { 28 | sizeofPtr = sizeof(void*), 29 | }; 30 | 31 | 32 | */ 33 | import "C" 34 | 35 | // Machine characteristics; for internal use. 36 | 37 | const ( 38 | CTLKern = 1 // "high kernel": proc, limits 39 | KernProc = 14 // struct: process entries 40 | KernProcPID = 1 // by process id 41 | KernProcProc = 8 // only return procs 42 | KernProcPathname = 12 // path to executable 43 | KernProcArgs = 7 // get/set arguments/proctitle 44 | ) 45 | 46 | const ( 47 | sizeofPtr = C.sizeofPtr 48 | sizeofShort = C.sizeof_short 49 | sizeofInt = C.sizeof_int 50 | sizeofLong = C.sizeof_long 51 | sizeofLongLong = C.sizeof_longlong 52 | ) 53 | 54 | const ( 55 | sizeOfKinfoVmentry = C.sizeof_struct_kinfo_vmentry 56 | sizeOfKinfoProc = C.sizeof_struct_kinfo_proc 57 | ) 58 | 59 | // from sys/proc.h 60 | const ( 61 | SIDL = 1 /* Process being created by fork. */ 62 | SRUN = 2 /* Currently runnable. */ 63 | SSLEEP = 3 /* Sleeping on an address. */ 64 | SSTOP = 4 /* Process debugging or suspension. */ 65 | SZOMB = 5 /* Awaiting collection by parent. */ 66 | SWAIT = 6 /* Waiting for interrupt. */ 67 | SLOCK = 7 /* Blocked on a lock. */ 68 | ) 69 | 70 | // Basic types 71 | 72 | type ( 73 | _C_short C.short 74 | _C_int C.int 75 | _C_long C.long 76 | _C_long_long C.longlong 77 | ) 78 | 79 | // Time 80 | 81 | type Timespec C.struct_timespec 82 | 83 | type Timeval C.struct_timeval 84 | 85 | // Processes 86 | 87 | type Rusage C.struct_rusage 88 | 89 | type Rlimit C.struct_rlimit 90 | 91 | type KinfoProc C.struct_kinfo_proc 92 | 93 | type Priority C.struct_priority 94 | 95 | type KinfoVmentry C.struct_kinfo_vmentry 96 | -------------------------------------------------------------------------------- /cmd/ss/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | var config struct { 9 | summary bool 10 | process bool 11 | 12 | all bool 13 | v4, v6 bool 14 | listen bool 15 | tcp bool 16 | udp bool 17 | } 18 | 19 | func showAllSocket() { 20 | config.udp = true 21 | config.tcp = true 22 | config.v4 = true 23 | config.v6 = true 24 | config.listen = true 25 | } 26 | 27 | func isMixConfig() bool { 28 | isMix := func(predicts ...bool) bool { 29 | count := 0 30 | for _, p := range predicts { 31 | if !p { 32 | continue 33 | } 34 | 35 | count++ 36 | if count == 2 { 37 | return true 38 | } 39 | } 40 | return false 41 | } 42 | return isMix( 43 | config.tcp, 44 | config.udp, 45 | ) 46 | } 47 | 48 | func noSock() bool { 49 | notToListSockets := func(predicts ...bool) bool { 50 | for _, p := range predicts { 51 | if p { 52 | return false 53 | } 54 | } 55 | return true 56 | } 57 | return notToListSockets( 58 | config.tcp, 59 | config.udp, 60 | ) 61 | } 62 | 63 | func main() { 64 | config.v4 = true 65 | config.v6 = true 66 | 67 | for _, arg := range os.Args[1:] { 68 | if arg[0] != '-' { 69 | continue 70 | } 71 | 72 | for _, b := range arg[1:] { 73 | switch b { 74 | case 's': 75 | config.summary = true 76 | case 'a': 77 | config.all = true 78 | case '4': 79 | config.v4 = true 80 | config.v6 = false 81 | case '6': 82 | config.v4 = false 83 | config.v6 = true 84 | case 'l': 85 | config.listen = true 86 | case 't': 87 | config.tcp = true 88 | case 'u': 89 | config.udp = true 90 | case 'p': 91 | config.process = true 92 | } 93 | } 94 | } 95 | 96 | if config.process { 97 | if err := prepareProcs(); err != nil { 98 | log.Fatalf("failed to prepare process, err: %v", err) 99 | } 100 | } 101 | 102 | if config.summary { 103 | showSummary() 104 | } 105 | 106 | if config.all { 107 | showAllSocket() 108 | } 109 | if noSock() { 110 | if config.summary { 111 | return 112 | } 113 | 114 | // list all listening sockets 115 | config.tcp = true 116 | config.udp = true 117 | } 118 | 119 | c, err := dialNetlink() 120 | if err != nil { 121 | log.Fatalf("failed to create netlink socket, err: %v", err) 122 | } 123 | defer c.Close() 124 | 125 | c.showSocketInfoHeader() 126 | if config.udp { 127 | c.showUDP(config.listen, config.v4, config.v6) 128 | } 129 | if config.tcp { 130 | c.showTCP(config.listen, config.v4, config.v6) 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_windows.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | 3 | package load 4 | 5 | import ( 6 | "context" 7 | "log" 8 | "math" 9 | "sync" 10 | "time" 11 | 12 | "github.com/shirou/gopsutil/internal/common" 13 | ) 14 | 15 | var ( 16 | loadErr error 17 | loadAvg1M float64 = 0.0 18 | loadAvg5M float64 = 0.0 19 | loadAvg15M float64 = 0.0 20 | loadAvgMutex sync.RWMutex 21 | loadAvgGoroutineOnce sync.Once 22 | ) 23 | 24 | // loadAvgGoroutine updates avg data by fetching current load by interval 25 | // TODO instead of this goroutine, we can register a Win32 counter just as psutil does 26 | // see https://psutil.readthedocs.io/en/latest/#psutil.getloadavg 27 | // code https://github.com/giampaolo/psutil/blob/8415355c8badc9c94418b19bdf26e622f06f0cce/psutil/arch/windows/wmi.c 28 | func loadAvgGoroutine() { 29 | var ( 30 | samplingFrequency time.Duration = 5 * time.Second 31 | loadAvgFactor1M float64 = 1 / math.Exp(samplingFrequency.Seconds()/time.Minute.Seconds()) 32 | loadAvgFactor5M float64 = 1 / math.Exp(samplingFrequency.Seconds()/(5*time.Minute).Seconds()) 33 | loadAvgFactor15M float64 = 1 / math.Exp(samplingFrequency.Seconds()/(15*time.Minute).Seconds()) 34 | currentLoad float64 35 | ) 36 | 37 | counter, err := common.ProcessorQueueLengthCounter() 38 | if err != nil || counter == nil { 39 | log.Println("gopsutil: unexpected processor queue length counter error, please file an issue on github: err") 40 | return 41 | } 42 | 43 | tick := time.NewTicker(samplingFrequency).C 44 | for { 45 | currentLoad, err = counter.GetValue() 46 | loadAvgMutex.Lock() 47 | loadErr = err 48 | loadAvg1M = loadAvg1M*loadAvgFactor1M + currentLoad*(1-loadAvgFactor1M) 49 | loadAvg5M = loadAvg5M*loadAvgFactor5M + currentLoad*(1-loadAvgFactor5M) 50 | loadAvg15M = loadAvg15M*loadAvgFactor15M + currentLoad*(1-loadAvgFactor15M) 51 | loadAvgMutex.Unlock() 52 | <-tick 53 | } 54 | } 55 | 56 | // Avg for Windows may return 0 values for the first few 5 second intervals 57 | func Avg() (*AvgStat, error) { 58 | return AvgWithContext(context.Background()) 59 | } 60 | 61 | func AvgWithContext(ctx context.Context) (*AvgStat, error) { 62 | loadAvgGoroutineOnce.Do(func() { 63 | go loadAvgGoroutine() 64 | }) 65 | loadAvgMutex.RLock() 66 | defer loadAvgMutex.RUnlock() 67 | ret := AvgStat{ 68 | Load1: loadAvg1M, 69 | Load5: loadAvg5M, 70 | Load15: loadAvg15M, 71 | } 72 | 73 | return &ret, loadErr 74 | } 75 | 76 | func Misc() (*MiscStat, error) { 77 | return MiscWithContext(context.Background()) 78 | } 79 | 80 | func MiscWithContext(ctx context.Context) (*MiscStat, error) { 81 | ret := MiscStat{} 82 | 83 | return &ret, common.ErrNotImplementedError 84 | } 85 | -------------------------------------------------------------------------------- /pkg/gopsutil/host/host_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | 3 | package host 4 | 5 | import ( 6 | "bytes" 7 | "context" 8 | "encoding/binary" 9 | "io/ioutil" 10 | "os" 11 | "strings" 12 | "unsafe" 13 | 14 | "github.com/shirou/gopsutil/internal/common" 15 | "github.com/shirou/gopsutil/process" 16 | "golang.org/x/sys/unix" 17 | ) 18 | 19 | const ( 20 | UTNameSize = 32 /* see MAXLOGNAME in */ 21 | UTLineSize = 8 22 | UTHostSize = 16 23 | ) 24 | 25 | func HostIDWithContext(ctx context.Context) (string, error) { 26 | return "", common.ErrNotImplementedError 27 | } 28 | 29 | func numProcs(ctx context.Context) (uint64, error) { 30 | procs, err := process.PidsWithContext(ctx) 31 | if err != nil { 32 | return 0, err 33 | } 34 | return uint64(len(procs)), nil 35 | } 36 | 37 | func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) { 38 | platform := "" 39 | family := "" 40 | version := "" 41 | 42 | p, err := unix.Sysctl("kern.ostype") 43 | if err == nil { 44 | platform = strings.ToLower(p) 45 | } 46 | v, err := unix.Sysctl("kern.osrelease") 47 | if err == nil { 48 | version = strings.ToLower(v) 49 | } 50 | 51 | return platform, family, version, nil 52 | } 53 | 54 | func VirtualizationWithContext(ctx context.Context) (string, string, error) { 55 | return "", "", common.ErrNotImplementedError 56 | } 57 | 58 | func UsersWithContext(ctx context.Context) ([]UserStat, error) { 59 | var ret []UserStat 60 | utmpfile := "/var/run/utmp" 61 | file, err := os.Open(utmpfile) 62 | if err != nil { 63 | return ret, err 64 | } 65 | defer file.Close() 66 | 67 | buf, err := ioutil.ReadAll(file) 68 | if err != nil { 69 | return ret, err 70 | } 71 | 72 | u := Utmp{} 73 | entrySize := int(unsafe.Sizeof(u)) 74 | count := len(buf) / entrySize 75 | 76 | for i := 0; i < count; i++ { 77 | b := buf[i*entrySize : i*entrySize+entrySize] 78 | var u Utmp 79 | br := bytes.NewReader(b) 80 | err := binary.Read(br, binary.LittleEndian, &u) 81 | if err != nil || u.Time == 0 || u.Name[0] == 0 { 82 | continue 83 | } 84 | user := UserStat{ 85 | User: common.IntToString(u.Name[:]), 86 | Terminal: common.IntToString(u.Line[:]), 87 | Host: common.IntToString(u.Host[:]), 88 | Started: int(u.Time), 89 | } 90 | 91 | ret = append(ret, user) 92 | } 93 | 94 | return ret, nil 95 | } 96 | 97 | func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, error) { 98 | return []TemperatureStat{}, common.ErrNotImplementedError 99 | } 100 | 101 | func KernelVersionWithContext(ctx context.Context) (string, error) { 102 | _, _, version, err := PlatformInformationWithContext(ctx) 103 | return version, err 104 | } 105 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/process_bsd.go: -------------------------------------------------------------------------------- 1 | // +build darwin freebsd openbsd 2 | 3 | package process 4 | 5 | import ( 6 | "bytes" 7 | "context" 8 | "encoding/binary" 9 | 10 | "github.com/shirou/gopsutil/cpu" 11 | "github.com/shirou/gopsutil/internal/common" 12 | "github.com/shirou/gopsutil/net" 13 | ) 14 | 15 | type MemoryInfoExStat struct{} 16 | 17 | type MemoryMapsStat struct{} 18 | 19 | func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { 20 | return 0, common.ErrNotImplementedError 21 | } 22 | 23 | func (p *Process) CwdWithContext(ctx context.Context) (string, error) { 24 | return "", common.ErrNotImplementedError 25 | } 26 | 27 | func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { 28 | return 0, common.ErrNotImplementedError 29 | } 30 | 31 | func (p *Process) RlimitWithContext(ctx context.Context) ([]RlimitStat, error) { 32 | return nil, common.ErrNotImplementedError 33 | } 34 | 35 | func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ([]RlimitStat, error) { 36 | return nil, common.ErrNotImplementedError 37 | } 38 | 39 | func (p *Process) NumCtxSwitchesWithContext(ctx context.Context) (*NumCtxSwitchesStat, error) { 40 | return nil, common.ErrNotImplementedError 41 | } 42 | 43 | func (p *Process) NumFDsWithContext(ctx context.Context) (int32, error) { 44 | return 0, common.ErrNotImplementedError 45 | } 46 | 47 | func (p *Process) CPUAffinityWithContext(ctx context.Context) ([]int32, error) { 48 | return nil, common.ErrNotImplementedError 49 | } 50 | 51 | func (p *Process) MemoryInfoExWithContext(ctx context.Context) (*MemoryInfoExStat, error) { 52 | return nil, common.ErrNotImplementedError 53 | } 54 | 55 | func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, error) { 56 | return nil, common.ErrNotImplementedError 57 | } 58 | 59 | func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, error) { 60 | return nil, common.ErrNotImplementedError 61 | } 62 | 63 | func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { 64 | return nil, common.ErrNotImplementedError 65 | } 66 | 67 | func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { 68 | return nil, common.ErrNotImplementedError 69 | } 70 | 71 | func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { 72 | return nil, common.ErrNotImplementedError 73 | } 74 | 75 | func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { 76 | return nil, common.ErrNotImplementedError 77 | } 78 | 79 | func parseKinfoProc(buf []byte) (KinfoProc, error) { 80 | var k KinfoProc 81 | br := bytes.NewReader(buf) 82 | err := common.Read(br, binary.LittleEndian, &k) 83 | return k, err 84 | } 85 | -------------------------------------------------------------------------------- /pkg/gopsutil/docker/docker.go: -------------------------------------------------------------------------------- 1 | package docker 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | 7 | "github.com/shirou/gopsutil/cpu" 8 | "github.com/shirou/gopsutil/internal/common" 9 | ) 10 | 11 | var ErrDockerNotAvailable = errors.New("docker not available") 12 | var ErrCgroupNotAvailable = errors.New("cgroup not available") 13 | 14 | var invoke common.Invoker = common.Invoke{} 15 | 16 | const nanoseconds = 1e9 17 | 18 | type CgroupCPUStat struct { 19 | cpu.TimesStat 20 | Usage float64 21 | } 22 | 23 | type CgroupMemStat struct { 24 | ContainerID string `json:"containerID"` 25 | Cache uint64 `json:"cache"` 26 | RSS uint64 `json:"rss"` 27 | RSSHuge uint64 `json:"rssHuge"` 28 | MappedFile uint64 `json:"mappedFile"` 29 | Pgpgin uint64 `json:"pgpgin"` 30 | Pgpgout uint64 `json:"pgpgout"` 31 | Pgfault uint64 `json:"pgfault"` 32 | Pgmajfault uint64 `json:"pgmajfault"` 33 | InactiveAnon uint64 `json:"inactiveAnon"` 34 | ActiveAnon uint64 `json:"activeAnon"` 35 | InactiveFile uint64 `json:"inactiveFile"` 36 | ActiveFile uint64 `json:"activeFile"` 37 | Unevictable uint64 `json:"unevictable"` 38 | HierarchicalMemoryLimit uint64 `json:"hierarchicalMemoryLimit"` 39 | TotalCache uint64 `json:"totalCache"` 40 | TotalRSS uint64 `json:"totalRss"` 41 | TotalRSSHuge uint64 `json:"totalRssHuge"` 42 | TotalMappedFile uint64 `json:"totalMappedFile"` 43 | TotalPgpgIn uint64 `json:"totalPgpgin"` 44 | TotalPgpgOut uint64 `json:"totalPgpgout"` 45 | TotalPgFault uint64 `json:"totalPgfault"` 46 | TotalPgMajFault uint64 `json:"totalPgmajfault"` 47 | TotalInactiveAnon uint64 `json:"totalInactiveAnon"` 48 | TotalActiveAnon uint64 `json:"totalActiveAnon"` 49 | TotalInactiveFile uint64 `json:"totalInactiveFile"` 50 | TotalActiveFile uint64 `json:"totalActiveFile"` 51 | TotalUnevictable uint64 `json:"totalUnevictable"` 52 | MemUsageInBytes uint64 `json:"memUsageInBytes"` 53 | MemMaxUsageInBytes uint64 `json:"memMaxUsageInBytes"` 54 | MemLimitInBytes uint64 `json:"memoryLimitInBbytes"` 55 | MemFailCnt uint64 `json:"memoryFailcnt"` 56 | } 57 | 58 | func (m CgroupMemStat) String() string { 59 | s, _ := json.Marshal(m) 60 | return string(s) 61 | } 62 | 63 | type CgroupDockerStat struct { 64 | ContainerID string `json:"containerID"` 65 | Name string `json:"name"` 66 | Image string `json:"image"` 67 | Status string `json:"status"` 68 | Running bool `json:"running"` 69 | } 70 | 71 | func (c CgroupDockerStat) String() string { 72 | s, _ := json.Marshal(c) 73 | return string(s) 74 | } 75 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/types_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build ignore 2 | 3 | // We still need editing by hands. 4 | // go tool cgo -godefs types_openbsd.go | sed 's/\*int64/int64/' | sed 's/\*byte/int64/' > process_openbsd_amd64.go 5 | 6 | /* 7 | Input to cgo -godefs. 8 | */ 9 | 10 | // +godefs map struct_pargs int64 /* pargs */ 11 | // +godefs map struct_proc int64 /* proc */ 12 | // +godefs map struct_user int64 /* user */ 13 | // +godefs map struct_vnode int64 /* vnode */ 14 | // +godefs map struct_vnode int64 /* vnode */ 15 | // +godefs map struct_filedesc int64 /* filedesc */ 16 | // +godefs map struct_vmspace int64 /* vmspace */ 17 | // +godefs map struct_pcb int64 /* pcb */ 18 | // +godefs map struct_thread int64 /* thread */ 19 | // +godefs map struct___sigset [16]byte /* sigset */ 20 | 21 | package process 22 | 23 | /* 24 | #include 25 | #include 26 | #include 27 | 28 | enum { 29 | sizeofPtr = sizeof(void*), 30 | }; 31 | 32 | 33 | */ 34 | import "C" 35 | 36 | // Machine characteristics; for internal use. 37 | 38 | const ( 39 | CTLKern = 1 // "high kernel": proc, limits 40 | KernProc = 66 // struct: process entries 41 | KernProcAll = 0 42 | KernProcPID = 1 // by process id 43 | KernProcProc = 8 // only return procs 44 | KernProcPathname = 12 // path to executable 45 | KernProcArgs = 55 // get/set arguments/proctitle 46 | KernProcArgv = 1 47 | KernProcEnv = 3 48 | ) 49 | 50 | const ( 51 | ArgMax = 256 * 1024 // sys/syslimits.h:#define ARG_MAX 52 | ) 53 | 54 | const ( 55 | sizeofPtr = C.sizeofPtr 56 | sizeofShort = C.sizeof_short 57 | sizeofInt = C.sizeof_int 58 | sizeofLong = C.sizeof_long 59 | sizeofLongLong = C.sizeof_longlong 60 | ) 61 | 62 | const ( 63 | sizeOfKinfoVmentry = C.sizeof_struct_kinfo_vmentry 64 | sizeOfKinfoProc = C.sizeof_struct_kinfo_proc 65 | ) 66 | 67 | // from sys/proc.h 68 | const ( 69 | SIDL = 1 /* Process being created by fork. */ 70 | SRUN = 2 /* Currently runnable. */ 71 | SSLEEP = 3 /* Sleeping on an address. */ 72 | SSTOP = 4 /* Process debugging or suspension. */ 73 | SZOMB = 5 /* Awaiting collection by parent. */ 74 | SDEAD = 6 /* Thread is almost gone */ 75 | SONPROC = 7 /* Thread is currently on a CPU. */ 76 | ) 77 | 78 | // Basic types 79 | 80 | type ( 81 | _C_short C.short 82 | _C_int C.int 83 | _C_long C.long 84 | _C_long_long C.longlong 85 | ) 86 | 87 | // Time 88 | 89 | type Timespec C.struct_timespec 90 | 91 | type Timeval C.struct_timeval 92 | 93 | // Processes 94 | 95 | type Rusage C.struct_rusage 96 | 97 | type Rlimit C.struct_rlimit 98 | 99 | type KinfoProc C.struct_kinfo_proc 100 | 101 | type Priority C.struct_priority 102 | 103 | type KinfoVmentry C.struct_kinfo_vmentry 104 | -------------------------------------------------------------------------------- /pkg/gopsutil/disk/disk.go: -------------------------------------------------------------------------------- 1 | package disk 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | 7 | "github.com/shirou/gopsutil/internal/common" 8 | ) 9 | 10 | var invoke common.Invoker = common.Invoke{} 11 | 12 | type UsageStat struct { 13 | Path string `json:"path"` 14 | Fstype string `json:"fstype"` 15 | Total uint64 `json:"total"` 16 | Free uint64 `json:"free"` 17 | Used uint64 `json:"used"` 18 | UsedPercent float64 `json:"usedPercent"` 19 | InodesTotal uint64 `json:"inodesTotal"` 20 | InodesUsed uint64 `json:"inodesUsed"` 21 | InodesFree uint64 `json:"inodesFree"` 22 | InodesUsedPercent float64 `json:"inodesUsedPercent"` 23 | } 24 | 25 | type PartitionStat struct { 26 | Device string `json:"device"` 27 | Mountpoint string `json:"mountpoint"` 28 | Fstype string `json:"fstype"` 29 | Opts string `json:"opts"` 30 | } 31 | 32 | type IOCountersStat struct { 33 | ReadCount uint64 `json:"readCount"` 34 | MergedReadCount uint64 `json:"mergedReadCount"` 35 | WriteCount uint64 `json:"writeCount"` 36 | MergedWriteCount uint64 `json:"mergedWriteCount"` 37 | ReadBytes uint64 `json:"readBytes"` 38 | WriteBytes uint64 `json:"writeBytes"` 39 | ReadTime uint64 `json:"readTime"` 40 | WriteTime uint64 `json:"writeTime"` 41 | IopsInProgress uint64 `json:"iopsInProgress"` 42 | IoTime uint64 `json:"ioTime"` 43 | WeightedIO uint64 `json:"weightedIO"` 44 | Name string `json:"name"` 45 | SerialNumber string `json:"serialNumber"` 46 | Label string `json:"label"` 47 | } 48 | 49 | func (d UsageStat) String() string { 50 | s, _ := json.Marshal(d) 51 | return string(s) 52 | } 53 | 54 | func (d PartitionStat) String() string { 55 | s, _ := json.Marshal(d) 56 | return string(s) 57 | } 58 | 59 | func (d IOCountersStat) String() string { 60 | s, _ := json.Marshal(d) 61 | return string(s) 62 | } 63 | 64 | // Usage returns a file system usage. path is a filesystem path such 65 | // as "/", not device file path like "/dev/vda1". If you want to use 66 | // a return value of disk.Partitions, use "Mountpoint" not "Device". 67 | func Usage(path string) (*UsageStat, error) { 68 | return UsageWithContext(context.Background(), path) 69 | } 70 | 71 | // Partitions returns disk partitions. If all is false, returns 72 | // physical devices only (e.g. hard disks, cd-rom drives, USB keys) 73 | // and ignore all others (e.g. memory partitions such as /dev/shm) 74 | // 75 | // 'all' argument is ignored for BSD, see: https://github.com/giampaolo/psutil/issues/906 76 | func Partitions(all bool) ([]PartitionStat, error) { 77 | return PartitionsWithContext(context.Background(), all) 78 | } 79 | 80 | func IOCounters(names ...string) (map[string]IOCountersStat, error) { 81 | return IOCountersWithContext(context.Background(), names...) 82 | } 83 | -------------------------------------------------------------------------------- /pkg/gopsutil/_tools/v3migration/v3migration.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "go/ast" 7 | "go/format" 8 | "go/parser" 9 | "go/token" 10 | "log" 11 | "os" 12 | 13 | "golang.org/x/tools/go/ast/astutil" 14 | ) 15 | 16 | // https://github.com/shirou/gopsutil/issues/429 17 | func issue429() error { 18 | f := func(filename string) error { 19 | fset := token.NewFileSet() 20 | expr, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) 21 | if err != nil { 22 | return err 23 | } 24 | n := astutil.Apply(expr, func(cr *astutil.Cursor) bool { 25 | if cr.Name() == "Decls" { 26 | switch n := cr.Node().(type) { 27 | case *ast.FuncDecl: 28 | if n.Name.Name == "NetIOCounters" || n.Name.Name == ("NetIOCountersWithContext") { 29 | cr.Delete() 30 | } 31 | } 32 | } 33 | return true 34 | }, nil) 35 | return replace(filename, fset, n) 36 | } 37 | 38 | root := "process/" 39 | fnames := []string{"process.go", "process_darwin.go", "process_fallback.go", "process_freebsd.go", "process_linux.go", "process_openbsd.go", "process_bsd.go", "process_posix.go", "process_windows.go", "process_test.go"} 40 | for _, fname := range fnames { 41 | if err := f(root + fname); err != nil { 42 | log.Fatalln("run 429:", err) 43 | } 44 | } 45 | return nil 46 | } 47 | 48 | func issueRemoveUnusedValue() error { 49 | f := func(filename string) error { 50 | fset := token.NewFileSet() 51 | expr, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) 52 | if err != nil { 53 | return err 54 | } 55 | n := astutil.Apply(expr, func(cr *astutil.Cursor) bool { 56 | if cr.Name() == "Decls" { 57 | switch n := cr.Node().(type) { 58 | case *ast.GenDecl: 59 | if n.Tok != token.TYPE { 60 | break 61 | } 62 | ts := n.Specs[0].(*ast.TypeSpec) 63 | if ts.Name.Name == "SystemProcessInformation" { 64 | cr.Delete() 65 | } 66 | } 67 | } 68 | return true 69 | }, nil) 70 | return replace(filename, fset, n) 71 | } 72 | 73 | if err := f("process/process_windows.go"); err != nil { 74 | log.Fatalln("run 429:", err) 75 | } 76 | return nil 77 | } 78 | 79 | func replace(filename string, fset *token.FileSet, n ast.Node) error { 80 | if err := os.Remove(filename); err != nil { 81 | return err 82 | } 83 | fp, err := os.Create(filename) 84 | if err != nil { 85 | return err 86 | } 87 | defer fp.Close() 88 | if err := format.Node(fp, fset, n); err != nil { 89 | return err 90 | } 91 | fp.WriteString("\n") 92 | return nil 93 | } 94 | 95 | func main() { 96 | flag.Parse() 97 | for _, n := range flag.Args() { 98 | fmt.Println("issue:" + n) 99 | switch n { 100 | case "429": 101 | issue429() 102 | case "issueRemoveUnusedValue": 103 | issueRemoveUnusedValue() 104 | } 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_openbsd.go: -------------------------------------------------------------------------------- 1 | // +build openbsd 2 | 3 | package mem 4 | 5 | import ( 6 | "bytes" 7 | "context" 8 | "encoding/binary" 9 | "errors" 10 | "fmt" 11 | "os/exec" 12 | 13 | "github.com/shirou/gopsutil/internal/common" 14 | "golang.org/x/sys/unix" 15 | ) 16 | 17 | func GetPageSize() (uint64, error) { 18 | return GetPageSizeWithContext(context.Background()) 19 | } 20 | 21 | func GetPageSizeWithContext(ctx context.Context) (uint64, error) { 22 | uvmexp, err := unix.SysctlUvmexp("vm.uvmexp") 23 | if err != nil { 24 | return 0, err 25 | } 26 | return uint64(uvmexp.Pagesize), nil 27 | } 28 | 29 | func VirtualMemory() (*VirtualMemoryStat, error) { 30 | return VirtualMemoryWithContext(context.Background()) 31 | } 32 | 33 | func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { 34 | uvmexp, err := unix.SysctlUvmexp("vm.uvmexp") 35 | if err != nil { 36 | return nil, err 37 | } 38 | p := uint64(uvmexp.Pagesize) 39 | 40 | ret := &VirtualMemoryStat{ 41 | Total: uint64(uvmexp.Npages) * p, 42 | Free: uint64(uvmexp.Free) * p, 43 | Active: uint64(uvmexp.Active) * p, 44 | Inactive: uint64(uvmexp.Inactive) * p, 45 | Cached: 0, // not available 46 | Wired: uint64(uvmexp.Wired) * p, 47 | } 48 | 49 | ret.Available = ret.Inactive + ret.Cached + ret.Free 50 | ret.Used = ret.Total - ret.Available 51 | ret.UsedPercent = float64(ret.Used) / float64(ret.Total) * 100.0 52 | 53 | mib := []int32{CTLVfs, VfsGeneric, VfsBcacheStat} 54 | buf, length, err := common.CallSyscall(mib) 55 | if err != nil { 56 | return nil, err 57 | } 58 | if length < sizeOfBcachestats { 59 | return nil, fmt.Errorf("short syscall ret %d bytes", length) 60 | } 61 | var bcs Bcachestats 62 | br := bytes.NewReader(buf) 63 | err = common.Read(br, binary.LittleEndian, &bcs) 64 | if err != nil { 65 | return nil, err 66 | } 67 | ret.Buffers = uint64(bcs.Numbufpages) * p 68 | 69 | return ret, nil 70 | } 71 | 72 | // Return swapctl summary info 73 | func SwapMemory() (*SwapMemoryStat, error) { 74 | return SwapMemoryWithContext(context.Background()) 75 | } 76 | 77 | func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { 78 | swapctl, err := exec.LookPath("swapctl") 79 | if err != nil { 80 | return nil, err 81 | } 82 | 83 | out, err := invoke.CommandWithContext(ctx, swapctl, "-sk") 84 | if err != nil { 85 | return &SwapMemoryStat{}, nil 86 | } 87 | 88 | line := string(out) 89 | var total, used, free uint64 90 | 91 | _, err = fmt.Sscanf(line, 92 | "total: %d 1K-blocks allocated, %d used, %d available", 93 | &total, &used, &free) 94 | if err != nil { 95 | return nil, errors.New("failed to parse swapctl output") 96 | } 97 | 98 | percent := float64(used) / float64(total) * 100 99 | return &SwapMemoryStat{ 100 | Total: total * 1024, 101 | Used: used * 1024, 102 | Free: free * 1024, 103 | UsedPercent: percent, 104 | }, nil 105 | } 106 | -------------------------------------------------------------------------------- /ss/ss.go: -------------------------------------------------------------------------------- 1 | package ss 2 | 3 | import ( 4 | "net" 5 | "syscall" 6 | 7 | "github.com/Asphaltt/go-iproute2" 8 | "github.com/mdlayher/netlink" 9 | ) 10 | 11 | // A Client can manipulate ss netlink interface. 12 | type Client struct { 13 | conn *netlink.Conn 14 | } 15 | 16 | // New creates a Client which can issue ss commands. 17 | func New() (*Client, error) { 18 | conn, err := netlink.Dial(iproute2.FamilySocketMonitoring, nil) 19 | if err != nil { 20 | return nil, err 21 | } 22 | 23 | return NewWithConn(conn), nil 24 | } 25 | 26 | // NewWithConn creates a Client which can issue ss commands using an existing 27 | // netlink connection. 28 | func NewWithConn(conn *netlink.Conn) *Client { 29 | return &Client{ 30 | conn: conn, 31 | } 32 | } 33 | 34 | // Entry contains sockets' information, such as state, receive queue size, 35 | // send queue size, local address, local port , peer address and peer port. 36 | type Entry struct { 37 | State iproute2.SockStateType 38 | RecvQ, SendQ uint32 39 | LocalAddr, PeerAddr net.IP 40 | LocalPort, PeerPort int 41 | Ifindex int 42 | Inode int 43 | IsIPv4 bool 44 | } 45 | 46 | func (c *Client) listSockets(req *iproute2.InetDiagReq) ([]*Entry, error) { 47 | var msg netlink.Message 48 | msg.Header.Type = iproute2.MsgTypeSockDiagByFamily 49 | msg.Header.Flags = netlink.Dump | netlink.Request 50 | msg.Data, _ = req.MarshalBinary() 51 | 52 | msgs, err := c.conn.Execute(msg) 53 | if err != nil { 54 | return nil, err 55 | } 56 | 57 | entries := make([]*Entry, 0, len(msgs)) 58 | for _, msg := range msgs { 59 | if msg.Header.Type != iproute2.MsgTypeSockDiagByFamily { 60 | continue 61 | } 62 | 63 | data := msg.Data 64 | var diagMsg iproute2.InetDiagMsg 65 | if err := diagMsg.UnmarshalBinary(data); err != nil { 66 | return entries, err 67 | } 68 | if diagMsg.Family != syscall.AF_INET && 69 | diagMsg.Family != syscall.AF_INET6 { 70 | continue 71 | } 72 | 73 | var e Entry 74 | e.State = iproute2.SockStateType(diagMsg.State) 75 | e.RecvQ = diagMsg.RQueue 76 | e.SendQ = diagMsg.WQueue 77 | e.LocalPort = int(diagMsg.Sport) 78 | e.PeerPort = int(diagMsg.Dport) 79 | e.Inode = int(diagMsg.Inode) 80 | e.Ifindex = int(diagMsg.Ifindex) 81 | if diagMsg.Family == syscall.AF_INET { 82 | e.IsIPv4 = true 83 | e.LocalAddr = net.IP(diagMsg.Saddr[:4]) 84 | e.PeerAddr = net.IP(diagMsg.Daddr[:4]) 85 | } else { 86 | e.LocalAddr = net.IP(diagMsg.Saddr[:]) 87 | e.PeerAddr = net.IP(diagMsg.Daddr[:]) 88 | } 89 | 90 | data = data[iproute2.SizeofInetDiagMsg:] 91 | ad, err := netlink.NewAttributeDecoder(data) 92 | if err != nil { 93 | return entries, err 94 | } 95 | for ad.Next() { 96 | switch ad.Type() { 97 | } 98 | } 99 | if err := ad.Err(); err != nil { 100 | return entries, err 101 | } 102 | 103 | entries = append(entries, &e) 104 | } 105 | return entries, nil 106 | } 107 | -------------------------------------------------------------------------------- /pkg/gopsutil/mem/mem_bsd.go: -------------------------------------------------------------------------------- 1 | // +build freebsd openbsd 2 | 3 | package mem 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | const swapCommand = "swapctl" 14 | 15 | // swapctl column indexes 16 | const ( 17 | nameCol = 0 18 | totalKiBCol = 1 19 | usedKiBCol = 2 20 | ) 21 | 22 | func SwapDevices() ([]*SwapDevice, error) { 23 | return SwapDevicesWithContext(context.Background()) 24 | } 25 | 26 | func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { 27 | swapCommandPath, err := exec.LookPath(swapCommand) 28 | if err != nil { 29 | return nil, fmt.Errorf("could not find command %q: %w", swapCommand, err) 30 | } 31 | output, err := invoke.CommandWithContext(ctx, swapCommandPath, "-lk") 32 | if err != nil { 33 | return nil, fmt.Errorf("could not execute %q: %w", swapCommand, err) 34 | } 35 | 36 | return parseSwapctlOutput(string(output)) 37 | } 38 | 39 | func parseSwapctlOutput(output string) ([]*SwapDevice, error) { 40 | lines := strings.Split(output, "\n") 41 | if len(lines) == 0 { 42 | return nil, fmt.Errorf("could not parse output of %q: no lines in %q", swapCommand, output) 43 | } 44 | 45 | // Check header headerFields are as expected. 46 | header := lines[0] 47 | header = strings.ToLower(header) 48 | header = strings.ReplaceAll(header, ":", "") 49 | headerFields := strings.Fields(header) 50 | if len(headerFields) < usedKiBCol { 51 | return nil, fmt.Errorf("couldn't parse %q: too few fields in header %q", swapCommand, header) 52 | } 53 | if headerFields[nameCol] != "device" { 54 | return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[nameCol], "device") 55 | } 56 | if headerFields[totalKiBCol] != "1kb-blocks" && headerFields[totalKiBCol] != "1k-blocks" { 57 | return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[totalKiBCol], "1kb-blocks") 58 | } 59 | if headerFields[usedKiBCol] != "used" { 60 | return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[usedKiBCol], "used") 61 | } 62 | 63 | var swapDevices []*SwapDevice 64 | for _, line := range lines[1:] { 65 | if line == "" { 66 | continue // the terminal line is typically empty 67 | } 68 | fields := strings.Fields(line) 69 | if len(fields) < usedKiBCol { 70 | return nil, fmt.Errorf("couldn't parse %q: too few fields", swapCommand) 71 | } 72 | 73 | totalKiB, err := strconv.ParseUint(fields[totalKiBCol], 10, 64) 74 | if err != nil { 75 | return nil, fmt.Errorf("couldn't parse 'Size' column in %q: %w", swapCommand, err) 76 | } 77 | 78 | usedKiB, err := strconv.ParseUint(fields[usedKiBCol], 10, 64) 79 | if err != nil { 80 | return nil, fmt.Errorf("couldn't parse 'Used' column in %q: %w", swapCommand, err) 81 | } 82 | 83 | swapDevices = append(swapDevices, &SwapDevice{ 84 | Name: fields[nameCol], 85 | UsedBytes: usedKiB * 1024, 86 | FreeBytes: (totalKiB - usedKiB) * 1024, 87 | }) 88 | } 89 | 90 | return swapDevices, nil 91 | } 92 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/testdata/linux/1037/proc/cpuinfo: -------------------------------------------------------------------------------- 1 | processor : 0 2 | Processor : ARMv7 Processor rev 4 (v7l) 3 | model name : ARMv7 Processor rev 4 (v7l) 4 | BogoMIPS : 42.43 5 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 6 | CPU implementer : 0x41 7 | CPU architecture: 7 8 | CPU variant : 0x0 9 | CPU part : 0xd03 10 | CPU revision : 4 11 | 12 | processor : 1 13 | Processor : ARMv7 Processor rev 4 (v7l) 14 | model name : ARMv7 Processor rev 4 (v7l) 15 | BogoMIPS : 42.43 16 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 17 | CPU implementer : 0x41 18 | CPU architecture: 7 19 | CPU variant : 0x0 20 | CPU part : 0xd03 21 | CPU revision : 4 22 | 23 | processor : 2 24 | Processor : ARMv7 Processor rev 4 (v7l) 25 | model name : ARMv7 Processor rev 4 (v7l) 26 | BogoMIPS : 42.43 27 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 28 | CPU implementer : 0x41 29 | CPU architecture: 7 30 | CPU variant : 0x0 31 | CPU part : 0xd03 32 | CPU revision : 4 33 | 34 | processor : 3 35 | Processor : ARMv7 Processor rev 4 (v7l) 36 | model name : ARMv7 Processor rev 4 (v7l) 37 | BogoMIPS : 42.43 38 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 39 | CPU implementer : 0x41 40 | CPU architecture: 7 41 | CPU variant : 0x0 42 | CPU part : 0xd03 43 | CPU revision : 4 44 | 45 | processor : 4 46 | Processor : ARMv7 Processor rev 2 (v7l) 47 | model name : ARMv7 Processor rev 2 (v7l) 48 | BogoMIPS : 29.52 49 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 50 | CPU implementer : 0x41 51 | CPU architecture: 7 52 | CPU variant : 0x0 53 | CPU part : 0xd09 54 | CPU revision : 2 55 | 56 | processor : 5 57 | Processor : ARMv7 Processor rev 2 (v7l) 58 | model name : ARMv7 Processor rev 2 (v7l) 59 | BogoMIPS : 29.52 60 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 61 | CPU implementer : 0x41 62 | CPU architecture: 7 63 | CPU variant : 0x0 64 | CPU part : 0xd09 65 | CPU revision : 2 66 | 67 | processor : 6 68 | Processor : ARMv7 Processor rev 2 (v7l) 69 | model name : ARMv7 Processor rev 2 (v7l) 70 | BogoMIPS : 29.52 71 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 72 | CPU implementer : 0x41 73 | CPU architecture: 7 74 | CPU variant : 0x0 75 | CPU part : 0xd09 76 | CPU revision : 2 77 | 78 | processor : 7 79 | Processor : ARMv7 Processor rev 2 (v7l) 80 | model name : ARMv7 Processor rev 2 (v7l) 81 | BogoMIPS : 29.52 82 | Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 83 | CPU implementer : 0x41 84 | CPU architecture: 7 85 | CPU variant : 0x0 86 | CPU part : 0xd09 87 | CPU revision : 2 88 | 89 | Hardware : MT8183 90 | Revision : 0000 91 | Serial : 29aa1cf5ba0159c3 92 | -------------------------------------------------------------------------------- /pkg/gopsutil/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: help check 2 | .DEFAULT_GOAL := help 3 | 4 | SUBPKGS=cpu disk docker host internal load mem net process 5 | TAG=$(shell date +'v3.%y.%-m' --date='last Month') 6 | 7 | help: ## Show help 8 | @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' 9 | 10 | check: ## Check 11 | errcheck -ignore="Close|Run|Write" ./... 12 | golint ./... | egrep -v 'underscores|HttpOnly|should have comment|comment on exported|CamelCase|VM|UID' && exit 1 || exit 0 13 | 14 | BUILD_FAIL_PATTERN=grep -v "exec format error" | grep "build failed" && exit 1 || exit 0 15 | build_test: ## test only buildable 16 | # Supported operating systems 17 | GOOS=linux GOARCH=amd64 go test ./... | $(BUILD_FAIL_PATTERN) 18 | GOOS=linux GOARCH=386 go test ./... | $(BUILD_FAIL_PATTERN) 19 | GOOS=linux GOARCH=arm go test ./... | $(BUILD_FAIL_PATTERN) 20 | GOOS=linux GOARCH=arm64 go test ./... | $(BUILD_FAIL_PATTERN) 21 | GOOS=linux GOARCH=riscv64 go test ./... | $(BUILD_FAIL_PATTERN) 22 | GOOS=freebsd go test ./... | $(BUILD_FAIL_PATTERN) 23 | GOOS=freebsd GOARCH=arm go test ./... | $(BUILD_FAIL_PATTERN) 24 | CGO_ENABLED=0 GOOS=darwin go test ./... | $(BUILD_FAIL_PATTERN) 25 | GOOS=windows go test ./... | $(BUILD_FAIL_PATTERN) 26 | # Operating systems supported for building only (not implemented error if used) 27 | GOOS=solaris go test ./... | $(BUILD_FAIL_PATTERN) 28 | GOOS=dragonfly go test ./... | $(BUILD_FAIL_PATTERN) 29 | GOOS=netbsd go test ./... | $(BUILD_FAIL_PATTERN) 30 | # cross build to OpenBSD not worked since process has "C" 31 | # GOOS=openbsd go test ./... | $(BUILD_FAIL_PATTERN) 32 | 33 | ifeq ($(shell uname -s), Darwin) 34 | CGO_ENABLED=1 GOOS=darwin go test ./... | $(BUILD_FAIL_PATTERN) 35 | endif 36 | @echo 'Successfully built on all known operating systems' 37 | 38 | vet: 39 | GOOS=darwin GOARCH=amd64 go vet ./... 40 | GOOS=darwin GOARCH=386 go vet ./... 41 | GOOS=darwin GOARCH=arm64 go vet ./... 42 | 43 | GOOS=dragonfly GOARCH=amd64 go vet ./... 44 | 45 | GOOS=freebsd GOARCH=amd64 go vet ./... 46 | GOOS=freebsd GOARCH=386 go vet ./... 47 | GOOS=freebsd GOARCH=arm go vet ./... 48 | 49 | GOOS=linux GOARCH=386 go vet ./... 50 | GOOS=linux GOARCH=amd64 go vet ./... 51 | GOOS=linux GOARCH=arm64 go vet ./... 52 | GOOS=linux GOARCH=arm go vet ./... 53 | GOOS=linux GOARCH=mips64 go vet ./... 54 | GOOS=linux GOARCH=mips64le go vet ./... 55 | GOOS=linux GOARCH=mips go vet ./... 56 | GOOS=linux GOARCH=mipsle go vet ./... 57 | GOOS=linux GOARCH=ppc64le go vet ./... 58 | GOOS=linux GOARCH=riscv64 go vet ./... 59 | GOOS=linux GOARCH=s390x go vet ./... 60 | 61 | GOOS=netbsd GOARCH=amd64 go vet ./... 62 | 63 | GOOS=openbsd GOARCH=386 go vet ./... 64 | GOOS=openbsd GOARCH=amd64 go vet ./... 65 | 66 | GOOS=solaris GOARCH=amd64 go vet ./... 67 | 68 | GOOS=windows GOARCH=amd64 go vet ./... 69 | GOOS=windows GOARCH=386 go vet ./... 70 | 71 | macos_test: 72 | CGO_ENABLED=0 GOOS=darwin go test ./... | $(BUILD_FAIL_PATTERN) 73 | CGO_ENABLED=1 GOOS=darwin go test ./... | $(BUILD_FAIL_PATTERN) 74 | 75 | init_tools: 76 | go get github.com/golang/dep/cmd/dep 77 | 78 | release: 79 | git tag $(TAG) 80 | git push origin $(TAG) 81 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_darwin.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | 3 | package cpu 4 | 5 | import ( 6 | "context" 7 | "strconv" 8 | "strings" 9 | 10 | "github.com/tklauser/go-sysconf" 11 | "golang.org/x/sys/unix" 12 | ) 13 | 14 | // sys/resource.h 15 | const ( 16 | CPUser = 0 17 | CPNice = 1 18 | CPSys = 2 19 | CPIntr = 3 20 | CPIdle = 4 21 | CPUStates = 5 22 | ) 23 | 24 | // default value. from time.h 25 | var ClocksPerSec = float64(128) 26 | 27 | func init() { 28 | clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) 29 | // ignore errors 30 | if err == nil { 31 | ClocksPerSec = float64(clkTck) 32 | } 33 | } 34 | 35 | func Times(percpu bool) ([]TimesStat, error) { 36 | return TimesWithContext(context.Background(), percpu) 37 | } 38 | 39 | func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { 40 | if percpu { 41 | return perCPUTimes() 42 | } 43 | 44 | return allCPUTimes() 45 | } 46 | 47 | // Returns only one CPUInfoStat on FreeBSD 48 | func Info() ([]InfoStat, error) { 49 | return InfoWithContext(context.Background()) 50 | } 51 | 52 | func InfoWithContext(ctx context.Context) ([]InfoStat, error) { 53 | var ret []InfoStat 54 | 55 | c := InfoStat{} 56 | c.ModelName, _ = unix.Sysctl("machdep.cpu.brand_string") 57 | family, _ := unix.SysctlUint32("machdep.cpu.family") 58 | c.Family = strconv.FormatUint(uint64(family), 10) 59 | model, _ := unix.SysctlUint32("machdep.cpu.model") 60 | c.Model = strconv.FormatUint(uint64(model), 10) 61 | stepping, _ := unix.SysctlUint32("machdep.cpu.stepping") 62 | c.Stepping = int32(stepping) 63 | features, err := unix.Sysctl("machdep.cpu.features") 64 | if err == nil { 65 | for _, v := range strings.Fields(features) { 66 | c.Flags = append(c.Flags, strings.ToLower(v)) 67 | } 68 | } 69 | leaf7Features, err := unix.Sysctl("machdep.cpu.leaf7_features") 70 | if err == nil { 71 | for _, v := range strings.Fields(leaf7Features) { 72 | c.Flags = append(c.Flags, strings.ToLower(v)) 73 | } 74 | } 75 | extfeatures, err := unix.Sysctl("machdep.cpu.extfeatures") 76 | if err == nil { 77 | for _, v := range strings.Fields(extfeatures) { 78 | c.Flags = append(c.Flags, strings.ToLower(v)) 79 | } 80 | } 81 | cores, _ := unix.SysctlUint32("machdep.cpu.core_count") 82 | c.Cores = int32(cores) 83 | cacheSize, _ := unix.SysctlUint32("machdep.cpu.cache.size") 84 | c.CacheSize = int32(cacheSize) 85 | c.VendorID, _ = unix.Sysctl("machdep.cpu.vendor") 86 | 87 | // Use the rated frequency of the CPU. This is a static value and does not 88 | // account for low power or Turbo Boost modes. 89 | cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency") 90 | if err != nil { 91 | return ret, err 92 | } 93 | c.Mhz = float64(cpuFrequency) / 1000000.0 94 | 95 | return append(ret, c), nil 96 | } 97 | 98 | func CountsWithContext(ctx context.Context, logical bool) (int, error) { 99 | var cpuArgument string 100 | if logical { 101 | cpuArgument = "hw.logicalcpu" 102 | } else { 103 | cpuArgument = "hw.physicalcpu" 104 | } 105 | 106 | count, err := unix.SysctlUint32(cpuArgument) 107 | if err != nil { 108 | return 0, err 109 | } 110 | 111 | return int(count), nil 112 | } 113 | -------------------------------------------------------------------------------- /pkg/gopsutil/process/process_windows_arm64.go: -------------------------------------------------------------------------------- 1 | //go:build windows && arm64 2 | // +build windows,arm64 3 | 4 | package process 5 | 6 | import ( 7 | "errors" 8 | "syscall" 9 | "unsafe" 10 | 11 | "github.com/shirou/gopsutil/internal/common" 12 | ) 13 | 14 | type PROCESS_MEMORY_COUNTERS struct { 15 | CB uint32 16 | PageFaultCount uint32 17 | PeakWorkingSetSize uint32 18 | WorkingSetSize uint32 19 | QuotaPeakPagedPoolUsage uint32 20 | QuotaPagedPoolUsage uint32 21 | QuotaPeakNonPagedPoolUsage uint32 22 | QuotaNonPagedPoolUsage uint32 23 | PagefileUsage uint32 24 | PeakPagefileUsage uint32 25 | } 26 | 27 | func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { 28 | if is32BitProcess { 29 | //we are on a 32-bit process reading an external 32-bit process 30 | var info processBasicInformation32 31 | 32 | ret, _, _ := common.ProcNtQueryInformationProcess.Call( 33 | uintptr(procHandle), 34 | uintptr(common.ProcessBasicInformation), 35 | uintptr(unsafe.Pointer(&info)), 36 | uintptr(unsafe.Sizeof(info)), 37 | uintptr(0), 38 | ) 39 | if int(ret) >= 0 { 40 | return uint64(info.PebBaseAddress), nil 41 | } 42 | } else { 43 | //we are on a 32-bit process reading an external 64-bit process 44 | if common.ProcNtWow64QueryInformationProcess64.Find() == nil { //avoid panic 45 | var info processBasicInformation64 46 | 47 | ret, _, _ := common.ProcNtWow64QueryInformationProcess64.Call( 48 | uintptr(procHandle), 49 | uintptr(common.ProcessBasicInformation), 50 | uintptr(unsafe.Pointer(&info)), 51 | uintptr(unsafe.Sizeof(info)), 52 | uintptr(0), 53 | ) 54 | if int(ret) >= 0 { 55 | return info.PebBaseAddress, nil 56 | } 57 | } 58 | } 59 | 60 | //return 0 on error 61 | return 0, errors.New("could not query PEB address") 62 | } 63 | 64 | func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, size uint) []byte { 65 | if is32BitProcess { 66 | var read uint 67 | 68 | buffer := make([]byte, size) 69 | 70 | ret, _, _ := common.ProcNtReadVirtualMemory.Call( 71 | uintptr(h), 72 | uintptr(address), 73 | uintptr(unsafe.Pointer(&buffer[0])), 74 | uintptr(size), 75 | uintptr(unsafe.Pointer(&read)), 76 | ) 77 | if int(ret) >= 0 && read > 0 { 78 | return buffer[:read] 79 | } 80 | } else { 81 | //reading a 64-bit process from a 32-bit one 82 | if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { //avoid panic 83 | var read uint64 84 | 85 | buffer := make([]byte, size) 86 | 87 | ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call( 88 | uintptr(h), 89 | uintptr(address&0xFFFFFFFF), //the call expects a 64-bit value 90 | uintptr(address>>32), 91 | uintptr(unsafe.Pointer(&buffer[0])), 92 | uintptr(size), //the call expects a 64-bit value 93 | uintptr(0), //but size is 32-bit so pass zero as the high dword 94 | uintptr(unsafe.Pointer(&read)), 95 | ) 96 | if int(ret) >= 0 && read > 0 { 97 | return buffer[:uint(read)] 98 | } 99 | } 100 | } 101 | 102 | //if we reach here, an error happened 103 | return nil 104 | } 105 | -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_linux_test.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | import ( 4 | "os" 5 | "os/exec" 6 | "strconv" 7 | "strings" 8 | "testing" 9 | ) 10 | 11 | func TestTimesEmpty(t *testing.T) { 12 | orig := os.Getenv("HOST_PROC") 13 | os.Setenv("HOST_PROC", "testdata/linux/times_empty") 14 | _, err := Times(true) 15 | if err != nil { 16 | t.Error("Times(true) failed") 17 | } 18 | _, err = Times(false) 19 | if err != nil { 20 | t.Error("Times(false) failed") 21 | } 22 | os.Setenv("HOST_PROC", orig) 23 | } 24 | 25 | func TestCPUparseStatLine_424(t *testing.T) { 26 | orig := os.Getenv("HOST_PROC") 27 | os.Setenv("HOST_PROC", "testdata/linux/424/proc") 28 | { 29 | l, err := Times(true) 30 | if err != nil || len(l) == 0 { 31 | t.Error("Times(true) failed") 32 | } 33 | t.Logf("Times(true): %#v", l) 34 | } 35 | { 36 | l, err := Times(false) 37 | if err != nil || len(l) == 0 { 38 | t.Error("Times(false) failed") 39 | } 40 | t.Logf("Times(false): %#v", l) 41 | } 42 | os.Setenv("HOST_PROC", orig) 43 | } 44 | 45 | func TestCPUCountsAgainstLscpu(t *testing.T) { 46 | lscpu, err := exec.LookPath("lscpu") 47 | if err != nil { 48 | t.Skip("no lscpu to compare with") 49 | } 50 | cmd := exec.Command(lscpu) 51 | cmd.Env = []string{"LC_ALL=C"} 52 | out, err := cmd.Output() 53 | if err != nil { 54 | t.Errorf("error executing lscpu: %v", err) 55 | } 56 | var threadsPerCore, coresPerSocket, sockets int 57 | lines := strings.Split(string(out), "\n") 58 | for _, line := range lines { 59 | fields := strings.Split(line, ":") 60 | if len(fields) < 2 { 61 | continue 62 | } 63 | switch fields[0] { 64 | case "Thread(s) per core": 65 | threadsPerCore, _ = strconv.Atoi(strings.TrimSpace(fields[1])) 66 | case "Core(s) per socket": 67 | coresPerSocket, _ = strconv.Atoi(strings.TrimSpace(fields[1])) 68 | case "Socket(s)": 69 | sockets, _ = strconv.Atoi(strings.TrimSpace(fields[1])) 70 | } 71 | } 72 | if threadsPerCore == 0 || coresPerSocket == 0 || sockets == 0 { 73 | t.Errorf("missing info from lscpu: threadsPerCore=%d coresPerSocket=%d sockets=%d", threadsPerCore, coresPerSocket, sockets) 74 | } 75 | expectedPhysical := coresPerSocket * sockets 76 | expectedLogical := expectedPhysical * threadsPerCore 77 | physical, err := Counts(false) 78 | skipIfNotImplementedErr(t, err) 79 | if err != nil { 80 | t.Errorf("error %v", err) 81 | } 82 | logical, err := Counts(true) 83 | skipIfNotImplementedErr(t, err) 84 | if err != nil { 85 | t.Errorf("error %v", err) 86 | } 87 | if expectedPhysical != physical { 88 | t.Errorf("expected %v, got %v", expectedPhysical, physical) 89 | } 90 | if expectedLogical != logical { 91 | t.Errorf("expected %v, got %v", expectedLogical, logical) 92 | } 93 | } 94 | 95 | func TestCPUCountsLogicalAndroid_1037(t *testing.T) { // https://github.com/shirou/gopsutil/issues/1037 96 | orig := os.Getenv("HOST_PROC") 97 | os.Setenv("HOST_PROC", "testdata/linux/1037/proc") 98 | defer os.Setenv("HOST_PROC", orig) 99 | 100 | count, err := Counts(true) 101 | if err != nil { 102 | t.Errorf("error %v", err) 103 | } 104 | expected := 8 105 | if count != expected { 106 | t.Errorf("expected %v, got %v", expected, count) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /pkg/gopsutil/.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: Test 3 | jobs: 4 | test_v3_module: 5 | strategy: 6 | matrix: 7 | go-version: [1.16.x, 1.17.x] 8 | os: [ubuntu-20.04, ubuntu-18.04, windows-2019, windows-2016, macOS-10.15, macos-11] 9 | runs-on: ${{ matrix.os }} 10 | steps: 11 | - name: Install Go 12 | uses: actions/setup-go@v2 13 | with: 14 | go-version: ${{ matrix.go-version }} 15 | - name: Checkout code 16 | uses: actions/checkout@v2 17 | - name: Test 18 | run: | 19 | cd ./v3/ 20 | go test ./... 21 | 22 | test_v3_gopath: 23 | env: 24 | GOPATH: ${{ github.workspace }} 25 | GO111MODULE: off 26 | strategy: 27 | matrix: 28 | go-version: [1.16.x, 1.17.x] 29 | os: [ubuntu-20.04, ubuntu-18.04, windows-2019, windows-2016, macOS-10.15, macos-11] 30 | runs-on: ${{ matrix.os }} 31 | steps: 32 | - name: Install Go 33 | uses: actions/setup-go@v2 34 | with: 35 | go-version: ${{ matrix.go-version }} 36 | - name: Checkout code 37 | uses: actions/checkout@v2 38 | with: 39 | path: ${{ github.workspace }}/src/github.com/shirou/gopsutil 40 | - name: Get dependencies 41 | run: | 42 | go get -t github.com/shirou/gopsutil/v3/... 43 | - name: Test 44 | run: | 45 | go test github.com/shirou/gopsutil/v3/... 46 | 47 | test_v2_gopath: 48 | env: 49 | GOPATH: ${{ github.workspace }} 50 | GO111MODULE: off 51 | strategy: 52 | matrix: 53 | go-version: [1.16.x, 1.17.x] 54 | os: [ubuntu-20.04, ubuntu-18.04, windows-2019, windows-2016, macOS-10.15, macos-11] 55 | runs-on: ${{ matrix.os }} 56 | steps: 57 | - name: Install Go 58 | uses: actions/setup-go@v2 59 | with: 60 | go-version: ${{ matrix.go-version }} 61 | - name: Checkout code 62 | uses: actions/checkout@v2 63 | with: 64 | path: ${{ github.workspace }}/src/github.com/shirou/gopsutil 65 | - name: Get dependencies 66 | if: runner.os == 'Windows' 67 | run: | 68 | go get -d -u github.com/golang/dep 69 | cd $Env:GOPATH/src/github.com/golang/dep 70 | git checkout v0.5.4 71 | go install -ldflags="-X main.version=v0.5.4" ./cmd/dep 72 | echo "$Env:GOPATH/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append 73 | cd $Env:GOPATH/src/github.com/shirou/gopsutil 74 | dep ensure 75 | # exclude v3 from being run with ./... 76 | try { rm -ErrorAction:Stop -Recurse -Force $Env:GOPATH/src/github.com/shirou/gopsutil/v3 } catch [System.Management.Automation.ItemNotFoundException] {} 77 | - name: Get dependencies 78 | if: runner.os != 'Windows' 79 | run: | 80 | if ! command -v dep &>/dev/null; then 81 | mkdir -p $GOPATH/bin 82 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 83 | echo "PATH=$GOPATH/bin:$PATH" >> $GITHUB_PATH 84 | fi 85 | cd $GOPATH/src/github.com/shirou/gopsutil 86 | dep ensure 87 | # exclude v3 from being run with ./... 88 | rm -rf $GOPATH/src/github.com/shirou/gopsutil/v3 89 | - name: Test 90 | run: | 91 | go test github.com/shirou/gopsutil/... 92 | -------------------------------------------------------------------------------- /cmd/ip/route.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "strings" 7 | 8 | "github.com/Asphaltt/go-iproute2/ip" 9 | "github.com/spf13/cobra" 10 | "golang.org/x/sys/unix" 11 | ) 12 | 13 | func init() { 14 | rootCmd.AddCommand(routeCmd()) 15 | } 16 | 17 | func routeCmd() *cobra.Command { 18 | routeCmd := &cobra.Command{ 19 | Use: "route", 20 | Aliases: []string{"r", "ro", "rou", "rout"}, 21 | Run: func(cmd *cobra.Command, args []string) { 22 | cli.runCmd(cli.listRoutes) 23 | }, 24 | } 25 | routeCmd.AddCommand(&cobra.Command{ 26 | Use: "list", 27 | Aliases: []string{"l", "li", "lis", "lst", "s", "sh", "sho", "show"}, 28 | Run: func(cmd *cobra.Command, args []string) { 29 | cli.runCmd(cli.listRoutes) 30 | }, 31 | }) 32 | return routeCmd 33 | } 34 | 35 | func (c *client) listRoutes() { 36 | ipcli := ip.NewWithConn(c.conn) 37 | entries, err := ipcli.ListRoutes() 38 | if err != nil { 39 | fmt.Println("failed to list route entries, err:", err) 40 | return 41 | } 42 | 43 | for _, e := range entries { 44 | printRouteEntry(e) 45 | } 46 | } 47 | 48 | func printRouteEntry(e *ip.RouteEntry) { 49 | table := e.Table 50 | if table == -1 { 51 | table = e.TableID 52 | } 53 | // if int(table) != unix.RT_TABLE_MAIN { 54 | // continue 55 | // } 56 | 57 | var s strings.Builder 58 | 59 | if e.Type != unix.RTN_UNICAST { 60 | s.WriteString(fmt.Sprintf("%s ", e.Type)) 61 | } 62 | 63 | if e.Daddr != nil { 64 | if e.DstLen != 32 { // IPv4 地址有 32 个比特 65 | s.WriteString(fmt.Sprintf("%s/%d ", e.Daddr, e.DstLen)) 66 | } else { 67 | s.WriteString(fmt.Sprintf("%s ", e.Daddr)) 68 | } 69 | } else if e.DstLen != 0 { 70 | s.WriteString(fmt.Sprintf("0/%d ", e.DstLen)) 71 | } else { 72 | s.WriteString("default ") 73 | } 74 | 75 | if e.Saddr != nil { 76 | if e.SrcLen != 32 { 77 | s.WriteString(fmt.Sprintf("from %s/%d ", e.Saddr, e.SrcLen)) 78 | } else { 79 | s.WriteString(fmt.Sprintf("from %s ", e.Saddr)) 80 | } 81 | } else if e.SrcLen != 0 { 82 | s.WriteString(fmt.Sprintf("from 0/%d ", e.SrcLen)) 83 | } 84 | 85 | if e.Tos != 0 { 86 | s.WriteString(fmt.Sprintf("tos %d ", e.Tos)) 87 | } 88 | 89 | if e.Gateway != nil { 90 | s.WriteString(fmt.Sprintf("via %s ", e.Gateway)) 91 | } 92 | 93 | if e.OutIfindex != 0 { 94 | ifi, err := net.InterfaceByIndex(e.OutIfindex) 95 | if err == nil { 96 | s.WriteString(fmt.Sprintf("dev %s ", ifi.Name)) 97 | } 98 | } 99 | 100 | if int(table) != unix.RT_TABLE_MAIN { 101 | s.WriteString(fmt.Sprintf("table %s ", table)) 102 | } 103 | 104 | if int(e.Flags)&unix.RTM_F_CLONED == 0 { 105 | if int(e.Protocol) != unix.RTPROT_BOOT { 106 | s.WriteString(fmt.Sprintf("proto %s ", e.Protocol)) 107 | } 108 | 109 | if int(e.Scope) != unix.RT_SCOPE_UNIVERSE { 110 | s.WriteString(fmt.Sprintf("scope %s ", e.Scope)) 111 | } 112 | } 113 | 114 | if e.PrefSrc != nil { 115 | s.WriteString(fmt.Sprintf("src %s ", e.PrefSrc)) 116 | } 117 | 118 | if e.Priority != -1 { 119 | s.WriteString(fmt.Sprintf("metric %d ", e.Priority)) 120 | } 121 | 122 | s.WriteString(e.Flags.String()) 123 | 124 | if e.Pref != -1 { 125 | s.WriteString(fmt.Sprintf("pref %s ", e.Pref)) 126 | } 127 | 128 | fmt.Println(s.String()) 129 | } 130 | -------------------------------------------------------------------------------- /pkg/gopsutil/LICENSE: -------------------------------------------------------------------------------- 1 | gopsutil is distributed under BSD license reproduced below. 2 | 3 | Copyright (c) 2014, WAKAYAMA Shirou 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without modification, 7 | are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | * Neither the name of the gopsutil authors nor the names of its contributors 15 | may be used to endorse or promote products derived from this software without 16 | specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 25 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | 30 | ------- 31 | internal/common/binary.go in the gopsutil is copied and modifid from golang/encoding/binary.go. 32 | 33 | 34 | 35 | Copyright (c) 2009 The Go Authors. All rights reserved. 36 | 37 | Redistribution and use in source and binary forms, with or without 38 | modification, are permitted provided that the following conditions are 39 | met: 40 | 41 | * Redistributions of source code must retain the above copyright 42 | notice, this list of conditions and the following disclaimer. 43 | * Redistributions in binary form must reproduce the above 44 | copyright notice, this list of conditions and the following disclaimer 45 | in the documentation and/or other materials provided with the 46 | distribution. 47 | * Neither the name of Google Inc. nor the names of its 48 | contributors may be used to endorse or promote products derived from 49 | this software without specific prior written permission. 50 | 51 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 52 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 53 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 54 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 55 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 56 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 57 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 58 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 59 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 60 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 61 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /pkg/gopsutil/cpu/cpu_darwin_cgo.go: -------------------------------------------------------------------------------- 1 | // +build darwin 2 | // +build cgo 3 | 4 | package cpu 5 | 6 | /* 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #if TARGET_OS_MAC 15 | #include 16 | #endif 17 | #include 18 | #include 19 | */ 20 | import "C" 21 | 22 | import ( 23 | "bytes" 24 | "encoding/binary" 25 | "fmt" 26 | "unsafe" 27 | ) 28 | 29 | // these CPU times for darwin is borrowed from influxdb/telegraf. 30 | 31 | func perCPUTimes() ([]TimesStat, error) { 32 | var ( 33 | count C.mach_msg_type_number_t 34 | cpuload *C.processor_cpu_load_info_data_t 35 | ncpu C.natural_t 36 | ) 37 | 38 | status := C.host_processor_info(C.host_t(C.mach_host_self()), 39 | C.PROCESSOR_CPU_LOAD_INFO, 40 | &ncpu, 41 | (*C.processor_info_array_t)(unsafe.Pointer(&cpuload)), 42 | &count) 43 | 44 | if status != C.KERN_SUCCESS { 45 | return nil, fmt.Errorf("host_processor_info error=%d", status) 46 | } 47 | 48 | // jump through some cgo casting hoops and ensure we properly free 49 | // the memory that cpuload points to 50 | target := C.vm_map_t(C.mach_task_self_) 51 | address := C.vm_address_t(uintptr(unsafe.Pointer(cpuload))) 52 | defer C.vm_deallocate(target, address, C.vm_size_t(ncpu)) 53 | 54 | // the body of struct processor_cpu_load_info 55 | // aka processor_cpu_load_info_data_t 56 | var cpu_ticks [C.CPU_STATE_MAX]uint32 57 | 58 | // copy the cpuload array to a []byte buffer 59 | // where we can binary.Read the data 60 | size := int(ncpu) * binary.Size(cpu_ticks) 61 | buf := (*[1 << 30]byte)(unsafe.Pointer(cpuload))[:size:size] 62 | 63 | bbuf := bytes.NewBuffer(buf) 64 | 65 | var ret []TimesStat 66 | 67 | for i := 0; i < int(ncpu); i++ { 68 | err := binary.Read(bbuf, binary.LittleEndian, &cpu_ticks) 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | c := TimesStat{ 74 | CPU: fmt.Sprintf("cpu%d", i), 75 | User: float64(cpu_ticks[C.CPU_STATE_USER]) / ClocksPerSec, 76 | System: float64(cpu_ticks[C.CPU_STATE_SYSTEM]) / ClocksPerSec, 77 | Nice: float64(cpu_ticks[C.CPU_STATE_NICE]) / ClocksPerSec, 78 | Idle: float64(cpu_ticks[C.CPU_STATE_IDLE]) / ClocksPerSec, 79 | } 80 | 81 | ret = append(ret, c) 82 | } 83 | 84 | return ret, nil 85 | } 86 | 87 | func allCPUTimes() ([]TimesStat, error) { 88 | var count C.mach_msg_type_number_t 89 | var cpuload C.host_cpu_load_info_data_t 90 | 91 | count = C.HOST_CPU_LOAD_INFO_COUNT 92 | 93 | status := C.host_statistics(C.host_t(C.mach_host_self()), 94 | C.HOST_CPU_LOAD_INFO, 95 | C.host_info_t(unsafe.Pointer(&cpuload)), 96 | &count) 97 | 98 | if status != C.KERN_SUCCESS { 99 | return nil, fmt.Errorf("host_statistics error=%d", status) 100 | } 101 | 102 | c := TimesStat{ 103 | CPU: "cpu-total", 104 | User: float64(cpuload.cpu_ticks[C.CPU_STATE_USER]) / ClocksPerSec, 105 | System: float64(cpuload.cpu_ticks[C.CPU_STATE_SYSTEM]) / ClocksPerSec, 106 | Nice: float64(cpuload.cpu_ticks[C.CPU_STATE_NICE]) / ClocksPerSec, 107 | Idle: float64(cpuload.cpu_ticks[C.CPU_STATE_IDLE]) / ClocksPerSec, 108 | } 109 | 110 | return []TimesStat{c}, nil 111 | 112 | } 113 | -------------------------------------------------------------------------------- /pkg/gopsutil/load/load_linux.go: -------------------------------------------------------------------------------- 1 | // +build linux 2 | 3 | package load 4 | 5 | import ( 6 | "context" 7 | "io/ioutil" 8 | "strconv" 9 | "strings" 10 | "syscall" 11 | 12 | "github.com/shirou/gopsutil/internal/common" 13 | ) 14 | 15 | func Avg() (*AvgStat, error) { 16 | return AvgWithContext(context.Background()) 17 | } 18 | 19 | func AvgWithContext(ctx context.Context) (*AvgStat, error) { 20 | stat, err := fileAvgWithContext(ctx) 21 | if err != nil { 22 | stat, err = sysinfoAvgWithContext(ctx) 23 | } 24 | return stat, err 25 | } 26 | 27 | func sysinfoAvgWithContext(ctx context.Context) (*AvgStat, error) { 28 | var info syscall.Sysinfo_t 29 | if err := syscall.Sysinfo(&info); err != nil { 30 | return nil, err 31 | } 32 | 33 | const siLoadShift = 16 34 | return &AvgStat{ 35 | Load1: float64(info.Loads[0]) / float64(1<