diff --git a/go.mod b/go.mod index e2933213a..0118419ad 100644 --- a/go.mod +++ b/go.mod @@ -19,13 +19,13 @@ require ( github.com/prometheus/client_model v0.4.0 github.com/prometheus/common v0.44.0 github.com/prometheus/procfs v0.10.1 - github.com/shirou/gopsutil v3.21.11+incompatible + github.com/shirou/gopsutil/v3 v3.23.8 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.8.4 go.opencensus.io v0.24.0 golang.org/x/crypto v0.11.0 golang.org/x/oauth2 v0.9.0 - golang.org/x/sys v0.10.0 + golang.org/x/sys v0.11.0 google.golang.org/api v0.114.0 k8s.io/api v0.28.1 k8s.io/apimachinery v0.28.1 @@ -70,6 +70,7 @@ require ( github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect @@ -77,11 +78,13 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/nxadm/tail v1.4.8 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect github.com/prometheus/client_golang v1.16.0 // indirect + github.com/shoenig/go-m1cpu v0.1.6 // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/tedsuo/ifrit v0.0.0-20230516164442-7862c310ad26 // indirect - github.com/tklauser/go-sysconf v0.3.11 // indirect - github.com/tklauser/numcpus v0.6.0 // indirect + github.com/tklauser/go-sysconf v0.3.12 // indirect + github.com/tklauser/numcpus v0.6.1 // indirect github.com/yusufpapurcu/wmi v1.2.3 // indirect golang.org/x/net v0.13.0 // indirect golang.org/x/sync v0.3.0 // indirect diff --git a/go.sum b/go.sum index cc354fd52..2dc2f7f6e 100644 --- a/go.sum +++ b/go.sum @@ -1264,6 +1264,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= github.com/lyft/protoc-gen-star v0.6.0/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= github.com/lyft/protoc-gen-star v0.6.1/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= github.com/lyft/protoc-gen-star/v2 v2.0.1/go.mod h1:RcCdONR2ScXaYnQC5tUzxzlpA3WVYF7/opLeUgcQs/o= @@ -1427,6 +1429,8 @@ github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qR github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= github.com/prometheus/client_golang v0.0.0-20180209125602-c332b6f63c06/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= @@ -1491,8 +1495,12 @@ github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZ github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sclevine/spec v1.2.0/go.mod h1:W4J29eT/Kzv7/b9IWLB055Z+qvVC9vt0Arko24q7p+U= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= -github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= -github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/shirou/gopsutil/v3 v3.23.8 h1:xnATPiybo6GgdRoC4YoGnxXZFRc3dqQTGi73oLvvBrE= +github.com/shirou/gopsutil/v3 v3.23.8/go.mod h1:7hmCaBn+2ZwaZOr6jmPBZDfawwMGuo1id3C6aM8EDqQ= +github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= +github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= +github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= +github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= github.com/shurcooL/githubv4 v0.0.0-20190718010115-4ba037080260/go.mod h1:hAF0iLZy4td2EX+/8Tw+4nodhlMrwN3HupfaXj3zkGo= github.com/shurcooL/githubv4 v0.0.0-20191102174205-af46314aec7b/go.mod h1:hAF0iLZy4td2EX+/8Tw+4nodhlMrwN3HupfaXj3zkGo= github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f/go.mod h1:AuYgA5Kyo4c7HfUmvRGs/6rGlMMV/6B1bVnB9JxJEEg= @@ -1560,10 +1568,10 @@ github.com/tektoncd/pipeline v0.11.0/go.mod h1:hlkH32S92+/UODROH0dmxzyuMxfRFp/Nc github.com/tektoncd/plumbing v0.0.0-20200217163359-cd0db6e567d2/go.mod h1:QZHgU07PRBTRF6N57w4+ApRu8OgfYLFNqCDlfEZaD9Y= github.com/tektoncd/plumbing/pipelinerun-logs v0.0.0-20191206114338-712d544c2c21/go.mod h1:S62EUWtqmejjJgUMOGB1CCCHRp6C706laH06BoALkzU= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= -github.com/tklauser/go-sysconf v0.3.11 h1:89WgdJhk5SNwJfu+GKyYveZ4IaJ7xAkecBo+KdJV0CM= -github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI= -github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms= -github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= +github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU= +github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI= +github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk= +github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= @@ -1918,6 +1926,7 @@ golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1970,8 +1979,9 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/pkg/systemstatsmonitor/cpu_collector.go b/pkg/systemstatsmonitor/cpu_collector.go index e4c5b6752..d6f09a505 100644 --- a/pkg/systemstatsmonitor/cpu_collector.go +++ b/pkg/systemstatsmonitor/cpu_collector.go @@ -18,7 +18,7 @@ package systemstatsmonitor import ( "github.com/golang/glog" - "github.com/shirou/gopsutil/cpu" + "github.com/shirou/gopsutil/v3/cpu" ssmtypes "k8s.io/node-problem-detector/pkg/systemstatsmonitor/types" "k8s.io/node-problem-detector/pkg/util/metrics" diff --git a/pkg/systemstatsmonitor/cpu_collector_linux.go b/pkg/systemstatsmonitor/cpu_collector_linux.go index 9ab1b9c20..f761fcf41 100644 --- a/pkg/systemstatsmonitor/cpu_collector_linux.go +++ b/pkg/systemstatsmonitor/cpu_collector_linux.go @@ -21,7 +21,7 @@ import ( "github.com/golang/glog" "github.com/prometheus/procfs" - "github.com/shirou/gopsutil/load" + "github.com/shirou/gopsutil/v3/load" ) func (cc *cpuCollector) recordLoad() { diff --git a/pkg/systemstatsmonitor/disk_collector.go b/pkg/systemstatsmonitor/disk_collector.go index 726e7bb79..886f6bf76 100644 --- a/pkg/systemstatsmonitor/disk_collector.go +++ b/pkg/systemstatsmonitor/disk_collector.go @@ -23,7 +23,7 @@ import ( "time" "github.com/golang/glog" - "github.com/shirou/gopsutil/disk" + "github.com/shirou/gopsutil/v3/disk" ssmtypes "k8s.io/node-problem-detector/pkg/systemstatsmonitor/types" "k8s.io/node-problem-detector/pkg/util/metrics" @@ -288,7 +288,7 @@ func (dc *diskCollector) collect() { } deviceName := strings.TrimPrefix(partition.Device, "/dev/") fstype := partition.Fstype - opttypes := partition.Opts + opttypes := strings.Join(partition.Opts, ",") dc.mBytesUsed.Record(map[string]string{deviceNameLabel: deviceName, fsTypeLabel: fstype, mountOptionLabel: opttypes, stateLabel: "free"}, int64(usageStat.Free)) dc.mBytesUsed.Record(map[string]string{deviceNameLabel: deviceName, fsTypeLabel: fstype, mountOptionLabel: opttypes, stateLabel: "used"}, int64(usageStat.Used)) } diff --git a/pkg/systemstatsmonitor/host_collector.go b/pkg/systemstatsmonitor/host_collector.go index b1305aa20..d85225567 100644 --- a/pkg/systemstatsmonitor/host_collector.go +++ b/pkg/systemstatsmonitor/host_collector.go @@ -18,7 +18,7 @@ package systemstatsmonitor import ( "github.com/golang/glog" - "github.com/shirou/gopsutil/host" + "github.com/shirou/gopsutil/v3/host" ssmtypes "k8s.io/node-problem-detector/pkg/systemstatsmonitor/types" "k8s.io/node-problem-detector/pkg/util" diff --git a/pkg/systemstatsmonitor/memory_collector_windows.go b/pkg/systemstatsmonitor/memory_collector_windows.go index eab5ea173..020e245b2 100644 --- a/pkg/systemstatsmonitor/memory_collector_windows.go +++ b/pkg/systemstatsmonitor/memory_collector_windows.go @@ -19,7 +19,7 @@ package systemstatsmonitor import ( "github.com/golang/glog" - "github.com/shirou/gopsutil/mem" + "github.com/shirou/gopsutil/v3/mem" ) func (mc *memoryCollector) collect() { diff --git a/pkg/util/helpers_windows.go b/pkg/util/helpers_windows.go index 0d4ddac83..897e0cfb5 100644 --- a/pkg/util/helpers_windows.go +++ b/pkg/util/helpers_windows.go @@ -19,7 +19,7 @@ import ( "fmt" "time" - "github.com/shirou/gopsutil/host" + "github.com/shirou/gopsutil/v3/host" "golang.org/x/sys/windows" "golang.org/x/sys/windows/registry" ) diff --git a/vendor/github.com/lufia/plan9stats/.gitignore b/vendor/github.com/lufia/plan9stats/.gitignore new file mode 100644 index 000000000..f1c181ec9 --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/.gitignore @@ -0,0 +1,12 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out diff --git a/vendor/github.com/lufia/plan9stats/LICENSE b/vendor/github.com/lufia/plan9stats/LICENSE new file mode 100644 index 000000000..a6d47e807 --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2019, KADOTA, Kyohei +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/lufia/plan9stats/README.md b/vendor/github.com/lufia/plan9stats/README.md new file mode 100644 index 000000000..a21700c0c --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/README.md @@ -0,0 +1,2 @@ +# plan9stats +A module for retrieving statistics of Plan 9 diff --git a/vendor/github.com/lufia/plan9stats/cpu.go b/vendor/github.com/lufia/plan9stats/cpu.go new file mode 100644 index 000000000..a101b9119 --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/cpu.go @@ -0,0 +1,288 @@ +package stats + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" +) + +// CPUType represents /dev/cputype. +type CPUType struct { + Name string + Clock int // clock rate in MHz +} + +func ReadCPUType(ctx context.Context, opts ...Option) (*CPUType, error) { + cfg := newConfig(opts...) + var c CPUType + if err := readCPUType(cfg.rootdir, &c); err != nil { + return nil, err + } + return &c, nil +} + +type SysStats struct { + ID int + NumCtxSwitch int64 + NumInterrupt int64 + NumSyscall int64 + NumFault int64 + NumTLBFault int64 + NumTLBPurge int64 + LoadAvg int64 // in units of milli-CPUs and is decayed over time + Idle int // percentage + Interrupt int // percentage +} + +// ReadSysStats reads system statistics from /dev/sysstat. +func ReadSysStats(ctx context.Context, opts ...Option) ([]*SysStats, error) { + cfg := newConfig(opts...) + file := filepath.Join(cfg.rootdir, "/dev/sysstat") + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + + scanner := bufio.NewScanner(f) + var stats []*SysStats + for scanner.Scan() { + a := strings.Fields(scanner.Text()) + if len(a) != 10 { + continue + } + var ( + p intParser + stat SysStats + ) + stat.ID = p.ParseInt(a[0], 10) + stat.NumCtxSwitch = p.ParseInt64(a[1], 10) + stat.NumInterrupt = p.ParseInt64(a[2], 10) + stat.NumSyscall = p.ParseInt64(a[3], 10) + stat.NumFault = p.ParseInt64(a[4], 10) + stat.NumTLBFault = p.ParseInt64(a[5], 10) + stat.NumTLBPurge = p.ParseInt64(a[6], 10) + stat.LoadAvg = p.ParseInt64(a[7], 10) + stat.Idle = p.ParseInt(a[8], 10) + stat.Interrupt = p.ParseInt(a[9], 10) + if err := p.Err(); err != nil { + return nil, err + } + stats = append(stats, &stat) + } + if err := scanner.Err(); err != nil { + return nil, err + } + return stats, nil +} + +func readCPUType(rootdir string, c *CPUType) error { + file := filepath.Join(rootdir, "/dev/cputype") + b, err := ioutil.ReadFile(file) + if err != nil { + return err + } + b = bytes.TrimSpace(b) + i := bytes.LastIndexByte(b, ' ') + if i < 0 { + return fmt.Errorf("%s: invalid format", file) + } + clock, err := strconv.Atoi(string(b[i+1:])) + if err != nil { + return err + } + c.Name = string(b[:i]) + c.Clock = clock + return nil +} + +// Time represents /dev/time. +type Time struct { + Unix time.Duration + UnixNano time.Duration + Ticks int64 // clock ticks + Freq int64 //cloc frequency +} + +// Uptime returns uptime. +func (t *Time) Uptime() time.Duration { + v := float64(t.Ticks) / float64(t.Freq) + return time.Duration(v*1000_000_000) * time.Nanosecond +} + +func ReadTime(ctx context.Context, opts ...Option) (*Time, error) { + cfg := newConfig(opts...) + file := filepath.Join(cfg.rootdir, "/dev/time") + var t Time + if err := readTime(file, &t); err != nil { + return nil, err + } + return &t, nil +} + +// ProcStatus represents a /proc/n/status. +type ProcStatus struct { + Name string + User string + State string + Times CPUTime + MemUsed int64 // in units of 1024 bytes + BasePriority uint32 // 0(low) to 19(high) + Priority uint32 // 0(low) to 19(high) +} + +// CPUTime represents /dev/cputime or a part of /proc/n/status. +type CPUTime struct { + User time.Duration // the time in user mode (millisecconds) + Sys time.Duration + Real time.Duration + ChildUser time.Duration // exited children and descendants time in user mode + ChildSys time.Duration + ChildReal time.Duration +} + +// CPUStats emulates Linux's /proc/stat. +type CPUStats struct { + User time.Duration + Sys time.Duration + Idle time.Duration +} + +func ReadCPUStats(ctx context.Context, opts ...Option) (*CPUStats, error) { + cfg := newConfig(opts...) + a, err := ReadSysStats(ctx, opts...) + if err != nil { + return nil, err + } + + dir := filepath.Join(cfg.rootdir, "/proc") + d, err := os.Open(dir) + if err != nil { + return nil, err + } + defer d.Close() + + names, err := d.Readdirnames(0) + if err != nil { + return nil, err + } + var up uint32parser + pids := make([]uint32, len(names)) + for i, s := range names { + pids[i] = up.Parse(s) + } + if up.err != nil { + return nil, err + } + sort.Slice(pids, func(i, j int) bool { + return pids[i] < pids[j] + }) + + var stat CPUStats + for _, pid := range pids { + s := strconv.FormatUint(uint64(pid), 10) + file := filepath.Join(dir, s, "status") + var p ProcStatus + if err := readProcStatus(file, &p); err != nil { + return nil, err + } + stat.User += p.Times.User + stat.Sys += p.Times.Sys + } + + var t Time + file := filepath.Join(cfg.rootdir, "/dev/time") + if err := readTime(file, &t); err != nil { + return nil, err + } + // In multi-processor host, Idle should multiple by number of cores. + u := t.Uptime() * time.Duration(len(a)) + stat.Idle = u - stat.User - stat.Sys + return &stat, nil +} + +func readProcStatus(file string, p *ProcStatus) error { + b, err := ioutil.ReadFile(file) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + fields := strings.Fields(string(b)) + if len(fields) != 12 { + return errors.New("invalid format") + } + p.Name = string(fields[0]) + p.User = string(fields[1]) + p.State = string(fields[2]) + var up uint32parser + p.Times.User = time.Duration(up.Parse(fields[3])) * time.Millisecond + p.Times.Sys = time.Duration(up.Parse(fields[4])) * time.Millisecond + p.Times.Real = time.Duration(up.Parse(fields[5])) * time.Millisecond + p.Times.ChildUser = time.Duration(up.Parse(fields[6])) * time.Millisecond + p.Times.ChildSys = time.Duration(up.Parse(fields[7])) * time.Millisecond + p.Times.ChildReal = time.Duration(up.Parse(fields[8])) * time.Millisecond + p.MemUsed, err = strconv.ParseInt(fields[9], 10, 64) + if err != nil { + return err + } + p.BasePriority = up.Parse(fields[10]) + p.Priority = up.Parse(fields[11]) + return up.err +} + +func readTime(file string, t *Time) error { + b, err := ioutil.ReadFile(file) + if err != nil { + return err + } + fields := strings.Fields(string(b)) + if len(fields) != 4 { + return errors.New("invalid format") + } + n, err := strconv.ParseInt(fields[0], 10, 32) + if err != nil { + return err + } + t.Unix = time.Duration(n) * time.Second + v, err := strconv.ParseInt(fields[1], 10, 64) + if err != nil { + return err + } + t.UnixNano = time.Duration(v) * time.Nanosecond + t.Ticks, err = strconv.ParseInt(fields[2], 10, 64) + if err != nil { + return err + } + t.Freq, err = strconv.ParseInt(fields[3], 10, 64) + if err != nil { + return err + } + return nil +} + +type uint32parser struct { + err error +} + +func (p *uint32parser) Parse(s string) uint32 { + if p.err != nil { + return 0 + } + n, err := strconv.ParseUint(s, 10, 32) + if err != nil { + p.err = err + return 0 + } + return uint32(n) +} diff --git a/vendor/github.com/lufia/plan9stats/doc.go b/vendor/github.com/lufia/plan9stats/doc.go new file mode 100644 index 000000000..10e398e7a --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/doc.go @@ -0,0 +1,2 @@ +// Package stats provides statistic utilities for Plan 9. +package stats diff --git a/vendor/github.com/lufia/plan9stats/host.go b/vendor/github.com/lufia/plan9stats/host.go new file mode 100644 index 000000000..957e90348 --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/host.go @@ -0,0 +1,303 @@ +package stats + +import ( + "bufio" + "bytes" + "context" + "fmt" + "io/ioutil" + "net" + "os" + "path/filepath" + "strconv" + "strings" +) + +var ( + delim = []byte{' '} +) + +// Host represents host status. +type Host struct { + Sysname string + Storages []*Storage + Interfaces []*Interface +} + +// MemStats represents the memory statistics. +type MemStats struct { + Total int64 // total memory in byte + PageSize int64 // a page size in byte + KernelPages int64 + UserPages Gauge + SwapPages Gauge + + Malloced Gauge // kernel malloced data in byte + Graphics Gauge // kernel graphics data in byte +} + +// Gauge is used/available gauge. +type Gauge struct { + Used int64 + Avail int64 +} + +func (g Gauge) Free() int64 { + return g.Avail - g.Used +} + +// ReadMemStats reads memory statistics from /dev/swap. +func ReadMemStats(ctx context.Context, opts ...Option) (*MemStats, error) { + cfg := newConfig(opts...) + swap := filepath.Join(cfg.rootdir, "/dev/swap") + f, err := os.Open(swap) + if err != nil { + return nil, err + } + defer f.Close() + + var stat MemStats + m := map[string]interface{}{ + "memory": &stat.Total, + "pagesize": &stat.PageSize, + "kernel": &stat.KernelPages, + "user": &stat.UserPages, + "swap": &stat.SwapPages, + "kernel malloc": &stat.Malloced, + "kernel draw": &stat.Graphics, + } + scanner := bufio.NewScanner(f) + for scanner.Scan() { + fields := bytes.SplitN(scanner.Bytes(), delim, 2) + if len(fields) < 2 { + continue + } + switch key := string(fields[1]); key { + case "memory", "pagesize", "kernel": + v := m[key].(*int64) + n, err := strconv.ParseInt(string(fields[0]), 10, 64) + if err != nil { + return nil, err + } + *v = n + case "user", "swap", "kernel malloc", "kernel draw": + v := m[key].(*Gauge) + if err := parseGauge(string(fields[0]), v); err != nil { + return nil, err + } + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return &stat, nil +} + +func parseGauge(s string, r *Gauge) error { + a := strings.SplitN(s, "/", 2) + if len(a) != 2 { + return fmt.Errorf("can't parse ratio: %s", s) + } + var p intParser + u := p.ParseInt64(a[0], 10) + n := p.ParseInt64(a[1], 10) + if err := p.Err(); err != nil { + return err + } + r.Used = u + r.Avail = n + return nil +} + +type Storage struct { + Name string + Model string + Capacity int64 +} + +type Interface struct { + Name string + Addr string +} + +const ( + numEther = 8 // see ether(3) + numIpifc = 16 // see ip(3) +) + +// ReadInterfaces reads network interfaces from etherN. +func ReadInterfaces(ctx context.Context, opts ...Option) ([]*Interface, error) { + cfg := newConfig(opts...) + var a []*Interface + for i := 0; i < numEther; i++ { + p, err := readInterface(cfg.rootdir, i) + if os.IsNotExist(err) { + continue + } + if err != nil { + return nil, err + } + a = append(a, p) + } + return a, nil +} + +func readInterface(netroot string, i int) (*Interface, error) { + ether := fmt.Sprintf("ether%d", i) + dir := filepath.Join(netroot, ether) + info, err := os.Stat(dir) + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, fmt.Errorf("%s: is not directory", dir) + } + + addr, err := ioutil.ReadFile(filepath.Join(dir, "addr")) + if err != nil { + return nil, err + } + return &Interface{ + Name: ether, + Addr: string(addr), + }, nil +} + +var ( + netdirs = []string{"/net", "/net.alt"} +) + +// ReadHost reads host status. +func ReadHost(ctx context.Context, opts ...Option) (*Host, error) { + cfg := newConfig(opts...) + var h Host + name, err := readSysname(cfg.rootdir) + if err != nil { + return nil, err + } + h.Sysname = name + + a, err := readStorages(cfg.rootdir) + if err != nil { + return nil, err + } + h.Storages = a + + for _, s := range netdirs { + netroot := filepath.Join(cfg.rootdir, s) + ifaces, err := ReadInterfaces(ctx, WithRootDir(netroot)) + if err != nil { + return nil, err + } + h.Interfaces = append(h.Interfaces, ifaces...) + } + return &h, nil +} + +func readSysname(rootdir string) (string, error) { + file := filepath.Join(rootdir, "/dev/sysname") + b, err := ioutil.ReadFile(file) + if err != nil { + return "", err + } + return string(bytes.TrimSpace(b)), nil +} + +func readStorages(rootdir string) ([]*Storage, error) { + sdctl := filepath.Join(rootdir, "/dev/sdctl") + f, err := os.Open(sdctl) + if err != nil { + return nil, err + } + defer f.Close() + + var a []*Storage + scanner := bufio.NewScanner(f) + for scanner.Scan() { + fields := bytes.Split(scanner.Bytes(), delim) + if len(fields) == 0 { + continue + } + exp := string(fields[0]) + "*" + if !strings.HasPrefix(exp, "sd") { + continue + } + dir := filepath.Join(rootdir, "/dev", exp) + m, err := filepath.Glob(dir) + if err != nil { + return nil, err + } + for _, dir := range m { + s, err := readStorage(dir) + if err != nil { + return nil, err + } + a = append(a, s) + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return a, nil +} + +func readStorage(dir string) (*Storage, error) { + ctl := filepath.Join(dir, "ctl") + f, err := os.Open(ctl) + if err != nil { + return nil, err + } + defer f.Close() + + var s Storage + s.Name = filepath.Base(dir) + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := scanner.Bytes() + switch { + case bytes.HasPrefix(line, []byte("inquiry")): + s.Model = string(bytes.TrimSpace(line[7:])) + case bytes.HasPrefix(line, []byte("geometry")): + fields := bytes.Split(line, delim) + if len(fields) < 3 { + continue + } + var p intParser + sec := p.ParseInt64(string(fields[1]), 10) + size := p.ParseInt64(string(fields[2]), 10) + if err := p.Err(); err != nil { + return nil, err + } + s.Capacity = sec * size + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return &s, nil +} + +type IPStats struct { + ID int // number of interface in ipifc dir + Device string // associated physical device + MTU int // max transfer unit + Sendra6 uint8 // on == send router adv + Recvra6 uint8 // on == recv router adv + + Pktin int64 // packets read + Pktout int64 // packets written + Errin int64 // read errors + Errout int64 // write errors +} + +type Iplifc struct { + IP net.IP + Mask net.IPMask + Net net.IP // ip & mask + PerfLifetime int64 // preferred lifetime + ValidLifetime int64 // valid lifetime +} + +type Ipv6rp struct { + // TODO(lufia): see ip(2) +} diff --git a/vendor/github.com/lufia/plan9stats/int.go b/vendor/github.com/lufia/plan9stats/int.go new file mode 100644 index 000000000..db133c43e --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/int.go @@ -0,0 +1,31 @@ +package stats + +import ( + "strconv" +) + +type intParser struct { + err error +} + +func (p *intParser) ParseInt(s string, base int) int { + if p.err != nil { + return 0 + } + var n int64 + n, p.err = strconv.ParseInt(s, base, 0) + return int(n) +} + +func (p *intParser) ParseInt64(s string, base int) int64 { + if p.err != nil { + return 0 + } + var n int64 + n, p.err = strconv.ParseInt(s, base, 64) + return n +} + +func (p *intParser) Err() error { + return p.err +} diff --git a/vendor/github.com/lufia/plan9stats/opts.go b/vendor/github.com/lufia/plan9stats/opts.go new file mode 100644 index 000000000..05b7d036a --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/opts.go @@ -0,0 +1,21 @@ +package stats + +type Config struct { + rootdir string +} + +type Option func(*Config) + +func newConfig(opts ...Option) *Config { + var cfg Config + for _, opt := range opts { + opt(&cfg) + } + return &cfg +} + +func WithRootDir(dir string) Option { + return func(cfg *Config) { + cfg.rootdir = dir + } +} diff --git a/vendor/github.com/lufia/plan9stats/stats.go b/vendor/github.com/lufia/plan9stats/stats.go new file mode 100644 index 000000000..d4ecdcfa0 --- /dev/null +++ b/vendor/github.com/lufia/plan9stats/stats.go @@ -0,0 +1,88 @@ +package stats + +import ( + "bufio" + "context" + "os" + "path/filepath" + "strings" +) + +type InterfaceStats struct { + PacketsReceived int64 // in packets + Link int // link status + PacketsSent int64 // out packets + NumCRCErr int // input CRC errors + NumOverflows int // packet overflows + NumSoftOverflows int // software overflow + NumFramingErr int // framing errors + NumBufferingErr int // buffering errors + NumOutputErr int // output errors + Promiscuous int // number of promiscuous opens + Mbps int // megabits per sec + Addr string +} + +func ReadInterfaceStats(ctx context.Context, opts ...Option) (*InterfaceStats, error) { + cfg := newConfig(opts...) + file := filepath.Join(cfg.rootdir, "stats") + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + + var stats InterfaceStats + scanner := bufio.NewScanner(f) + for scanner.Scan() { + s := strings.TrimSpace(scanner.Text()) + a := strings.SplitN(s, ":", 2) + if len(a) != 2 { + continue + } + var p intParser + v := strings.TrimSpace(a[1]) + switch a[0] { + case "in": + stats.PacketsReceived = p.ParseInt64(v, 10) + case "link": + stats.Link = p.ParseInt(v, 10) + case "out": + stats.PacketsSent = p.ParseInt64(v, 10) + case "crc": + stats.NumCRCErr = p.ParseInt(v, 10) + case "overflows": + stats.NumOverflows = p.ParseInt(v, 10) + case "soft overflows": + stats.NumSoftOverflows = p.ParseInt(v, 10) + case "framing errs": + stats.NumFramingErr = p.ParseInt(v, 10) + case "buffer errs": + stats.NumBufferingErr = p.ParseInt(v, 10) + case "output errs": + stats.NumOutputErr = p.ParseInt(v, 10) + case "prom": + stats.Promiscuous = p.ParseInt(v, 10) + case "mbps": + stats.Mbps = p.ParseInt(v, 10) + case "addr": + stats.Addr = v + } + if err := p.Err(); err != nil { + return nil, err + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return &stats, nil +} + +type TCPStats struct { + MaxConn int + MaxSegment int + ActiveOpens int + PassiveOpens int + EstablishedResets int + CurrentEstablished int +} diff --git a/vendor/github.com/power-devops/perfstat/LICENSE b/vendor/github.com/power-devops/perfstat/LICENSE new file mode 100644 index 000000000..ec4e5d39d --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2020 Power DevOps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + diff --git a/vendor/github.com/power-devops/perfstat/c_helpers.c b/vendor/github.com/power-devops/perfstat/c_helpers.c new file mode 100644 index 000000000..49ba1ad7e --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/c_helpers.c @@ -0,0 +1,159 @@ +#include "c_helpers.h" + +GETFUNC(cpu) +GETFUNC(disk) +GETFUNC(diskadapter) +GETFUNC(diskpath) +GETFUNC(fcstat) +GETFUNC(logicalvolume) +GETFUNC(memory_page) +GETFUNC(netadapter) +GETFUNC(netbuffer) +GETFUNC(netinterface) +GETFUNC(pagingspace) +GETFUNC(process) +GETFUNC(thread) +GETFUNC(volumegroup) + +double get_partition_mhz(perfstat_partition_config_t pinfo) { + return pinfo.processorMHz; +} + +char *get_ps_hostname(perfstat_pagingspace_t *ps) { + return ps->u.nfs_paging.hostname; +} + +char *get_ps_filename(perfstat_pagingspace_t *ps) { + return ps->u.nfs_paging.filename; +} + +char *get_ps_vgname(perfstat_pagingspace_t *ps) { + return ps->u.lv_paging.vgname; +} + +time_t boottime() +{ + register struct utmpx *utmp; + + setutxent(); + while ( (utmp = getutxent()) != NULL ) { + if (utmp->ut_type == BOOT_TIME) { + return utmp->ut_tv.tv_sec; + } + } + endutxent(); + return -1; +} + +struct fsinfo *get_filesystem_stat(struct fsinfo *fs_all, int n) { + if (!fs_all) return NULL; + return &(fs_all[n]); +} + +int get_mounts(struct vmount **vmountpp) { + int size; + struct vmount *vm; + int nmounts; + + size = BUFSIZ; + + while (1) { + if ((vm = (struct vmount *)malloc((size_t)size)) == NULL) { + perror("malloc failed"); + exit(-1); + } + if ((nmounts = mntctl(MCTL_QUERY, size, (caddr_t)vm)) > 0) { + *vmountpp = vm; + return nmounts; + } else if (nmounts == 0) { + size = *(int *)vm; + free((void *)vm); + } else { + free((void *)vm); + return -1; + } + } +} + +void fill_fsinfo(struct statfs statbuf, struct fsinfo *fs) { + fsblkcnt_t freeblks, totblks, usedblks; + fsblkcnt_t tinodes, ninodes, ifree; + uint cfactor; + + if (statbuf.f_blocks == -1) { + fs->totalblks = 0; + fs->freeblks = 0; + fs->totalinodes = 0; + fs->freeinodes = 0; + return; + } + + cfactor = statbuf.f_bsize / 512; + fs->freeblks = statbuf.f_bavail * cfactor; + fs->totalblks = statbuf.f_blocks * cfactor; + + fs->freeinodes = statbuf.f_ffree; + fs->totalinodes = statbuf.f_files; + + if (fs->freeblks < 0) + fs->freeblks = 0; +} + +int getfsinfo(char *fsname, char *devname, char *host, char *options, int flags, int fstype, struct fsinfo *fs) { + struct statfs statbuf; + int devname_size = strlen(devname); + int fsname_size = strlen(fsname); + char buf[BUFSIZ]; + char *p; + + if (fs == NULL) { + return 1; + } + + for (p = strtok(options, ","); p != NULL; p = strtok(NULL, ",")) + if (strcmp(p, "ignore") == 0) + return 0; + + if (*host != 0 && strcmp(host, "-") != 0) { + sprintf(buf, "%s:%s", host, devname); + devname = buf; + } + fs->devname = (char *)calloc(devname_size+1, 1); + fs->fsname = (char *)calloc(fsname_size+1, 1); + strncpy(fs->devname, devname, devname_size); + strncpy(fs->fsname, fsname, fsname_size); + fs->flags = flags; + fs->fstype = fstype; + + if (statfs(fsname,&statbuf) < 0) { + return 1; + } + + fill_fsinfo(statbuf, fs); + return 0; +} + +struct fsinfo *get_all_fs(int *rc) { + struct vmount *mnt; + struct fsinfo *fs_all; + int nmounts; + + *rc = -1; + if ((nmounts = get_mounts(&mnt)) <= 0) { + perror("Can't get mount table info"); + return NULL; + } + + fs_all = (struct fsinfo *)calloc(sizeof(struct fsinfo), nmounts); + while ((*rc)++, nmounts--) { + getfsinfo(vmt2dataptr(mnt, VMT_STUB), + vmt2dataptr(mnt, VMT_OBJECT), + vmt2dataptr(mnt, VMT_HOST), + vmt2dataptr(mnt, VMT_ARGS), + mnt->vmt_flags, + mnt->vmt_gfstype, + &fs_all[*rc]); + mnt = (struct vmount *)((char *)mnt + mnt->vmt_length); + } + return fs_all; +} diff --git a/vendor/github.com/power-devops/perfstat/c_helpers.h b/vendor/github.com/power-devops/perfstat/c_helpers.h new file mode 100644 index 000000000..b66bc53c3 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/c_helpers.h @@ -0,0 +1,58 @@ +#ifndef C_HELPERS_H +#define C_HELPERS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define GETFUNC(TYPE) perfstat_##TYPE##_t *get_##TYPE##_stat(perfstat_##TYPE##_t *b, int n) { \ + if (!b) return NULL; \ + return &(b[n]); \ +} + +#define GETFUNC_EXT(TYPE) extern perfstat_##TYPE##_t *get_##TYPE##_stat(perfstat_##TYPE##_t *, int); + +GETFUNC_EXT(cpu) +GETFUNC_EXT(disk) +GETFUNC_EXT(diskadapter) +GETFUNC_EXT(diskpath) +GETFUNC_EXT(fcstat) +GETFUNC_EXT(logicalvolume) +GETFUNC_EXT(memory_page) +GETFUNC_EXT(netadapter) +GETFUNC_EXT(netbuffer) +GETFUNC_EXT(netinterface) +GETFUNC_EXT(pagingspace) +GETFUNC_EXT(process) +GETFUNC_EXT(thread) +GETFUNC_EXT(volumegroup) + +struct fsinfo { + char *devname; + char *fsname; + int flags; + int fstype; + unsigned long totalblks; + unsigned long freeblks; + unsigned long totalinodes; + unsigned long freeinodes; +}; + +extern double get_partition_mhz(perfstat_partition_config_t); +extern char *get_ps_hostname(perfstat_pagingspace_t *); +extern char *get_ps_filename(perfstat_pagingspace_t *); +extern char *get_ps_vgname(perfstat_pagingspace_t *); +extern time_t boottime(); +struct fsinfo *get_filesystem_stat(struct fsinfo *, int); +int get_mounts(struct vmount **); +void fill_statfs(struct statfs, struct fsinfo *); +int getfsinfo(char *, char *, char *, char *, int, int, struct fsinfo *); +struct fsinfo *get_all_fs(int *); + +#endif diff --git a/vendor/github.com/power-devops/perfstat/config.go b/vendor/github.com/power-devops/perfstat/config.go new file mode 100644 index 000000000..de7230d28 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/config.go @@ -0,0 +1,18 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +*/ +import "C" + +func EnableLVMStat() { + C.perfstat_config(C.PERFSTAT_ENABLE|C.PERFSTAT_LV|C.PERFSTAT_VG, nil) +} + +func DisableLVMStat() { + C.perfstat_config(C.PERFSTAT_DISABLE|C.PERFSTAT_LV|C.PERFSTAT_VG, nil) +} diff --git a/vendor/github.com/power-devops/perfstat/cpustat.go b/vendor/github.com/power-devops/perfstat/cpustat.go new file mode 100644 index 000000000..902727fb8 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/cpustat.go @@ -0,0 +1,98 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +#include +#include + +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" + "runtime" + "time" + "unsafe" +) + +func CpuStat() ([]CPU, error) { + var cpustat *C.perfstat_cpu_t + var cpu C.perfstat_id_t + + ncpu := runtime.NumCPU() + + cpustat_len := C.sizeof_perfstat_cpu_t * C.ulong(ncpu) + cpustat = (*C.perfstat_cpu_t)(C.malloc(cpustat_len)) + defer C.free(unsafe.Pointer(cpustat)) + C.strcpy(&cpu.name[0], C.CString(C.FIRST_CPU)) + r := C.perfstat_cpu(&cpu, cpustat, C.sizeof_perfstat_cpu_t, C.int(ncpu)) + if r <= 0 { + return nil, fmt.Errorf("error perfstat_cpu()") + } + c := make([]CPU, r) + for i := 0; i < int(r); i++ { + n := C.get_cpu_stat(cpustat, C.int(i)) + if n != nil { + c[i] = perfstatcpu2cpu(n) + } + } + return c, nil +} + +func CpuTotalStat() (*CPUTotal, error) { + var cpustat *C.perfstat_cpu_total_t + + cpustat = (*C.perfstat_cpu_total_t)(C.malloc(C.sizeof_perfstat_cpu_total_t)) + defer C.free(unsafe.Pointer(cpustat)) + r := C.perfstat_cpu_total(nil, cpustat, C.sizeof_perfstat_cpu_total_t, 1) + if r <= 0 { + return nil, fmt.Errorf("error perfstat_cpu_total()") + } + c := perfstatcputotal2cputotal(cpustat) + return &c, nil +} + +func CpuUtilStat(intvl time.Duration) (*CPUUtil, error) { + var cpuutil *C.perfstat_cpu_util_t + var newt *C.perfstat_cpu_total_t + var oldt *C.perfstat_cpu_total_t + var data C.perfstat_rawdata_t + + oldt = (*C.perfstat_cpu_total_t)(C.malloc(C.sizeof_perfstat_cpu_total_t)) + newt = (*C.perfstat_cpu_total_t)(C.malloc(C.sizeof_perfstat_cpu_total_t)) + cpuutil = (*C.perfstat_cpu_util_t)(C.malloc(C.sizeof_perfstat_cpu_util_t)) + defer C.free(unsafe.Pointer(oldt)) + defer C.free(unsafe.Pointer(newt)) + defer C.free(unsafe.Pointer(cpuutil)) + + r := C.perfstat_cpu_total(nil, oldt, C.sizeof_perfstat_cpu_total_t, 1) + if r <= 0 { + return nil, fmt.Errorf("error perfstat_cpu_total()") + } + + time.Sleep(intvl) + + r = C.perfstat_cpu_total(nil, newt, C.sizeof_perfstat_cpu_total_t, 1) + if r <= 0 { + return nil, fmt.Errorf("error perfstat_cpu_total()") + } + + data._type = C.UTIL_CPU_TOTAL + data.curstat = unsafe.Pointer(newt) + data.prevstat = unsafe.Pointer(oldt) + data.sizeof_data = C.sizeof_perfstat_cpu_total_t + data.cur_elems = 1 + data.prev_elems = 1 + + r = C.perfstat_cpu_util(&data, cpuutil, C.sizeof_perfstat_cpu_util_t, 1) + if r <= 0 { + return nil, fmt.Errorf("error perfstat_cpu_util()") + } + u := perfstatcpuutil2cpuutil(cpuutil) + return &u, nil +} diff --git a/vendor/github.com/power-devops/perfstat/diskstat.go b/vendor/github.com/power-devops/perfstat/diskstat.go new file mode 100644 index 000000000..fc70dfaa4 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/diskstat.go @@ -0,0 +1,137 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +#include +#include +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" +) + +func DiskTotalStat() (*DiskTotal, error) { + var disk C.perfstat_disk_total_t + + rc := C.perfstat_disk_total(nil, &disk, C.sizeof_perfstat_disk_total_t, 1) + if rc != 1 { + return nil, fmt.Errorf("perfstat_disk_total() error") + } + d := perfstatdisktotal2disktotal(disk) + return &d, nil +} + +func DiskAdapterStat() ([]DiskAdapter, error) { + var adapter *C.perfstat_diskadapter_t + var adptname C.perfstat_id_t + + numadpt := C.perfstat_diskadapter(nil, nil, C.sizeof_perfstat_diskadapter_t, 0) + if numadpt <= 0 { + return nil, fmt.Errorf("perfstat_diskadapter() error") + } + + adapter_len := C.sizeof_perfstat_diskadapter_t * C.ulong(numadpt) + adapter = (*C.perfstat_diskadapter_t)(C.malloc(adapter_len)) + defer C.free(unsafe.Pointer(adapter)) + C.strcpy(&adptname.name[0], C.CString(C.FIRST_DISKADAPTER)) + r := C.perfstat_diskadapter(&adptname, adapter, C.sizeof_perfstat_diskadapter_t, numadpt) + if r < 0 { + return nil, fmt.Errorf("perfstat_diskadapter() error") + } + da := make([]DiskAdapter, r) + for i := 0; i < int(r); i++ { + d := C.get_diskadapter_stat(adapter, C.int(i)) + if d != nil { + da[i] = perfstatdiskadapter2diskadapter(d) + } + } + return da, nil +} + +func DiskStat() ([]Disk, error) { + var disk *C.perfstat_disk_t + var diskname C.perfstat_id_t + + numdisk := C.perfstat_disk(nil, nil, C.sizeof_perfstat_disk_t, 0) + if numdisk <= 0 { + return nil, fmt.Errorf("perfstat_disk() error") + } + + disk_len := C.sizeof_perfstat_disk_t * C.ulong(numdisk) + disk = (*C.perfstat_disk_t)(C.malloc(disk_len)) + defer C.free(unsafe.Pointer(disk)) + C.strcpy(&diskname.name[0], C.CString(C.FIRST_DISK)) + r := C.perfstat_disk(&diskname, disk, C.sizeof_perfstat_disk_t, numdisk) + if r < 0 { + return nil, fmt.Errorf("perfstat_disk() error") + } + d := make([]Disk, r) + for i := 0; i < int(r); i++ { + ds := C.get_disk_stat(disk, C.int(i)) + if ds != nil { + d[i] = perfstatdisk2disk(ds) + } + } + return d, nil +} + +func DiskPathStat() ([]DiskPath, error) { + var diskpath *C.perfstat_diskpath_t + var pathname C.perfstat_id_t + + numpaths := C.perfstat_diskpath(nil, nil, C.sizeof_perfstat_diskpath_t, 0) + if numpaths <= 0 { + return nil, fmt.Errorf("perfstat_diskpath() error") + } + + path_len := C.sizeof_perfstat_diskpath_t * C.ulong(numpaths) + diskpath = (*C.perfstat_diskpath_t)(C.malloc(path_len)) + defer C.free(unsafe.Pointer(diskpath)) + C.strcpy(&pathname.name[0], C.CString(C.FIRST_DISKPATH)) + r := C.perfstat_diskpath(&pathname, diskpath, C.sizeof_perfstat_diskpath_t, numpaths) + if r < 0 { + return nil, fmt.Errorf("perfstat_diskpath() error") + } + d := make([]DiskPath, r) + for i := 0; i < int(r); i++ { + p := C.get_diskpath_stat(diskpath, C.int(i)) + if p != nil { + d[i] = perfstatdiskpath2diskpath(p) + } + } + return d, nil +} + +func FCAdapterStat() ([]FCAdapter, error) { + var fcstat *C.perfstat_fcstat_t + var fcname C.perfstat_id_t + + numadpt := C.perfstat_fcstat(nil, nil, C.sizeof_perfstat_fcstat_t, 0) + if numadpt <= 0 { + return nil, fmt.Errorf("perfstat_fcstat() error") + } + + fcstat_len := C.sizeof_perfstat_fcstat_t * C.ulong(numadpt) + fcstat = (*C.perfstat_fcstat_t)(C.malloc(fcstat_len)) + defer C.free(unsafe.Pointer(fcstat)) + C.strcpy(&fcname.name[0], C.CString(C.FIRST_NETINTERFACE)) + r := C.perfstat_fcstat(&fcname, fcstat, C.sizeof_perfstat_fcstat_t, numadpt) + if r < 0 { + return nil, fmt.Errorf("perfstat_fcstat() error") + } + fca := make([]FCAdapter, r) + for i := 0; i < int(r); i++ { + f := C.get_fcstat_stat(fcstat, C.int(i)) + if f != nil { + fca[i] = perfstatfcstat2fcadapter(f) + } + } + return fca, nil +} diff --git a/vendor/github.com/power-devops/perfstat/doc.go b/vendor/github.com/power-devops/perfstat/doc.go new file mode 100644 index 000000000..85eaf3e7e --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/doc.go @@ -0,0 +1,315 @@ +// +build !aix + +// Copyright 2020 Power-Devops.com. All rights reserved. +// Use of this source code is governed by the license +// that can be found in the LICENSE file. +/* +Package perfstat is Go interface to IBM AIX libperfstat. +To use it you need AIX with installed bos.perf.libperfstat. You can check, if is installed using the following command: + + $ lslpp -L bos.perf.perfstat + +The package is written using Go 1.14.7 and AIX 7.2 TL5. It should work with earlier TLs of AIX 7.2, but I +can't guarantee that perfstat structures in the TLs have all the same fields as the structures in AIX 7.2 TL5. + +For documentation of perfstat on AIX and using it in programs refer to the official IBM documentation: +https://www.ibm.com/support/knowledgecenter/ssw_aix_72/performancetools/idprftools_perfstat.html +*/ +package perfstat + +import ( + "fmt" + "time" +) + +// EnableLVMStat() switches on LVM (logical volumes and volume groups) performance statistics. +// With this enabled you can use fields KBReads, KBWrites, and IOCnt +// in LogicalVolume and VolumeGroup data types. +func EnableLVMStat() {} + +// DisableLVMStat() switchess of LVM (logical volumes and volume groups) performance statistics. +// This is the default state. In this case LogicalVolume and VolumeGroup data types are +// populated with informations about LVM structures, but performance statistics fields +// (KBReads, KBWrites, IOCnt) are empty. +func DisableLVMStat() {} + +// CpuStat() returns array of CPU structures with information about +// logical CPUs on the system. +// IBM documentation: +// * https://www.ibm.com/support/knowledgecenter/ssw_aix_72/performancetools/idprftools_perfstat_int_cpu.html +// * https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/p_bostechref/perfstat_cpu.html +func CpuStat() ([]CPU, error) { + return nil, fmt.Errorf("not implemented") +} + +// CpuTotalStat() returns general information about CPUs on the system. +// IBM documentation: +// * https://www.ibm.com/support/knowledgecenter/ssw_aix_72/performancetools/idprftools_perfstat_glob_cpu.html +// * https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/p_bostechref/perfstat_cputot.html +func CpuTotalStat() (*CPUTotal, error) { + return nil, fmt.Errorf("not implemented") +} + +// CpuUtilStat() calculates CPU utilization. +// IBM documentation: +// * https://www.ibm.com/support/knowledgecenter/ssw_aix_72/performancetools/idprftools_perfstat_cpu_util.html +// * https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/p_bostechref/perfstat_cpu_util.html +func CpuUtilStat(intvl time.Duration) (*CPUUtil, error) { + return nil, fmt.Errorf("not implemented") +} + +func DiskTotalStat() (*DiskTotal, error) { + return nil, fmt.Errorf("not implemented") +} + +func DiskAdapterStat() ([]DiskAdapter, error) { + return nil, fmt.Errorf("not implemented") +} + +func DiskStat() ([]Disk, error) { + return nil, fmt.Errorf("not implemented") +} + +func DiskPathStat() ([]DiskPath, error) { + return nil, fmt.Errorf("not implemented") +} + +func FCAdapterStat() ([]FCAdapter, error) { + return nil, fmt.Errorf("not implemented") +} + +func PartitionStat() (*PartitionConfig, error) { + return nil, fmt.Errorf("not implemented") +} + +func LogicalVolumeStat() ([]LogicalVolume, error) { + return nil, fmt.Errorf("not implemented") +} + +func VolumeGroupStat() ([]VolumeGroup, error) { + return nil, fmt.Errorf("not implemented") +} + +func MemoryTotalStat() (*MemoryTotal, error) { + return nil, fmt.Errorf("not implemented") +} + +func MemoryPageStat() ([]MemoryPage, error) { + return nil, fmt.Errorf("not implemented") +} + +func PagingSpaceStat() ([]PagingSpace, error) { + return nil, fmt.Errorf("not implemented") +} + +func NetIfaceTotalStat() (*NetIfaceTotal, error) { + return nil, fmt.Errorf("not implemented") +} + +func NetBufferStat() ([]NetBuffer, error) { + return nil, fmt.Errorf("not implemented") +} + +func NetIfaceStat() ([]NetIface, error) { + return nil, fmt.Errorf("not implemented") +} + +func NetAdapterStat() ([]NetAdapter, error) { + return nil, fmt.Errorf("not implemented") +} + +func ProcessStat() ([]Process, error) { + return nil, fmt.Errorf("not implemented") +} + +func ThreadStat() ([]Thread, error) { + return nil, fmt.Errorf("not implemented") +} + +func Sysconf(name int32) (int64, error) { + return 0, fmt.Errorf("not implemented") +} + +func GetCPUImplementation() string { + return "" +} + +func POWER9OrNewer() bool { + return false +} + +func POWER9() bool { + return false +} + +func POWER8OrNewer() bool { + return false +} + +func POWER8() bool { + return false +} + +func POWER7OrNewer() bool { + return false +} + +func POWER7() bool { + return false +} + +func HasTransactionalMemory() bool { + return false +} + +func Is64Bit() bool { + return false +} + +func IsSMP() bool { + return false +} + +func HasVMX() bool { + return false +} + +func HasVSX() bool { + return false +} + +func HasDFP() bool { + return false +} + +func HasNxGzip() bool { + return false +} + +func PksCapable() bool { + return false +} + +func PksEnabled() bool { + return false +} + +func CPUMode() string { + return "" +} + +func KernelBits() int { + return 0 +} + +func IsLPAR() bool { + return false +} + +func CpuAddCapable() bool { + return false +} + +func CpuRemoveCapable() bool { + return false +} + +func MemoryAddCapable() bool { + return false +} + +func MemoryRemoveCapable() bool { + return false +} + +func DLparCapable() bool { + return false +} + +func IsNUMA() bool { + return false +} + +func KernelKeys() bool { + return false +} + +func RecoveryMode() bool { + return false +} + +func EnhancedAffinity() bool { + return false +} + +func VTpmEnabled() bool { + return false +} + +func IsVIOS() bool { + return false +} + +func MLSEnabled() bool { + return false +} + +func SPLparCapable() bool { + return false +} + +func SPLparEnabled() bool { + return false +} + +func DedicatedLpar() bool { + return false +} + +func SPLparCapped() bool { + return false +} + +func SPLparDonating() bool { + return false +} + +func SmtCapable() bool { + return false +} + +func SmtEnabled() bool { + return false +} + +func VrmCapable() bool { + return false +} + +func VrmEnabled() bool { + return false +} + +func AmeEnabled() bool { + return false +} + +func EcoCapable() bool { + return false +} + +func EcoEnabled() bool { + return false +} + +func BootTime() (uint64, error) { + return 0, fmt.Errorf("Not implemented") +} + +func UptimeSeconds() (uint64, error) { + return 0, fmt.Errorf("Not implemented") +} + +func FileSystemStat() ([]FileSystem, error) { + return nil, fmt.Errorf("Not implemented") +} diff --git a/vendor/github.com/power-devops/perfstat/fsstat.go b/vendor/github.com/power-devops/perfstat/fsstat.go new file mode 100644 index 000000000..27f4c06c1 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/fsstat.go @@ -0,0 +1,31 @@ +// +build aix + +package perfstat + +/* +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" +) + +func FileSystemStat() ([]FileSystem, error) { + var fsinfo *C.struct_fsinfo + var nmounts C.int + + fsinfo = C.get_all_fs(&nmounts) + if nmounts <= 0 { + return nil, fmt.Errorf("No mounts found") + } + + fs := make([]FileSystem, nmounts) + for i := 0; i < int(nmounts); i++ { + f := C.get_filesystem_stat(fsinfo, C.int(i)) + if f != nil { + fs[i] = fsinfo2filesystem(f) + } + } + return fs, nil +} diff --git a/vendor/github.com/power-devops/perfstat/helpers.go b/vendor/github.com/power-devops/perfstat/helpers.go new file mode 100644 index 000000000..e8d699766 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/helpers.go @@ -0,0 +1,764 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +#include + +#include "c_helpers.h" +*/ +import "C" + +func perfstatcpu2cpu(n *C.perfstat_cpu_t) CPU { + var c CPU + c.Name = C.GoString(&n.name[0]) + c.User = int64(n.user) + c.Sys = int64(n.sys) + c.Idle = int64(n.idle) + c.Wait = int64(n.wait) + c.PSwitch = int64(n.pswitch) + c.Syscall = int64(n.syscall) + c.Sysread = int64(n.sysread) + c.Syswrite = int64(n.syswrite) + c.Sysfork = int64(n.sysfork) + c.Sysexec = int64(n.sysexec) + c.Readch = int64(n.readch) + c.Writech = int64(n.writech) + c.Bread = int64(n.bread) + c.Bwrite = int64(n.bwrite) + c.Lread = int64(n.lread) + c.Lwrite = int64(n.lwrite) + c.Phread = int64(n.phread) + c.Phwrite = int64(n.phwrite) + c.Iget = int64(n.iget) + c.Namei = int64(n.namei) + c.Dirblk = int64(n.dirblk) + c.Msg = int64(n.msg) + c.Sema = int64(n.sema) + c.MinFaults = int64(n.minfaults) + c.MajFaults = int64(n.majfaults) + c.PUser = int64(n.puser) + c.PSys = int64(n.psys) + c.PIdle = int64(n.pidle) + c.PWait = int64(n.pwait) + c.RedispSD0 = int64(n.redisp_sd0) + c.RedispSD1 = int64(n.redisp_sd1) + c.RedispSD2 = int64(n.redisp_sd2) + c.RedispSD3 = int64(n.redisp_sd3) + c.RedispSD4 = int64(n.redisp_sd4) + c.RedispSD5 = int64(n.redisp_sd5) + c.MigrationPush = int64(n.migration_push) + c.MigrationS3grq = int64(n.migration_S3grq) + c.MigrationS3pul = int64(n.migration_S3pul) + c.InvolCSwitch = int64(n.invol_cswitch) + c.VolCSwitch = int64(n.vol_cswitch) + c.RunQueue = int64(n.runque) + c.Bound = int64(n.bound) + c.DecrIntrs = int64(n.decrintrs) + c.MpcRIntrs = int64(n.mpcrintrs) + c.MpcSIntrs = int64(n.mpcsintrs) + c.SoftIntrs = int64(n.softintrs) + c.DevIntrs = int64(n.devintrs) + c.PhantIntrs = int64(n.phantintrs) + c.IdleDonatedPurr = int64(n.idle_donated_purr) + c.IdleDonatedSpurr = int64(n.idle_donated_spurr) + c.BusyDonatedPurr = int64(n.busy_donated_purr) + c.BusyDonatedSpurr = int64(n.busy_donated_spurr) + c.IdleStolenPurr = int64(n.idle_stolen_purr) + c.IdleStolenSpurr = int64(n.idle_stolen_spurr) + c.BusyStolenPurr = int64(n.busy_stolen_purr) + c.BusyStolenSpurr = int64(n.busy_stolen_spurr) + c.Hpi = int64(n.hpi) + c.Hpit = int64(n.hpit) + c.PUserSpurr = int64(n.puser_spurr) + c.PSysSpurr = int64(n.psys_spurr) + c.PIdleSpurr = int64(n.pidle_spurr) + c.PWaitSpurr = int64(n.pwait_spurr) + c.SpurrFlag = int32(n.spurrflag) + c.LocalDispatch = int64(n.localdispatch) + c.NearDispatch = int64(n.neardispatch) + c.FarDispatch = int64(n.fardispatch) + c.CSwitches = int64(n.cswitches) + c.Version = int64(n.version) + c.TbLast = int64(n.tb_last) + c.State = int(n.state) + c.VtbLast = int64(n.vtb_last) + c.ICountLast = int64(n.icount_last) + return c +} + +func perfstatcputotal2cputotal(n *C.perfstat_cpu_total_t) CPUTotal { + var c CPUTotal + c.NCpus = int(n.ncpus) + c.NCpusCfg = int(n.ncpus_cfg) + c.Description = C.GoString(&n.description[0]) + c.ProcessorHz = int64(n.processorHZ) + c.User = int64(n.user) + c.Sys = int64(n.sys) + c.Idle = int64(n.idle) + c.Wait = int64(n.wait) + c.PSwitch = int64(n.pswitch) + c.Syscall = int64(n.syscall) + c.Sysread = int64(n.sysread) + c.Syswrite = int64(n.syswrite) + c.Sysfork = int64(n.sysfork) + c.Sysexec = int64(n.sysexec) + c.Readch = int64(n.readch) + c.Writech = int64(n.writech) + c.DevIntrs = int64(n.devintrs) + c.SoftIntrs = int64(n.softintrs) + c.Lbolt = int64(n.lbolt) + c.LoadAvg1 = (float32(n.loadavg[0]) / (1 << C.SBITS)) + c.LoadAvg5 = (float32(n.loadavg[1]) / (1 << C.SBITS)) + c.LoadAvg15 = (float32(n.loadavg[2]) / (1 << C.SBITS)) + c.RunQueue = int64(n.runque) + c.SwpQueue = int64(n.swpque) + c.Bread = int64(n.bread) + c.Bwrite = int64(n.bwrite) + c.Lread = int64(n.lread) + c.Lwrite = int64(n.lwrite) + c.Phread = int64(n.phread) + c.Phwrite = int64(n.phwrite) + c.RunOcc = int64(n.runocc) + c.SwpOcc = int64(n.swpocc) + c.Iget = int64(n.iget) + c.Namei = int64(n.namei) + c.Dirblk = int64(n.dirblk) + c.Msg = int64(n.msg) + c.Sema = int64(n.sema) + c.RcvInt = int64(n.rcvint) + c.XmtInt = int64(n.xmtint) + c.MdmInt = int64(n.mdmint) + c.TtyRawInch = int64(n.tty_rawinch) + c.TtyCanInch = int64(n.tty_caninch) + c.TtyRawOutch = int64(n.tty_rawoutch) + c.Ksched = int64(n.ksched) + c.Koverf = int64(n.koverf) + c.Kexit = int64(n.kexit) + c.Rbread = int64(n.rbread) + c.Rcread = int64(n.rcread) + c.Rbwrt = int64(n.rbwrt) + c.Rcwrt = int64(n.rcwrt) + c.Traps = int64(n.traps) + c.NCpusHigh = int64(n.ncpus_high) + c.PUser = int64(n.puser) + c.PSys = int64(n.psys) + c.PIdle = int64(n.pidle) + c.PWait = int64(n.pwait) + c.DecrIntrs = int64(n.decrintrs) + c.MpcRIntrs = int64(n.mpcrintrs) + c.MpcSIntrs = int64(n.mpcsintrs) + c.PhantIntrs = int64(n.phantintrs) + c.IdleDonatedPurr = int64(n.idle_donated_purr) + c.IdleDonatedSpurr = int64(n.idle_donated_spurr) + c.BusyDonatedPurr = int64(n.busy_donated_purr) + c.BusyDonatedSpurr = int64(n.busy_donated_spurr) + c.IdleStolenPurr = int64(n.idle_stolen_purr) + c.IdleStolenSpurr = int64(n.idle_stolen_spurr) + c.BusyStolenPurr = int64(n.busy_stolen_purr) + c.BusyStolenSpurr = int64(n.busy_stolen_spurr) + c.IOWait = int32(n.iowait) + c.PhysIO = int32(n.physio) + c.TWait = int64(n.twait) + c.Hpi = int64(n.hpi) + c.Hpit = int64(n.hpit) + c.PUserSpurr = int64(n.puser_spurr) + c.PSysSpurr = int64(n.psys_spurr) + c.PIdleSpurr = int64(n.pidle_spurr) + c.PWaitSpurr = int64(n.pwait_spurr) + c.SpurrFlag = int(n.spurrflag) + c.Version = int64(n.version) + c.TbLast = int64(n.tb_last) + c.PurrCoalescing = int64(n.purr_coalescing) + c.SpurrCoalescing = int64(n.spurr_coalescing) + return c +} + +func perfstatcpuutil2cpuutil(n *C.perfstat_cpu_util_t) CPUUtil { + var c CPUUtil + + c.Version = int64(n.version) + c.CpuID = C.GoString(&n.cpu_id[0]) + c.Entitlement = float32(n.entitlement) + c.UserPct = float32(n.user_pct) + c.KernPct = float32(n.kern_pct) + c.IdlePct = float32(n.idle_pct) + c.WaitPct = float32(n.wait_pct) + c.PhysicalBusy = float32(n.physical_busy) + c.PhysicalConsumed = float32(n.physical_consumed) + c.FreqPct = float32(n.freq_pct) + c.EntitlementPct = float32(n.entitlement_pct) + c.BusyPct = float32(n.busy_pct) + c.IdleDonatedPct = float32(n.idle_donated_pct) + c.BusyDonatedPct = float32(n.busy_donated_pct) + c.IdleStolenPct = float32(n.idle_stolen_pct) + c.BusyStolenPct = float32(n.busy_stolen_pct) + c.LUserPct = float32(n.l_user_pct) + c.LKernPct = float32(n.l_kern_pct) + c.LIdlePct = float32(n.l_idle_pct) + c.LWaitPct = float32(n.l_wait_pct) + c.DeltaTime = int64(n.delta_time) + + return c +} + +func perfstatdisktotal2disktotal(n C.perfstat_disk_total_t) DiskTotal { + var d DiskTotal + + d.Number = int32(n.number) + d.Size = int64(n.size) + d.Free = int64(n.free) + d.XRate = int64(n.xrate) + d.Xfers = int64(n.xfers) + d.Wblks = int64(n.wblks) + d.Rblks = int64(n.rblks) + d.Time = int64(n.time) + d.Version = int64(n.version) + d.Rserv = int64(n.rserv) + d.MinRserv = int64(n.min_rserv) + d.MaxRserv = int64(n.max_rserv) + d.RTimeOut = int64(n.rtimeout) + d.RFailed = int64(n.rfailed) + d.Wserv = int64(n.wserv) + d.MinWserv = int64(n.min_wserv) + d.MaxWserv = int64(n.max_wserv) + d.WTimeOut = int64(n.wtimeout) + d.WFailed = int64(n.wfailed) + d.WqDepth = int64(n.wq_depth) + d.WqTime = int64(n.wq_time) + d.WqMinTime = int64(n.wq_min_time) + d.WqMaxTime = int64(n.wq_max_time) + + return d +} + +func perfstatdiskadapter2diskadapter(n *C.perfstat_diskadapter_t) DiskAdapter { + var d DiskAdapter + + d.Name = C.GoString(&n.name[0]) + d.Description = C.GoString(&n.description[0]) + d.Number = int32(n.number) + d.Size = int64(n.size) + d.Free = int64(n.free) + d.XRate = int64(n.xrate) + d.Xfers = int64(n.xfers) + d.Rblks = int64(n.rblks) + d.Wblks = int64(n.wblks) + d.Time = int64(n.time) + d.Version = int64(n.version) + d.AdapterType = int64(n.adapter_type) + d.DkBSize = int64(n.dk_bsize) + d.DkRserv = int64(n.dk_rserv) + d.DkWserv = int64(n.dk_wserv) + d.MinRserv = int64(n.min_rserv) + d.MaxRserv = int64(n.max_rserv) + d.MinWserv = int64(n.min_wserv) + d.MaxWserv = int64(n.max_wserv) + d.WqDepth = int64(n.wq_depth) + d.WqSampled = int64(n.wq_sampled) + d.WqTime = int64(n.wq_time) + d.WqMinTime = int64(n.wq_min_time) + d.WqMaxTime = int64(n.wq_max_time) + d.QFull = int64(n.q_full) + d.QSampled = int64(n.q_sampled) + + return d +} + +func perfstatpartitionconfig2partitionconfig(n C.perfstat_partition_config_t) PartitionConfig { + var p PartitionConfig + p.Version = int64(n.version) + p.Name = C.GoString(&n.partitionname[0]) + p.Node = C.GoString(&n.nodename[0]) + p.Conf.SmtCapable = (n.conf[0] & (1 << 7)) > 0 + p.Conf.SmtEnabled = (n.conf[0] & (1 << 6)) > 0 + p.Conf.LparCapable = (n.conf[0] & (1 << 5)) > 0 + p.Conf.LparEnabled = (n.conf[0] & (1 << 4)) > 0 + p.Conf.SharedCapable = (n.conf[0] & (1 << 3)) > 0 + p.Conf.SharedEnabled = (n.conf[0] & (1 << 2)) > 0 + p.Conf.DLparCapable = (n.conf[0] & (1 << 1)) > 0 + p.Conf.Capped = (n.conf[0] & (1 << 0)) > 0 + p.Conf.Kernel64bit = (n.conf[1] & (1 << 7)) > 0 + p.Conf.PoolUtilAuthority = (n.conf[1] & (1 << 6)) > 0 + p.Conf.DonateCapable = (n.conf[1] & (1 << 5)) > 0 + p.Conf.DonateEnabled = (n.conf[1] & (1 << 4)) > 0 + p.Conf.AmsCapable = (n.conf[1] & (1 << 3)) > 0 + p.Conf.AmsEnabled = (n.conf[1] & (1 << 2)) > 0 + p.Conf.PowerSave = (n.conf[1] & (1 << 1)) > 0 + p.Conf.AmeEnabled = (n.conf[1] & (1 << 0)) > 0 + p.Conf.SharedExtended = (n.conf[2] & (1 << 7)) > 0 + p.Number = int32(n.partitionnum) + p.GroupID = int32(n.groupid) + p.ProcessorFamily = C.GoString(&n.processorFamily[0]) + p.ProcessorModel = C.GoString(&n.processorModel[0]) + p.MachineID = C.GoString(&n.machineID[0]) + p.ProcessorMhz = float64(C.get_partition_mhz(n)) + p.NumProcessors.Online = int64(n.numProcessors.online) + p.NumProcessors.Max = int64(n.numProcessors.max) + p.NumProcessors.Min = int64(n.numProcessors.min) + p.NumProcessors.Desired = int64(n.numProcessors.desired) + p.OSName = C.GoString(&n.OSName[0]) + p.OSVersion = C.GoString(&n.OSVersion[0]) + p.OSBuild = C.GoString(&n.OSBuild[0]) + p.LCpus = int32(n.lcpus) + p.SmtThreads = int32(n.smtthreads) + p.Drives = int32(n.drives) + p.NetworkAdapters = int32(n.nw_adapters) + p.CpuCap.Online = int64(n.cpucap.online) + p.CpuCap.Max = int64(n.cpucap.max) + p.CpuCap.Min = int64(n.cpucap.min) + p.CpuCap.Desired = int64(n.cpucap.desired) + p.Weightage = int32(n.cpucap_weightage) + p.EntCapacity = int32(n.entitled_proc_capacity) + p.VCpus.Online = int64(n.vcpus.online) + p.VCpus.Max = int64(n.vcpus.max) + p.VCpus.Min = int64(n.vcpus.min) + p.VCpus.Desired = int64(n.vcpus.desired) + p.PoolID = int32(n.processor_poolid) + p.ActiveCpusInPool = int32(n.activecpusinpool) + p.PoolWeightage = int32(n.cpupool_weightage) + p.SharedPCpu = int32(n.sharedpcpu) + p.MaxPoolCap = int32(n.maxpoolcap) + p.EntPoolCap = int32(n.entpoolcap) + p.Mem.Online = int64(n.mem.online) + p.Mem.Max = int64(n.mem.max) + p.Mem.Min = int64(n.mem.min) + p.Mem.Desired = int64(n.mem.desired) + p.MemWeightage = int32(n.mem_weightage) + p.TotalIOMemoryEntitlement = int64(n.totiomement) + p.MemPoolID = int32(n.mempoolid) + p.HyperPgSize = int64(n.hyperpgsize) + p.ExpMem.Online = int64(n.exp_mem.online) + p.ExpMem.Max = int64(n.exp_mem.max) + p.ExpMem.Min = int64(n.exp_mem.min) + p.ExpMem.Desired = int64(n.exp_mem.desired) + p.TargetMemExpFactor = int64(n.targetmemexpfactor) + p.TargetMemExpSize = int64(n.targetmemexpsize) + p.SubProcessorMode = int32(n.subprocessor_mode) + return p +} + +func perfstatmemorytotal2memorytotal(n C.perfstat_memory_total_t) MemoryTotal { + var m MemoryTotal + m.VirtualTotal = int64(n.virt_total) + m.RealTotal = int64(n.real_total) + m.RealFree = int64(n.real_free) + m.RealPinned = int64(n.real_pinned) + m.RealInUse = int64(n.real_inuse) + m.BadPages = int64(n.pgbad) + m.PageFaults = int64(n.pgexct) + m.PageIn = int64(n.pgins) + m.PageOut = int64(n.pgouts) + m.PgSpIn = int64(n.pgspins) + m.PgSpOut = int64(n.pgspouts) + m.Scans = int64(n.scans) + m.Cycles = int64(n.cycles) + m.PgSteals = int64(n.pgsteals) + m.NumPerm = int64(n.numperm) + m.PgSpTotal = int64(n.pgsp_total) + m.PgSpFree = int64(n.pgsp_free) + m.PgSpRsvd = int64(n.pgsp_rsvd) + m.RealSystem = int64(n.real_system) + m.RealUser = int64(n.real_user) + m.RealProcess = int64(n.real_process) + m.VirtualActive = int64(n.virt_active) + m.IOME = int64(n.iome) + m.IOMU = int64(n.iomu) + m.IOHWM = int64(n.iohwm) + m.PMem = int64(n.pmem) + m.CompressedTotal = int64(n.comprsd_total) + m.CompressedWSegPg = int64(n.comprsd_wseg_pgs) + m.CPgIn = int64(n.cpgins) + m.CPgOut = int64(n.cpgouts) + m.TrueSize = int64(n.true_size) + m.ExpandedMemory = int64(n.expanded_memory) + m.CompressedWSegSize = int64(n.comprsd_wseg_size) + m.TargetCPoolSize = int64(n.target_cpool_size) + m.MaxCPoolSize = int64(n.max_cpool_size) + m.MinUCPoolSize = int64(n.min_ucpool_size) + m.CPoolSize = int64(n.cpool_size) + m.UCPoolSize = int64(n.ucpool_size) + m.CPoolInUse = int64(n.cpool_inuse) + m.UCPoolInUse = int64(n.ucpool_inuse) + m.Version = int64(n.version) + m.RealAvailable = int64(n.real_avail) + m.BytesCoalesced = int64(n.bytes_coalesced) + m.BytesCoalescedMemPool = int64(n.bytes_coalesced_mempool) + + return m +} + +func perfstatnetinterfacetotal2netifacetotal(n C.perfstat_netinterface_total_t) NetIfaceTotal { + var i NetIfaceTotal + + i.Number = int32(n.number) + i.IPackets = int64(n.ipackets) + i.IBytes = int64(n.ibytes) + i.IErrors = int64(n.ierrors) + i.OPackets = int64(n.opackets) + i.OBytes = int64(n.obytes) + i.OErrors = int64(n.oerrors) + i.Collisions = int64(n.collisions) + i.XmitDrops = int64(n.xmitdrops) + i.Version = int64(n.version) + + return i +} + +func perfstatdisk2disk(n *C.perfstat_disk_t) Disk { + var d Disk + + d.Name = C.GoString(&n.name[0]) + d.Description = C.GoString(&n.description[0]) + d.VGName = C.GoString(&n.vgname[0]) + d.Size = int64(n.size) + d.Free = int64(n.free) + d.BSize = int64(n.bsize) + d.XRate = int64(n.xrate) + d.Xfers = int64(n.xfers) + d.Wblks = int64(n.wblks) + d.Rblks = int64(n.rblks) + d.QDepth = int64(n.qdepth) + d.Time = int64(n.time) + d.Adapter = C.GoString(&n.adapter[0]) + d.PathsCount = int32(n.paths_count) + d.QFull = int64(n.q_full) + d.Rserv = int64(n.rserv) + d.RTimeOut = int64(n.rtimeout) + d.Rfailed = int64(n.rfailed) + d.MinRserv = int64(n.min_rserv) + d.MaxRserv = int64(n.max_rserv) + d.Wserv = int64(n.wserv) + d.WTimeOut = int64(n.wtimeout) + d.Wfailed = int64(n.wfailed) + d.MinWserv = int64(n.min_wserv) + d.MaxWserv = int64(n.max_wserv) + d.WqDepth = int64(n.wq_depth) + d.WqSampled = int64(n.wq_sampled) + d.WqTime = int64(n.wq_time) + d.WqMinTime = int64(n.wq_min_time) + d.WqMaxTime = int64(n.wq_max_time) + d.QSampled = int64(n.q_sampled) + d.Version = int64(n.version) + d.PseudoDisk = (n.dk_type[0] & (1 << 7)) > 0 + d.VTDisk = (n.dk_type[0] & (1 << 6)) > 0 + + return d +} + +func perfstatdiskpath2diskpath(n *C.perfstat_diskpath_t) DiskPath { + var d DiskPath + + d.Name = C.GoString(&n.name[0]) + d.XRate = int64(n.xrate) + d.Xfers = int64(n.xfers) + d.Rblks = int64(n.rblks) + d.Wblks = int64(n.wblks) + d.Time = int64(n.time) + d.Adapter = C.GoString(&n.adapter[0]) + d.QFull = int64(n.q_full) + d.Rserv = int64(n.rserv) + d.RTimeOut = int64(n.rtimeout) + d.Rfailed = int64(n.rfailed) + d.MinRserv = int64(n.min_rserv) + d.MaxRserv = int64(n.max_rserv) + d.Wserv = int64(n.wserv) + d.WTimeOut = int64(n.wtimeout) + d.Wfailed = int64(n.wfailed) + d.MinWserv = int64(n.min_wserv) + d.MaxWserv = int64(n.max_wserv) + d.WqDepth = int64(n.wq_depth) + d.WqSampled = int64(n.wq_sampled) + d.WqTime = int64(n.wq_time) + d.WqMinTime = int64(n.wq_min_time) + d.WqMaxTime = int64(n.wq_max_time) + d.QSampled = int64(n.q_sampled) + d.Version = int64(n.version) + + return d +} + +func perfstatfcstat2fcadapter(n *C.perfstat_fcstat_t) FCAdapter { + var f FCAdapter + + f.Version = int64(n.version) + f.Name = C.GoString(&n.name[0]) + f.State = int32(n.state) + f.InputRequests = int64(n.InputRequests) + f.OutputRequests = int64(n.OutputRequests) + f.InputBytes = int64(n.InputBytes) + f.OutputBytes = int64(n.OutputBytes) + f.EffMaxTransfer = int64(n.EffMaxTransfer) + f.NoDMAResourceCnt = int64(n.NoDMAResourceCnt) + f.NoCmdResourceCnt = int64(n.NoCmdResourceCnt) + f.AttentionType = int32(n.AttentionType) + f.SecondsSinceLastReset = int64(n.SecondsSinceLastReset) + f.TxFrames = int64(n.TxFrames) + f.TxWords = int64(n.TxWords) + f.RxFrames = int64(n.RxFrames) + f.RxWords = int64(n.RxWords) + f.LIPCount = int64(n.LIPCount) + f.NOSCount = int64(n.NOSCount) + f.ErrorFrames = int64(n.ErrorFrames) + f.DumpedFrames = int64(n.DumpedFrames) + f.LinkFailureCount = int64(n.LinkFailureCount) + f.LossofSyncCount = int64(n.LossofSyncCount) + f.LossofSignal = int64(n.LossofSignal) + f.PrimitiveSeqProtocolErrCount = int64(n.PrimitiveSeqProtocolErrCount) + f.InvalidTxWordCount = int64(n.InvalidTxWordCount) + f.InvalidCRCCount = int64(n.InvalidCRCCount) + f.PortFcId = int64(n.PortFcId) + f.PortSpeed = int64(n.PortSpeed) + f.PortType = C.GoString(&n.PortType[0]) + f.PortWWN = int64(n.PortWWN) + f.PortSupportedSpeed = int64(n.PortSupportedSpeed) + f.AdapterType = int(n.adapter_type) + f.VfcName = C.GoString(&n.vfc_name[0]) + f.ClientPartName = C.GoString(&n.client_part_name[0]) + + return f +} + +func perfstatlogicalvolume2logicalvolume(n *C.perfstat_logicalvolume_t) LogicalVolume { + var l LogicalVolume + + l.Name = C.GoString(&n.name[0]) + l.VGName = C.GoString(&n.vgname[0]) + l.OpenClose = int64(n.open_close) + l.State = int64(n.state) + l.MirrorPolicy = int64(n.mirror_policy) + l.MirrorWriteConsistency = int64(n.mirror_write_consistency) + l.WriteVerify = int64(n.write_verify) + l.PPsize = int64(n.ppsize) + l.LogicalPartitions = int64(n.logical_partitions) + l.Mirrors = int32(n.mirrors) + l.IOCnt = int64(n.iocnt) + l.KBReads = int64(n.kbreads) + l.KBWrites = int64(n.kbwrites) + l.Version = int64(n.version) + + return l +} + +func perfstatvolumegroup2volumegroup(n *C.perfstat_volumegroup_t) VolumeGroup { + var v VolumeGroup + + v.Name = C.GoString(&n.name[0]) + v.TotalDisks = int64(n.total_disks) + v.ActiveDisks = int64(n.active_disks) + v.TotalLogicalVolumes = int64(n.total_logical_volumes) + v.OpenedLogicalVolumes = int64(n.opened_logical_volumes) + v.IOCnt = int64(n.iocnt) + v.KBReads = int64(n.kbreads) + v.KBWrites = int64(n.kbwrites) + v.Version = int64(n.version) + v.VariedState = int(n.variedState) + + return v +} + +func perfstatmemorypage2memorypage(n *C.perfstat_memory_page_t) MemoryPage { + var m MemoryPage + + m.PSize = int64(n.psize) + m.RealTotal = int64(n.real_total) + m.RealFree = int64(n.real_free) + m.RealPinned = int64(n.real_pinned) + m.RealInUse = int64(n.real_inuse) + m.PgExct = int64(n.pgexct) + m.PgIns = int64(n.pgins) + m.PgOuts = int64(n.pgouts) + m.PgSpIns = int64(n.pgspins) + m.PgSpOuts = int64(n.pgspouts) + m.Scans = int64(n.scans) + m.Cycles = int64(n.cycles) + m.PgSteals = int64(n.pgsteals) + m.NumPerm = int64(n.numperm) + m.NumPgSp = int64(n.numpgsp) + m.RealSystem = int64(n.real_system) + m.RealUser = int64(n.real_user) + m.RealProcess = int64(n.real_process) + m.VirtActive = int64(n.virt_active) + m.ComprsdTotal = int64(n.comprsd_total) + m.ComprsdWsegPgs = int64(n.comprsd_wseg_pgs) + m.CPgIns = int64(n.cpgins) + m.CPgOuts = int64(n.cpgouts) + m.CPoolInUse = int64(n.cpool_inuse) + m.UCPoolSize = int64(n.ucpool_size) + m.ComprsdWsegSize = int64(n.comprsd_wseg_size) + m.Version = int64(n.version) + m.RealAvail = int64(n.real_avail) + + return m +} + +func perfstatnetbuffer2netbuffer(n *C.perfstat_netbuffer_t) NetBuffer { + var b NetBuffer + + b.Name = C.GoString(&n.name[0]) + b.InUse = int64(n.inuse) + b.Calls = int64(n.calls) + b.Delayed = int64(n.delayed) + b.Free = int64(n.free) + b.Failed = int64(n.failed) + b.HighWatermark = int64(n.highwatermark) + b.Freed = int64(n.freed) + b.Version = int64(n.version) + + return b +} + +func perfstatnetinterface2netiface(n *C.perfstat_netinterface_t) NetIface { + var i NetIface + + i.Name = C.GoString(&n.name[0]) + i.Description = C.GoString(&n.description[0]) + i.Type = uint8(n._type) + i.MTU = int64(n.mtu) + i.IPackets = int64(n.ipackets) + i.IBytes = int64(n.ibytes) + i.IErrors = int64(n.ierrors) + i.OPackets = int64(n.opackets) + i.OBytes = int64(n.obytes) + i.OErrors = int64(n.oerrors) + i.Collisions = int64(n.collisions) + i.Bitrate = int64(n.bitrate) + i.XmitDrops = int64(n.xmitdrops) + i.Version = int64(n.version) + i.IfIqDrops = int64(n.if_iqdrops) + i.IfArpDrops = int64(n.if_arpdrops) + + return i +} + +func perfstatnetadapter2netadapter(n *C.perfstat_netadapter_t) NetAdapter { + var i NetAdapter + + i.Version = int64(n.version) + i.Name = C.GoString(&n.name[0]) + i.TxPackets = int64(n.tx_packets) + i.TxBytes = int64(n.tx_bytes) + i.TxInterrupts = int64(n.tx_interrupts) + i.TxErrors = int64(n.tx_errors) + i.TxPacketsDropped = int64(n.tx_packets_dropped) + i.TxQueueSize = int64(n.tx_queue_size) + i.TxQueueLen = int64(n.tx_queue_len) + i.TxQueueOverflow = int64(n.tx_queue_overflow) + i.TxBroadcastPackets = int64(n.tx_broadcast_packets) + i.TxMulticastPackets = int64(n.tx_multicast_packets) + i.TxCarrierSense = int64(n.tx_carrier_sense) + i.TxDMAUnderrun = int64(n.tx_DMA_underrun) + i.TxLostCTSErrors = int64(n.tx_lost_CTS_errors) + i.TxMaxCollisionErrors = int64(n.tx_max_collision_errors) + i.TxLateCollisionErrors = int64(n.tx_late_collision_errors) + i.TxDeferred = int64(n.tx_deferred) + i.TxTimeoutErrors = int64(n.tx_timeout_errors) + i.TxSingleCollisionCount = int64(n.tx_single_collision_count) + i.TxMultipleCollisionCount = int64(n.tx_multiple_collision_count) + i.RxPackets = int64(n.rx_packets) + i.RxBytes = int64(n.rx_bytes) + i.RxInterrupts = int64(n.rx_interrupts) + i.RxErrors = int64(n.rx_errors) + i.RxPacketsDropped = int64(n.rx_packets_dropped) + i.RxBadPackets = int64(n.rx_bad_packets) + i.RxMulticastPackets = int64(n.rx_multicast_packets) + i.RxBroadcastPackets = int64(n.rx_broadcast_packets) + i.RxCRCErrors = int64(n.rx_CRC_errors) + i.RxDMAOverrun = int64(n.rx_DMA_overrun) + i.RxAlignmentErrors = int64(n.rx_alignment_errors) + i.RxNoResourceErrors = int64(n.rx_noresource_errors) + i.RxCollisionErrors = int64(n.rx_collision_errors) + i.RxPacketTooShortErrors = int64(n.rx_packet_tooshort_errors) + i.RxPacketTooLongErrors = int64(n.rx_packet_toolong_errors) + i.RxPacketDiscardedByAdapter = int64(n.rx_packets_discardedbyadapter) + i.AdapterType = int32(n.adapter_type) + + return i +} + +func perfstatpagingspace2pagingspace(n *C.perfstat_pagingspace_t) PagingSpace { + var i PagingSpace + + i.Name = C.GoString(&n.name[0]) + i.Type = uint8(n._type) + i.VGName = C.GoString(C.get_ps_vgname(n)) + i.Hostname = C.GoString(C.get_ps_hostname(n)) + i.Filename = C.GoString(C.get_ps_filename(n)) + i.LPSize = int64(n.lp_size) + i.MBSize = int64(n.mb_size) + i.MBUsed = int64(n.mb_used) + i.IOPending = int64(n.io_pending) + i.Active = uint8(n.active) + i.Automatic = uint8(n.automatic) + i.Version = int64(n.version) + + return i +} + +func perfstatprocess2process(n *C.perfstat_process_t) Process { + var i Process + + i.Version = int64(n.version) + i.PID = int64(n.pid) + i.ProcessName = C.GoString(&n.proc_name[0]) + i.Priority = int32(n.proc_priority) + i.NumThreads = int64(n.num_threads) + i.UID = int64(n.proc_uid) + i.ClassID = int64(n.proc_classid) + i.Size = int64(n.proc_size) + i.RealMemData = int64(n.proc_real_mem_data) + i.RealMemText = int64(n.proc_real_mem_text) + i.VirtMemData = int64(n.proc_virt_mem_data) + i.VirtMemText = int64(n.proc_virt_mem_text) + i.SharedLibDataSize = int64(n.shared_lib_data_size) + i.HeapSize = int64(n.heap_size) + i.RealInUse = int64(n.real_inuse) + i.VirtInUse = int64(n.virt_inuse) + i.Pinned = int64(n.pinned) + i.PgSpInUse = int64(n.pgsp_inuse) + i.FilePages = int64(n.filepages) + i.RealInUseMap = int64(n.real_inuse_map) + i.VirtInUseMap = int64(n.virt_inuse_map) + i.PinnedInUseMap = int64(n.pinned_inuse_map) + i.UCpuTime = float64(n.ucpu_time) + i.SCpuTime = float64(n.scpu_time) + i.LastTimeBase = int64(n.last_timebase) + i.InBytes = int64(n.inBytes) + i.OutBytes = int64(n.outBytes) + i.InOps = int64(n.inOps) + i.OutOps = int64(n.outOps) + + return i +} + +func perfstatthread2thread(n *C.perfstat_thread_t) Thread { + var i Thread + + i.TID = int64(n.tid) + i.PID = int64(n.pid) + i.CpuID = int64(n.cpuid) + i.UCpuTime = float64(n.ucpu_time) + i.SCpuTime = float64(n.scpu_time) + i.LastTimeBase = int64(n.last_timebase) + i.Version = int64(n.version) + + return i +} + +func fsinfo2filesystem(n *C.struct_fsinfo) FileSystem { + var i FileSystem + + i.Device = C.GoString(n.devname) + i.MountPoint = C.GoString(n.fsname) + i.FSType = int(n.fstype) + i.Flags = int(n.flags) + i.TotalBlocks = int64(n.totalblks) + i.FreeBlocks = int64(n.freeblks) + i.TotalInodes = int64(n.totalinodes) + i.FreeInodes = int64(n.freeinodes) + + return i +} diff --git a/vendor/github.com/power-devops/perfstat/lparstat.go b/vendor/github.com/power-devops/perfstat/lparstat.go new file mode 100644 index 000000000..0ce35e3c5 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/lparstat.go @@ -0,0 +1,26 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +*/ +import "C" + +import ( + "fmt" +) + +func PartitionStat() (*PartitionConfig, error) { + var part C.perfstat_partition_config_t + + rc := C.perfstat_partition_config(nil, &part, C.sizeof_perfstat_partition_config_t, 1) + if rc != 1 { + return nil, fmt.Errorf("perfstat_partition_config() error") + } + p := perfstatpartitionconfig2partitionconfig(part) + return &p, nil + +} diff --git a/vendor/github.com/power-devops/perfstat/lvmstat.go b/vendor/github.com/power-devops/perfstat/lvmstat.go new file mode 100644 index 000000000..eb2064c80 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/lvmstat.go @@ -0,0 +1,72 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +#include +#include +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" +) + +func LogicalVolumeStat() ([]LogicalVolume, error) { + var lv *C.perfstat_logicalvolume_t + var lvname C.perfstat_id_t + + numlvs := C.perfstat_logicalvolume(nil, nil, C.sizeof_perfstat_logicalvolume_t, 0) + if numlvs <= 0 { + return nil, fmt.Errorf("perfstat_logicalvolume() error") + } + + lv_len := C.sizeof_perfstat_logicalvolume_t * C.ulong(numlvs) + lv = (*C.perfstat_logicalvolume_t)(C.malloc(lv_len)) + defer C.free(unsafe.Pointer(lv)) + C.strcpy(&lvname.name[0], C.CString("")) + r := C.perfstat_logicalvolume(&lvname, lv, C.sizeof_perfstat_logicalvolume_t, numlvs) + if r < 0 { + return nil, fmt.Errorf("perfstat_logicalvolume() error") + } + lvs := make([]LogicalVolume, r) + for i := 0; i < int(r); i++ { + l := C.get_logicalvolume_stat(lv, C.int(i)) + if l != nil { + lvs[i] = perfstatlogicalvolume2logicalvolume(l) + } + } + return lvs, nil +} + +func VolumeGroupStat() ([]VolumeGroup, error) { + var vg *C.perfstat_volumegroup_t + var vgname C.perfstat_id_t + + numvgs := C.perfstat_volumegroup(nil, nil, C.sizeof_perfstat_volumegroup_t, 0) + if numvgs <= 0 { + return nil, fmt.Errorf("perfstat_volumegroup() error") + } + + vg_len := C.sizeof_perfstat_volumegroup_t * C.ulong(numvgs) + vg = (*C.perfstat_volumegroup_t)(C.malloc(vg_len)) + defer C.free(unsafe.Pointer(vg)) + C.strcpy(&vgname.name[0], C.CString("")) + r := C.perfstat_volumegroup(&vgname, vg, C.sizeof_perfstat_volumegroup_t, numvgs) + if r < 0 { + return nil, fmt.Errorf("perfstat_volumegroup() error") + } + vgs := make([]VolumeGroup, r) + for i := 0; i < int(r); i++ { + v := C.get_volumegroup_stat(vg, C.int(i)) + if v != nil { + vgs[i] = perfstatvolumegroup2volumegroup(v) + } + } + return vgs, nil +} diff --git a/vendor/github.com/power-devops/perfstat/memstat.go b/vendor/github.com/power-devops/perfstat/memstat.go new file mode 100644 index 000000000..d211a73aa --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/memstat.go @@ -0,0 +1,84 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +#include +#include + +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" +) + +func MemoryTotalStat() (*MemoryTotal, error) { + var memory C.perfstat_memory_total_t + + rc := C.perfstat_memory_total(nil, &memory, C.sizeof_perfstat_memory_total_t, 1) + if rc != 1 { + return nil, fmt.Errorf("perfstat_memory_total() error") + } + m := perfstatmemorytotal2memorytotal(memory) + return &m, nil +} + +func MemoryPageStat() ([]MemoryPage, error) { + var mempage *C.perfstat_memory_page_t + var fps C.perfstat_psize_t + + numps := C.perfstat_memory_page(nil, nil, C.sizeof_perfstat_memory_page_t, 0) + if numps < 1 { + return nil, fmt.Errorf("perfstat_memory_page() error") + } + + mp_len := C.sizeof_perfstat_memory_page_t * C.ulong(numps) + mempage = (*C.perfstat_memory_page_t)(C.malloc(mp_len)) + defer C.free(unsafe.Pointer(mempage)) + fps.psize = C.FIRST_PSIZE + r := C.perfstat_memory_page(&fps, mempage, C.sizeof_perfstat_memory_page_t, numps) + if r < 1 { + return nil, fmt.Errorf("perfstat_memory_page() error") + } + ps := make([]MemoryPage, r) + for i := 0; i < int(r); i++ { + p := C.get_memory_page_stat(mempage, C.int(i)) + if p != nil { + ps[i] = perfstatmemorypage2memorypage(p) + } + } + return ps, nil +} + +func PagingSpaceStat() ([]PagingSpace, error) { + var pspace *C.perfstat_pagingspace_t + var fps C.perfstat_id_t + + numps := C.perfstat_pagingspace(nil, nil, C.sizeof_perfstat_pagingspace_t, 0) + if numps <= 0 { + return nil, fmt.Errorf("perfstat_pagingspace() error") + } + + ps_len := C.sizeof_perfstat_pagingspace_t * C.ulong(numps) + pspace = (*C.perfstat_pagingspace_t)(C.malloc(ps_len)) + defer C.free(unsafe.Pointer(pspace)) + C.strcpy(&fps.name[0], C.CString(C.FIRST_PAGINGSPACE)) + r := C.perfstat_pagingspace(&fps, pspace, C.sizeof_perfstat_pagingspace_t, numps) + if r < 1 { + return nil, fmt.Errorf("perfstat_pagingspace() error") + } + ps := make([]PagingSpace, r) + for i := 0; i < int(r); i++ { + p := C.get_pagingspace_stat(pspace, C.int(i)) + if p != nil { + ps[i] = perfstatpagingspace2pagingspace(p) + } + } + return ps, nil +} diff --git a/vendor/github.com/power-devops/perfstat/netstat.go b/vendor/github.com/power-devops/perfstat/netstat.go new file mode 100644 index 000000000..4070da211 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/netstat.go @@ -0,0 +1,117 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +#include +#include + +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" +) + +func NetIfaceTotalStat() (*NetIfaceTotal, error) { + var nif C.perfstat_netinterface_total_t + + rc := C.perfstat_netinterface_total(nil, &nif, C.sizeof_perfstat_netinterface_total_t, 1) + if rc != 1 { + return nil, fmt.Errorf("perfstat_netinterface_total() error") + } + n := perfstatnetinterfacetotal2netifacetotal(nif) + return &n, nil +} + +func NetBufferStat() ([]NetBuffer, error) { + var nbuf *C.perfstat_netbuffer_t + var first C.perfstat_id_t + + numbuf := C.perfstat_netbuffer(nil, nil, C.sizeof_perfstat_netbuffer_t, 0) + if numbuf < 1 { + return nil, fmt.Errorf("perfstat_netbuffer() error") + } + + nblen := C.sizeof_perfstat_netbuffer_t * C.ulong(numbuf) + nbuf = (*C.perfstat_netbuffer_t)(C.malloc(nblen)) + defer C.free(unsafe.Pointer(nbuf)) + C.strcpy(&first.name[0], C.CString(C.FIRST_NETBUFFER)) + r := C.perfstat_netbuffer(&first, nbuf, C.sizeof_perfstat_netbuffer_t, numbuf) + if r < 0 { + return nil, fmt.Errorf("perfstat_netbuffer() error") + } + nb := make([]NetBuffer, r) + for i := 0; i < int(r); i++ { + b := C.get_netbuffer_stat(nbuf, C.int(i)) + if b != nil { + nb[i] = perfstatnetbuffer2netbuffer(b) + } + } + return nb, nil +} + +func NetIfaceStat() ([]NetIface, error) { + var nif *C.perfstat_netinterface_t + var first C.perfstat_id_t + + numif := C.perfstat_netinterface(nil, nil, C.sizeof_perfstat_netinterface_t, 0) + if numif < 0 { + return nil, fmt.Errorf("perfstat_netinterface() error") + } + if numif == 0 { + return []NetIface{}, fmt.Errorf("no network interfaces found") + } + + iflen := C.sizeof_perfstat_netinterface_t * C.ulong(numif) + nif = (*C.perfstat_netinterface_t)(C.malloc(iflen)) + defer C.free(unsafe.Pointer(nif)) + C.strcpy(&first.name[0], C.CString(C.FIRST_NETINTERFACE)) + r := C.perfstat_netinterface(&first, nif, C.sizeof_perfstat_netinterface_t, numif) + if r < 0 { + return nil, fmt.Errorf("perfstat_netinterface() error") + } + ifs := make([]NetIface, r) + for i := 0; i < int(r); i++ { + b := C.get_netinterface_stat(nif, C.int(i)) + if b != nil { + ifs[i] = perfstatnetinterface2netiface(b) + } + } + return ifs, nil +} + +func NetAdapterStat() ([]NetAdapter, error) { + var adapters *C.perfstat_netadapter_t + var first C.perfstat_id_t + + numad := C.perfstat_netadapter(nil, nil, C.sizeof_perfstat_netadapter_t, 0) + if numad < 0 { + return nil, fmt.Errorf("perfstat_netadater() error") + } + if numad == 0 { + return []NetAdapter{}, fmt.Errorf("no network adapters found") + } + + adplen := C.sizeof_perfstat_netadapter_t * C.ulong(numad) + adapters = (*C.perfstat_netadapter_t)(C.malloc(adplen)) + defer C.free(unsafe.Pointer(adapters)) + C.strcpy(&first.name[0], C.CString(C.FIRST_NETINTERFACE)) + r := C.perfstat_netadapter(&first, adapters, C.sizeof_perfstat_netadapter_t, numad) + if r < 0 { + return nil, fmt.Errorf("perfstat_netadapter() error") + } + ads := make([]NetAdapter, r) + for i := 0; i < int(r); i++ { + b := C.get_netadapter_stat(adapters, C.int(i)) + if b != nil { + ads[i] = perfstatnetadapter2netadapter(b) + } + } + return ads, nil +} diff --git a/vendor/github.com/power-devops/perfstat/procstat.go b/vendor/github.com/power-devops/perfstat/procstat.go new file mode 100644 index 000000000..ecafebd8d --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/procstat.go @@ -0,0 +1,75 @@ +// +build aix + +package perfstat + +/* +#cgo LDFLAGS: -lperfstat + +#include +#include +#include + +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" +) + +func ProcessStat() ([]Process, error) { + var proc *C.perfstat_process_t + var first C.perfstat_id_t + + numproc := C.perfstat_process(nil, nil, C.sizeof_perfstat_process_t, 0) + if numproc < 1 { + return nil, fmt.Errorf("perfstat_process() error") + } + + plen := C.sizeof_perfstat_process_t * C.ulong(numproc) + proc = (*C.perfstat_process_t)(C.malloc(plen)) + defer C.free(unsafe.Pointer(proc)) + C.strcpy(&first.name[0], C.CString("")) + r := C.perfstat_process(&first, proc, C.sizeof_perfstat_process_t, numproc) + if r < 0 { + return nil, fmt.Errorf("perfstat_process() error") + } + + ps := make([]Process, r) + for i := 0; i < int(r); i++ { + p := C.get_process_stat(proc, C.int(i)) + if p != nil { + ps[i] = perfstatprocess2process(p) + } + } + return ps, nil +} + +func ThreadStat() ([]Thread, error) { + var thread *C.perfstat_thread_t + var first C.perfstat_id_t + + numthr := C.perfstat_thread(nil, nil, C.sizeof_perfstat_thread_t, 0) + if numthr < 1 { + return nil, fmt.Errorf("perfstat_thread() error") + } + + thlen := C.sizeof_perfstat_thread_t * C.ulong(numthr) + thread = (*C.perfstat_thread_t)(C.malloc(thlen)) + defer C.free(unsafe.Pointer(thread)) + C.strcpy(&first.name[0], C.CString("")) + r := C.perfstat_thread(&first, thread, C.sizeof_perfstat_thread_t, numthr) + if r < 0 { + return nil, fmt.Errorf("perfstat_thread() error") + } + + th := make([]Thread, r) + for i := 0; i < int(r); i++ { + t := C.get_thread_stat(thread, C.int(i)) + if t != nil { + th[i] = perfstatthread2thread(t) + } + } + return th, nil +} diff --git a/vendor/github.com/power-devops/perfstat/sysconf.go b/vendor/github.com/power-devops/perfstat/sysconf.go new file mode 100644 index 000000000..c7454d03d --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/sysconf.go @@ -0,0 +1,195 @@ +// +build aix + +package perfstat + +/* +#include +*/ +import "C" + +import "fmt" + +const ( + SC_ARG_MAX = 0 + SC_CHILD_MAX = 1 + SC_CLK_TCK = 2 + SC_NGROUPS_MAX = 3 + SC_OPEN_MAX = 4 + SC_STREAM_MAX = 5 + SC_TZNAME_MAX = 6 + SC_JOB_CONTROL = 7 + SC_SAVED_IDS = 8 + SC_VERSION = 9 + SC_POSIX_ARG_MAX = 10 + SC_POSIX_CHILD_MAX = 11 + SC_POSIX_LINK_MAX = 12 + SC_POSIX_MAX_CANON = 13 + SC_POSIX_MAX_INPUT = 14 + SC_POSIX_NAME_MAX = 15 + SC_POSIX_NGROUPS_MAX = 16 + SC_POSIX_OPEN_MAX = 17 + SC_POSIX_PATH_MAX = 18 + SC_POSIX_PIPE_BUF = 19 + SC_POSIX_SSIZE_MAX = 20 + SC_POSIX_STREAM_MAX = 21 + SC_POSIX_TZNAME_MAX = 22 + SC_BC_BASE_MAX = 23 + SC_BC_DIM_MAX = 24 + SC_BC_SCALE_MAX = 25 + SC_BC_STRING_MAX = 26 + SC_EQUIV_CLASS_MAX = 27 + SC_EXPR_NEST_MAX = 28 + SC_LINE_MAX = 29 + SC_RE_DUP_MAX = 30 + SC_2_VERSION = 31 + SC_2_C_DEV = 32 + SC_2_FORT_DEV = 33 + SC_2_FORT_RUN = 34 + SC_2_LOCALEDEF = 35 + SC_2_SW_DEV = 36 + SC_POSIX2_BC_BASE_MAX = 37 + SC_POSIX2_BC_DIM_MAX = 38 + SC_POSIX2_BC_SCALE_MAX = 39 + SC_POSIX2_BC_STRING_MAX = 40 + SC_POSIX2_BC_EQUIV_CLASS_MAX = 41 + SC_POSIX2_BC_EXPR_NEST_MAX = 42 + SC_POSIX2_BC_LINE_MAX = 43 + SC_POSIX2_BC_RE_DUP_MAX = 44 + SC_PASS_MAX = 45 + SC_XOPEN_VERSION = 46 + SC_ATEXIT_MAX = 47 + SC_PAGE_SIZE = 48 + SC_PAGESIZE = SC_PAGE_SIZE + SC_AES_OS_VERSION = 49 + SC_COLL_WEIGHTS_MAX = 50 + SC_2_C_WIND = 51 + SC_2_C_VERSION = 52 + SC_2_UPE = 53 + SC_2_CHAR_TERM = 54 + SC_XOPEN_SHM = 55 + SC_XOPEN_CRYPT = 56 + SC_XOPEN_ENH_I18N = 57 + SC_IOV_MAX = 58 + SC_THREAD_SAFE_FUNCTIONS = 59 + SC_THREADS = 60 + SC_THREAD_ATTR_STACKADDR = 61 + SC_THREAD_ATTR_STACKSIZE = 62 + SC_THREAD_FORKALL = 63 + SC_THREAD_PRIORITY_SCHEDULING = 64 + SC_THREAD_PRIO_INHERIT = 65 + SC_THREAD_PRIO_PROTECT = 66 + SC_THREAD_PROCESS_SHARED = 67 + SC_THREAD_KEYS_MAX = 68 + SC_THREAD_DATAKEYS_MAX = SC_THREAD_KEYS_MAX + SC_THREAD_STACK_MIN = 69 + SC_THREAD_THREADS_MAX = 70 + SC_NPROCESSORS_CONF = 71 + SC_NPROCESSORS_ONLN = 72 + SC_XOPEN_UNIX = 73 + SC_AIO_LISTIO_MAX = 75 + SC_AIO_MAX = 76 + SC_AIO_PRIO_DELTA_MAX = 77 + SC_ASYNCHRONOUS_IO = 78 + SC_DELAYTIMER_MAX = 79 + SC_FSYNC = 80 + SC_GETGR_R_SIZE_MAX = 81 + SC_GETPW_R_SIZE_MAX = 82 + SC_LOGIN_NAME_MAX = 83 + SC_MAPPED_FILES = 84 + SC_MEMLOCK = 85 + SC_MEMLOCK_RANGE = 86 + SC_MEMORY_PROTECTION = 87 + SC_MESSAGE_PASSING = 88 + SC_MQ_OPEN_MAX = 89 + SC_MQ_PRIO_MAX = 90 + SC_PRIORITIZED_IO = 91 + SC_PRIORITY_SCHEDULING = 92 + SC_REALTIME_SIGNALS = 93 + SC_RTSIG_MAX = 94 + SC_SEMAPHORES = 95 + SC_SEM_NSEMS_MAX = 96 + SC_SEM_VALUE_MAX = 97 + SC_SHARED_MEMORY_OBJECTS = 98 + SC_SIGQUEUE_MAX = 99 + SC_SYNCHRONIZED_IO = 100 + SC_THREAD_DESTRUCTOR_ITERATIONS = 101 + SC_TIMERS = 102 + SC_TIMER_MAX = 103 + SC_TTY_NAME_MAX = 104 + SC_XBS5_ILP32_OFF32 = 105 + SC_XBS5_ILP32_OFFBIG = 106 + SC_XBS5_LP64_OFF64 = 107 + SC_XBS5_LPBIG_OFFBIG = 108 + SC_XOPEN_XCU_VERSION = 109 + SC_XOPEN_REALTIME = 110 + SC_XOPEN_REALTIME_THREADS = 111 + SC_XOPEN_LEGACY = 112 + SC_REENTRANT_FUNCTIONS = SC_THREAD_SAFE_FUNCTIONS + SC_PHYS_PAGES = 113 + SC_AVPHYS_PAGES = 114 + SC_LPAR_ENABLED = 115 + SC_LARGE_PAGESIZE = 116 + SC_AIX_KERNEL_BITMODE = 117 + SC_AIX_REALMEM = 118 + SC_AIX_HARDWARE_BITMODE = 119 + SC_AIX_MP_CAPABLE = 120 + SC_V6_ILP32_OFF32 = 121 + SC_V6_ILP32_OFFBIG = 122 + SC_V6_LP64_OFF64 = 123 + SC_V6_LPBIG_OFFBIG = 124 + SC_XOPEN_STREAMS = 125 + SC_HOST_NAME_MAX = 126 + SC_REGEXP = 127 + SC_SHELL = 128 + SC_SYMLOOP_MAX = 129 + SC_ADVISORY_INFO = 130 + SC_FILE_LOCKING = 131 + SC_2_PBS = 132 + SC_2_PBS_ACCOUNTING = 133 + SC_2_PBS_CHECKPOINT = 134 + SC_2_PBS_LOCATE = 135 + SC_2_PBS_MESSAGE = 136 + SC_2_PBS_TRACK = 137 + SC_BARRIERS = 138 + SC_CLOCK_SELECTION = 139 + SC_CPUTIME = 140 + SC_MONOTONIC_CLOCK = 141 + SC_READER_WRITER_LOCKS = 142 + SC_SPAWN = 143 + SC_SPIN_LOCKS = 144 + SC_SPORADIC_SERVER = 145 + SC_THREAD_CPUTIME = 146 + SC_THREAD_SPORADIC_SERVER = 147 + SC_TIMEOUTS = 148 + SC_TRACE = 149 + SC_TRACE_EVENT_FILTER = 150 + SC_TRACE_INHERIT = 151 + SC_TRACE_LOG = 152 + SC_TYPED_MEMORY_OBJECTS = 153 + SC_IPV6 = 154 + SC_RAW_SOCKETS = 155 + SC_SS_REPL_MAX = 156 + SC_TRACE_EVENT_NAME_MAX = 157 + SC_TRACE_NAME_MAX = 158 + SC_TRACE_SYS_MAX = 159 + SC_TRACE_USER_EVENT_MAX = 160 + SC_AIX_UKEYS = 161 + SC_AIX_ENHANCED_AFFINITY = 162 + SC_V7_ILP32_OFF32 = 163 + SC_V7_ILP32_OFFBIG = 164 + SC_V7_LP64_OFF64 = 165 + SC_V7_LPBIG_OFFBIG = 166 + SC_THREAD_ROBUST_PRIO_INHERIT = 167 + SC_THREAD_ROBUST_PRIO_PROTECT = 168 + SC_XOPEN_UUCP = 169 + SC_XOPEN_ARMOR = 170 +) + +func Sysconf(name int32) (int64, error) { + r := C.sysconf(C.int(name)) + if r == -1 { + return 0, fmt.Errorf("sysconf error") + } else { + return int64(r), nil + } +} diff --git a/vendor/github.com/power-devops/perfstat/systemcfg.go b/vendor/github.com/power-devops/perfstat/systemcfg.go new file mode 100644 index 000000000..6287eb46a --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/systemcfg.go @@ -0,0 +1,635 @@ +// +build aix + +package perfstat + +import "golang.org/x/sys/unix" + +// function Getsystemcfg() is defined in golang.org/x/sys/unix +// we define here just missing constants for the function and some helpers + +// Calls to getsystemcfg() +const ( + SC_ARCH = 1 /* processor architecture */ + SC_IMPL = 2 /* processor implementation */ + SC_VERS = 3 /* processor version */ + SC_WIDTH = 4 /* width (32 || 64) */ + SC_NCPUS = 5 /* 1 = UP, n = n-way MP */ + SC_L1C_ATTR = 6 /* L1 cache attributes (bit flags) */ + SC_L1C_ISZ = 7 /* size of L1 instruction cache */ + SC_L1C_DSZ = 8 /* size of L1 data cache */ + SC_L1C_ICA = 9 /* L1 instruction cache associativity */ + SC_L1C_DCA = 10 /* L1 data cache associativity */ + SC_L1C_IBS = 11 /* L1 instruction cache block size */ + SC_L1C_DBS = 12 /* L1 data cache block size */ + SC_L1C_ILS = 13 /* L1 instruction cache line size */ + SC_L1C_DLS = 14 /* L1 data cache line size */ + SC_L2C_SZ = 15 /* size of L2 cache, 0 = No L2 cache */ + SC_L2C_AS = 16 /* L2 cache associativity */ + SC_TLB_ATTR = 17 /* TLB attributes (bit flags) */ + SC_ITLB_SZ = 18 /* entries in instruction TLB */ + SC_DTLB_SZ = 19 /* entries in data TLB */ + SC_ITLB_ATT = 20 /* instruction tlb associativity */ + SC_DTLB_ATT = 21 /* data tlb associativity */ + SC_RESRV_SZ = 22 /* size of reservation */ + SC_PRI_LC = 23 /* spin lock count in supevisor mode */ + SC_PRO_LC = 24 /* spin lock count in problem state */ + SC_RTC_TYPE = 25 /* RTC type */ + SC_VIRT_AL = 26 /* 1 if hardware aliasing is supported */ + SC_CAC_CONG = 27 /* number of page bits for cache synonym */ + SC_MOD_ARCH = 28 /* used by system for model determination */ + SC_MOD_IMPL = 29 /* used by system for model determination */ + SC_XINT = 30 /* used by system for time base conversion */ + SC_XFRAC = 31 /* used by system for time base conversion */ + SC_KRN_ATTR = 32 /* kernel attributes, see below */ + SC_PHYSMEM = 33 /* bytes of OS available memory */ + SC_SLB_ATTR = 34 /* SLB attributes */ + SC_SLB_SZ = 35 /* size of slb (0 = no slb) */ + SC_ORIG_NCPUS = 36 /* original number of CPUs */ + SC_MAX_NCPUS = 37 /* max cpus supported by this AIX image */ + SC_MAX_REALADDR = 38 /* max supported real memory address +1 */ + SC_ORIG_ENT_CAP = 39 /* configured entitled processor capacity at boot required by cross-partition LPAR tools. */ + SC_ENT_CAP = 40 /* entitled processor capacity */ + SC_DISP_WHE = 41 /* Dispatch wheel time period (TB units) */ + SC_CAPINC = 42 /* delta by which capacity can change */ + SC_VCAPW = 43 /* priority weight for idle capacity distribution */ + SC_SPLP_STAT = 44 /* State of SPLPAR enablement: 0x1 => 1=SPLPAR capable; 0=not, 0x2 => SPLPAR enabled 0=dedicated, 1=shared */ + SC_SMT_STAT = 45 /* State of SMT enablement: 0x1 = SMT Capable 0=no/1=yes, 0x2 = SMT Enabled 0=no/1=yes, 0x4 = SMT threads bound true 0=no/1=yes */ + SC_SMT_TC = 46 /* Number of SMT Threads per Physical CPU */ + SC_VMX_VER = 47 /* RPA defined VMX version: 0 = VMX not available or disabled, 1 = VMX capable, 2 = VMX and VSX capable */ + SC_LMB_SZ = 48 /* Size of an LMB on this system. */ + SC_MAX_XCPU = 49 /* Number of exclusive cpus on line */ + SC_EC_LVL = 50 /* Kernel error checking level */ + SC_AME_STAT = 51 /* AME status */ + SC_ECO_STAT = 52 /* extended cache options */ + SC_DFP_STAT = 53 /* RPA defined DFP version, 0=none/disabled */ + SC_VRM_STAT = 54 /* VRM Capable/enabled */ + SC_PHYS_IMP = 55 /* physical processor implementation */ + SC_PHYS_VER = 56 /* physical processor version */ + SC_SPCM_STATUS = 57 + SC_SPCM_MAX = 58 + SC_TM_VER = 59 /* Transaction Memory version, 0 - not capable */ + SC_NX_CAP = 60 /* NX GZIP capable */ + SC_PKS_STATE = 61 /* Platform KeyStore */ +) + +/* kernel attributes */ +/* bit 0/1 meaning */ +/* -----------------------------------------*/ +/* 31 32-bit kernel / 64-bit kernel */ +/* 30 non-LPAR / LPAR */ +/* 29 old 64bit ABI / 64bit Large ABI */ +/* 28 non-NUMA / NUMA */ +/* 27 UP / MP */ +/* 26 no DR CPU add / DR CPU add support */ +/* 25 no DR CPU rm / DR CPU rm support */ +/* 24 no DR MEM add / DR MEM add support */ +/* 23 no DR MEM rm / DR MEM rm support */ +/* 22 kernel keys disabled / enabled */ +/* 21 no recovery / recovery enabled */ +/* 20 non-MLS / MLS enabled */ +/* 19 enhanced affinity indicator */ +/* 18 non-vTPM / vTPM enabled */ +/* 17 non-VIOS / VIOS */ + +// Values for architecture field +const ( + ARCH_POWER_RS = 0x0001 /* Power Classic architecture */ + ARCH_POWER_PC = 0x0002 /* Power PC architecture */ + ARCH_IA64 = 0x0003 /* Intel IA64 architecture */ +) + +// Values for implementation field for POWER_PC Architectures +const ( + IMPL_POWER_RS1 = 0x00001 /* RS1 class CPU */ + IMPL_POWER_RSC = 0x00002 /* RSC class CPU */ + IMPL_POWER_RS2 = 0x00004 /* RS2 class CPU */ + IMPL_POWER_601 = 0x00008 /* 601 class CPU */ + IMPL_POWER_603 = 0x00020 /* 603 class CPU */ + IMPL_POWER_604 = 0x00010 /* 604 class CPU */ + IMPL_POWER_620 = 0x00040 /* 620 class CPU */ + IMPL_POWER_630 = 0x00080 /* 630 class CPU */ + IMPL_POWER_A35 = 0x00100 /* A35 class CPU */ + IMPL_POWER_RS64II = 0x0200 /* RS64-II class CPU */ + IMPL_POWER_RS64III = 0x0400 /* RS64-III class CPU */ + IMPL_POWER4 = 0x0800 /* 4 class CPU */ + IMPL_POWER_RS64IV = IMPL_POWER4 /* 4 class CPU */ + IMPL_POWER_MPC7450 = 0x1000 /* MPC7450 class CPU */ + IMPL_POWER5 = 0x2000 /* 5 class CPU */ + IMPL_POWER6 = 0x4000 /* 6 class CPU */ + IMPL_POWER7 = 0x8000 /* 7 class CPU */ + IMPL_POWER8 = 0x10000 /* 8 class CPU */ + IMPL_POWER9 = 0x20000 /* 9 class CPU */ +) + +// Values for implementation field for IA64 Architectures +const ( + IMPL_IA64_M1 = 0x0001 /* IA64 M1 class CPU (Itanium) */ + IMPL_IA64_M2 = 0x0002 /* IA64 M2 class CPU */ +) + +// Values for the version field +const ( + PV_601 = 0x010001 /* Power PC 601 */ + PV_601A = 0x010002 /* Power PC 601 */ + PV_603 = 0x060000 /* Power PC 603 */ + PV_604 = 0x050000 /* Power PC 604 */ + PV_620 = 0x070000 /* Power PC 620 */ + PV_630 = 0x080000 /* Power PC 630 */ + PV_A35 = 0x090000 /* Power PC A35 */ + PV_RS64II = 0x0A0000 /* Power PC RS64II */ + PV_RS64III = 0x0B0000 /* Power PC RS64III */ + PV_4 = 0x0C0000 /* Power PC 4 */ + PV_RS64IV = PV_4 /* Power PC 4 */ + PV_MPC7450 = 0x0D0000 /* Power PC MPC7450 */ + PV_4_2 = 0x0E0000 /* Power PC 4 */ + PV_4_3 = 0x0E0001 /* Power PC 4 */ + PV_5 = 0x0F0000 /* Power PC 5 */ + PV_5_2 = 0x0F0001 /* Power PC 5 */ + PV_5_3 = 0x0F0002 /* Power PC 5 */ + PV_6 = 0x100000 /* Power PC 6 */ + PV_6_1 = 0x100001 /* Power PC 6 DD1.x */ + PV_7 = 0x200000 /* Power PC 7 */ + PV_8 = 0x300000 /* Power PC 8 */ + PV_9 = 0x400000 /* Power PC 9 */ + PV_5_Compat = 0x0F8000 /* Power PC 5 */ + PV_6_Compat = 0x108000 /* Power PC 6 */ + PV_7_Compat = 0x208000 /* Power PC 7 */ + PV_8_Compat = 0x308000 /* Power PC 8 */ + PV_9_Compat = 0x408000 /* Power PC 9 */ + PV_RESERVED_2 = 0x0A0000 /* source compatability */ + PV_RESERVED_3 = 0x0B0000 /* source compatability */ + PV_RS2 = 0x040000 /* Power RS2 */ + PV_RS1 = 0x020000 /* Power RS1 */ + PV_RSC = 0x030000 /* Power RSC */ + PV_M1 = 0x008000 /* Intel IA64 M1 */ + PV_M2 = 0x008001 /* Intel IA64 M2 */ +) + +// Values for rtc_type +const ( + RTC_POWER = 1 /* rtc as defined by Power Arch. */ + RTC_POWER_PC = 2 /* rtc as defined by Power PC Arch. */ + RTC_IA64 = 3 /* rtc as defined by IA64 Arch. */ +) + +const NX_GZIP_PRESENT = 0x00000001 + +const ( + PKS_STATE_CAPABLE = 1 + PKS_STATE_ENABLED = 2 +) + +// Macros for identifying physical processor +const ( + PPI4_1 = 0x35 + PPI4_2 = 0x38 + PPI4_3 = 0x39 + PPI4_4 = 0x3C + PPI4_5 = 0x44 + PPI5_1 = 0x3A + PPI5_2 = 0x3B + PPI6_1 = 0x3E + PPI7_1 = 0x3F + PPI7_2 = 0x4A + PPI8_1 = 0x4B + PPI8_2 = 0x4D + PPI9 = 0x4E +) + +// Macros for kernel attributes +const ( + KERN_TYPE = 0x1 + KERN_LPAR = 0x2 + KERN_64BIT_LARGE_ABI = 0x4 + KERN_NUMA = 0x8 + KERN_UPMP = 0x10 + KERN_DR_CPU_ADD = 0x20 + KERN_DR_CPU_RM = 0x40 + KERN_DR_MEM_ADD = 0x80 + KERN_DR_MEM_RM = 0x100 + KERN_KKEY_ENABLED = 0x200 + KERN_RECOVERY = 0x400 + KERN_MLS = 0x800 + KERN_ENH_AFFINITY = 0x1000 + KERN_VTPM = 0x2000 + KERN_VIOS = 0x4000 +) + +// macros for SPLPAR environment. +const ( + SPLPAR_CAPABLE = 0x1 + SPLPAR_ENABLED = 0x2 + SPLPAR_DONATE_CAPABLE = 0x4 +) + +// Macros for SMT status determination +const ( + SMT_CAPABLE = 0x1 + SMT_ENABLE = 0x2 + SMT_BOUND = 0x4 + SMT_ORDER = 0x8 +) + +// Macros for VRM status determination +const ( + VRM_CAPABLE = 0x1 + VRM_ENABLE = 0x2 + CMOX_CAPABLE = 0x4 +) + +// Macros for AME status determination +const AME_ENABLE = 0x1 + +// Macros for extended cache options +const ( + ECO_CAPABLE = 0x1 + ECO_ENABLE = 0x2 +) + +// These define blocks of values for model_arch and model_impl that are reserved for OEM use. +const ( + MODEL_ARCH_RSPC = 2 + MODEL_ARCH_CHRP = 3 + MODEL_ARCH_IA64 = 4 + MODEL_ARCH_OEM_START = 1024 + MODEL_ARCH_OEM_END = 2047 + MODEL_IMPL_RS6K_UP_MCA = 1 + MODEL_IMPL_RS6K_SMP_MCA = 2 + MODEL_IMPL_RSPC_UP_PCI = 3 + MODEL_IMPL_RSPC_SMP_PCI = 4 + MODEL_IMPL_CHRP_UP_PCI = 5 + MODEL_IMPL_CHRP_SMP_PCI = 6 + MODEL_IMPL_IA64_COM = 7 + MODEL_IMPL_IA64_SOFTSDV = 8 + MODEL_IMPL_MAMBO_SIM = 9 + MODEL_IMPL_POWER_KVM = 10 + MODEL_IMPL_OEM_START = 1024 + MODEL_IMPL_OEM_END = 2047 +) + +// example determining processor compatibilty mode on AIX: +// impl := unix.Getsystemcfg(SC_IMPL) +// if impl&IMPL_POWER8 != 0 { +// // we are running on POWER8 +// } +// if impl&IMPL_POWER9 != 0 { +// // we are running on POWER9 +// } + +func GetCPUImplementation() string { + impl := unix.Getsystemcfg(SC_IMPL) + switch { + case impl&IMPL_POWER4 != 0: + return "POWER4" + case impl&IMPL_POWER5 != 0: + return "POWER5" + case impl&IMPL_POWER6 != 0: + return "POWER6" + case impl&IMPL_POWER7 != 0: + return "POWER7" + case impl&IMPL_POWER8 != 0: + return "POWER8" + case impl&IMPL_POWER9 != 0: + return "POWER9" + default: + return "Unknown" + } +} + +func POWER9OrNewer() bool { + impl := unix.Getsystemcfg(SC_IMPL) + if impl&IMPL_POWER9 != 0 { + return true + } + return false +} + +func POWER9() bool { + impl := unix.Getsystemcfg(SC_IMPL) + if impl&IMPL_POWER9 != 0 { + return true + } + return false +} + +func POWER8OrNewer() bool { + impl := unix.Getsystemcfg(SC_IMPL) + if impl&IMPL_POWER9 != 0 || impl&IMPL_POWER8 != 0 { + return true + } + return false +} + +func POWER8() bool { + impl := unix.Getsystemcfg(SC_IMPL) + if impl&IMPL_POWER8 != 0 { + return true + } + return false +} + +func POWER7OrNewer() bool { + impl := unix.Getsystemcfg(SC_IMPL) + if impl&IMPL_POWER9 != 0 || impl&IMPL_POWER8 != 0 || impl&IMPL_POWER7 != 0 { + return true + } + return false +} + +func POWER7() bool { + impl := unix.Getsystemcfg(SC_IMPL) + if impl&IMPL_POWER7 != 0 { + return true + } + return false +} + +func HasTransactionalMemory() bool { + impl := unix.Getsystemcfg(SC_TM_VER) + if impl > 0 { + return true + } + return false +} + +func Is64Bit() bool { + impl := unix.Getsystemcfg(SC_WIDTH) + if impl == 64 { + return true + } + return false +} + +func IsSMP() bool { + impl := unix.Getsystemcfg(SC_NCPUS) + if impl > 1 { + return true + } + return false +} + +func HasVMX() bool { + impl := unix.Getsystemcfg(SC_VMX_VER) + if impl > 0 { + return true + } + return false +} + +func HasVSX() bool { + impl := unix.Getsystemcfg(SC_VMX_VER) + if impl > 1 { + return true + } + return false +} + +func HasDFP() bool { + impl := unix.Getsystemcfg(SC_DFP_STAT) + if impl > 1 { + return true + } + return false +} + +func HasNxGzip() bool { + impl := unix.Getsystemcfg(SC_NX_CAP) + if impl&NX_GZIP_PRESENT > 0 { + return true + } + return false +} + +func PksCapable() bool { + impl := unix.Getsystemcfg(SC_PKS_STATE) + if impl&PKS_STATE_CAPABLE > 0 { + return true + } + return false +} + +func PksEnabled() bool { + impl := unix.Getsystemcfg(SC_PKS_STATE) + if impl&PKS_STATE_ENABLED > 0 { + return true + } + return false +} + +func CPUMode() string { + impl := unix.Getsystemcfg(SC_VERS) + switch impl { + case PV_9, PV_9_Compat: + return "POWER9" + case PV_8, PV_8_Compat: + return "POWER8" + case PV_7, PV_7_Compat: + return "POWER7" + default: + return "Unknown" + } +} + +func KernelBits() int { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_TYPE == KERN_TYPE { + return 64 + } + return 32 +} + +func IsLPAR() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_LPAR == KERN_LPAR { + return true + } + return false +} + +func CpuAddCapable() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_DR_CPU_ADD == KERN_DR_CPU_ADD { + return true + } + return false +} + +func CpuRemoveCapable() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_DR_CPU_RM == KERN_DR_CPU_RM { + return true + } + return false +} + +func MemoryAddCapable() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_DR_MEM_ADD == KERN_DR_MEM_ADD { + return true + } + return false +} + +func MemoryRemoveCapable() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_DR_MEM_RM == KERN_DR_MEM_RM { + return true + } + return false +} + +func DLparCapable() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&(KERN_DR_CPU_ADD|KERN_DR_CPU_RM|KERN_DR_MEM_ADD|KERN_DR_MEM_RM) > 0 { + return true + } + return false +} + +func IsNUMA() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_NUMA > 0 { + return true + } + return false +} + +func KernelKeys() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_KKEY_ENABLED > 0 { + return true + } + return false +} + +func RecoveryMode() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_RECOVERY > 0 { + return true + } + return false +} + +func EnhancedAffinity() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_ENH_AFFINITY > 0 { + return true + } + return false +} + +func VTpmEnabled() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_VTPM > 0 { + return true + } + return false +} + +func IsVIOS() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_VIOS > 0 { + return true + } + return false +} + +func MLSEnabled() bool { + impl := unix.Getsystemcfg(SC_KRN_ATTR) + if impl&KERN_MLS > 0 { + return true + } + return false +} + +func SPLparCapable() bool { + impl := unix.Getsystemcfg(SC_SPLP_STAT) + if impl&SPLPAR_CAPABLE > 0 { + return true + } + return false +} + +func SPLparEnabled() bool { + impl := unix.Getsystemcfg(SC_SPLP_STAT) + if impl&SPLPAR_ENABLED > 0 { + return true + } + return false +} + +func DedicatedLpar() bool { + return !SPLparEnabled() +} + +func SPLparCapped() bool { + impl := unix.Getsystemcfg(SC_VCAPW) + if impl == 0 { + return true + } + return false +} + +func SPLparDonating() bool { + impl := unix.Getsystemcfg(SC_SPLP_STAT) + if impl&SPLPAR_DONATE_CAPABLE > 0 { + return true + } + return false +} + +func SmtCapable() bool { + impl := unix.Getsystemcfg(SC_SMT_STAT) + if impl&SMT_CAPABLE > 0 { + return true + } + return false +} + +func SmtEnabled() bool { + impl := unix.Getsystemcfg(SC_SMT_STAT) + if impl&SMT_ENABLE > 0 { + return true + } + return false +} + +func VrmCapable() bool { + impl := unix.Getsystemcfg(SC_VRM_STAT) + if impl&VRM_CAPABLE > 0 { + return true + } + return false +} + +func VrmEnabled() bool { + impl := unix.Getsystemcfg(SC_VRM_STAT) + if impl&VRM_ENABLE > 0 { + return true + } + return false +} + +func AmeEnabled() bool { + impl := unix.Getsystemcfg(SC_AME_STAT) + if impl&AME_ENABLE > 0 { + return true + } + return false +} + +func EcoCapable() bool { + impl := unix.Getsystemcfg(SC_ECO_STAT) + if impl&ECO_CAPABLE > 0 { + return true + } + return false +} + +func EcoEnabled() bool { + impl := unix.Getsystemcfg(SC_ECO_STAT) + if impl&ECO_ENABLE > 0 { + return true + } + return false +} diff --git a/vendor/github.com/power-devops/perfstat/types_cpu.go b/vendor/github.com/power-devops/perfstat/types_cpu.go new file mode 100644 index 000000000..84425e92f --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_cpu.go @@ -0,0 +1,186 @@ +package perfstat + +type CPU struct { + Name string /* logical processor name (cpu0, cpu1, ..) */ + User int64 /* raw number of clock ticks spent in user mode */ + Sys int64 /* raw number of clock ticks spent in system mode */ + Idle int64 /* raw number of clock ticks spent idle */ + Wait int64 /* raw number of clock ticks spent waiting for I/O */ + PSwitch int64 /* number of context switches (changes of currently running process) */ + Syscall int64 /* number of system calls executed */ + Sysread int64 /* number of read system calls executed */ + Syswrite int64 /* number of write system calls executed */ + Sysfork int64 /* number of fork system call executed */ + Sysexec int64 /* number of exec system call executed */ + Readch int64 /* number of characters tranferred with read system call */ + Writech int64 /* number of characters tranferred with write system call */ + Bread int64 /* number of block reads */ + Bwrite int64 /* number of block writes */ + Lread int64 /* number of logical read requests */ + Lwrite int64 /* number of logical write requests */ + Phread int64 /* number of physical reads (reads on raw device) */ + Phwrite int64 /* number of physical writes (writes on raw device) */ + Iget int64 /* number of inode lookups */ + Namei int64 /* number of vnode lookup from a path name */ + Dirblk int64 /* number of 512-byte block reads by the directory search routine to locate an entry for a file */ + Msg int64 /* number of IPC message operations */ + Sema int64 /* number of IPC semaphore operations */ + MinFaults int64 /* number of page faults with no I/O */ + MajFaults int64 /* number of page faults with disk I/O */ + PUser int64 /* raw number of physical processor tics in user mode */ + PSys int64 /* raw number of physical processor tics in system mode */ + PIdle int64 /* raw number of physical processor tics idle */ + PWait int64 /* raw number of physical processor tics waiting for I/O */ + RedispSD0 int64 /* number of thread redispatches within the scheduler affinity domain 0 */ + RedispSD1 int64 /* number of thread redispatches within the scheduler affinity domain 1 */ + RedispSD2 int64 /* number of thread redispatches within the scheduler affinity domain 2 */ + RedispSD3 int64 /* number of thread redispatches within the scheduler affinity domain 3 */ + RedispSD4 int64 /* number of thread redispatches within the scheduler affinity domain 4 */ + RedispSD5 int64 /* number of thread redispatches within the scheduler affinity domain 5 */ + MigrationPush int64 /* number of thread migrations from the local runque to another queue due to starvation load balancing */ + MigrationS3grq int64 /* number of thread migrations from the global runque to the local runque resulting in a move accross scheduling domain 3 */ + MigrationS3pul int64 /* number of thread migrations from another processor's runque resulting in a move accross scheduling domain 3 */ + InvolCSwitch int64 /* number of involuntary thread context switches */ + VolCSwitch int64 /* number of voluntary thread context switches */ + RunQueue int64 /* number of threads on the runque */ + Bound int64 /* number of bound threads */ + DecrIntrs int64 /* number of decrementer tics interrupts */ + MpcRIntrs int64 /* number of mpc's received interrupts */ + MpcSIntrs int64 /* number of mpc's sent interrupts */ + DevIntrs int64 /* number of device interrupts */ + SoftIntrs int64 /* number of offlevel handlers called */ + PhantIntrs int64 /* number of phantom interrupts */ + IdleDonatedPurr int64 /* number of idle cycles donated by a dedicated partition enabled for donation */ + IdleDonatedSpurr int64 /* number of idle spurr cycles donated by a dedicated partition enabled for donation */ + BusyDonatedPurr int64 /* number of busy cycles donated by a dedicated partition enabled for donation */ + BusyDonatedSpurr int64 /* number of busy spurr cycles donated by a dedicated partition enabled for donation */ + IdleStolenPurr int64 /* number of idle cycles stolen by the hypervisor from a dedicated partition */ + IdleStolenSpurr int64 /* number of idle spurr cycles stolen by the hypervisor from a dedicated partition */ + BusyStolenPurr int64 /* number of busy cycles stolen by the hypervisor from a dedicated partition */ + BusyStolenSpurr int64 /* number of busy spurr cycles stolen by the hypervisor from a dedicated partition */ + Hpi int64 /* number of hypervisor page-ins */ + Hpit int64 /* Time spent in hypervisor page-ins (in nanoseconds)*/ + PUserSpurr int64 /* number of spurr cycles spent in user mode */ + PSysSpurr int64 /* number of spurr cycles spent in kernel mode */ + PIdleSpurr int64 /* number of spurr cycles spent in idle mode */ + PWaitSpurr int64 /* number of spurr cycles spent in wait mode */ + SpurrFlag int32 /* set if running in spurr mode */ + LocalDispatch int64 /* number of local thread dispatches on this logical CPU */ + NearDispatch int64 /* number of near thread dispatches on this logical CPU */ + FarDispatch int64 /* number of far thread dispatches on this logical CPU */ + CSwitches int64 /* Context switches */ + Version int64 /* version number (1, 2, etc.,) */ + TbLast int64 /* timebase counter */ + State int /* Show whether the CPU is offline or online */ + VtbLast int64 /* Last virtual timebase read */ + ICountLast int64 /* Last instruction count read */ +} + +type CPUTotal struct { + NCpus int /* number of active logical processors */ + NCpusCfg int /* number of configured processors */ + Description string /* processor description (type/official name) */ + ProcessorHz int64 /* processor speed in Hz */ + User int64 /* raw total number of clock ticks spent in user mode */ + Sys int64 /* raw total number of clock ticks spent in system mode */ + Idle int64 /* raw total number of clock ticks spent idle */ + Wait int64 /* raw total number of clock ticks spent waiting for I/O */ + PSwitch int64 /* number of process switches (change in currently running process) */ + Syscall int64 /* number of system calls executed */ + Sysread int64 /* number of read system calls executed */ + Syswrite int64 /* number of write system calls executed */ + Sysfork int64 /* number of forks system calls executed */ + Sysexec int64 /* number of execs system calls executed */ + Readch int64 /* number of characters tranferred with read system call */ + Writech int64 /* number of characters tranferred with write system call */ + DevIntrs int64 /* number of device interrupts */ + SoftIntrs int64 /* number of software interrupts */ + Lbolt int64 /* number of ticks since last reboot */ + LoadAvg1 float32 /* times the average number of runnables processes during the last 1, 5 and 15 minutes. */ + LoadAvg5 float32 /* times the average number of runnables processes during the last 1, 5 and 15 minutes. */ + LoadAvg15 float32 /* times the average number of runnables processes during the last 1, 5 and 15 minutes. */ + RunQueue int64 /* length of the run queue (processes ready) */ + SwpQueue int64 /* length of the swap queue (processes waiting to be paged in) */ + Bread int64 /* number of blocks read */ + Bwrite int64 /* number of blocks written */ + Lread int64 /* number of logical read requests */ + Lwrite int64 /* number of logical write requests */ + Phread int64 /* number of physical reads (reads on raw devices) */ + Phwrite int64 /* number of physical writes (writes on raw devices) */ + RunOcc int64 /* updated whenever runque is updated, i.e. the runqueue is occupied. This can be used to compute the simple average of ready processes */ + SwpOcc int64 /* updated whenever swpque is updated. i.e. the swpqueue is occupied. This can be used to compute the simple average processes waiting to be paged in */ + Iget int64 /* number of inode lookups */ + Namei int64 /* number of vnode lookup from a path name */ + Dirblk int64 /* number of 512-byte block reads by the directory search routine to locate an entry for a file */ + Msg int64 /* number of IPC message operations */ + Sema int64 /* number of IPC semaphore operations */ + RcvInt int64 /* number of tty receive interrupts */ + XmtInt int64 /* number of tyy transmit interrupts */ + MdmInt int64 /* number of modem interrupts */ + TtyRawInch int64 /* number of raw input characters */ + TtyCanInch int64 /* number of canonical input characters (always zero) */ + TtyRawOutch int64 /* number of raw output characters */ + Ksched int64 /* number of kernel processes created */ + Koverf int64 /* kernel process creation attempts where: -the user has forked to their maximum limit -the configuration limit of processes has been reached */ + Kexit int64 /* number of kernel processes that became zombies */ + Rbread int64 /* number of remote read requests */ + Rcread int64 /* number of cached remote reads */ + Rbwrt int64 /* number of remote writes */ + Rcwrt int64 /* number of cached remote writes */ + Traps int64 /* number of traps */ + NCpusHigh int64 /* index of highest processor online */ + PUser int64 /* raw number of physical processor tics in user mode */ + PSys int64 /* raw number of physical processor tics in system mode */ + PIdle int64 /* raw number of physical processor tics idle */ + PWait int64 /* raw number of physical processor tics waiting for I/O */ + DecrIntrs int64 /* number of decrementer tics interrupts */ + MpcRIntrs int64 /* number of mpc's received interrupts */ + MpcSIntrs int64 /* number of mpc's sent interrupts */ + PhantIntrs int64 /* number of phantom interrupts */ + IdleDonatedPurr int64 /* number of idle cycles donated by a dedicated partition enabled for donation */ + IdleDonatedSpurr int64 /* number of idle spurr cycles donated by a dedicated partition enabled for donation */ + BusyDonatedPurr int64 /* number of busy cycles donated by a dedicated partition enabled for donation */ + BusyDonatedSpurr int64 /* number of busy spurr cycles donated by a dedicated partition enabled for donation */ + IdleStolenPurr int64 /* number of idle cycles stolen by the hypervisor from a dedicated partition */ + IdleStolenSpurr int64 /* number of idle spurr cycles stolen by the hypervisor from a dedicated partition */ + BusyStolenPurr int64 /* number of busy cycles stolen by the hypervisor from a dedicated partition */ + BusyStolenSpurr int64 /* number of busy spurr cycles stolen by the hypervisor from a dedicated partition */ + IOWait int32 /* number of processes that are asleep waiting for buffered I/O */ + PhysIO int32 /* number of processes waiting for raw I/O */ + TWait int64 /* number of threads that are waiting for filesystem direct(cio) */ + Hpi int64 /* number of hypervisor page-ins */ + Hpit int64 /* Time spent in hypervisor page-ins (in nanoseconds) */ + PUserSpurr int64 /* number of spurr cycles spent in user mode */ + PSysSpurr int64 /* number of spurr cycles spent in kernel mode */ + PIdleSpurr int64 /* number of spurr cycles spent in idle mode */ + PWaitSpurr int64 /* number of spurr cycles spent in wait mode */ + SpurrFlag int /* set if running in spurr mode */ + Version int64 /* version number (1, 2, etc.,) */ + TbLast int64 /*time base counter */ + PurrCoalescing int64 /* If the calling partition is authorized to see pool wide statistics then PURR cycles consumed to coalesce data else set to zero.*/ + SpurrCoalescing int64 /* If the calling partition is authorized to see pool wide statistics then SPURR cycles consumed to coalesce data else set to zero. */ +} + +type CPUUtil struct { + Version int64 + CpuID string /* holds the id of the cpu */ + Entitlement float32 /* Partition's entitlement */ + UserPct float32 /* % of utilization in user mode */ + KernPct float32 /* % of utilization in kernel mode */ + IdlePct float32 /* % of utilization in idle mode */ + WaitPct float32 /* % of utilization in wait mode */ + PhysicalBusy float32 /* physical cpus busy */ + PhysicalConsumed float32 /* total cpus consumed by the partition */ + FreqPct float32 /* Average freq% over the last interval */ + EntitlementPct float32 /* % of entitlement used */ + BusyPct float32 /* % of entitlement busy */ + IdleDonatedPct float32 /* % idle cycles donated */ + BusyDonatedPct float32 /* % of busy cycles donated */ + IdleStolenPct float32 /* % idle cycles stolen */ + BusyStolenPct float32 /* % busy cycles stolen */ + LUserPct float32 /* % of utilization in user mode, in terms of logical processor ticks */ + LKernPct float32 /* % of utilization in kernel mode, in terms of logical processor ticks*/ + LIdlePct float32 /* % of utilization in idle mode, in terms of logical processor ticks */ + LWaitPct float32 /* % of utilization in wait mode, in terms of logical processor ticks */ + DeltaTime int64 /* delta time in milliseconds, for which utilization is evaluated */ +} diff --git a/vendor/github.com/power-devops/perfstat/types_disk.go b/vendor/github.com/power-devops/perfstat/types_disk.go new file mode 100644 index 000000000..ca1493d87 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_disk.go @@ -0,0 +1,176 @@ +package perfstat + +type DiskTotal struct { + Number int32 /* total number of disks */ + Size int64 /* total size of all disks (in MB) */ + Free int64 /* free portion of all disks (in MB) */ + XRate int64 /* __rxfers: total number of transfers from disk */ + Xfers int64 /* total number of transfers to/from disk */ + Wblks int64 /* 512 bytes blocks written to all disks */ + Rblks int64 /* 512 bytes blocks read from all disks */ + Time int64 /* amount of time disks are active */ + Version int64 /* version number (1, 2, etc.,) */ + Rserv int64 /* Average read or receive service time */ + MinRserv int64 /* min read or receive service time */ + MaxRserv int64 /* max read or receive service time */ + RTimeOut int64 /* number of read request timeouts */ + RFailed int64 /* number of failed read requests */ + Wserv int64 /* Average write or send service time */ + MinWserv int64 /* min write or send service time */ + MaxWserv int64 /* max write or send service time */ + WTimeOut int64 /* number of write request timeouts */ + WFailed int64 /* number of failed write requests */ + WqDepth int64 /* instantaneous wait queue depth (number of requests waiting to be sent to disk) */ + WqTime int64 /* accumulated wait queueing time */ + WqMinTime int64 /* min wait queueing time */ + WqMaxTime int64 /* max wait queueing time */ +} + +// Disk Adapter Types +const ( + DA_SCSI = 0 /* 0 ==> SCSI, SAS, other legacy adapter types */ + DA_VSCSI /* 1 ==> Virtual SCSI/SAS Adapter */ + DA_FCA /* 2 ==> Fiber Channel Adapter */ +) + +type DiskAdapter struct { + Name string /* name of the adapter (from ODM) */ + Description string /* adapter description (from ODM) */ + Number int32 /* number of disks connected to adapter */ + Size int64 /* total size of all disks (in MB) */ + Free int64 /* free portion of all disks (in MB) */ + XRate int64 /* __rxfers: total number of reads via adapter */ + Xfers int64 /* total number of transfers via adapter */ + Rblks int64 /* 512 bytes blocks written via adapter */ + Wblks int64 /* 512 bytes blocks read via adapter */ + Time int64 /* amount of time disks are active */ + Version int64 /* version number (1, 2, etc.,) */ + AdapterType int64 /* 0 ==> SCSI, SAS, other legacy adapter types, 1 ==> Virtual SCSI/SAS Adapter, 2 ==> Fiber Channel Adapter */ + DkBSize int64 /* Number of Bytes in a block for this disk*/ + DkRxfers int64 /* Number of transfers from disk */ + DkRserv int64 /* read or receive service time */ + DkWserv int64 /* write or send service time */ + MinRserv int64 /* Minimum read service time */ + MaxRserv int64 /* Maximum read service time */ + MinWserv int64 /* Minimum Write service time */ + MaxWserv int64 /* Maximum write service time */ + WqDepth int64 /* driver wait queue depth */ + WqSampled int64 /* accumulated sampled dk_wq_depth */ + WqTime int64 /* accumulated wait queueing time */ + WqMinTime int64 /* minimum wait queueing time */ + WqMaxTime int64 /* maximum wait queueing time */ + QFull int64 /* "Service" queue full occurrence count (number of times the adapter/devices connected to the adapter is not accepting any more request) */ + QSampled int64 /* accumulated sampled */ +} + +type Disk struct { + Name string /* name of the disk */ + Description string /* disk description (from ODM) */ + VGName string /* volume group name (from ODM) */ + Size int64 /* size of the disk (in MB) */ + Free int64 /* free portion of the disk (in MB) */ + BSize int64 /* disk block size (in bytes) */ + XRate int64 /* number of transfers from disk */ + Xfers int64 /* number of transfers to/from disk */ + Wblks int64 /* number of blocks written to disk */ + Rblks int64 /* number of blocks read from disk */ + QDepth int64 /* instantaneous "service" queue depth (number of requests sent to disk and not completed yet) */ + Time int64 /* amount of time disk is active */ + Adapter string /* disk adapter name */ + PathsCount int32 /* number of paths to this disk */ + QFull int64 /* "service" queue full occurrence count (number of times the disk is not accepting any more request) */ + Rserv int64 /* read or receive service time */ + RTimeOut int64 /* number of read request timeouts */ + Rfailed int64 /* number of failed read requests */ + MinRserv int64 /* min read or receive service time */ + MaxRserv int64 /* max read or receive service time */ + Wserv int64 /* write or send service time */ + WTimeOut int64 /* number of write request timeouts */ + Wfailed int64 /* number of failed write requests */ + MinWserv int64 /* min write or send service time */ + MaxWserv int64 /* max write or send service time */ + WqDepth int64 /* instantaneous wait queue depth (number of requests waiting to be sent to disk) */ + WqSampled int64 /* accumulated sampled dk_wq_depth */ + WqTime int64 /* accumulated wait queueing time */ + WqMinTime int64 /* min wait queueing time */ + WqMaxTime int64 /* max wait queueing time */ + QSampled int64 /* accumulated sampled dk_q_depth */ + Version int64 /* version number (1, 2, etc.,) */ + PseudoDisk bool /*Indicates whether pseudo or physical disk */ + VTDisk bool /* 1- Virtual Target Disk, 0 - Others */ +} + +type DiskPath struct { + Name string /* name of the path */ + XRate int64 /* __rxfers: number of reads via the path */ + Xfers int64 /* number of transfers via the path */ + Rblks int64 /* 512 bytes blocks written via the path */ + Wblks int64 /* 512 bytes blocks read via the path */ + Time int64 /* amount of time disks are active */ + Adapter string /* disk adapter name (from ODM) */ + QFull int64 /* "service" queue full occurrence count (number of times the disk is not accepting any more request) */ + Rserv int64 /* read or receive service time */ + RTimeOut int64 /* number of read request timeouts */ + Rfailed int64 /* number of failed read requests */ + MinRserv int64 /* min read or receive service time */ + MaxRserv int64 /* max read or receive service time */ + Wserv int64 /* write or send service time */ + WTimeOut int64 /* number of write request timeouts */ + Wfailed int64 /* number of failed write requests */ + MinWserv int64 /* min write or send service time */ + MaxWserv int64 /* max write or send service time */ + WqDepth int64 /* instantaneous wait queue depth (number of requests waiting to be sent to disk) */ + WqSampled int64 /* accumulated sampled dk_wq_depth */ + WqTime int64 /* accumulated wait queueing time */ + WqMinTime int64 /* min wait queueing time */ + WqMaxTime int64 /* max wait queueing time */ + QSampled int64 /* accumulated sampled dk_q_depth */ + Version int64 /* version number (1, 2, etc.,) */ +} + +const ( + FC_DOWN = 0 // FC Adapter state is DOWN + FC_UP = 1 // FC Adapter state is UP +) + +const ( + FCT_FCHBA = 0 // FC type - real Fiber Channel Adapter + FCT_VFC = 1 // FC type - virtual Fiber Channel +) + +type FCAdapter struct { + Version int64 /* version number (1, 2, etc.,) */ + Name string /* name of the adapter */ + State int32 /* FC Adapter state UP or DOWN */ + InputRequests int64 /* Number of Input Requests*/ + OutputRequests int64 /* Number of Output Requests */ + InputBytes int64 /* Number of Input Bytes */ + OutputBytes int64 /* Number of Output Bytes */ + EffMaxTransfer int64 /* Adapter's Effective Maximum Transfer Value */ + NoDMAResourceCnt int64 /* Count of DMA failures due to no DMA Resource available */ + NoCmdResourceCnt int64 /* Count of failures to allocate a command due to no command resource available */ + AttentionType int32 /* Link up or down Indicator */ + SecondsSinceLastReset int64 /* Displays the seconds since last reset of the statistics on the adapter */ + TxFrames int64 /* Number of frames transmitted */ + TxWords int64 /* Fiber Channel Kbytes transmitted */ + RxFrames int64 /* Number of Frames Received */ + RxWords int64 /* Fiber Channel Kbytes Received */ + LIPCount int64 /* Count of LIP (Loop Initialization Protocol) Events received in case we have FC-AL */ + NOSCount int64 /* Count of NOS (Not_Operational) Events. This indicates a link failure state. */ + ErrorFrames int64 /* Number of frames received with the CRC Error */ + DumpedFrames int64 /* Number of lost frames */ + LinkFailureCount int64 /* Count of Link failures */ + LossofSyncCount int64 /* Count of loss of sync */ + LossofSignal int64 /* Count of loss of Signal */ + PrimitiveSeqProtocolErrCount int64 /* number of times a primitive sequence was in error */ + InvalidTxWordCount int64 /* Count of Invalid Transmission words received */ + InvalidCRCCount int64 /* Count of CRC Errors in a Received Frame */ + PortFcId int64 /* SCSI Id of the adapter */ + PortSpeed int64 /* Speed of Adapter in GBIT */ + PortType string /* Type of connection. The Possible Values are Fabric, Private Loop, Point-to-Point, unknown */ + PortWWN int64 /* World Wide Port name */ + PortSupportedSpeed int64 /* Supported Port Speed in GBIT */ + AdapterType int /* 0 - Fiber Chanel, 1 - Virtual Fiber Chanel Adapter */ + VfcName string /* name of the Virtual Fiber Chanel(VFC) adapter */ + ClientPartName string /* name of the client partition */ +} diff --git a/vendor/github.com/power-devops/perfstat/types_fs.go b/vendor/github.com/power-devops/perfstat/types_fs.go new file mode 100644 index 000000000..0be048a38 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_fs.go @@ -0,0 +1,195 @@ +package perfstat + +import ( + "strings" +) + +type FileSystem struct { + Device string /* name of the mounted device */ + MountPoint string /* where the device is mounted */ + FSType int /* File system type, see the constants below */ + Flags int /* Flags of the file system */ + TotalBlocks int64 /* number of 512 bytes blocks in the filesystem */ + FreeBlocks int64 /* number of free 512 bytes block in the filesystem */ + TotalInodes int64 /* total number of inodes in the filesystem */ + FreeInodes int64 /* number of free inodes in the filesystem */ +} + +func (f *FileSystem) TypeString() string { + switch f.FSType { + case FS_JFS2: + return "jfs2" + case FS_NAMEFS: + return "namefs" + case FS_NFS: + return "nfs" + case FS_JFS: + return "jfs" + case FS_CDROM: + return "cdrfs" + case FS_PROCFS: + return "procfs" + case FS_SFS: + return "sfs" + case FS_CACHEFS: + return "cachefs" + case FS_NFS3: + return "nfs3" + case FS_AUTOFS: + return "autofs" + case FS_POOLFS: + return "poolfs" + case FS_VXFS: + return "vxfs" + case FS_VXODM: + return "vxodm" + case FS_UDF: + return "udfs" + case FS_NFS4: + return "nfs4" + case FS_RFS4: + return "rfs4" + case FS_CIFS: + return "cifs" + case FS_PMEMFS: + return "pmemfs" + case FS_AHAFS: + return "ahafs" + case FS_STNFS: + return "stnfs" + case FS_ASMFS: + return "asmfs" + } + return "unknown" +} + +func (f *FileSystem) FlagsString() string { + var flags []string + + switch { + case f.Flags&VFS_READONLY != 0: + flags = append(flags, "ro") + case f.Flags&VFS_REMOVABLE != 0: + flags = append(flags, "removable") + case f.Flags&VFS_DEVMOUNT != 0: + flags = append(flags, "local") + case f.Flags&VFS_REMOTE != 0: + flags = append(flags, "remote") + case f.Flags&VFS_SYSV_MOUNT != 0: + flags = append(flags, "sysv") + case f.Flags&VFS_UNMOUNTING != 0: + flags = append(flags, "unmounting") + case f.Flags&VFS_NOSUID != 0: + flags = append(flags, "nosuid") + case f.Flags&VFS_NODEV != 0: + flags = append(flags, "nodev") + case f.Flags&VFS_NOINTEG != 0: + flags = append(flags, "nointeg") + case f.Flags&VFS_NOMANAGER != 0: + flags = append(flags, "nomanager") + case f.Flags&VFS_NOCASE != 0: + flags = append(flags, "nocase") + case f.Flags&VFS_UPCASE != 0: + flags = append(flags, "upcase") + case f.Flags&VFS_NBC != 0: + flags = append(flags, "nbc") + case f.Flags&VFS_MIND != 0: + flags = append(flags, "mind") + case f.Flags&VFS_RBR != 0: + flags = append(flags, "rbr") + case f.Flags&VFS_RBW != 0: + flags = append(flags, "rbw") + case f.Flags&VFS_DISCONNECTED != 0: + flags = append(flags, "disconnected") + case f.Flags&VFS_SHUTDOWN != 0: + flags = append(flags, "shutdown") + case f.Flags&VFS_VMOUNTOK != 0: + flags = append(flags, "vmountok") + case f.Flags&VFS_SUSER != 0: + flags = append(flags, "suser") + case f.Flags&VFS_SOFT_MOUNT != 0: + flags = append(flags, "soft") + case f.Flags&VFS_UNMOUNTED != 0: + flags = append(flags, "unmounted") + case f.Flags&VFS_DEADMOUNT != 0: + flags = append(flags, "deadmount") + case f.Flags&VFS_SNAPSHOT != 0: + flags = append(flags, "snapshot") + case f.Flags&VFS_VCM_ON != 0: + flags = append(flags, "vcm_on") + case f.Flags&VFS_VCM_MONITOR != 0: + flags = append(flags, "vcm_monitor") + case f.Flags&VFS_ATIMEOFF != 0: + flags = append(flags, "noatime") + case f.Flags&VFS_READMOSTLY != 0: + flags = append(flags, "readmostly") + case f.Flags&VFS_CIOR != 0: + flags = append(flags, "cior") + case f.Flags&VFS_CIO != 0: + flags = append(flags, "cio") + case f.Flags&VFS_DIO != 0: + flags = append(flags, "dio") + } + + return strings.Join(flags, ",") +} + +// Filesystem types +const ( + FS_JFS2 = 0 /* AIX physical fs "jfs2" */ + FS_NAMEFS = 1 /* AIX pseudo fs "namefs" */ + FS_NFS = 2 /* SUN Network File System "nfs" */ + FS_JFS = 3 /* AIX R3 physical fs "jfs" */ + FS_CDROM = 5 /* CDROM File System "cdrom" */ + FS_PROCFS = 6 /* PROCFS File System "proc" */ + FS_SFS = 16 /* AIX Special FS (STREAM mounts) */ + FS_CACHEFS = 17 /* Cachefs file system */ + FS_NFS3 = 18 /* NFSv3 file system */ + FS_AUTOFS = 19 /* Automount file system */ + FS_POOLFS = 20 /* Pool file system */ + FS_VXFS = 32 /* THRPGIO File System "vxfs" */ + FS_VXODM = 33 /* For Veritas File System */ + FS_UDF = 34 /* UDFS file system */ + FS_NFS4 = 35 /* NFSv4 file system */ + FS_RFS4 = 36 /* NFSv4 Pseudo file system */ + FS_CIFS = 37 /* AIX SMBFS (CIFS client) */ + FS_PMEMFS = 38 /* MCR Async Mobility pseudo file system */ + FS_AHAFS = 39 /* AHAFS File System "aha" */ + FS_STNFS = 40 /* Short-Term NFS */ + FS_ASMFS = 41 /* Oracle ASM FS */ +) + +// Filesystem flags +const ( + VFS_READONLY = 0x00000001 /* rdonly access to vfs */ + VFS_REMOVABLE = 0x00000002 /* removable (diskette) media */ + VFS_DEVMOUNT = 0x00000004 /* physical device mount */ + VFS_REMOTE = 0x00000008 /* file system is on network */ + VFS_SYSV_MOUNT = 0x00000010 /* System V style mount */ + VFS_UNMOUNTING = 0x00000020 /* originated by unmount() */ + VFS_NOSUID = 0x00000040 /* don't maintain suid-ness across this mount */ + VFS_NODEV = 0x00000080 /* don't allow device access across this mount */ + VFS_NOINTEG = 0x00000100 /* no integrity mount option */ + VFS_NOMANAGER = 0x00000200 /* mount managed fs w/o manager */ + VFS_NOCASE = 0x00000400 /* do not map dir names */ + VFS_UPCASE = 0x00000800 /* map dir names to uppercase */ + VFS_NBC = 0x00001000 /* NBC cached file in this vfs */ + VFS_MIND = 0x00002000 /* multi-segment .indirect */ + VFS_RBR = 0x00004000 /* Release-behind when reading */ + VFS_RBW = 0x00008000 /* Release-behind when writing */ + VFS_DISCONNECTED = 0x00010000 /* file mount not in use */ + VFS_SHUTDOWN = 0x00020000 /* forced unmount for shutdown */ + VFS_VMOUNTOK = 0x00040000 /* dir/file mnt permission flag */ + VFS_SUSER = 0x00080000 /* client-side suser perm. flag */ + VFS_SOFT_MOUNT = 0x00100000 /* file-over-file or directory over directory "soft" mount */ + VFS_UNMOUNTED = 0x00200000 /* unmount completed, stale vnodes are left in the vfs */ + VFS_DEADMOUNT = 0x00400000 /* softmount vfs should be disconnected at last vnode free */ + VFS_SNAPSHOT = 0x00800000 /* snapshot mount */ + VFS_VCM_ON = 0x01000000 /* VCM is currently active */ + VFS_VCM_MONITOR = 0x02000000 /* VCM monitoring is active */ + VFS_ATIMEOFF = 0x04000000 /* no atime updates during i/o */ + VFS_READMOSTLY = 0x10000000 /* ROFS allows open for write */ + VFS_CIOR = 0x20000000 /* O_CIOR mount */ + VFS_CIO = 0x40000000 /* O_CIO mount */ + VFS_DIO = 0x80000000 /* O_DIRECT mount */ +) diff --git a/vendor/github.com/power-devops/perfstat/types_lpar.go b/vendor/github.com/power-devops/perfstat/types_lpar.go new file mode 100644 index 000000000..2d3c32fa8 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_lpar.go @@ -0,0 +1,68 @@ +package perfstat + +type PartitionType struct { + SmtCapable bool /* OS supports SMT mode */ + SmtEnabled bool /* SMT mode is on */ + LparCapable bool /* OS supports logical partitioning */ + LparEnabled bool /* logical partitioning is on */ + SharedCapable bool /* OS supports shared processor LPAR */ + SharedEnabled bool /* partition runs in shared mode */ + DLparCapable bool /* OS supports dynamic LPAR */ + Capped bool /* partition is capped */ + Kernel64bit bool /* kernel is 64 bit */ + PoolUtilAuthority bool /* pool utilization available */ + DonateCapable bool /* capable of donating cycles */ + DonateEnabled bool /* enabled for donating cycles */ + AmsCapable bool /* 1 = AMS(Active Memory Sharing) capable, 0 = Not AMS capable */ + AmsEnabled bool /* 1 = AMS(Active Memory Sharing) enabled, 0 = Not AMS enabled */ + PowerSave bool /*1= Power saving mode is enabled*/ + AmeEnabled bool /* Active Memory Expansion is enabled */ + SharedExtended bool +} + +type PartitionValue struct { + Online int64 + Max int64 + Min int64 + Desired int64 +} + +type PartitionConfig struct { + Version int64 /* Version number */ + Name string /* Partition Name */ + Node string /* Node Name */ + Conf PartitionType /* Partition Properties */ + Number int32 /* Partition Number */ + GroupID int32 /* Group ID */ + ProcessorFamily string /* Processor Type */ + ProcessorModel string /* Processor Model */ + MachineID string /* Machine ID */ + ProcessorMhz float64 /* Processor Clock Speed in MHz */ + NumProcessors PartitionValue /* Number of Configured Physical Processors in frame*/ + OSName string /* Name of Operating System */ + OSVersion string /* Version of operating System */ + OSBuild string /* Build of Operating System */ + LCpus int32 /* Number of Logical CPUs */ + SmtThreads int32 /* Number of SMT Threads */ + Drives int32 /* Total Number of Drives */ + NetworkAdapters int32 /* Total Number of Network Adapters */ + CpuCap PartitionValue /* Min, Max and Online CPU Capacity */ + Weightage int32 /* Variable Processor Capacity Weightage */ + EntCapacity int32 /* number of processor units this partition is entitled to receive */ + VCpus PartitionValue /* Min, Max and Online Virtual CPUs */ + PoolID int32 /* Shared Pool ID of physical processors, to which this partition belongs*/ + ActiveCpusInPool int32 /* Count of physical CPUs in the shared processor pool, to which this partition belongs */ + PoolWeightage int32 /* Pool Weightage */ + SharedPCpu int32 /* Number of physical processors allocated for shared processor use */ + MaxPoolCap int32 /* Maximum processor capacity of partition's pool */ + EntPoolCap int32 /* Entitled processor capacity of partition's pool */ + Mem PartitionValue /* Min, Max and Online Memory */ + MemWeightage int32 /* Variable Memory Capacity Weightage */ + TotalIOMemoryEntitlement int64 /* I/O Memory Entitlement of the partition in bytes */ + MemPoolID int32 /* AMS pool id of the pool the LPAR belongs to */ + HyperPgSize int64 /* Hypervisor page size in KB*/ + ExpMem PartitionValue /* Min, Max and Online Expanded Memory */ + TargetMemExpFactor int64 /* Target Memory Expansion Factor scaled by 100 */ + TargetMemExpSize int64 /* Expanded Memory Size in MB */ + SubProcessorMode int32 /* Split core mode, its value can be 0,1,2 or 4. 0 for unsupported, 1 for capable but not enabled, 2 or 4 for enabled*/ +} diff --git a/vendor/github.com/power-devops/perfstat/types_lvm.go b/vendor/github.com/power-devops/perfstat/types_lvm.go new file mode 100644 index 000000000..8f7176a61 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_lvm.go @@ -0,0 +1,31 @@ +package perfstat + +type LogicalVolume struct { + Name string /* logical volume name */ + VGName string /* volume group name */ + OpenClose int64 /* LVM_QLVOPEN, etc. (see lvm.h) */ + State int64 /* LVM_UNDEF, etc. (see lvm.h) */ + MirrorPolicy int64 /* LVM_PARALLEL, etc. (see lvm.h) */ + MirrorWriteConsistency int64 /* LVM_CONSIST, etc. (see lvm.h) */ + WriteVerify int64 /* LVM_VERIFY, etc. (see lvm.h) */ + PPsize int64 /* physical partition size in MB */ + LogicalPartitions int64 /* total number of logical paritions configured for this logical volume */ + Mirrors int32 /* number of physical mirrors for each logical partition */ + IOCnt int64 /* Number of read and write requests */ + KBReads int64 /* Number of Kilobytes read */ + KBWrites int64 /* Number of Kilobytes written */ + Version int64 /* version number (1, 2, etc.,) */ +} + +type VolumeGroup struct { + Name string /* volume group name */ + TotalDisks int64 /* number of physical volumes in the volume group */ + ActiveDisks int64 /* number of active physical volumes in the volume group */ + TotalLogicalVolumes int64 /* number of logical volumes in the volume group */ + OpenedLogicalVolumes int64 /* number of logical volumes opened in the volume group */ + IOCnt int64 /* Number of read and write requests */ + KBReads int64 /* Number of Kilobytes read */ + KBWrites int64 /* Number of Kilobytes written */ + Version int64 /* version number (1, 2, etc.,) */ + VariedState int /* Indicates volume group available or not */ +} diff --git a/vendor/github.com/power-devops/perfstat/types_memory.go b/vendor/github.com/power-devops/perfstat/types_memory.go new file mode 100644 index 000000000..096d29ad2 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_memory.go @@ -0,0 +1,101 @@ +package perfstat + +type MemoryTotal struct { + VirtualTotal int64 /* total virtual memory (in 4KB pages) */ + RealTotal int64 /* total real memory (in 4KB pages) */ + RealFree int64 /* free real memory (in 4KB pages) */ + RealPinned int64 /* real memory which is pinned (in 4KB pages) */ + RealInUse int64 /* real memory which is in use (in 4KB pages) */ + BadPages int64 /* number of bad pages */ + PageFaults int64 /* number of page faults */ + PageIn int64 /* number of pages paged in */ + PageOut int64 /* number of pages paged out */ + PgSpIn int64 /* number of page ins from paging space */ + PgSpOut int64 /* number of page outs from paging space */ + Scans int64 /* number of page scans by clock */ + Cycles int64 /* number of page replacement cycles */ + PgSteals int64 /* number of page steals */ + NumPerm int64 /* number of frames used for files (in 4KB pages) */ + PgSpTotal int64 /* total paging space (in 4KB pages) */ + PgSpFree int64 /* free paging space (in 4KB pages) */ + PgSpRsvd int64 /* reserved paging space (in 4KB pages) */ + RealSystem int64 /* real memory used by system segments (in 4KB pages). */ + RealUser int64 /* real memory used by non-system segments (in 4KB pages). */ + RealProcess int64 /* real memory used by process segments (in 4KB pages). */ + VirtualActive int64 /* Active virtual pages. Virtual pages are considered active if they have been accessed */ + IOME int64 /* I/O memory entitlement of the partition in bytes*/ + IOMU int64 /* I/O memory entitlement of the partition in use in bytes*/ + IOHWM int64 /* High water mark of I/O memory entitlement used in bytes*/ + PMem int64 /* Amount of physical mmeory currently backing partition's logical memory in bytes*/ + CompressedTotal int64 /* Total numbers of pages in compressed pool (in 4KB pages) */ + CompressedWSegPg int64 /* Number of compressed working storage pages */ + CPgIn int64 /* number of page ins to compressed pool */ + CPgOut int64 /* number of page outs from compressed pool */ + TrueSize int64 /* True Memory Size in 4KB pages */ + ExpandedMemory int64 /* Expanded Memory Size in 4KB pages */ + CompressedWSegSize int64 /* Total size of the compressed working storage pages in the pool */ + TargetCPoolSize int64 /* Target Compressed Pool Size in bytes */ + MaxCPoolSize int64 /* Max Size of Compressed Pool in bytes */ + MinUCPoolSize int64 /* Min Size of Uncompressed Pool in bytes */ + CPoolSize int64 /* Compressed Pool size in bytes */ + UCPoolSize int64 /* Uncompressed Pool size in bytes */ + CPoolInUse int64 /* Compressed Pool Used in bytes */ + UCPoolInUse int64 /* Uncompressed Pool Used in bytes */ + Version int64 /* version number (1, 2, etc.,) */ + RealAvailable int64 /* number of pages (in 4KB pages) of memory available without paging out working segments */ + BytesCoalesced int64 /* The number of bytes of the calling partition.s logical real memory coalesced because they contained duplicated data */ + BytesCoalescedMemPool int64 /* number of bytes of logical real memory coalesced because they contained duplicated data in the calling partition.s memory */ +} + +type MemoryPage struct { + PSize int64 /* page size in bytes */ + RealTotal int64 /* number of real memory frames of this page size */ + RealFree int64 /* number of pages on free list */ + RealPinned int64 /* number of pages pinned */ + RealInUse int64 /* number of pages in use */ + PgExct int64 /* number of page faults */ + PgIns int64 /* number of pages paged in */ + PgOuts int64 /* number of pages paged out */ + PgSpIns int64 /* number of page ins from paging space */ + PgSpOuts int64 /* number of page outs from paging space */ + Scans int64 /* number of page scans by clock */ + Cycles int64 /* number of page replacement cycles */ + PgSteals int64 /* number of page steals */ + NumPerm int64 /* number of frames used for files */ + NumPgSp int64 /* number of pages with allocated paging space */ + RealSystem int64 /* number of pages used by system segments. */ + RealUser int64 /* number of pages used by non-system segments. */ + RealProcess int64 /* number of pages used by process segments. */ + VirtActive int64 /* Active virtual pages. */ + ComprsdTotal int64 /* Number of pages of this size compressed */ + ComprsdWsegPgs int64 /* Number of compressed working storage pages */ + CPgIns int64 /* number of page ins of this page size to compressed pool */ + CPgOuts int64 /* number of page outs of this page size from compressed pool */ + CPoolInUse int64 /* Compressed Size of this page size in Compressed Pool */ + UCPoolSize int64 /* Uncompressed Pool size in bytes of this page size */ + ComprsdWsegSize int64 /* Total size of the compressed working storage pages in the pool */ + Version int64 /* version number (1, 2, etc.,) */ + RealAvail int64 /* number of pages (in 4KB pages) of memory available without paging out working segments */ +} + +// paging space types +const ( + LV_PAGING = 1 + NFS_PAGING = 2 + UNKNOWN_PAGING = 3 +) + +type PagingSpace struct { + Name string /* Paging space name */ + Type uint8 /* type of paging device (LV_PAGING or NFS_PAGING) */ + VGName string /* volume group name */ + Hostname string /* host name of paging server */ + Filename string /* swap file name on server */ + LPSize int64 /* size in number of logical partitions */ + MBSize int64 /* size in megabytes */ + MBUsed int64 /* portion used in megabytes */ + IOPending int64 /* number of pending I/O */ + Active uint8 /* indicates if active (1 if so, 0 if not) */ + Automatic uint8 /* indicates if automatic (1 if so, 0 if not) */ + Version int64 /* version number (1, 2, etc.,) */ +} diff --git a/vendor/github.com/power-devops/perfstat/types_network.go b/vendor/github.com/power-devops/perfstat/types_network.go new file mode 100644 index 000000000..e69d0041d --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_network.go @@ -0,0 +1,163 @@ +package perfstat + +// Network Interface types +const ( + IFT_OTHER = 0x1 + IFT_1822 = 0x2 /* old-style arpanet imp */ + IFT_HDH1822 = 0x3 /* HDH arpanet imp */ + IFT_X25DDN = 0x4 /* x25 to imp */ + IFT_X25 = 0x5 /* PDN X25 interface (RFC877) */ + IFT_ETHER = 0x6 /* Ethernet CSMACD */ + IFT_ISO88023 = 0x7 /* CMSA CD */ + IFT_ISO88024 = 0x8 /* Token Bus */ + IFT_ISO88025 = 0x9 /* Token Ring */ + IFT_ISO88026 = 0xa /* MAN */ + IFT_STARLAN = 0xb + IFT_P10 = 0xc /* Proteon 10MBit ring */ + IFT_P80 = 0xd /* Proteon 10MBit ring */ + IFT_HY = 0xe /* Hyperchannel */ + IFT_FDDI = 0xf + IFT_LAPB = 0x10 + IFT_SDLC = 0x11 + IFT_T1 = 0x12 + IFT_CEPT = 0x13 /* E1 - european T1 */ + IFT_ISDNBASIC = 0x14 + IFT_ISDNPRIMARY = 0x15 + IFT_PTPSERIAL = 0x16 /* Proprietary PTP serial */ + IFT_PPP = 0x17 /* RFC 1331 */ + IFT_LOOP = 0x18 /* loopback */ + IFT_EON = 0x19 /* ISO over IP */ + IFT_XETHER = 0x1a /* obsolete 3MB experimental ethernet */ + IFT_NSIP = 0x1b /* XNS over IP */ + IFT_SLIP = 0x1c /* IP over generic TTY */ + IFT_ULTRA = 0x1d /* Ultra Technologies */ + IFT_DS3 = 0x1e /* Generic T3 */ + IFT_SIP = 0x1f /* SMDS */ + IFT_FRELAY = 0x20 /* Frame Relay DTE only */ + IFT_RS232 = 0x21 + IFT_PARA = 0x22 /* parallel-port */ + IFT_ARCNET = 0x23 + IFT_ARCNETPLUS = 0x24 + IFT_ATM = 0x25 /* ATM cells */ + IFT_MIOX25 = 0x26 + IFT_SONET = 0x27 /* SONET or SDH */ + IFT_X25PLE = 0x28 + IFT_ISO88022LLC = 0x29 + IFT_LOCALTALK = 0x2a + IFT_SMDSDXI = 0x2b + IFT_FRELAYDCE = 0x2c /* Frame Relay DCE */ + IFT_V35 = 0x2d + IFT_HSSI = 0x2e + IFT_HIPPI = 0x2f + IFT_MODEM = 0x30 /* Generic Modem */ + IFT_AAL5 = 0x31 /* AAL5 over ATM */ + IFT_SONETPATH = 0x32 + IFT_SONETVT = 0x33 + IFT_SMDSICIP = 0x34 /* SMDS InterCarrier Interface */ + IFT_PROPVIRTUAL = 0x35 /* Proprietary Virtual/internal */ + IFT_PROPMUX = 0x36 /* Proprietary Multiplexing */ + IFT_VIPA = 0x37 /* Virtual Interface */ + IFT_SN = 0x38 /* Federation Switch */ + IFT_SP = 0x39 /* SP switch */ + IFT_FCS = 0x3a /* IP over Fiber Channel */ + IFT_TUNNEL = 0x3b + IFT_GIFTUNNEL = 0x3c /* IPv4 over IPv6 tunnel */ + IFT_HF = 0x3d /* Support for PERCS HFI*/ + IFT_CLUSTER = 0x3e /* cluster pseudo network interface */ + IFT_FB = 0xc7 /* IP over Infiniband. Number by IANA */ +) + +type NetIfaceTotal struct { + Number int32 /* number of network interfaces */ + IPackets int64 /* number of packets received on interface */ + IBytes int64 /* number of bytes received on interface */ + IErrors int64 /* number of input errors on interface */ + OPackets int64 /* number of packets sent on interface */ + OBytes int64 /* number of bytes sent on interface */ + OErrors int64 /* number of output errors on interface */ + Collisions int64 /* number of collisions on csma interface */ + XmitDrops int64 /* number of packets not transmitted */ + Version int64 /* version number (1, 2, etc.,) */ +} + +type NetIface struct { + Name string /* name of the interface */ + Description string /* interface description (from ODM, similar to lscfg output) */ + Type uint8 /* ethernet, tokenring, etc. interpretation can be done using /usr/include/net/if_types.h */ + MTU int64 /* network frame size */ + IPackets int64 /* number of packets received on interface */ + IBytes int64 /* number of bytes received on interface */ + IErrors int64 /* number of input errors on interface */ + OPackets int64 /* number of packets sent on interface */ + OBytes int64 /* number of bytes sent on interface */ + OErrors int64 /* number of output errors on interface */ + Collisions int64 /* number of collisions on csma interface */ + Bitrate int64 /* adapter rating in bit per second */ + XmitDrops int64 /* number of packets not transmitted */ + Version int64 /* version number (1, 2, etc.,) */ + IfIqDrops int64 /* Dropped on input, this interface */ + IfArpDrops int64 /* Dropped because no arp response */ +} + +type NetBuffer struct { + Name string /* size in ascii, always power of 2 (ex: "32", "64", "128") */ + InUse int64 /* number of buffer currently allocated */ + Calls int64 /* number of buffer allocations since last reset */ + Delayed int64 /* number of delayed allocations */ + Free int64 /* number of free calls */ + Failed int64 /* number of failed allocations */ + HighWatermark int64 /* high threshold for number of buffer allocated */ + Freed int64 /* number of buffers freed */ + Version int64 /* version number (1, 2, etc.,) */ +} + +// Network adapter types +const ( + NET_PHY = 0 /* physical device */ + NET_SEA = 1 /* shared ethernet adapter */ + NET_VIR = 2 /* virtual device */ + NET_HEA = 3 /* host ethernet adapter */ + NET_EC = 4 /* etherchannel */ + NET_VLAN = 5 /* vlan pseudo device */ +) + +type NetAdapter struct { + Version int64 /* version number (1,2, etc) */ + Name string /* name of the adapter */ + TxPackets int64 /* Transmit Packets on interface */ + TxBytes int64 /* Transmit Bytes on interface */ + TxInterrupts int64 /* Transfer Interrupts */ + TxErrors int64 /* Transmit Errors */ + TxPacketsDropped int64 /* Packets Dropped at the time of Data Transmission */ + TxQueueSize int64 /* Maximum Packets on Software Transmit Queue */ + TxQueueLen int64 /* Transmission Queue Length */ + TxQueueOverflow int64 /* Transmission Queue Overflow */ + TxBroadcastPackets int64 /* Number of Broadcast Packets Transmitted */ + TxMulticastPackets int64 /* Number of Multicast packets Transmitted */ + TxCarrierSense int64 /* Lost Carrier Sense signal count */ + TxDMAUnderrun int64 /* Count of DMA Under-runs for Transmission */ + TxLostCTSErrors int64 /* The number of unsuccessful transmissions due to the loss of the Clear-to-Send signal error */ + TxMaxCollisionErrors int64 /* Maximum Collision Errors at Transmission */ + TxLateCollisionErrors int64 /* Late Collision Errors at Transmission */ + TxDeferred int64 /* The number of packets deferred for Transmission. */ + TxTimeoutErrors int64 /* Time Out Errors for Transmission */ + TxSingleCollisionCount int64 /* Count of Single Collision error at Transmission */ + TxMultipleCollisionCount int64 /* Count of Multiple Collision error at Transmission */ + RxPackets int64 /* Receive Packets on interface */ + RxBytes int64 /* Receive Bytes on interface */ + RxInterrupts int64 /* Receive Interrupts */ + RxErrors int64 /* Input errors on interface */ + RxPacketsDropped int64 /* The number of packets accepted by the device driver for transmission which were not (for any reason) given to the device. */ + RxBadPackets int64 /* Count of Bad Packets Received. */ + RxMulticastPackets int64 /* Number of MultiCast Packets Received */ + RxBroadcastPackets int64 /* Number of Broadcast Packets Received */ + RxCRCErrors int64 /* Count of Packets Received with CRC errors */ + RxDMAOverrun int64 /* Count of DMA over-runs for Data Receival. */ + RxAlignmentErrors int64 /* Packets Received with Alignment Error */ + RxNoResourceErrors int64 /* Packets Received with No Resource Errors */ + RxCollisionErrors int64 /* Packets Received with Collision errors */ + RxPacketTooShortErrors int64 /* Count of Short Packets Received. */ + RxPacketTooLongErrors int64 /* Count of Too Long Packets Received. */ + RxPacketDiscardedByAdapter int64 /* Count of Received Packets discarded by Adapter. */ + AdapterType int32 /* 0 - Physical, 1 - SEA, 2 - Virtual, 3 -HEA */ +} diff --git a/vendor/github.com/power-devops/perfstat/types_process.go b/vendor/github.com/power-devops/perfstat/types_process.go new file mode 100644 index 000000000..325c70b07 --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/types_process.go @@ -0,0 +1,43 @@ +package perfstat + +type Process struct { + Version int64 /* version number (1, 2, etc.,) */ + PID int64 /* Process ID */ + ProcessName string /* Name of The Process */ + Priority int32 /* Process Priority */ + NumThreads int64 /* Thread Count */ + UID int64 /* Owner Info */ + ClassID int64 /* WLM Class Name */ + Size int64 /* Virtual Size of the Process in KB(Exclusive Usage, Leaving all Shared Library Text & Shared File Pages, Shared Memory, Memory Mapped) */ + RealMemData int64 /* Real Memory used for Data in KB */ + RealMemText int64 /* Real Memory used for Text in KB */ + VirtMemData int64 /* Virtual Memory used to Data in KB */ + VirtMemText int64 /* Virtual Memory used for Text in KB */ + SharedLibDataSize int64 /* Data Size from Shared Library in KB */ + HeapSize int64 /* Heap Size in KB */ + RealInUse int64 /* The Real memory in use(in KB) by the process including all kind of segments (excluding system segments). This includes Text, Data, Shared Library Text, Shared Library Data, File Pages, Shared Memory & Memory Mapped */ + VirtInUse int64 /* The Virtual memory in use(in KB) by the process including all kind of segments (excluding system segments). This includes Text, Data, Shared Library Text, Shared Library Data, File Pages, Shared Memory & Memory Mapped */ + Pinned int64 /* Pinned Memory(in KB) for this process inclusive of all segments */ + PgSpInUse int64 /* Paging Space used(in KB) inclusive of all segments */ + FilePages int64 /* File Pages used(in KB) including shared pages */ + RealInUseMap int64 /* Real memory used(in KB) for Shared Memory and Memory Mapped regions */ + VirtInUseMap int64 /* Virtual Memory used(in KB) for Shared Memory and Memory Mapped regions */ + PinnedInUseMap int64 /* Pinned memory(in KB) for Shared Memory and Memory Mapped regions */ + UCpuTime float64 /* User Mode CPU time will be in percentage or milliseconds based on, whether it is filled by perfstat_process_util or perfstat_process respectively. */ + SCpuTime float64 /* System Mode CPU time will be in percentage or milliseconds based on, whether it is filled by perfstat_process_util or perfstat_process respectively. */ + LastTimeBase int64 /* Timebase Counter */ + InBytes int64 /* Bytes Read from Disk */ + OutBytes int64 /* Bytes Written to Disk */ + InOps int64 /* In Operations from Disk */ + OutOps int64 /* Out Operations from Disk */ +} + +type Thread struct { + TID int64 /* thread identifier */ + PID int64 /* process identifier */ + CpuID int64 /* processor on which I'm bound */ + UCpuTime float64 /* User Mode CPU time will be in percentage or milliseconds based on, whether it is filled by perfstat_thread_util or perfstat_thread respectively. */ + SCpuTime float64 /* System Mode CPU time will be in percentage or milliseconds based on, whether it is filled by perfstat_thread_util or perfstat_thread respectively. */ + LastTimeBase int64 /* Timebase Counter */ + Version int64 +} diff --git a/vendor/github.com/power-devops/perfstat/uptime.go b/vendor/github.com/power-devops/perfstat/uptime.go new file mode 100644 index 000000000..2bd3e568d --- /dev/null +++ b/vendor/github.com/power-devops/perfstat/uptime.go @@ -0,0 +1,35 @@ +// +build aix + +package perfstat + +/* +#include "c_helpers.h" +*/ +import "C" + +import ( + "fmt" + "time" +) + +func timeSince(ts uint64) uint64 { + return uint64(time.Now().Unix()) - ts +} + +// BootTime() returns the time of the last boot in UNIX seconds +func BootTime() (uint64, error) { + sec := C.boottime() + if sec == -1 { + return 0, fmt.Errorf("Can't determine boot time") + } + return uint64(sec), nil +} + +// UptimeSeconds() calculates uptime in seconds +func UptimeSeconds() (uint64, error) { + boot, err := BootTime() + if err != nil { + return 0, err + } + return timeSince(boot), nil +} diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_openbsd.go b/vendor/github.com/shirou/gopsutil/cpu/cpu_openbsd.go deleted file mode 100644 index c761aa21d..000000000 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_openbsd.go +++ /dev/null @@ -1,178 +0,0 @@ -// +build openbsd - -package cpu - -import ( - "bytes" - "context" - "encoding/binary" - "fmt" - "runtime" - "strconv" - "strings" - "syscall" - - "github.com/shirou/gopsutil/internal/common" - "github.com/tklauser/go-sysconf" - "golang.org/x/sys/unix" -) - -// sys/sched.h -var ( - CPUser = 0 - CPNice = 1 - CPSys = 2 - CPIntr = 3 - CPIdle = 4 - CPUStates = 5 -) - -// sys/sysctl.h -const ( - CTLKern = 1 // "high kernel": proc, limits - CTLHw = 6 // CTL_HW - SMT = 24 // HW_SMT - KernCptime = 40 // KERN_CPTIME - KernCptime2 = 71 // KERN_CPTIME2 -) - -var ClocksPerSec = float64(128) - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClocksPerSec = float64(clkTck) - } - - func() { - v, err := unix.Sysctl("kern.osrelease") // can't reuse host.PlatformInformation because of circular import - if err != nil { - return - } - v = strings.ToLower(v) - version, err := strconv.ParseFloat(v, 64) - if err != nil { - return - } - if version >= 6.4 { - CPIntr = 4 - CPIdle = 5 - CPUStates = 6 - } - }() -} - -func smt() (bool, error) { - mib := []int32{CTLHw, SMT} - buf, _, err := common.CallSyscall(mib) - if err != nil { - return false, err - } - - var ret bool - br := bytes.NewReader(buf) - if err := binary.Read(br, binary.LittleEndian, &ret); err != nil { - return false, err - } - - return ret, nil -} - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - var ret []TimesStat - - var ncpu int - if percpu { - ncpu, _ = Counts(true) - } else { - ncpu = 1 - } - - smt, err := smt() - if err == syscall.EOPNOTSUPP { - // if hw.smt is not applicable for this platform (e.g. i386), - // pretend it's enabled - smt = true - } else if err != nil { - return nil, err - } - - for i := 0; i < ncpu; i++ { - j := i - if !smt { - j *= 2 - } - - var cpuTimes = make([]int32, CPUStates) - var mib []int32 - if percpu { - mib = []int32{CTLKern, KernCptime2, int32(j)} - } else { - mib = []int32{CTLKern, KernCptime} - } - buf, _, err := common.CallSyscall(mib) - if err != nil { - return ret, err - } - - br := bytes.NewReader(buf) - err = binary.Read(br, binary.LittleEndian, &cpuTimes) - if err != nil { - return ret, err - } - c := TimesStat{ - User: float64(cpuTimes[CPUser]) / ClocksPerSec, - Nice: float64(cpuTimes[CPNice]) / ClocksPerSec, - System: float64(cpuTimes[CPSys]) / ClocksPerSec, - Idle: float64(cpuTimes[CPIdle]) / ClocksPerSec, - Irq: float64(cpuTimes[CPIntr]) / ClocksPerSec, - } - if percpu { - c.CPU = fmt.Sprintf("cpu%d", j) - } else { - c.CPU = "cpu-total" - } - ret = append(ret, c) - } - - return ret, nil -} - -// Returns only one (minimal) CPUInfoStat on OpenBSD -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - var ret []InfoStat - var err error - - c := InfoStat{} - - mhz, err := unix.SysctlUint32("hw.cpuspeed") - if err != nil { - return nil, err - } - c.Mhz = float64(mhz) - - ncpu, err := unix.SysctlUint32("hw.ncpuonline") - if err != nil { - return nil, err - } - c.Cores = int32(ncpu) - - if c.ModelName, err = unix.Sysctl("hw.model"); err != nil { - return nil, err - } - - return append(ret, c), nil -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - return runtime.NumCPU(), nil -} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_solaris.go b/vendor/github.com/shirou/gopsutil/disk/disk_solaris.go deleted file mode 100644 index 1c440ac4b..000000000 --- a/vendor/github.com/shirou/gopsutil/disk/disk_solaris.go +++ /dev/null @@ -1,115 +0,0 @@ -// +build solaris - -package disk - -import ( - "bufio" - "context" - "fmt" - "math" - "os" - "strings" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/unix" -) - -const ( - // _DEFAULT_NUM_MOUNTS is set to `cat /etc/mnttab | wc -l` rounded up to the - // nearest power of two. - _DEFAULT_NUM_MOUNTS = 32 - - // _MNTTAB default place to read mount information - _MNTTAB = "/etc/mnttab" -) - -var ( - // A blacklist of read-only virtual filesystems. Writable filesystems are of - // operational concern and must not be included in this list. - fsTypeBlacklist = map[string]struct{}{ - "ctfs": struct{}{}, - "dev": struct{}{}, - "fd": struct{}{}, - "lofs": struct{}{}, - "lxproc": struct{}{}, - "mntfs": struct{}{}, - "objfs": struct{}{}, - "proc": struct{}{}, - } -) - -func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { - ret := make([]PartitionStat, 0, _DEFAULT_NUM_MOUNTS) - - // Scan mnttab(4) - f, err := os.Open(_MNTTAB) - if err != nil { - } - defer func() { - if err == nil { - err = f.Close() - } else { - f.Close() - } - }() - - scanner := bufio.NewScanner(f) - for scanner.Scan() { - fields := strings.Split(scanner.Text(), "\t") - - if _, found := fsTypeBlacklist[fields[2]]; found { - continue - } - - ret = append(ret, PartitionStat{ - // NOTE(seanc@): Device isn't exactly accurate: from mnttab(4): "The name - // of the resource that has been mounted." Ideally this value would come - // from Statvfs_t.Fsid but I'm leaving it to the caller to traverse - // unix.Statvfs(). - Device: fields[0], - Mountpoint: fields[1], - Fstype: fields[2], - Opts: fields[3], - }) - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("unable to scan %q: %v", _MNTTAB, err) - } - - return ret, err -} - -func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { - statvfs := unix.Statvfs_t{} - if err := unix.Statvfs(path, &statvfs); err != nil { - return nil, fmt.Errorf("unable to call statvfs(2) on %q: %v", path, err) - } - - usageStat := &UsageStat{ - Path: path, - Fstype: common.IntToString(statvfs.Basetype[:]), - Total: statvfs.Blocks * statvfs.Frsize, - Free: statvfs.Bfree * statvfs.Frsize, - Used: (statvfs.Blocks - statvfs.Bfree) * statvfs.Frsize, - - // NOTE: ZFS (and FreeBZSD's UFS2) use dynamic inode/dnode allocation. - // Explicitly return a near-zero value for InodesUsedPercent so that nothing - // attempts to garbage collect based on a lack of available inodes/dnodes. - // Similarly, don't use the zero value to prevent divide-by-zero situations - // and inject a faux near-zero value. Filesystems evolve. Has your - // filesystem evolved? Probably not if you care about the number of - // available inodes. - InodesTotal: 1024.0 * 1024.0, - InodesUsed: 1024.0, - InodesFree: math.MaxUint64, - InodesUsedPercent: (1024.0 / (1024.0 * 1024.0)) * 100.0, - } - - usageStat.UsedPercent = (float64(usageStat.Used) / float64(usageStat.Total)) * 100.0 - - return usageStat, nil -} diff --git a/vendor/github.com/shirou/gopsutil/host/host_darwin_386.go b/vendor/github.com/shirou/gopsutil/host/host_darwin_386.go deleted file mode 100644 index c3596f9f5..000000000 --- a/vendor/github.com/shirou/gopsutil/host/host_darwin_386.go +++ /dev/null @@ -1,19 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -package host - -type Utmpx struct { - User [256]int8 - ID [4]int8 - Line [32]int8 - Pid int32 - Type int16 - Pad_cgo_0 [6]byte - Tv Timeval - Host [256]int8 - Pad [16]uint32 -} -type Timeval struct { - Sec int32 -} diff --git a/vendor/github.com/shirou/gopsutil/host/host_posix.go b/vendor/github.com/shirou/gopsutil/host/host_posix.go deleted file mode 100644 index 1cdf16d6f..000000000 --- a/vendor/github.com/shirou/gopsutil/host/host_posix.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build linux freebsd openbsd darwin solaris - -package host - -import ( - "bytes" - - "golang.org/x/sys/unix" -) - -func KernelArch() (string, error) { - var utsname unix.Utsname - err := unix.Uname(&utsname) - return string(utsname.Machine[:bytes.IndexByte(utsname.Machine[:], 0)]), err -} diff --git a/vendor/github.com/shirou/gopsutil/load/load_solaris.go b/vendor/github.com/shirou/gopsutil/load/load_solaris.go deleted file mode 100644 index 5cad05e36..000000000 --- a/vendor/github.com/shirou/gopsutil/load/load_solaris.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build solaris - -package load - -import ( - "context" - "os/exec" - "strings" - - "github.com/shirou/gopsutil/internal/common" -) - -func Avg() (*AvgStat, error) { - return AvgWithContext(context.Background()) -} - -func AvgWithContext(ctx context.Context) (*AvgStat, error) { - return nil, common.ErrNotImplementedError -} - -func Misc() (*MiscStat, error) { - return MiscWithContext(context.Background()) -} - -func MiscWithContext(ctx context.Context) (*MiscStat, error) { - bin, err := exec.LookPath("ps") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, bin, "-efo", "s") - if err != nil { - return nil, err - } - lines := strings.Split(string(out), "\n") - - ret := MiscStat{} - for _, l := range lines { - if l == "O" { - ret.ProcsRunning++ - } - } - - return &ret, nil -} diff --git a/vendor/github.com/shirou/gopsutil/process/process_darwin_386.go b/vendor/github.com/shirou/gopsutil/process/process_darwin_386.go deleted file mode 100644 index f8e922385..000000000 --- a/vendor/github.com/shirou/gopsutil/process/process_darwin_386.go +++ /dev/null @@ -1,234 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -package process - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type UGid_t uint32 - -type KinfoProc struct { - Proc ExternProc - Eproc Eproc -} - -type Eproc struct { - Paddr *uint64 - Sess *Session - Pcred Upcred - Ucred Uucred - Pad_cgo_0 [4]byte - Vm Vmspace - Ppid int32 - Pgid int32 - Jobc int16 - Pad_cgo_1 [2]byte - Tdev int32 - Tpgid int32 - Pad_cgo_2 [4]byte - Tsess *Session - Wmesg [8]int8 - Xsize int32 - Xrssize int16 - Xccount int16 - Xswrss int16 - Pad_cgo_3 [2]byte - Flag int32 - Login [12]int8 - Spare [4]int32 - Pad_cgo_4 [4]byte -} - -type Proc struct{} - -type Session struct{} - -type ucred struct { - Link _Ctype_struct___0 - Ref uint64 - Posix Posix_cred - Label *Label - Audit Au_session -} - -type Uucred struct { - Ref int32 - UID uint32 - Ngroups int16 - Pad_cgo_0 [2]byte - Groups [16]uint32 -} - -type Upcred struct { - Pc_lock [72]int8 - Pc_ucred *ucred - P_ruid uint32 - P_svuid uint32 - P_rgid uint32 - P_svgid uint32 - P_refcnt int32 - Pad_cgo_0 [4]byte -} - -type Vmspace struct { - Dummy int32 - Pad_cgo_0 [4]byte - Dummy2 *int8 - Dummy3 [5]int32 - Pad_cgo_1 [4]byte - Dummy4 [3]*int8 -} - -type Sigacts struct{} - -type ExternProc struct { - P_un [16]byte - P_vmspace uint64 - P_sigacts uint64 - Pad_cgo_0 [3]byte - P_flag int32 - P_stat int8 - P_pid int32 - P_oppid int32 - P_dupfd int32 - Pad_cgo_1 [4]byte - User_stack uint64 - Exit_thread uint64 - P_debugger int32 - Sigwait int32 - P_estcpu uint32 - P_cpticks int32 - P_pctcpu uint32 - Pad_cgo_2 [4]byte - P_wchan uint64 - P_wmesg uint64 - P_swtime uint32 - P_slptime uint32 - P_realtimer Itimerval - P_rtime Timeval - P_uticks uint64 - P_sticks uint64 - P_iticks uint64 - P_traceflag int32 - Pad_cgo_3 [4]byte - P_tracep uint64 - P_siglist int32 - Pad_cgo_4 [4]byte - P_textvp uint64 - P_holdcnt int32 - P_sigmask uint32 - P_sigignore uint32 - P_sigcatch uint32 - P_priority uint8 - P_usrpri uint8 - P_nice int8 - P_comm [17]int8 - Pad_cgo_5 [4]byte - P_pgrp uint64 - P_addr uint64 - P_xstat uint16 - P_acflag uint16 - Pad_cgo_6 [4]byte - P_ru uint64 -} - -type Itimerval struct { - Interval Timeval - Value Timeval -} - -type Vnode struct{} - -type Pgrp struct{} - -type UserStruct struct{} - -type Au_session struct { - Aia_p *AuditinfoAddr - Mask AuMask -} - -type Posix_cred struct { - UID uint32 - Ruid uint32 - Svuid uint32 - Ngroups int16 - Pad_cgo_0 [2]byte - Groups [16]uint32 - Rgid uint32 - Svgid uint32 - Gmuid uint32 - Flags int32 -} - -type Label struct{} - -type AuditinfoAddr struct { - Auid uint32 - Mask AuMask - Termid AuTidAddr - Asid int32 - Flags uint64 -} -type AuMask struct { - Success uint32 - Failure uint32 -} -type AuTidAddr struct { - Port int32 - Type uint32 - Addr [4]uint32 -} - -type UcredQueue struct { - Next *ucred - Prev **ucred -} diff --git a/vendor/github.com/shirou/gopsutil/process/process_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/process/process_darwin_cgo.go deleted file mode 100644 index a80817755..000000000 --- a/vendor/github.com/shirou/gopsutil/process/process_darwin_cgo.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build darwin -// +build cgo - -package process - -// #include -// #include -import "C" -import ( - "context" - "fmt" - "unsafe" -) - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - var c C.char // need a var for unsafe.Sizeof need a var - const bufsize = C.PROC_PIDPATHINFO_MAXSIZE * unsafe.Sizeof(c) - buffer := (*C.char)(C.malloc(C.size_t(bufsize))) - defer C.free(unsafe.Pointer(buffer)) - - ret, err := C.proc_pidpath(C.int(p.Pid), unsafe.Pointer(buffer), C.uint32_t(bufsize)) - if err != nil { - return "", err - } - if ret <= 0 { - return "", fmt.Errorf("unknown error: proc_pidpath returned %d", ret) - } - - return C.GoString(buffer), nil -} diff --git a/vendor/github.com/shirou/gopsutil/process/process_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/process/process_darwin_nocgo.go deleted file mode 100644 index 3583e1987..000000000 --- a/vendor/github.com/shirou/gopsutil/process/process_darwin_nocgo.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build darwin -// +build !cgo - -package process - -import ( - "context" - "fmt" - "os/exec" - "strconv" - "strings" -) - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - lsof_bin, err := exec.LookPath("lsof") - if err != nil { - return "", err - } - out, err := invoke.CommandWithContext(ctx, lsof_bin, "-p", strconv.Itoa(int(p.Pid)), "-Fpfn") - if err != nil { - return "", fmt.Errorf("bad call to lsof: %s", err) - } - txtFound := 0 - lines := strings.Split(string(out), "\n") - for i := 1; i < len(lines); i++ { - if lines[i] == "ftxt" { - txtFound++ - if txtFound == 2 { - return lines[i-1][1:], nil - } - } - } - return "", fmt.Errorf("missing txt data returned by lsof") -} diff --git a/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm64.go b/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm64.go deleted file mode 100644 index 99781d1a2..000000000 --- a/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm64.go +++ /dev/null @@ -1,201 +0,0 @@ -// +build freebsd -// +build arm64 -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs process/types_freebsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 14 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 7 -) - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x488 - sizeOfKinfoProc = 0x440 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SWAIT = 6 - SLOCK = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type KinfoProc struct { - Structsize int32 - Layout int32 - Args *int64 /* pargs */ - Paddr *int64 /* proc */ - Addr *int64 /* user */ - Tracep *int64 /* vnode */ - Textvp *int64 /* vnode */ - Fd *int64 /* filedesc */ - Vmspace *int64 /* vmspace */ - Wchan *byte - Pid int32 - Ppid int32 - Pgid int32 - Tpgid int32 - Sid int32 - Tsid int32 - Jobc int16 - Spare_short1 int16 - Tdev_freebsd11 uint32 - Siglist [16]byte /* sigset */ - Sigmask [16]byte /* sigset */ - Sigignore [16]byte /* sigset */ - Sigcatch [16]byte /* sigset */ - Uid uint32 - Ruid uint32 - Svuid uint32 - Rgid uint32 - Svgid uint32 - Ngroups int16 - Spare_short2 int16 - Groups [16]uint32 - Size uint64 - Rssize int64 - Swrss int64 - Tsize int64 - Dsize int64 - Ssize int64 - Xstat uint16 - Acflag uint16 - Pctcpu uint32 - Estcpu uint32 - Slptime uint32 - Swtime uint32 - Cow uint32 - Runtime uint64 - Start Timeval - Childtime Timeval - Flag int64 - Kiflag int64 - Traceflag int32 - Stat uint8 - Nice int8 - Lock uint8 - Rqindex uint8 - Oncpu_old uint8 - Lastcpu_old uint8 - Tdname [17]uint8 - Wmesg [9]uint8 - Login [18]uint8 - Lockname [9]uint8 - Comm [20]int8 - Emul [17]uint8 - Loginclass [18]uint8 - Moretdname [4]uint8 - Sparestrings [46]uint8 - Spareints [2]int32 - Tdev uint64 - Oncpu int32 - Lastcpu int32 - Tracer int32 - Flag2 int32 - Fibnum int32 - Cr_flags uint32 - Jid int32 - Numthreads int32 - Tid int32 - Pri Priority - Rusage Rusage - Rusage_ch Rusage - Pcb *int64 /* pcb */ - Kstack *byte - Udata *byte - Tdaddr *int64 /* thread */ - Spareptrs [6]*byte - Sparelongs [12]int64 - Sflag int64 - Tdflags int64 -} - -type Priority struct { - Class uint8 - Level uint8 - Native uint8 - User uint8 -} - -type KinfoVmentry struct { - Structsize int32 - Type int32 - Start uint64 - End uint64 - Offset uint64 - Vn_fileid uint64 - Vn_fsid_freebsd11 uint32 - Flags int32 - Resident int32 - Private_resident int32 - Protection int32 - Ref_count int32 - Shadow_count int32 - Vn_type int32 - Vn_size uint64 - Vn_rdev_freebsd11 uint32 - Vn_mode uint16 - Status uint16 - Vn_fsid uint64 - Vn_rdev uint64 - X_kve_ispare [8]int32 - Path [1024]uint8 -} diff --git a/vendor/github.com/shirou/gopsutil/process/process_windows_arm64.go b/vendor/github.com/shirou/gopsutil/process/process_windows_arm64.go deleted file mode 100644 index ddaf19544..000000000 --- a/vendor/github.com/shirou/gopsutil/process/process_windows_arm64.go +++ /dev/null @@ -1,104 +0,0 @@ -//go:build windows && arm64 -// +build windows,arm64 - -package process - -import ( - "errors" - "syscall" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" -) - -type PROCESS_MEMORY_COUNTERS struct { - CB uint32 - PageFaultCount uint32 - PeakWorkingSetSize uint32 - WorkingSetSize uint32 - QuotaPeakPagedPoolUsage uint32 - QuotaPagedPoolUsage uint32 - QuotaPeakNonPagedPoolUsage uint32 - QuotaNonPagedPoolUsage uint32 - PagefileUsage uint32 - PeakPagefileUsage uint32 -} - -func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { - if is32BitProcess { - //we are on a 32-bit process reading an external 32-bit process - var info processBasicInformation32 - - ret, _, _ := common.ProcNtQueryInformationProcess.Call( - uintptr(procHandle), - uintptr(common.ProcessBasicInformation), - uintptr(unsafe.Pointer(&info)), - uintptr(unsafe.Sizeof(info)), - uintptr(0), - ) - if int(ret) >= 0 { - return uint64(info.PebBaseAddress), nil - } - } else { - //we are on a 32-bit process reading an external 64-bit process - if common.ProcNtWow64QueryInformationProcess64.Find() == nil { //avoid panic - var info processBasicInformation64 - - ret, _, _ := common.ProcNtWow64QueryInformationProcess64.Call( - uintptr(procHandle), - uintptr(common.ProcessBasicInformation), - uintptr(unsafe.Pointer(&info)), - uintptr(unsafe.Sizeof(info)), - uintptr(0), - ) - if int(ret) >= 0 { - return info.PebBaseAddress, nil - } - } - } - - //return 0 on error - return 0, errors.New("could not query PEB address") -} - -func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, size uint) []byte { - if is32BitProcess { - var read uint - - buffer := make([]byte, size) - - ret, _, _ := common.ProcNtReadVirtualMemory.Call( - uintptr(h), - uintptr(address), - uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), - uintptr(unsafe.Pointer(&read)), - ) - if int(ret) >= 0 && read > 0 { - return buffer[:read] - } - } else { - //reading a 64-bit process from a 32-bit one - if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { //avoid panic - var read uint64 - - buffer := make([]byte, size) - - ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call( - uintptr(h), - uintptr(address&0xFFFFFFFF), //the call expects a 64-bit value - uintptr(address>>32), - uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), //the call expects a 64-bit value - uintptr(0), //but size is 32-bit so pass zero as the high dword - uintptr(unsafe.Pointer(&read)), - ) - if int(ret) >= 0 && read > 0 { - return buffer[:uint(read)] - } - } - } - - //if we reach here, an error happened - return nil -} diff --git a/vendor/github.com/shirou/gopsutil/LICENSE b/vendor/github.com/shirou/gopsutil/v3/LICENSE similarity index 96% rename from vendor/github.com/shirou/gopsutil/LICENSE rename to vendor/github.com/shirou/gopsutil/v3/LICENSE index da71a5e72..6f06adcbf 100644 --- a/vendor/github.com/shirou/gopsutil/LICENSE +++ b/vendor/github.com/shirou/gopsutil/v3/LICENSE @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------- -internal/common/binary.go in the gopsutil is copied and modifid from golang/encoding/binary.go. +internal/common/binary.go in the gopsutil is copied and modified from golang/encoding/binary.go. diff --git a/vendor/github.com/shirou/gopsutil/v3/common/env.go b/vendor/github.com/shirou/gopsutil/v3/common/env.go new file mode 100644 index 000000000..4b5f4980c --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/common/env.go @@ -0,0 +1,23 @@ +package common + +type EnvKeyType string + +// EnvKey is a context key that can be used to set programmatically the environment +// gopsutil relies on to perform calls against the OS. +// Example of use: +// +// ctx := context.WithValue(context.Background(), common.EnvKey, EnvMap{common.HostProcEnvKey: "/myproc"}) +// avg, err := load.AvgWithContext(ctx) +var EnvKey = EnvKeyType("env") + +const ( + HostProcEnvKey EnvKeyType = "HOST_PROC" + HostSysEnvKey EnvKeyType = "HOST_SYS" + HostEtcEnvKey EnvKeyType = "HOST_ETC" + HostVarEnvKey EnvKeyType = "HOST_VAR" + HostRunEnvKey EnvKeyType = "HOST_RUN" + HostDevEnvKey EnvKeyType = "HOST_DEV" + HostRootEnvKey EnvKeyType = "HOST_ROOT" +) + +type EnvMap map[EnvKeyType]string diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu.go similarity index 82% rename from vendor/github.com/shirou/gopsutil/cpu/cpu.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu.go index 24a81167d..83bc23d45 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu.go @@ -5,12 +5,13 @@ import ( "encoding/json" "fmt" "math" + "runtime" "strconv" "strings" "sync" "time" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) // TimesStat contains the amounts of time the CPU has spent performing different @@ -51,8 +52,10 @@ type lastPercent struct { lastPerCPUTimes []TimesStat } -var lastCPUPercent lastPercent -var invoke common.Invoker = common.Invoke{} +var ( + lastCPUPercent lastPercent + invoke common.Invoker = common.Invoke{} +) func init() { lastCPUPercent.Lock() @@ -84,10 +87,12 @@ func (c TimesStat) String() string { return `{` + strings.Join(v, ",") + `}` } -// Total returns the total number of seconds in a CPUTimesStat +// Deprecated: Total returns the total number of seconds in a CPUTimesStat +// Please do not use this internal function. func (c TimesStat) Total() float64 { - total := c.User + c.System + c.Nice + c.Iowait + c.Irq + c.Softirq + - c.Steal + c.Idle + total := c.User + c.System + c.Idle + c.Nice + c.Iowait + c.Irq + + c.Softirq + c.Steal + c.Guest + c.GuestNice + return total } @@ -97,9 +102,15 @@ func (c InfoStat) String() string { } func getAllBusy(t TimesStat) (float64, float64) { - busy := t.User + t.System + t.Nice + t.Iowait + t.Irq + - t.Softirq + t.Steal - return busy + t.Idle, busy + tot := t.Total() + if runtime.GOOS == "linux" { + tot -= t.Guest // Linux 2.6.24+ + tot -= t.GuestNice // Linux 3.2.0+ + } + + busy := tot - t.Idle - t.Iowait + + return tot, busy } func calculateBusy(t1, t2 TimesStat) float64 { @@ -140,11 +151,11 @@ func Percent(interval time.Duration, percpu bool) ([]float64, error) { func PercentWithContext(ctx context.Context, interval time.Duration, percpu bool) ([]float64, error) { if interval <= 0 { - return percentUsedFromLastCall(percpu) + return percentUsedFromLastCallWithContext(ctx, percpu) } // Get CPU usage at the start of the interval. - cpuTimes1, err := Times(percpu) + cpuTimes1, err := TimesWithContext(ctx, percpu) if err != nil { return nil, err } @@ -154,7 +165,7 @@ func PercentWithContext(ctx context.Context, interval time.Duration, percpu bool } // And at the end of the interval. - cpuTimes2, err := Times(percpu) + cpuTimes2, err := TimesWithContext(ctx, percpu) if err != nil { return nil, err } @@ -163,7 +174,11 @@ func PercentWithContext(ctx context.Context, interval time.Duration, percpu bool } func percentUsedFromLastCall(percpu bool) ([]float64, error) { - cpuTimes, err := Times(percpu) + return percentUsedFromLastCallWithContext(context.Background(), percpu) +} + +func percentUsedFromLastCallWithContext(ctx context.Context, percpu bool) ([]float64, error) { + cpuTimes, err := TimesWithContext(ctx, percpu) if err != nil { return nil, err } diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix.go new file mode 100644 index 000000000..1439d1d79 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix.go @@ -0,0 +1,16 @@ +//go:build aix +// +build aix + +package cpu + +import ( + "context" +) + +func Times(percpu bool) ([]TimesStat, error) { + return TimesWithContext(context.Background(), percpu) +} + +func Info() ([]InfoStat, error) { + return InfoWithContext(context.Background()) +} diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix_cgo.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix_cgo.go new file mode 100644 index 000000000..9c1e70b17 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix_cgo.go @@ -0,0 +1,66 @@ +//go:build aix && cgo +// +build aix,cgo + +package cpu + +import ( + "context" + + "github.com/power-devops/perfstat" +) + +func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { + var ret []TimesStat + if percpu { + cpus, err := perfstat.CpuStat() + if err != nil { + return nil, err + } + for _, c := range cpus { + ct := &TimesStat{ + CPU: c.Name, + Idle: float64(c.Idle), + User: float64(c.User), + System: float64(c.Sys), + Iowait: float64(c.Wait), + } + ret = append(ret, *ct) + } + } else { + c, err := perfstat.CpuUtilTotalStat() + if err != nil { + return nil, err + } + ct := &TimesStat{ + CPU: "cpu-total", + Idle: float64(c.IdlePct), + User: float64(c.UserPct), + System: float64(c.KernPct), + Iowait: float64(c.WaitPct), + } + ret = append(ret, *ct) + } + return ret, nil +} + +func InfoWithContext(ctx context.Context) ([]InfoStat, error) { + c, err := perfstat.CpuTotalStat() + if err != nil { + return nil, err + } + info := InfoStat{ + CPU: 0, + Mhz: float64(c.ProcessorHz / 1000000), + Cores: int32(c.NCpusCfg), + } + result := []InfoStat{info} + return result, nil +} + +func CountsWithContext(ctx context.Context, logical bool) (int, error) { + c, err := perfstat.CpuTotalStat() + if err != nil { + return 0, err + } + return c.NCpusCfg, nil +} diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix_nocgo.go new file mode 100644 index 000000000..1a291532a --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_aix_nocgo.go @@ -0,0 +1,95 @@ +//go:build aix && !cgo +// +build aix,!cgo + +package cpu + +import ( + "context" + "regexp" + "strconv" + "strings" + + "github.com/shirou/gopsutil/v3/internal/common" +) + +var whiteSpaces = regexp.MustCompile(`\s+`) + +func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { + if percpu { + return []TimesStat{}, common.ErrNotImplementedError + } else { + out, err := invoke.CommandWithContext(ctx, "sar", "-u", "10", "1") + if err != nil { + return nil, err + } + lines := strings.Split(string(out), "\n") + if len(lines) < 5 { + return []TimesStat{}, common.ErrNotImplementedError + } + + ret := TimesStat{CPU: "cpu-total"} + h := whiteSpaces.Split(lines[len(lines)-3], -1) // headers + v := whiteSpaces.Split(lines[len(lines)-2], -1) // values + for i, header := range h { + if t, err := strconv.ParseFloat(v[i], 64); err == nil { + switch header { + case `%usr`: + ret.User = t + case `%sys`: + ret.System = t + case `%wio`: + ret.Iowait = t + case `%idle`: + ret.Idle = t + } + } + } + + return []TimesStat{ret}, nil + } +} + +func InfoWithContext(ctx context.Context) ([]InfoStat, error) { + out, err := invoke.CommandWithContext(ctx, "prtconf") + if err != nil { + return nil, err + } + + ret := InfoStat{} + for _, line := range strings.Split(string(out), "\n") { + if strings.HasPrefix(line, "Number Of Processors:") { + p := whiteSpaces.Split(line, 4) + if len(p) > 3 { + if t, err := strconv.ParseUint(p[3], 10, 64); err == nil { + ret.Cores = int32(t) + } + } + } else if strings.HasPrefix(line, "Processor Clock Speed:") { + p := whiteSpaces.Split(line, 5) + if len(p) > 4 { + if t, err := strconv.ParseFloat(p[3], 64); err == nil { + switch strings.ToUpper(p[4]) { + case "MHZ": + ret.Mhz = t + case "GHZ": + ret.Mhz = t * 1000.0 + case "KHZ": + ret.Mhz = t / 1000.0 + default: + ret.Mhz = t + } + } + } + break + } + } + return []InfoStat{ret}, nil +} + +func CountsWithContext(ctx context.Context, logical bool) (int, error) { + info, err := InfoWithContext(ctx) + if err == nil { + return int(info[0].Cores), nil + } + return 0, err +} diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin.go similarity index 83% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin.go index 421f1e16b..41f395e5e 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package cpu @@ -7,6 +8,7 @@ import ( "strconv" "strings" + "github.com/shoenig/go-m1cpu" "github.com/tklauser/go-sysconf" "golang.org/x/sys/unix" ) @@ -14,11 +16,11 @@ import ( // sys/resource.h const ( CPUser = 0 - CPNice = 1 - CPSys = 2 - CPIntr = 3 - CPIdle = 4 - CPUStates = 5 + cpNice = 1 + cpSys = 2 + cpIntr = 3 + cpIdle = 4 + cpUStates = 5 ) // default value. from time.h @@ -84,13 +86,16 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { c.CacheSize = int32(cacheSize) c.VendorID, _ = unix.Sysctl("machdep.cpu.vendor") - // Use the rated frequency of the CPU. This is a static value and does not - // account for low power or Turbo Boost modes. - cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency") - if err != nil { - return ret, err + if m1cpu.IsAppleSilicon() { + c.Mhz = float64(m1cpu.PCoreHz() / 1_000_000) + } else { + // Use the rated frequency of the CPU. This is a static value and does not + // account for low power or Turbo Boost modes. + cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency") + if err == nil { + c.Mhz = float64(cpuFrequency) / 1000000.0 + } } - c.Mhz = float64(cpuFrequency) / 1000000.0 return append(ret, c), nil } diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go similarity index 98% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_cgo.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go index 2a7d4a115..1d5f0772e 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_cgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build cgo +//go:build darwin && cgo +// +build darwin,cgo package cpu @@ -108,5 +108,4 @@ func allCPUTimes() ([]TimesStat, error) { } return []TimesStat{c}, nil - } diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_nocgo.go similarity index 67% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_nocgo.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_nocgo.go index 242b4a8e7..e067e99f9 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_nocgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_nocgo.go @@ -1,9 +1,9 @@ -// +build darwin -// +build !cgo +//go:build darwin && !cgo +// +build darwin,!cgo package cpu -import "github.com/shirou/gopsutil/internal/common" +import "github.com/shirou/gopsutil/v3/internal/common" func perCPUTimes() ([]TimesStat, error) { return []TimesStat{}, common.ErrNotImplementedError diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_dragonfly.go similarity index 89% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_dragonfly.go index 45094df1d..fef53e5dc 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_dragonfly.go @@ -10,19 +10,21 @@ import ( "strings" "unsafe" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "github.com/tklauser/go-sysconf" "golang.org/x/sys/unix" ) -var ClocksPerSec = float64(128) -var cpuMatch = regexp.MustCompile(`^CPU:`) -var originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) -var featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) -var featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) -var cpuEnd = regexp.MustCompile(`^Trying to mount root`) -var cpuTimesSize int -var emptyTimes cpuTimes +var ( + ClocksPerSec = float64(128) + cpuMatch = regexp.MustCompile(`^CPU:`) + originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) + featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) + featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) + cpuEnd = regexp.MustCompile(`^Trying to mount root`) + cpuTimesSize int + emptyTimes cpuTimes +) func init() { clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly_amd64.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_dragonfly_amd64.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_dragonfly_amd64.go diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_fallback.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_fallback.go similarity index 78% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_fallback.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_fallback.go index 5551c49d1..6d7007ff9 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_fallback.go @@ -1,4 +1,5 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!dragonfly +//go:build !darwin && !linux && !freebsd && !openbsd && !solaris && !windows && !dragonfly && !plan9 && !aix +// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!dragonfly,!plan9,!aix package cpu @@ -6,7 +7,7 @@ import ( "context" "runtime" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func Times(percpu bool) ([]TimesStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd.go similarity index 88% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd.go index 24527af20..d3f47353c 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd.go @@ -10,20 +10,22 @@ import ( "strings" "unsafe" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "github.com/tklauser/go-sysconf" "golang.org/x/sys/unix" ) -var ClocksPerSec = float64(128) -var cpuMatch = regexp.MustCompile(`^CPU:`) -var originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Family\s*=\s*(.+)\s+Model\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) -var featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) -var featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) -var cpuEnd = regexp.MustCompile(`^Trying to mount root`) -var cpuCores = regexp.MustCompile(`FreeBSD/SMP: (\d*) package\(s\) x (\d*) core\(s\)`) -var cpuTimesSize int -var emptyTimes cpuTimes +var ( + ClocksPerSec = float64(128) + cpuMatch = regexp.MustCompile(`^CPU:`) + originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Family\s*=\s*(.+)\s+Model\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) + featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) + featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) + cpuEnd = regexp.MustCompile(`^Trying to mount root`) + cpuCores = regexp.MustCompile(`FreeBSD/SMP: (\d*) package\(s\) x (\d*) core\(s\)`) + cpuTimesSize int + emptyTimes cpuTimes +) func init() { clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_386.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_386.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_386.go diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_amd64.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_amd64.go diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_arm.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_arm.go diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_arm64.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_freebsd_arm64.go diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_linux.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_linux.go similarity index 75% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_linux.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_linux.go index 21006bc33..b5a20e366 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package cpu @@ -10,12 +11,78 @@ import ( "strconv" "strings" - "github.com/shirou/gopsutil/internal/common" "github.com/tklauser/go-sysconf" + + "github.com/shirou/gopsutil/v3/internal/common" ) var ClocksPerSec = float64(100) +var armModelToModelName = map[uint64]string{ + 0x810: "ARM810", + 0x920: "ARM920", + 0x922: "ARM922", + 0x926: "ARM926", + 0x940: "ARM940", + 0x946: "ARM946", + 0x966: "ARM966", + 0xa20: "ARM1020", + 0xa22: "ARM1022", + 0xa26: "ARM1026", + 0xb02: "ARM11 MPCore", + 0xb36: "ARM1136", + 0xb56: "ARM1156", + 0xb76: "ARM1176", + 0xc05: "Cortex-A5", + 0xc07: "Cortex-A7", + 0xc08: "Cortex-A8", + 0xc09: "Cortex-A9", + 0xc0d: "Cortex-A17", + 0xc0f: "Cortex-A15", + 0xc0e: "Cortex-A17", + 0xc14: "Cortex-R4", + 0xc15: "Cortex-R5", + 0xc17: "Cortex-R7", + 0xc18: "Cortex-R8", + 0xc20: "Cortex-M0", + 0xc21: "Cortex-M1", + 0xc23: "Cortex-M3", + 0xc24: "Cortex-M4", + 0xc27: "Cortex-M7", + 0xc60: "Cortex-M0+", + 0xd01: "Cortex-A32", + 0xd02: "Cortex-A34", + 0xd03: "Cortex-A53", + 0xd04: "Cortex-A35", + 0xd05: "Cortex-A55", + 0xd06: "Cortex-A65", + 0xd07: "Cortex-A57", + 0xd08: "Cortex-A72", + 0xd09: "Cortex-A73", + 0xd0a: "Cortex-A75", + 0xd0b: "Cortex-A76", + 0xd0c: "Neoverse-N1", + 0xd0d: "Cortex-A77", + 0xd0e: "Cortex-A76AE", + 0xd13: "Cortex-R52", + 0xd20: "Cortex-M23", + 0xd21: "Cortex-M33", + 0xd40: "Neoverse-V1", + 0xd41: "Cortex-A78", + 0xd42: "Cortex-A78AE", + 0xd43: "Cortex-A65AE", + 0xd44: "Cortex-X1", + 0xd46: "Cortex-A510", + 0xd47: "Cortex-A710", + 0xd48: "Cortex-X2", + 0xd49: "Neoverse-N2", + 0xd4a: "Neoverse-E1", + 0xd4b: "Cortex-A78C", + 0xd4c: "Cortex-X1C", + 0xd4d: "Cortex-A715", + 0xd4e: "Cortex-X3", +} + func init() { clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) // ignore errors @@ -29,8 +96,8 @@ func Times(percpu bool) ([]TimesStat, error) { } func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - filename := common.HostProc("stat") - var lines = []string{} + filename := common.HostProcWithContext(ctx, "stat") + lines := []string{} if percpu { statlines, err := common.ReadLines(filename) if err != nil || len(statlines) < 2 { @@ -59,17 +126,17 @@ func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { return ret, nil } -func sysCPUPath(cpu int32, relPath string) string { - return common.HostSys(fmt.Sprintf("devices/system/cpu/cpu%d", cpu), relPath) +func sysCPUPath(ctx context.Context, cpu int32, relPath string) string { + return common.HostSysWithContext(ctx, fmt.Sprintf("devices/system/cpu/cpu%d", cpu), relPath) } -func finishCPUInfo(c *InfoStat) error { +func finishCPUInfo(ctx context.Context, c *InfoStat) { var lines []string var err error var value float64 if len(c.CoreID) == 0 { - lines, err = common.ReadLines(sysCPUPath(c.CPU, "topology/core_id")) + lines, err = common.ReadLines(sysCPUPath(ctx, c.CPU, "topology/core_id")) if err == nil { c.CoreID = lines[0] } @@ -78,21 +145,20 @@ func finishCPUInfo(c *InfoStat) error { // override the value of c.Mhz with cpufreq/cpuinfo_max_freq regardless // of the value from /proc/cpuinfo because we want to report the maximum // clock-speed of the CPU for c.Mhz, matching the behaviour of Windows - lines, err = common.ReadLines(sysCPUPath(c.CPU, "cpufreq/cpuinfo_max_freq")) + lines, err = common.ReadLines(sysCPUPath(ctx, c.CPU, "cpufreq/cpuinfo_max_freq")) // if we encounter errors below such as there are no cpuinfo_max_freq file, // we just ignore. so let Mhz is 0. if err != nil || len(lines) == 0 { - return nil + return } value, err = strconv.ParseFloat(lines[0], 64) if err != nil { - return nil + return } c.Mhz = value / 1000.0 // value is in kHz if c.Mhz > 9999 { c.Mhz = c.Mhz / 1000.0 // value in Hz } - return nil } // CPUInfo on linux will return 1 item per physical thread. @@ -107,7 +173,7 @@ func Info() ([]InfoStat, error) { } func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - filename := common.HostProc("cpuinfo") + filename := common.HostProcWithContext(ctx, "cpuinfo") lines, _ := common.ReadLines(filename) var ret []InfoStat @@ -125,12 +191,9 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { switch key { case "Processor": processorName = value - case "processor": + case "processor", "cpu number": if c.CPU >= 0 { - err := finishCPUInfo(&c) - if err != nil { - return ret, err - } + finishCPUInfo(ctx, &c) ret = append(ret, c) } c = InfoStat{Cores: 1, ModelName: processorName} @@ -141,6 +204,9 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { c.CPU = int32(t) case "vendorId", "vendor_id": c.VendorID = value + if strings.Contains(value, "S390") { + processorName = "S390" + } case "CPU implementer": if v, err := strconv.ParseUint(value, 0, 8); err == nil { switch v { @@ -180,10 +246,20 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { c.Family = value case "model", "CPU part": c.Model = value - case "model name", "cpu": + // if CPU is arm based, model name is found via model number. refer to: arch/arm64/kernel/cpuinfo.c + if c.VendorID == "ARM" { + if v, err := strconv.ParseUint(c.Model, 0, 16); err == nil { + modelName, exist := armModelToModelName[v] + if exist { + c.ModelName = modelName + } else { + c.ModelName = "Undefined" + } + } + } + case "Model Name", "model name", "cpu": c.ModelName = value - if strings.Contains(value, "POWER8") || - strings.Contains(value, "POWER7") { + if strings.Contains(value, "POWER") { c.Model = strings.Split(value, " ")[0] c.Family = "POWER" c.VendorID = "IBM" @@ -200,7 +276,7 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { return ret, err } c.Stepping = int32(t) - case "cpu MHz", "clock": + case "cpu MHz", "clock", "cpu MHz dynamic": // treat this as the fallback value, thus we ignore error if t, err := strconv.ParseFloat(strings.Replace(value, "MHz", "", 1), 64); err == nil { c.Mhz = t @@ -224,10 +300,7 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { } } if c.CPU >= 0 { - err := finishCPUInfo(&c) - if err != nil { - return ret, err - } + finishCPUInfo(ctx, &c) ret = append(ret, c) } return ret, nil @@ -240,7 +313,7 @@ func parseStatLine(line string) (*TimesStat, error) { return nil, errors.New("stat does not contain cpu info") } - if strings.HasPrefix(fields[0], "cpu") == false { + if !strings.HasPrefix(fields[0], "cpu") { return nil, errors.New("not contain cpu") } @@ -316,12 +389,12 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) { if logical { ret := 0 // https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_pslinux.py#L599 - procCpuinfo := common.HostProc("cpuinfo") + procCpuinfo := common.HostProcWithContext(ctx, "cpuinfo") lines, err := common.ReadLines(procCpuinfo) if err == nil { for _, line := range lines { line = strings.ToLower(line) - if strings.HasPrefix(line, "processor") { + if strings.HasPrefix(line, "processor") { _, err = strconv.Atoi(strings.TrimSpace(line[strings.IndexByte(line, ':')+1:])) if err == nil { ret++ @@ -330,7 +403,7 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) { } } if ret == 0 { - procStat := common.HostProc("stat") + procStat := common.HostProcWithContext(ctx, "stat") lines, err = common.ReadLines(procStat) if err != nil { return 0, err @@ -345,13 +418,13 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) { } // physical cores // https://github.com/giampaolo/psutil/blob/8415355c8badc9c94418b19bdf26e622f06f0cce/psutil/_pslinux.py#L615-L628 - var threadSiblingsLists = make(map[string]bool) + threadSiblingsLists := make(map[string]bool) // These 2 files are the same but */core_cpus_list is newer while */thread_siblings_list is deprecated and may disappear in the future. // https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst // https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964 // https://lkml.org/lkml/2019/2/26/41 for _, glob := range []string{"devices/system/cpu/cpu[0-9]*/topology/core_cpus_list", "devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"} { - if files, err := filepath.Glob(common.HostSys(glob)); err == nil { + if files, err := filepath.Glob(common.HostSysWithContext(ctx, glob)); err == nil { for _, file := range files { lines, err := common.ReadLines(file) if err != nil || len(lines) != 1 { @@ -366,7 +439,7 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) { } } // https://github.com/giampaolo/psutil/blob/122174a10b75c9beebe15f6c07dcf3afbe3b120d/psutil/_pslinux.py#L631-L652 - filename := common.HostProc("cpuinfo") + filename := common.HostProcWithContext(ctx, "cpuinfo") lines, err := common.ReadLines(filename) if err != nil { return 0, err diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd.go new file mode 100644 index 000000000..fe3329030 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd.go @@ -0,0 +1,137 @@ +//go:build openbsd +// +build openbsd + +package cpu + +import ( + "context" + "fmt" + "runtime" + "unsafe" + + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/tklauser/go-sysconf" + "golang.org/x/sys/unix" +) + +const ( + // sys/sched.h + cpuOnline = 0x0001 // CPUSTATS_ONLINE + + // sys/sysctl.h + ctlKern = 1 // "high kernel": proc, limits + ctlHw = 6 // CTL_HW + smt = 24 // HW_SMT + kernCpTime = 40 // KERN_CPTIME + kernCPUStats = 85 // KERN_CPUSTATS +) + +var ClocksPerSec = float64(128) + +type cpuStats struct { + // cs_time[CPUSTATES] + User uint64 + Nice uint64 + Sys uint64 + Spin uint64 + Intr uint64 + Idle uint64 + + // cs_flags + Flags uint64 +} + +func init() { + clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) + // ignore errors + if err == nil { + ClocksPerSec = float64(clkTck) + } +} + +func Times(percpu bool) ([]TimesStat, error) { + return TimesWithContext(context.Background(), percpu) +} + +func TimesWithContext(ctx context.Context, percpu bool) (ret []TimesStat, err error) { + if !percpu { + mib := []int32{ctlKern, kernCpTime} + buf, _, err := common.CallSyscall(mib) + if err != nil { + return ret, err + } + times := (*cpuTimes)(unsafe.Pointer(&buf[0])) + stat := TimesStat{ + CPU: "cpu-total", + User: float64(times.User) / ClocksPerSec, + Nice: float64(times.Nice) / ClocksPerSec, + System: float64(times.Sys) / ClocksPerSec, + Idle: float64(times.Idle) / ClocksPerSec, + Irq: float64(times.Intr) / ClocksPerSec, + } + return []TimesStat{stat}, nil + } + + ncpu, err := unix.SysctlUint32("hw.ncpu") + if err != nil { + return + } + + var i uint32 + for i = 0; i < ncpu; i++ { + mib := []int32{ctlKern, kernCPUStats, int32(i)} + buf, _, err := common.CallSyscall(mib) + if err != nil { + return ret, err + } + + stats := (*cpuStats)(unsafe.Pointer(&buf[0])) + if (stats.Flags & cpuOnline) == 0 { + continue + } + ret = append(ret, TimesStat{ + CPU: fmt.Sprintf("cpu%d", i), + User: float64(stats.User) / ClocksPerSec, + Nice: float64(stats.Nice) / ClocksPerSec, + System: float64(stats.Sys) / ClocksPerSec, + Idle: float64(stats.Idle) / ClocksPerSec, + Irq: float64(stats.Intr) / ClocksPerSec, + }) + } + + return ret, nil +} + +// Returns only one (minimal) CPUInfoStat on OpenBSD +func Info() ([]InfoStat, error) { + return InfoWithContext(context.Background()) +} + +func InfoWithContext(ctx context.Context) ([]InfoStat, error) { + var ret []InfoStat + var err error + + c := InfoStat{} + + mhz, err := unix.SysctlUint32("hw.cpuspeed") + if err != nil { + return nil, err + } + c.Mhz = float64(mhz) + + ncpu, err := unix.SysctlUint32("hw.ncpuonline") + if err != nil { + return nil, err + } + c.Cores = int32(ncpu) + + if c.ModelName, err = unix.Sysctl("hw.model"); err != nil { + return nil, err + } + + return append(ret, c), nil +} + +func CountsWithContext(ctx context.Context, logical bool) (int, error) { + return runtime.NumCPU(), nil +} diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_386.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_386.go new file mode 100644 index 000000000..5e878399a --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_386.go @@ -0,0 +1,10 @@ +package cpu + +type cpuTimes struct { + User uint32 + Nice uint32 + Sys uint32 + Spin uint32 + Intr uint32 + Idle uint32 +} diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_amd64.go new file mode 100644 index 000000000..d659058cd --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_amd64.go @@ -0,0 +1,10 @@ +package cpu + +type cpuTimes struct { + User uint64 + Nice uint64 + Sys uint64 + Spin uint64 + Intr uint64 + Idle uint64 +} diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_arm.go new file mode 100644 index 000000000..5e878399a --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_arm.go @@ -0,0 +1,10 @@ +package cpu + +type cpuTimes struct { + User uint32 + Nice uint32 + Sys uint32 + Spin uint32 + Intr uint32 + Idle uint32 +} diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_arm64.go new file mode 100644 index 000000000..d659058cd --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd_arm64.go @@ -0,0 +1,10 @@ +package cpu + +type cpuTimes struct { + User uint64 + Nice uint64 + Sys uint64 + Spin uint64 + Intr uint64 + Idle uint64 +} diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_plan9.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_plan9.go new file mode 100644 index 000000000..a2e99d8c0 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_plan9.go @@ -0,0 +1,50 @@ +//go:build plan9 +// +build plan9 + +package cpu + +import ( + "context" + "os" + "runtime" + + stats "github.com/lufia/plan9stats" + "github.com/shirou/gopsutil/v3/internal/common" +) + +func Times(percpu bool) ([]TimesStat, error) { + return TimesWithContext(context.Background(), percpu) +} + +func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { + // BUG: percpu flag is not supported yet. + root := os.Getenv("HOST_ROOT") + c, err := stats.ReadCPUType(ctx, stats.WithRootDir(root)) + if err != nil { + return nil, err + } + s, err := stats.ReadCPUStats(ctx, stats.WithRootDir(root)) + if err != nil { + return nil, err + } + return []TimesStat{ + { + CPU: c.Name, + User: s.User.Seconds(), + System: s.Sys.Seconds(), + Idle: s.Idle.Seconds(), + }, + }, nil +} + +func Info() ([]InfoStat, error) { + return InfoWithContext(context.Background()) +} + +func InfoWithContext(ctx context.Context) ([]InfoStat, error) { + return []InfoStat{}, common.ErrNotImplementedError +} + +func CountsWithContext(ctx context.Context, logical bool) (int, error) { + return runtime.NumCPU(), nil +} diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_solaris.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_solaris.go similarity index 91% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_solaris.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_solaris.go index 4e3dea02a..f828c843e 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_solaris.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_solaris.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "os/exec" "regexp" "runtime" "sort" @@ -24,7 +23,7 @@ func init() { } } -//sum all values in a float64 map with float64 keys +// sum all values in a float64 map with float64 keys func msum(x map[float64]float64) float64 { total := 0.0 for _, y := range x { @@ -38,20 +37,16 @@ func Times(percpu bool) ([]TimesStat, error) { } func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - kstatSys, err := exec.LookPath("kstat") + kstatSysOut, err := invoke.CommandWithContext(ctx, "kstat", "-p", "cpu_stat:*:*:/^idle$|^user$|^kernel$|^iowait$|^swap$/") if err != nil { - return nil, fmt.Errorf("cannot find kstat: %s", err) + return nil, fmt.Errorf("cannot execute kstat: %s", err) } cpu := make(map[float64]float64) idle := make(map[float64]float64) user := make(map[float64]float64) kern := make(map[float64]float64) iowt := make(map[float64]float64) - //swap := make(map[float64]float64) - kstatSysOut, err := invoke.CommandWithContext(ctx, kstatSys, "-p", "cpu_stat:*:*:/^idle$|^user$|^kernel$|^iowait$|^swap$/") - if err != nil { - return nil, fmt.Errorf("cannot execute kstat: %s", err) - } + // swap := make(map[float64]float64) re := regexp.MustCompile(`[:\s]+`) for _, line := range strings.Split(string(kstatSysOut), "\n") { fields := re.Split(line, -1) @@ -122,27 +117,19 @@ func Info() ([]InfoStat, error) { } func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - psrInfo, err := exec.LookPath("psrinfo") - if err != nil { - return nil, fmt.Errorf("cannot find psrinfo: %s", err) - } - psrInfoOut, err := invoke.CommandWithContext(ctx, psrInfo, "-p", "-v") + psrInfoOut, err := invoke.CommandWithContext(ctx, "psrinfo", "-p", "-v") if err != nil { return nil, fmt.Errorf("cannot execute psrinfo: %s", err) } - isaInfo, err := exec.LookPath("isainfo") - if err != nil { - return nil, fmt.Errorf("cannot find isainfo: %s", err) - } - isaInfoOut, err := invoke.CommandWithContext(ctx, isaInfo, "-b", "-v") + procs, err := parseProcessorInfo(string(psrInfoOut)) if err != nil { - return nil, fmt.Errorf("cannot execute isainfo: %s", err) + return nil, fmt.Errorf("error parsing psrinfo output: %s", err) } - procs, err := parseProcessorInfo(string(psrInfoOut)) + isaInfoOut, err := invoke.CommandWithContext(ctx, "isainfo", "-b", "-v") if err != nil { - return nil, fmt.Errorf("error parsing psrinfo output: %s", err) + return nil, fmt.Errorf("cannot execute isainfo: %s", err) } flags, err := parseISAInfo(string(isaInfoOut)) diff --git a/vendor/github.com/shirou/gopsutil/cpu/cpu_windows.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_windows.go similarity index 78% rename from vendor/github.com/shirou/gopsutil/cpu/cpu_windows.go rename to vendor/github.com/shirou/gopsutil/v3/cpu/cpu_windows.go index 0176c4775..e10612fd1 100644 --- a/vendor/github.com/shirou/gopsutil/cpu/cpu_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package cpu @@ -5,28 +6,18 @@ package cpu import ( "context" "fmt" - "strings" "unsafe" + "github.com/shirou/gopsutil/v3/internal/common" "github.com/yusufpapurcu/wmi" - "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/windows" ) var ( - procGetActiveProcessorCount = common.Modkernel32.NewProc("GetActiveProcessorCount") - procGetNativeSystemInfo = common.Modkernel32.NewProc("GetNativeSystemInfo") + procGetNativeSystemInfo = common.Modkernel32.NewProc("GetNativeSystemInfo") ) -type Win32_Processor struct { - Win32_ProcessorWithoutLoadPct - LoadPercentage *uint16 -} - -// LoadPercentage takes a linearly more time as the number of sockets increases. -// For vSphere by default corespersocket = 1, meaning for a 40 vCPU VM Get Processor Info -// could take more than half a minute. -type Win32_ProcessorWithoutLoadPct struct { +type win32_Processor struct { Family uint16 Manufacturer string Name string @@ -51,12 +42,6 @@ type win32_SystemProcessorPerformanceInformation struct { InterruptCount uint32 } -// Win32_PerfFormattedData_PerfOS_System struct to have count of processes and processor queue length -type Win32_PerfFormattedData_PerfOS_System struct { - Processes uint32 - ProcessorQueueLength uint32 -} - const ( ClocksPerSec = 10000000.0 @@ -112,9 +97,8 @@ func Info() ([]InfoStat, error) { func InfoWithContext(ctx context.Context) ([]InfoStat, error) { var ret []InfoStat - var dst []Win32_ProcessorWithoutLoadPct + var dst []win32_Processor q := wmi.CreateQuery(&dst, "") - q = strings.ReplaceAll(q, "Win32_ProcessorWithoutLoadPct", "Win32_Processor") if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil { return ret, err } @@ -142,22 +126,6 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) { return ret, nil } -// ProcInfo returns processes count and processor queue length in the system. -// There is a single queue for processor even on multiprocessors systems. -func ProcInfo() ([]Win32_PerfFormattedData_PerfOS_System, error) { - return ProcInfoWithContext(context.Background()) -} - -func ProcInfoWithContext(ctx context.Context) ([]Win32_PerfFormattedData_PerfOS_System, error) { - var ret []Win32_PerfFormattedData_PerfOS_System - q := wmi.CreateQuery(&ret, "") - err := common.WMIQueryWithContext(ctx, q, &ret) - if err != nil { - return []Win32_PerfFormattedData_PerfOS_System{}, err - } - return ret, err -} - // perCPUTimes returns times stat per cpu, per core and overall for all CPUs func perCPUTimes() ([]TimesStat, error) { var ret []TimesStat @@ -235,15 +203,12 @@ type systemInfo struct { func CountsWithContext(ctx context.Context, logical bool) (int, error) { if logical { // https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_psutil_windows.c#L97 - err := procGetActiveProcessorCount.Find() - if err == nil { // Win7+ - ret, _, _ := procGetActiveProcessorCount.Call(uintptr(0xffff)) // ALL_PROCESSOR_GROUPS is 0xffff according to Rust's winapi lib https://docs.rs/winapi/*/x86_64-pc-windows-msvc/src/winapi/shared/ntdef.rs.html#120 - if ret != 0 { - return int(ret), nil - } + ret := windows.GetActiveProcessorCount(windows.ALL_PROCESSOR_GROUPS) + if ret != 0 { + return int(ret), nil } var systemInfo systemInfo - _, _, err = procGetNativeSystemInfo.Call(uintptr(unsafe.Pointer(&systemInfo))) + _, _, err := procGetNativeSystemInfo.Call(uintptr(unsafe.Pointer(&systemInfo))) if systemInfo.dwNumberOfProcessors == 0 { return 0, err } @@ -251,9 +216,8 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) { } // physical cores https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_psutil_windows.c#L499 // for the time being, try with unreliable and slow WMI call… - var dst []Win32_ProcessorWithoutLoadPct + var dst []win32_Processor q := wmi.CreateQuery(&dst, "") - q = strings.ReplaceAll(q, "Win32_ProcessorWithoutLoadPct", "Win32_Processor") if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil { return 0, err } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk.go similarity index 74% rename from vendor/github.com/shirou/gopsutil/disk/disk.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk.go index fb2eaf18b..0d4b25345 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk.go @@ -4,11 +4,13 @@ import ( "context" "encoding/json" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) var invoke common.Invoker = common.Invoke{} +type Warnings = common.Warnings + type UsageStat struct { Path string `json:"path"` Fstype string `json:"fstype"` @@ -23,10 +25,10 @@ type UsageStat struct { } type PartitionStat struct { - Device string `json:"device"` - Mountpoint string `json:"mountpoint"` - Fstype string `json:"fstype"` - Opts string `json:"opts"` + Device string `json:"device"` + Mountpoint string `json:"mountpoint"` + Fstype string `json:"fstype"` + Opts []string `json:"opts"` } type IOCountersStat struct { @@ -80,3 +82,17 @@ func Partitions(all bool) ([]PartitionStat, error) { func IOCounters(names ...string) (map[string]IOCountersStat, error) { return IOCountersWithContext(context.Background(), names...) } + +// SerialNumber returns Serial Number of given device or empty string +// on error. Name of device is expected, eg. /dev/sda +func SerialNumber(name string) (string, error) { + return SerialNumberWithContext(context.Background(), name) +} + +// Label returns label of given device or empty string on error. +// Name of device is expected, eg. /dev/sda +// Supports label based on devicemapper name +// See https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-block-dm +func Label(name string) (string, error) { + return LabelWithContext(context.Background(), name) +} diff --git a/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix.go new file mode 100644 index 000000000..bc71712ea --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix.go @@ -0,0 +1,22 @@ +//go:build aix +// +build aix + +package disk + +import ( + "context" + + "github.com/shirou/gopsutil/v3/internal/common" +) + +func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { + return nil, common.ErrNotImplementedError +} + +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} + +func LabelWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix_cgo.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix_cgo.go new file mode 100644 index 000000000..aa534df30 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix_cgo.go @@ -0,0 +1,76 @@ +//go:build aix && cgo +// +build aix,cgo + +package disk + +import ( + "context" + "fmt" + + "github.com/power-devops/perfstat" +) + +var FSType map[int]string + +func init() { + FSType = map[int]string{ + 0: "jfs2", 1: "namefs", 2: "nfs", 3: "jfs", 5: "cdrom", 6: "proc", + 16: "special-fs", 17: "cache-fs", 18: "nfs3", 19: "automount-fs", 20: "pool-fs", 32: "vxfs", + 33: "veritas-fs", 34: "udfs", 35: "nfs4", 36: "nfs4-pseudo", 37: "smbfs", 38: "mcr-pseudofs", + 39: "ahafs", 40: "sterm-nfs", 41: "asmfs", + } +} + +func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { + f, err := perfstat.FileSystemStat() + if err != nil { + return nil, err + } + ret := make([]PartitionStat, len(f)) + + for _, fs := range f { + fstyp, exists := FSType[fs.FSType] + if !exists { + fstyp = "unknown" + } + info := PartitionStat{ + Device: fs.Device, + Mountpoint: fs.MountPoint, + Fstype: fstyp, + } + ret = append(ret, info) + } + + return ret, err +} + +func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { + f, err := perfstat.FileSystemStat() + if err != nil { + return nil, err + } + + blocksize := uint64(512) + for _, fs := range f { + if path == fs.MountPoint { + fstyp, exists := FSType[fs.FSType] + if !exists { + fstyp = "unknown" + } + info := UsageStat{ + Path: path, + Fstype: fstyp, + Total: uint64(fs.TotalBlocks) * blocksize, + Free: uint64(fs.FreeBlocks) * blocksize, + Used: uint64(fs.TotalBlocks-fs.FreeBlocks) * blocksize, + InodesTotal: uint64(fs.TotalInodes), + InodesFree: uint64(fs.FreeInodes), + InodesUsed: uint64(fs.TotalInodes - fs.FreeInodes), + } + info.UsedPercent = (float64(info.Used) / float64(info.Total)) * 100.0 + info.InodesUsedPercent = (float64(info.InodesUsed) / float64(info.InodesTotal)) * 100.0 + return &info, nil + } + } + return nil, fmt.Errorf("mountpoint %s not found", path) +} diff --git a/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix_nocgo.go new file mode 100644 index 000000000..4f93c7522 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_aix_nocgo.go @@ -0,0 +1,82 @@ +//go:build aix && !cgo +// +build aix,!cgo + +package disk + +import ( + "context" + "regexp" + "strings" + + "github.com/shirou/gopsutil/v3/internal/common" + "golang.org/x/sys/unix" +) + +var whiteSpaces = regexp.MustCompile(`\s+`) +var startBlank = regexp.MustCompile(`^\s+`) + +var ignoreFSType = map[string]bool{"procfs": true} +var FSType = map[int]string{ + 0: "jfs2", 1: "namefs", 2: "nfs", 3: "jfs", 5: "cdrom", 6: "proc", + 16: "special-fs", 17: "cache-fs", 18: "nfs3", 19: "automount-fs", 20: "pool-fs", 32: "vxfs", + 33: "veritas-fs", 34: "udfs", 35: "nfs4", 36: "nfs4-pseudo", 37: "smbfs", 38: "mcr-pseudofs", + 39: "ahafs", 40: "sterm-nfs", 41: "asmfs", +} + +func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { + var ret []PartitionStat + + out, err := invoke.CommandWithContext(ctx, "mount") + if err != nil { + return nil, err + } + + // parse head lines for column names + colidx := make(map[string]int) + lines := strings.Split(string(out), "\n") + if len(lines) < 3 { + return nil, common.ErrNotImplementedError + } + + idx := 0 + start := 0 + finished := false + for pos, ch := range lines[1] { + if ch == ' ' && !finished { + name := strings.TrimSpace(lines[0][start:pos]) + colidx[name] = idx + finished = true + } else if ch == '-' && finished { + idx++ + start = pos + finished = false + } + } + name := strings.TrimSpace(lines[0][start:len(lines[1])]) + colidx[name] = idx + + for idx := 2; idx < len(lines); idx++ { + line := lines[idx] + if startBlank.MatchString(line) { + line = "localhost" + line + } + p := whiteSpaces.Split(lines[idx], 6) + if len(p) < 5 || ignoreFSType[p[colidx["vfs"]]] { + continue + } + d := PartitionStat{ + Device: p[colidx["mounted"]], + Mountpoint: p[colidx["mounted over"]], + Fstype: p[colidx["vfs"]], + Opts: strings.Split(p[colidx["options"]], ","), + } + + ret = append(ret, d) + } + + return ret, nil +} + +func getFsType(stat unix.Statfs_t) string { + return FSType[int(stat.Vfstype)] +} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_darwin.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin.go similarity index 56% rename from vendor/github.com/shirou/gopsutil/disk/disk_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin.go index b23e7d043..9362d9e5d 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package disk @@ -5,8 +6,9 @@ package disk import ( "context" - "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" ) // PartitionsWithContext returns disk partition. @@ -19,46 +21,52 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro return ret, err } fs := make([]unix.Statfs_t, count) - if _, err = unix.Getfsstat(fs, unix.MNT_WAIT); err != nil { + count, err = unix.Getfsstat(fs, unix.MNT_WAIT) + if err != nil { return ret, err } + // On 10.14, and possibly other OS versions, the actual count may + // be less than from the first call. Truncate to the returned count + // to prevent accessing uninitialized entries. + // https://github.com/shirou/gopsutil/issues/1390 + fs = fs[:count] for _, stat := range fs { - opts := "rw" + opts := []string{"rw"} if stat.Flags&unix.MNT_RDONLY != 0 { - opts = "ro" + opts = []string{"ro"} } if stat.Flags&unix.MNT_SYNCHRONOUS != 0 { - opts += ",sync" + opts = append(opts, "sync") } if stat.Flags&unix.MNT_NOEXEC != 0 { - opts += ",noexec" + opts = append(opts, "noexec") } if stat.Flags&unix.MNT_NOSUID != 0 { - opts += ",nosuid" + opts = append(opts, "nosuid") } if stat.Flags&unix.MNT_UNION != 0 { - opts += ",union" + opts = append(opts, "union") } if stat.Flags&unix.MNT_ASYNC != 0 { - opts += ",async" + opts = append(opts, "async") } if stat.Flags&unix.MNT_DONTBROWSE != 0 { - opts += ",nobrowse" + opts = append(opts, "nobrowse") } if stat.Flags&unix.MNT_AUTOMOUNTED != 0 { - opts += ",automounted" + opts = append(opts, "automounted") } if stat.Flags&unix.MNT_JOURNALED != 0 { - opts += ",journaled" + opts = append(opts, "journaled") } if stat.Flags&unix.MNT_MULTILABEL != 0 { - opts += ",multilabel" + opts = append(opts, "multilabel") } if stat.Flags&unix.MNT_NOATIME != 0 { - opts += ",noatime" + opts = append(opts, "noatime") } if stat.Flags&unix.MNT_NODEV != 0 { - opts += ",nodev" + opts = append(opts, "nodev") } d := PartitionStat{ Device: common.ByteToString(stat.Mntfromname[:]), @@ -76,3 +84,11 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro func getFsType(stat unix.Statfs_t) string { return common.ByteToString(stat.Fstypename[:]) } + +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} + +func LabelWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin_cgo.go similarity index 85% rename from vendor/github.com/shirou/gopsutil/disk/disk_darwin_cgo.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin_cgo.go index d3db753be..27c24c922 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_darwin_cgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin_cgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build cgo +//go:build darwin && cgo && !ios +// +build darwin,cgo,!ios package disk @@ -14,12 +14,12 @@ import "C" import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { var buf [C.NDRIVE]C.DriveStats - n, err := C.readdrivestat(&buf[0], C.int(len(buf))) + n, err := C.gopsutil_v3_readdrivestat(&buf[0], C.int(len(buf))) if err != nil { return nil, err } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin_nocgo.go similarity index 62% rename from vendor/github.com/shirou/gopsutil/disk/disk_darwin_nocgo.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin_nocgo.go index 4fb8aca4b..1f099b7ca 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_darwin_nocgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_darwin_nocgo.go @@ -1,12 +1,12 @@ -// +build darwin -// +build !cgo +//go:build (darwin && !cgo) || ios +// +build darwin,!cgo ios package disk import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_fallback.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_fallback.go similarity index 50% rename from vendor/github.com/shirou/gopsutil/disk/disk_fallback.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_fallback.go index dd446ff8d..476873340 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_fallback.go @@ -1,11 +1,12 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris +//go:build !darwin && !linux && !freebsd && !openbsd && !windows && !solaris && !aix +// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris,!aix package disk import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { @@ -19,3 +20,11 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { return nil, common.ErrNotImplementedError } + +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} + +func LabelWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd.go similarity index 59% rename from vendor/github.com/shirou/gopsutil/disk/disk_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd.go index 812450025..9b53106c2 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd.go @@ -1,16 +1,19 @@ +//go:build freebsd // +build freebsd package disk import ( + "bufio" "bytes" "context" "encoding/binary" + "fmt" "strconv" + "strings" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/unix" - - "github.com/shirou/gopsutil/internal/common" ) // PartitionsWithContext returns disk partition. @@ -30,54 +33,54 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro } for _, stat := range fs { - opts := "rw" + opts := []string{"rw"} if stat.Flags&unix.MNT_RDONLY != 0 { - opts = "ro" + opts = []string{"ro"} } if stat.Flags&unix.MNT_SYNCHRONOUS != 0 { - opts += ",sync" + opts = append(opts, "sync") } if stat.Flags&unix.MNT_NOEXEC != 0 { - opts += ",noexec" + opts = append(opts, "noexec") } if stat.Flags&unix.MNT_NOSUID != 0 { - opts += ",nosuid" + opts = append(opts, "nosuid") } if stat.Flags&unix.MNT_UNION != 0 { - opts += ",union" + opts = append(opts, "union") } if stat.Flags&unix.MNT_ASYNC != 0 { - opts += ",async" + opts = append(opts, "async") } if stat.Flags&unix.MNT_SUIDDIR != 0 { - opts += ",suiddir" + opts = append(opts, "suiddir") } if stat.Flags&unix.MNT_SOFTDEP != 0 { - opts += ",softdep" + opts = append(opts, "softdep") } if stat.Flags&unix.MNT_NOSYMFOLLOW != 0 { - opts += ",nosymfollow" + opts = append(opts, "nosymfollow") } if stat.Flags&unix.MNT_GJOURNAL != 0 { - opts += ",gjournal" + opts = append(opts, "gjournal") } if stat.Flags&unix.MNT_MULTILABEL != 0 { - opts += ",multilabel" + opts = append(opts, "multilabel") } if stat.Flags&unix.MNT_ACLS != 0 { - opts += ",acls" + opts = append(opts, "acls") } if stat.Flags&unix.MNT_NOATIME != 0 { - opts += ",noatime" + opts = append(opts, "noatime") } if stat.Flags&unix.MNT_NOCLUSTERR != 0 { - opts += ",noclusterr" + opts = append(opts, "noclusterr") } if stat.Flags&unix.MNT_NOCLUSTERW != 0 { - opts += ",noclusterw" + opts = append(opts, "noclusterw") } if stat.Flags&unix.MNT_NFS4ACLS != 0 { - opts += ",nfsv4acls" + opts = append(opts, "nfsv4acls") } d := PartitionStat{ @@ -105,13 +108,13 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC buf := []byte(r) length := len(buf) - count := int(uint64(length) / uint64(sizeOfDevstat)) + count := int(uint64(length) / uint64(sizeOfdevstat)) buf = buf[8:] // devstat.all has version in the head. - // parse buf to Devstat + // parse buf to devstat for i := 0; i < count; i++ { - b := buf[i*sizeOfDevstat : i*sizeOfDevstat+sizeOfDevstat] - d, err := parseDevstat(b) + b := buf[i*sizeOfdevstat : i*sizeOfdevstat+sizeOfdevstat] + d, err := parsedevstat(b) if err != nil { continue } @@ -123,30 +126,31 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC } ds := IOCountersStat{ - ReadCount: d.Operations[DEVSTAT_READ], - WriteCount: d.Operations[DEVSTAT_WRITE], - ReadBytes: d.Bytes[DEVSTAT_READ], - WriteBytes: d.Bytes[DEVSTAT_WRITE], - ReadTime: uint64(d.Duration[DEVSTAT_READ].Compute() * 1000), - WriteTime: uint64(d.Duration[DEVSTAT_WRITE].Compute() * 1000), + ReadCount: d.Operations[devstat_READ], + WriteCount: d.Operations[devstat_WRITE], + ReadBytes: d.Bytes[devstat_READ], + WriteBytes: d.Bytes[devstat_WRITE], + ReadTime: uint64(d.Duration[devstat_READ].Compute() * 1000), + WriteTime: uint64(d.Duration[devstat_WRITE].Compute() * 1000), IoTime: uint64(d.Busy_time.Compute() * 1000), Name: name, } + ds.SerialNumber, _ = SerialNumberWithContext(ctx, name) ret[name] = ds } return ret, nil } -func (b Bintime) Compute() float64 { +func (b bintime) Compute() float64 { BINTIME_SCALE := 5.42101086242752217003726400434970855712890625e-20 return float64(b.Sec) + float64(b.Frac)*BINTIME_SCALE } // BT2LD(time) ((long double)(time).sec + (time).frac * BINTIME_SCALE) -func parseDevstat(buf []byte) (Devstat, error) { - var ds Devstat +func parsedevstat(buf []byte) (devstat, error) { + var ds devstat br := bytes.NewReader(buf) // err := binary.Read(br, binary.LittleEndian, &ds) err := common.Read(br, binary.LittleEndian, &ds) @@ -160,3 +164,29 @@ func parseDevstat(buf []byte) (Devstat, error) { func getFsType(stat unix.Statfs_t) string { return common.ByteToString(stat.Fstypename[:]) } + +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { + geomOut, err := invoke.CommandWithContext(ctx, "geom", "disk", "list", name) + if err != nil { + return "", fmt.Errorf("exec geom: %w", err) + } + s := bufio.NewScanner(bytes.NewReader(geomOut)) + serial := "" + for s.Scan() { + flds := strings.Fields(s.Text()) + if len(flds) == 2 && flds[0] == "ident:" { + if flds[1] != "(null)" { + serial = flds[1] + } + break + } + } + if err = s.Err(); err != nil { + return "", err + } + return serial, nil +} + +func LabelWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_386.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_386.go similarity index 76% rename from vendor/github.com/shirou/gopsutil/disk/disk_freebsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_386.go index e2793a4fe..7fa1783dc 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_386.go @@ -11,14 +11,14 @@ const ( sizeofLongLong = 0x8 sizeofLongDouble = 0x8 - DEVSTAT_NO_DATA = 0x00 - DEVSTAT_READ = 0x01 - DEVSTAT_WRITE = 0x02 - DEVSTAT_FREE = 0x03 + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 ) const ( - sizeOfDevstat = 0xf0 + sizeOfdevstat = 0xf0 ) type ( @@ -29,21 +29,21 @@ type ( _C_long_double int64 ) -type Devstat struct { +type devstat struct { Sequence0 uint32 Allocated int32 Start_count uint32 End_count uint32 - Busy_from Bintime + Busy_from bintime Dev_links _Ctype_struct___0 Device_number uint32 Device_name [16]int8 Unit_number int32 Bytes [4]uint64 Operations [4]uint64 - Duration [4]Bintime - Busy_time Bintime - Creation_time Bintime + Duration [4]bintime + Busy_time bintime + Creation_time bintime Block_size uint32 Tag_types [3]uint64 Flags uint32 @@ -52,7 +52,8 @@ type Devstat struct { Id *byte Sequence1 uint32 } -type Bintime struct { + +type bintime struct { Sec int32 Frac uint64 } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_amd64.go similarity index 77% rename from vendor/github.com/shirou/gopsutil/disk/disk_freebsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_amd64.go index e9613dc5c..d86a308be 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_amd64.go @@ -11,14 +11,14 @@ const ( sizeofLongLong = 0x8 sizeofLongDouble = 0x8 - DEVSTAT_NO_DATA = 0x00 - DEVSTAT_READ = 0x01 - DEVSTAT_WRITE = 0x02 - DEVSTAT_FREE = 0x03 + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 ) const ( - sizeOfDevstat = 0x120 + sizeOfdevstat = 0x120 ) type ( @@ -29,21 +29,21 @@ type ( _C_long_double int64 ) -type Devstat struct { +type devstat struct { Sequence0 uint32 Allocated int32 Start_count uint32 End_count uint32 - Busy_from Bintime + Busy_from bintime Dev_links _Ctype_struct___0 Device_number uint32 Device_name [16]int8 Unit_number int32 Bytes [4]uint64 Operations [4]uint64 - Duration [4]Bintime - Busy_time Bintime - Creation_time Bintime + Duration [4]bintime + Busy_time bintime + Creation_time bintime Block_size uint32 Pad_cgo_0 [4]byte Tag_types [3]uint64 @@ -55,7 +55,8 @@ type Devstat struct { Sequence1 uint32 Pad_cgo_2 [4]byte } -type Bintime struct { + +type bintime struct { Sec int64 Frac uint64 } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_arm.go similarity index 76% rename from vendor/github.com/shirou/gopsutil/disk/disk_freebsd_arm.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_arm.go index e2793a4fe..7fa1783dc 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_arm.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_arm.go @@ -11,14 +11,14 @@ const ( sizeofLongLong = 0x8 sizeofLongDouble = 0x8 - DEVSTAT_NO_DATA = 0x00 - DEVSTAT_READ = 0x01 - DEVSTAT_WRITE = 0x02 - DEVSTAT_FREE = 0x03 + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 ) const ( - sizeOfDevstat = 0xf0 + sizeOfdevstat = 0xf0 ) type ( @@ -29,21 +29,21 @@ type ( _C_long_double int64 ) -type Devstat struct { +type devstat struct { Sequence0 uint32 Allocated int32 Start_count uint32 End_count uint32 - Busy_from Bintime + Busy_from bintime Dev_links _Ctype_struct___0 Device_number uint32 Device_name [16]int8 Unit_number int32 Bytes [4]uint64 Operations [4]uint64 - Duration [4]Bintime - Busy_time Bintime - Creation_time Bintime + Duration [4]bintime + Busy_time bintime + Creation_time bintime Block_size uint32 Tag_types [3]uint64 Flags uint32 @@ -52,7 +52,8 @@ type Devstat struct { Id *byte Sequence1 uint32 } -type Bintime struct { + +type bintime struct { Sec int32 Frac uint64 } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_arm64.go similarity index 73% rename from vendor/github.com/shirou/gopsutil/disk/disk_freebsd_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_arm64.go index 1384131a8..f6b3f80df 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_freebsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_freebsd_arm64.go @@ -1,5 +1,6 @@ -// +build freebsd -// +build arm64 +//go:build freebsd && arm64 +// +build freebsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs disk/types_freebsd.go @@ -13,14 +14,14 @@ const ( sizeofLongLong = 0x8 sizeofLongDouble = 0x8 - DEVSTAT_NO_DATA = 0x00 - DEVSTAT_READ = 0x01 - DEVSTAT_WRITE = 0x02 - DEVSTAT_FREE = 0x03 + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 ) const ( - sizeOfDevstat = 0x120 + sizeOfdevstat = 0x120 ) type ( @@ -31,21 +32,21 @@ type ( _C_long_double int64 ) -type Devstat struct { +type devstat struct { Sequence0 uint32 Allocated int32 Start_count uint32 End_count uint32 - Busy_from Bintime + Busy_from bintime Dev_links _Ctype_struct___0 Device_number uint32 Device_name [16]int8 Unit_number int32 Bytes [4]uint64 Operations [4]uint64 - Duration [4]Bintime - Busy_time Bintime - Creation_time Bintime + Duration [4]bintime + Busy_time bintime + Creation_time bintime Block_size uint32 Tag_types [3]uint64 Flags uint32 @@ -55,7 +56,7 @@ type Devstat struct { Sequence1 uint32 Pad_cgo_0 [4]byte } -type Bintime struct { +type bintime struct { Sec int64 Frac uint64 } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_linux.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_linux.go similarity index 81% rename from vendor/github.com/shirou/gopsutil/disk/disk_linux.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_linux.go index 7fc0bb408..5015c34ae 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package disk @@ -6,20 +7,24 @@ import ( "bufio" "bytes" "context" + "errors" "fmt" "io/ioutil" "os" + "path" "path/filepath" "strconv" "strings" - "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" ) const ( - SectorSize = 512 + sectorSize = 512 ) + const ( // man statfs ADFS_SUPER_MAGIC = 0xadf5 @@ -97,8 +102,12 @@ const ( AFS_SUPER_MAGIC = 0x5346414F AUFS_SUPER_MAGIC = 0x61756673 ANON_INODE_FS_SUPER_MAGIC = 0x09041934 + BPF_FS_MAGIC = 0xCAFE4A11 CEPH_SUPER_MAGIC = 0x00C36400 + CGROUP2_SUPER_MAGIC = 0x63677270 + CONFIGFS_MAGIC = 0x62656570 ECRYPTFS_SUPER_MAGIC = 0xF15F + F2FS_SUPER_MAGIC = 0xF2F52010 FAT_SUPER_MAGIC = 0x4006 FHGFS_SUPER_MAGIC = 0x19830326 FUSEBLK_SUPER_MAGIC = 0x65735546 @@ -113,9 +122,11 @@ const ( KAFS_SUPER_MAGIC = 0x6B414653 LUSTRE_SUPER_MAGIC = 0x0BD00BD0 NFSD_SUPER_MAGIC = 0x6E667364 + NSFS_MAGIC = 0x6E736673 PANFS_SUPER_MAGIC = 0xAAD7AAEA RPC_PIPEFS_SUPER_MAGIC = 0x67596969 SECURITYFS_SUPER_MAGIC = 0x73636673 + TRACEFS_MAGIC = 0x74726163 UFS_BYTESWAPPED_SUPER_MAGIC = 0x54190100 VMHGFS_SUPER_MAGIC = 0xBACBACBC VZFS_SUPER_MAGIC = 0x565A4653 @@ -134,21 +145,26 @@ var fsTypeMap = map[int64]string{ BDEVFS_MAGIC: "bdevfs", /* 0x62646576 local */ BFS_MAGIC: "bfs", /* 0x1BADFACE local */ BINFMTFS_MAGIC: "binfmt_misc", /* 0x42494E4D local */ + BPF_FS_MAGIC: "bpf", /* 0xCAFE4A11 local */ BTRFS_SUPER_MAGIC: "btrfs", /* 0x9123683E local */ CEPH_SUPER_MAGIC: "ceph", /* 0x00C36400 remote */ CGROUP_SUPER_MAGIC: "cgroupfs", /* 0x0027E0EB local */ + CGROUP2_SUPER_MAGIC: "cgroup2fs", /* 0x63677270 local */ CIFS_MAGIC_NUMBER: "cifs", /* 0xFF534D42 remote */ CODA_SUPER_MAGIC: "coda", /* 0x73757245 remote */ COH_SUPER_MAGIC: "coh", /* 0x012FF7B7 local */ + CONFIGFS_MAGIC: "configfs", /* 0x62656570 local */ CRAMFS_MAGIC: "cramfs", /* 0x28CD3D45 local */ DEBUGFS_MAGIC: "debugfs", /* 0x64626720 local */ DEVFS_SUPER_MAGIC: "devfs", /* 0x1373 local */ DEVPTS_SUPER_MAGIC: "devpts", /* 0x1CD1 local */ ECRYPTFS_SUPER_MAGIC: "ecryptfs", /* 0xF15F local */ + EFIVARFS_MAGIC: "efivarfs", /* 0xDE5E81E4 local */ EFS_SUPER_MAGIC: "efs", /* 0x00414A53 local */ EXT_SUPER_MAGIC: "ext", /* 0x137D local */ EXT2_SUPER_MAGIC: "ext2/ext3", /* 0xEF53 local */ EXT2_OLD_SUPER_MAGIC: "ext2", /* 0xEF51 local */ + F2FS_SUPER_MAGIC: "f2fs", /* 0xF2F52010 local */ FAT_SUPER_MAGIC: "fat", /* 0x4006 local */ FHGFS_SUPER_MAGIC: "fhgfs", /* 0x19830326 remote */ FUSEBLK_SUPER_MAGIC: "fuseblk", /* 0x65735546 remote */ @@ -181,6 +197,7 @@ var fsTypeMap = map[int64]string{ NFS_SUPER_MAGIC: "nfs", /* 0x6969 remote */ NFSD_SUPER_MAGIC: "nfsd", /* 0x6E667364 remote */ NILFS_SUPER_MAGIC: "nilfs", /* 0x3434 local */ + NSFS_MAGIC: "nsfs", /* 0x6E736673 local */ NTFS_SB_MAGIC: "ntfs", /* 0x5346544E local */ OPENPROM_SUPER_MAGIC: "openprom", /* 0x9FA1 local */ OCFS2_SUPER_MAGIC: "ocfs2", /* 0x7461636f remote */ @@ -203,6 +220,7 @@ var fsTypeMap = map[int64]string{ SYSV2_SUPER_MAGIC: "sysv2", /* 0x012FF7B6 local */ SYSV4_SUPER_MAGIC: "sysv4", /* 0x012FF7B5 local */ TMPFS_MAGIC: "tmpfs", /* 0x01021994 local */ + TRACEFS_MAGIC: "tracefs", /* 0x74726163 local */ UDF_SUPER_MAGIC: "udf", /* 0x15013346 local */ UFS_MAGIC: "ufs", /* 0x00011954 local */ UFS_BYTESWAPPED_SUPER_MAGIC: "ufs", /* 0x54190100 local */ @@ -218,25 +236,51 @@ var fsTypeMap = map[int64]string{ ZFS_SUPER_MAGIC: "zfs", /* 0x2FC12FC1 local */ } -func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { - useMounts := false - - filename := common.HostProc("1/mountinfo") - lines, err := common.ReadLines(filename) +// readMountFile reads mountinfo or mounts file under the specified root path +// (eg, /proc/1, /proc/self, etc) +func readMountFile(root string) (lines []string, useMounts bool, filename string, err error) { + filename = path.Join(root, "mountinfo") + lines, err = common.ReadLines(filename) if err != nil { - if err != err.(*os.PathError) { - return nil, err + var pathErr *os.PathError + if !errors.As(err, &pathErr) { + return } // if kernel does not support 1/mountinfo, fallback to 1/mounts (<2.6.26) useMounts = true - filename = common.HostProc("1/mounts") + filename = path.Join(root, "mounts") lines, err = common.ReadLines(filename) + if err != nil { + return + } + return + } + return +} + +func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { + // by default, try "/proc/1/..." first + root := common.HostProcWithContext(ctx, path.Join("1")) + + // force preference for dirname of HOST_PROC_MOUNTINFO, if set #1271 + hpmPath := common.HostProcMountInfoWithContext(ctx) + if hpmPath != "" { + root = filepath.Dir(hpmPath) + } + + lines, useMounts, filename, err := readMountFile(root) + if err != nil { + if hpmPath != "" { // don't fallback with HOST_PROC_MOUNTINFO + return nil, err + } + // fallback to "/proc/self/..." #1159 + lines, useMounts, filename, err = readMountFile(common.HostProcWithContext(ctx, path.Join("self"))) if err != nil { return nil, err } } - fs, err := getFileSystems() + fs, err := getFileSystems(ctx) if err != nil && !all { return nil, err } @@ -252,7 +296,7 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro Device: fields[0], Mountpoint: unescapeFstab(fields[1]), Fstype: fields[2], - Opts: fields[3], + Opts: strings.Fields(fields[3]), } if !all { @@ -274,14 +318,10 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro fields := strings.Fields(parts[0]) blockDeviceID := fields[2] mountPoint := fields[4] - mountOpts := fields[5] + mountOpts := strings.Split(fields[5], ",") if rootDir := fields[3]; rootDir != "" && rootDir != "/" { - if len(mountOpts) == 0 { - mountOpts = "bind" - } else { - mountOpts = "bind," + mountOpts - } + mountOpts = append(mountOpts, "bind") } fields = strings.Fields(parts[1]) @@ -302,7 +342,7 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro } if strings.HasPrefix(d.Device, "/dev/mapper/") { - devpath, err := filepath.EvalSymlinks(common.HostDev(strings.Replace(d.Device, "/dev", "", -1))) + devpath, err := filepath.EvalSymlinks(common.HostDevWithContext(ctx, strings.Replace(d.Device, "/dev", "", 1))) if err == nil { d.Device = devpath } @@ -311,11 +351,10 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro // /dev/root is not the real device name // so we get the real device name from its major/minor number if d.Device == "/dev/root" { - devpath, err := os.Readlink(common.HostSys("/dev/block/" + blockDeviceID)) - if err != nil { - return nil, err + devpath, err := os.Readlink(common.HostSysWithContext(ctx, "/dev/block/"+blockDeviceID)) + if err == nil { + d.Device = strings.Replace(d.Device, "root", filepath.Base(devpath), 1) } - d.Device = strings.Replace(d.Device, "root", filepath.Base(devpath), 1) } } ret = append(ret, d) @@ -325,8 +364,8 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro } // getFileSystems returns supported filesystems from /proc/filesystems -func getFileSystems() ([]string, error) { - filename := common.HostProc("filesystems") +func getFileSystems(ctx context.Context) ([]string, error) { + filename := common.HostProcWithContext(ctx, "filesystems") lines, err := common.ReadLines(filename) if err != nil { return nil, err @@ -348,12 +387,12 @@ func getFileSystems() ([]string, error) { } func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { - filename := common.HostProc("diskstats") + filename := common.HostProcWithContext(ctx, "diskstats") lines, err := common.ReadLines(filename) if err != nil { return nil, err } - ret := make(map[string]IOCountersStat, 0) + ret := make(map[string]IOCountersStat) empty := IOCountersStat{} // use only basename such as "/dev/sda1" to "sda1" @@ -418,8 +457,8 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC return ret, err } d := IOCountersStat{ - ReadBytes: rbytes * SectorSize, - WriteBytes: wbytes * SectorSize, + ReadBytes: rbytes * sectorSize, + WriteBytes: wbytes * sectorSize, ReadCount: reads, WriteCount: writes, MergedReadCount: mergedReads, @@ -435,70 +474,63 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC } d.Name = name - d.SerialNumber = GetDiskSerialNumber(name) - d.Label = GetLabel(name) + // Names passed in can be full paths (/dev/sda) or just device names (sda). + // Since `name` here is already a basename, re-add the /dev path. + // This is not ideal, but we may break the API by changing how SerialNumberWithContext + // works. + d.SerialNumber, _ = SerialNumberWithContext(ctx, common.HostDevWithContext(ctx, name)) + d.Label, _ = LabelWithContext(ctx, name) ret[name] = d } return ret, nil } -// GetDiskSerialNumber returns Serial Number of given device or empty string -// on error. Name of device is expected, eg. /dev/sda -func GetDiskSerialNumber(name string) string { - return GetDiskSerialNumberWithContext(context.Background(), name) -} - -func GetDiskSerialNumberWithContext(ctx context.Context, name string) string { +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { var stat unix.Stat_t err := unix.Stat(name, &stat) if err != nil { - return "" + return "", err } major := unix.Major(uint64(stat.Rdev)) minor := unix.Minor(uint64(stat.Rdev)) // Try to get the serial from udev data - udevDataPath := common.HostRun(fmt.Sprintf("udev/data/b%d:%d", major, minor)) + udevDataPath := common.HostRunWithContext(ctx, fmt.Sprintf("udev/data/b%d:%d", major, minor)) if udevdata, err := ioutil.ReadFile(udevDataPath); err == nil { scanner := bufio.NewScanner(bytes.NewReader(udevdata)) for scanner.Scan() { values := strings.Split(scanner.Text(), "=") if len(values) == 2 && values[0] == "E:ID_SERIAL" { - return values[1] + return values[1], nil } } } // Try to get the serial from sysfs, look at the disk device (minor 0) directly // because if it is a partition it is not going to contain any device information - devicePath := common.HostSys(fmt.Sprintf("dev/block/%d:0/device", major)) + devicePath := common.HostSysWithContext(ctx, fmt.Sprintf("dev/block/%d:0/device", major)) model, _ := ioutil.ReadFile(filepath.Join(devicePath, "model")) serial, _ := ioutil.ReadFile(filepath.Join(devicePath, "serial")) if len(model) > 0 && len(serial) > 0 { - return fmt.Sprintf("%s_%s", string(model), string(serial)) + return fmt.Sprintf("%s_%s", string(model), string(serial)), nil } - return "" + return "", nil } -// GetLabel returns label of given device or empty string on error. -// Name of device is expected, eg. /dev/sda -// Supports label based on devicemapper name -// See https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-block-dm -func GetLabel(name string) string { +func LabelWithContext(ctx context.Context, name string) (string, error) { // Try label based on devicemapper name - dmname_filename := common.HostSys(fmt.Sprintf("block/%s/dm/name", name)) + dmname_filename := common.HostSysWithContext(ctx, fmt.Sprintf("block/%s/dm/name", name)) if !common.PathExists(dmname_filename) { - return "" + return "", nil } dmname, err := ioutil.ReadFile(dmname_filename) if err != nil { - return "" - } else { - return strings.TrimSpace(string(dmname)) + return "", err } + return strings.TrimSpace(string(dmname)), nil } func getFsType(stat unix.Statfs_t) string { diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd.go similarity index 77% rename from vendor/github.com/shirou/gopsutil/disk/disk_openbsd.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd.go index e6755803f..81ff23994 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package disk @@ -7,7 +8,7 @@ import ( "context" "encoding/binary" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/unix" ) @@ -26,39 +27,39 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro } for _, stat := range fs { - opts := "rw" + opts := []string{"rw"} if stat.F_flags&unix.MNT_RDONLY != 0 { - opts = "ro" + opts = []string{"rw"} } if stat.F_flags&unix.MNT_SYNCHRONOUS != 0 { - opts += ",sync" + opts = append(opts, "sync") } if stat.F_flags&unix.MNT_NOEXEC != 0 { - opts += ",noexec" + opts = append(opts, "noexec") } if stat.F_flags&unix.MNT_NOSUID != 0 { - opts += ",nosuid" + opts = append(opts, "nosuid") } if stat.F_flags&unix.MNT_NODEV != 0 { - opts += ",nodev" + opts = append(opts, "nodev") } if stat.F_flags&unix.MNT_ASYNC != 0 { - opts += ",async" + opts = append(opts, "async") } if stat.F_flags&unix.MNT_SOFTDEP != 0 { - opts += ",softdep" + opts = append(opts, "softdep") } if stat.F_flags&unix.MNT_NOATIME != 0 { - opts += ",noatime" + opts = append(opts, "noatime") } if stat.F_flags&unix.MNT_WXALLOWED != 0 { - opts += ",wxallowed" + opts = append(opts, "wxallowed") } d := PartitionStat{ - Device: common.IntToString(stat.F_mntfromname[:]), - Mountpoint: common.IntToString(stat.F_mntonname[:]), - Fstype: common.IntToString(stat.F_fstypename[:]), + Device: common.ByteToString(stat.F_mntfromname[:]), + Mountpoint: common.ByteToString(stat.F_mntonname[:]), + Fstype: common.ByteToString(stat.F_fstypename[:]), Opts: opts, } @@ -146,5 +147,13 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { } func getFsType(stat unix.Statfs_t) string { - return common.IntToString(stat.F_fstypename[:]) + return common.ByteToString(stat.F_fstypename[:]) +} + +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} + +func LabelWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd_386.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_386.go similarity index 72% rename from vendor/github.com/shirou/gopsutil/disk/disk_openbsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_386.go index 8f3f84ef6..f4c139f5e 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_386.go @@ -1,15 +1,16 @@ -// +build openbsd -// +build 386 +//go:build openbsd && 386 +// +build openbsd,386 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs disk/types_openbsd.go package disk const ( - DEVSTAT_NO_DATA = 0x00 - DEVSTAT_READ = 0x01 - DEVSTAT_WRITE = 0x02 - DEVSTAT_FREE = 0x03 + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 ) const ( @@ -34,4 +35,4 @@ type Timeval struct { } type Diskstat struct{} -type Bintime struct{} +type bintime struct{} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_amd64.go similarity index 79% rename from vendor/github.com/shirou/gopsutil/disk/disk_openbsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_amd64.go index 7c9ceaa8d..c1bd52ef8 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_amd64.go @@ -4,10 +4,10 @@ package disk const ( - DEVSTAT_NO_DATA = 0x00 - DEVSTAT_READ = 0x01 - DEVSTAT_WRITE = 0x02 - DEVSTAT_FREE = 0x03 + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 ) const ( @@ -33,4 +33,4 @@ type Timeval struct { } type Diskstat struct{} -type Bintime struct{} +type bintime struct{} diff --git a/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_arm.go new file mode 100644 index 000000000..86054a626 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_arm.go @@ -0,0 +1,38 @@ +//go:build openbsd && arm +// +build openbsd,arm + +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs disk/types_openbsd.go + +package disk + +const ( + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 +) + +const ( + sizeOfDiskstats = 0x60 +) + +type Diskstats struct { + Name [16]int8 + Busy int32 + Rxfer uint64 + Wxfer uint64 + Seek uint64 + Rbytes uint64 + Wbytes uint64 + Attachtime Timeval + Timestamp Timeval + Time Timeval +} +type Timeval struct { + Sec int64 + Usec int32 +} + +type Diskstat struct{} +type bintime struct{} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_arm64.go similarity index 72% rename from vendor/github.com/shirou/gopsutil/disk/disk_openbsd_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_arm64.go index 82adbc46c..ae1cf57e1 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_openbsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_openbsd_arm64.go @@ -1,15 +1,16 @@ -// +build openbsd -// +build arm64 +//go:build openbsd && arm64 +// +build openbsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs disk/types_openbsd.go package disk const ( - DEVSTAT_NO_DATA = 0x00 - DEVSTAT_READ = 0x01 - DEVSTAT_WRITE = 0x02 - DEVSTAT_FREE = 0x03 + devstat_NO_DATA = 0x00 + devstat_READ = 0x01 + devstat_WRITE = 0x02 + devstat_FREE = 0x03 ) const ( @@ -34,4 +35,4 @@ type Timeval struct { } type Diskstat struct{} -type Bintime struct{} +type bintime struct{} diff --git a/vendor/github.com/shirou/gopsutil/v3/disk/disk_solaris.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_solaris.go new file mode 100644 index 000000000..934d651ff --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_solaris.go @@ -0,0 +1,260 @@ +//go:build solaris +// +build solaris + +package disk + +import ( + "bufio" + "bytes" + "context" + "fmt" + "math" + "os" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + + "github.com/shirou/gopsutil/v3/internal/common" + "golang.org/x/sys/unix" +) + +const ( + // _DEFAULT_NUM_MOUNTS is set to `cat /etc/mnttab | wc -l` rounded up to the + // nearest power of two. + _DEFAULT_NUM_MOUNTS = 32 + + // _MNTTAB default place to read mount information + _MNTTAB = "/etc/mnttab" +) + +// A blacklist of read-only virtual filesystems. Writable filesystems are of +// operational concern and must not be included in this list. +var fsTypeBlacklist = map[string]struct{}{ + "ctfs": {}, + "dev": {}, + "fd": {}, + "lofs": {}, + "lxproc": {}, + "mntfs": {}, + "objfs": {}, + "proc": {}, +} + +func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { + ret := make([]PartitionStat, 0, _DEFAULT_NUM_MOUNTS) + + // Scan mnttab(4) + f, err := os.Open(_MNTTAB) + if err != nil { + } + defer func() { + if err == nil { + err = f.Close() + } else { + f.Close() + } + }() + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + fields := strings.Split(scanner.Text(), "\t") + + if _, found := fsTypeBlacklist[fields[2]]; found { + continue + } + + ret = append(ret, PartitionStat{ + // NOTE(seanc@): Device isn't exactly accurate: from mnttab(4): "The name + // of the resource that has been mounted." Ideally this value would come + // from Statvfs_t.Fsid but I'm leaving it to the caller to traverse + // unix.Statvfs(). + Device: fields[0], + Mountpoint: fields[1], + Fstype: fields[2], + Opts: strings.Split(fields[3], ","), + }) + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("unable to scan %q: %w", _MNTTAB, err) + } + + return ret, err +} + +func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { + var issolaris bool + if runtime.GOOS == "illumos" { + issolaris = false + } else { + issolaris = true + } + // check disks instead of zfs pools + filterstr := "/[^zfs]/:::/^nread$|^nwritten$|^reads$|^writes$|^rtime$|^wtime$/" + kstatSysOut, err := invoke.CommandWithContext(ctx, "kstat", "-c", "disk", "-p", filterstr) + if err != nil { + return nil, fmt.Errorf("cannot execute kstat: %w", err) + } + lines := strings.Split(strings.TrimSpace(string(kstatSysOut)), "\n") + if len(lines) == 0 { + return nil, fmt.Errorf("no disk class found") + } + dnamearr := make(map[string]string) + nreadarr := make(map[string]uint64) + nwrittenarr := make(map[string]uint64) + readsarr := make(map[string]uint64) + writesarr := make(map[string]uint64) + rtimearr := make(map[string]uint64) + wtimearr := make(map[string]uint64) + re := regexp.MustCompile(`[:\s]+`) + + // in case the name is "/dev/sda1", then convert to "sda1" + for i, name := range names { + names[i] = filepath.Base(name) + } + + for _, line := range lines { + fields := re.Split(line, -1) + if len(fields) == 0 { + continue + } + moduleName := fields[0] + instance := fields[1] + dname := fields[2] + + if len(names) > 0 && !common.StringsHas(names, dname) { + continue + } + dnamearr[moduleName+instance] = dname + // fields[3] is the statistic label, fields[4] is the value + switch fields[3] { + case "nread": + nreadarr[moduleName+instance], err = strconv.ParseUint((fields[4]), 10, 64) + if err != nil { + return nil, err + } + case "nwritten": + nwrittenarr[moduleName+instance], err = strconv.ParseUint((fields[4]), 10, 64) + if err != nil { + return nil, err + } + case "reads": + readsarr[moduleName+instance], err = strconv.ParseUint((fields[4]), 10, 64) + if err != nil { + return nil, err + } + case "writes": + writesarr[moduleName+instance], err = strconv.ParseUint((fields[4]), 10, 64) + if err != nil { + return nil, err + } + case "rtime": + if issolaris { + // from sec to milli secs + var frtime float64 + frtime, err = strconv.ParseFloat((fields[4]), 64) + rtimearr[moduleName+instance] = uint64(frtime * 1000) + } else { + // from nano to milli secs + rtimearr[moduleName+instance], err = strconv.ParseUint((fields[4]), 10, 64) + rtimearr[moduleName+instance] = rtimearr[moduleName+instance] / 1000 / 1000 + } + if err != nil { + return nil, err + } + case "wtime": + if issolaris { + // from sec to milli secs + var fwtime float64 + fwtime, err = strconv.ParseFloat((fields[4]), 64) + wtimearr[moduleName+instance] = uint64(fwtime * 1000) + } else { + // from nano to milli secs + wtimearr[moduleName+instance], err = strconv.ParseUint((fields[4]), 10, 64) + wtimearr[moduleName+instance] = wtimearr[moduleName+instance] / 1000 / 1000 + } + if err != nil { + return nil, err + } + } + } + + ret := make(map[string]IOCountersStat, 0) + for k := range dnamearr { + d := IOCountersStat{ + Name: dnamearr[k], + ReadBytes: nreadarr[k], + WriteBytes: nwrittenarr[k], + ReadCount: readsarr[k], + WriteCount: writesarr[k], + ReadTime: rtimearr[k], + WriteTime: wtimearr[k], + } + ret[d.Name] = d + } + return ret, nil +} + +func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { + statvfs := unix.Statvfs_t{} + if err := unix.Statvfs(path, &statvfs); err != nil { + return nil, fmt.Errorf("unable to call statvfs(2) on %q: %w", path, err) + } + + usageStat := &UsageStat{ + Path: path, + Fstype: common.IntToString(statvfs.Basetype[:]), + Total: statvfs.Blocks * statvfs.Frsize, + Free: statvfs.Bfree * statvfs.Frsize, + Used: (statvfs.Blocks - statvfs.Bfree) * statvfs.Frsize, + + // NOTE: ZFS (and FreeBZSD's UFS2) use dynamic inode/dnode allocation. + // Explicitly return a near-zero value for InodesUsedPercent so that nothing + // attempts to garbage collect based on a lack of available inodes/dnodes. + // Similarly, don't use the zero value to prevent divide-by-zero situations + // and inject a faux near-zero value. Filesystems evolve. Has your + // filesystem evolved? Probably not if you care about the number of + // available inodes. + InodesTotal: 1024.0 * 1024.0, + InodesUsed: 1024.0, + InodesFree: math.MaxUint64, + InodesUsedPercent: (1024.0 / (1024.0 * 1024.0)) * 100.0, + } + + usageStat.UsedPercent = (float64(usageStat.Used) / float64(usageStat.Total)) * 100.0 + + return usageStat, nil +} + +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { + out, err := invoke.CommandWithContext(ctx, "cfgadm", "-ls", "select=type(disk),cols=ap_id:info,cols2=,noheadings") + if err != nil { + return "", fmt.Errorf("exec cfgadm: %w", err) + } + + suf := "::" + strings.TrimPrefix(name, "/dev/") + s := bufio.NewScanner(bytes.NewReader(out)) + for s.Scan() { + flds := strings.Fields(s.Text()) + if strings.HasSuffix(flds[0], suf) { + flen := len(flds) + if flen >= 3 { + for i, f := range flds { + if i > 0 && i < flen-1 && f == "SN:" { + return flds[i+1], nil + } + } + } + return "", nil + } + } + if err := s.Err(); err != nil { + return "", err + } + return "", nil +} + +func LabelWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_unix.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_unix.go similarity index 93% rename from vendor/github.com/shirou/gopsutil/disk/disk_unix.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_unix.go index 9ca3bb34c..1e7352408 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_unix.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_unix.go @@ -1,4 +1,5 @@ -// +build freebsd linux darwin +//go:build freebsd || linux || darwin || (aix && !cgo) +// +build freebsd linux darwin aix,!cgo package disk @@ -26,13 +27,22 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { InodesFree: (uint64(stat.Ffree)), } + ret.Used = (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(bsize) + + if (ret.Used + ret.Free) == 0 { + ret.UsedPercent = 0 + } else { + // We don't use ret.Total to calculate percent. + // see https://github.com/shirou/gopsutil/issues/562 + ret.UsedPercent = (float64(ret.Used) / float64(ret.Used+ret.Free)) * 100.0 + } + // if could not get InodesTotal, return empty if ret.InodesTotal < ret.InodesFree { return ret, nil } ret.InodesUsed = (ret.InodesTotal - ret.InodesFree) - ret.Used = (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(bsize) if ret.InodesTotal == 0 { ret.InodesUsedPercent = 0 @@ -40,14 +50,6 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0 } - if (ret.Used + ret.Free) == 0 { - ret.UsedPercent = 0 - } else { - // We don't use ret.Total to calculate percent. - // see https://github.com/shirou/gopsutil/issues/562 - ret.UsedPercent = (float64(ret.Used) / float64(ret.Used+ret.Free)) * 100.0 - } - return ret, nil } diff --git a/vendor/github.com/shirou/gopsutil/disk/disk_windows.go b/vendor/github.com/shirou/gopsutil/v3/disk/disk_windows.go similarity index 54% rename from vendor/github.com/shirou/gopsutil/disk/disk_windows.go rename to vendor/github.com/shirou/gopsutil/v3/disk/disk_windows.go index 03dccb21c..e17db3e5b 100644 --- a/vendor/github.com/shirou/gopsutil/disk/disk_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/disk/disk_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package disk @@ -9,8 +10,9 @@ import ( "syscall" "unsafe" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" ) var ( @@ -21,8 +23,8 @@ var ( ) var ( - FileFileCompression = int64(16) // 0x00000010 - FileReadOnlyVolume = int64(524288) // 0x00080000 + fileFileCompression = int64(16) // 0x00000010 + fileReadOnlyVolume = int64(524288) // 0x00080000 ) // diskPerformance is an equivalent representation of DISK_PERFORMANCE in the Windows API. @@ -43,6 +45,15 @@ type diskPerformance struct { alignmentPadding uint32 // necessary for 32bit support, see https://github.com/elastic/beats/pull/16553 } +func init() { + // enable disk performance counters on Windows Server editions (needs to run as admin) + key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Services\PartMgr`, registry.SET_VALUE) + if err == nil { + key.SetDWordValue("EnableCounterForIoctl", 1) + key.Close() + } +} + func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { lpFreeBytesAvailable := int64(0) lpTotalNumberOfBytes := int64(0) @@ -69,66 +80,105 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { return ret, nil } +// PartitionsWithContext returns disk partitions. +// Since GetVolumeInformation doesn't have a timeout, this method uses context to set deadline by users. func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { - var ret []PartitionStat - lpBuffer := make([]byte, 254) - diskret, _, err := procGetLogicalDriveStringsW.Call( - uintptr(len(lpBuffer)), - uintptr(unsafe.Pointer(&lpBuffer[0]))) - if diskret == 0 { - return ret, err + warnings := Warnings{ + Verbose: true, } - for _, v := range lpBuffer { - if v >= 65 && v <= 90 { - path := string(v) + ":" - typepath, _ := windows.UTF16PtrFromString(path) - typeret, _, _ := procGetDriveType.Call(uintptr(unsafe.Pointer(typepath))) - if typeret == 0 { - return ret, windows.GetLastError() - } - // 2: DRIVE_REMOVABLE 3: DRIVE_FIXED 4: DRIVE_REMOTE 5: DRIVE_CDROM - - if typeret == 2 || typeret == 3 || typeret == 4 || typeret == 5 { - lpVolumeNameBuffer := make([]byte, 256) - lpVolumeSerialNumber := int64(0) - lpMaximumComponentLength := int64(0) - lpFileSystemFlags := int64(0) - lpFileSystemNameBuffer := make([]byte, 256) - volpath, _ := windows.UTF16PtrFromString(string(v) + ":/") - driveret, _, err := procGetVolumeInformation.Call( - uintptr(unsafe.Pointer(volpath)), - uintptr(unsafe.Pointer(&lpVolumeNameBuffer[0])), - uintptr(len(lpVolumeNameBuffer)), - uintptr(unsafe.Pointer(&lpVolumeSerialNumber)), - uintptr(unsafe.Pointer(&lpMaximumComponentLength)), - uintptr(unsafe.Pointer(&lpFileSystemFlags)), - uintptr(unsafe.Pointer(&lpFileSystemNameBuffer[0])), - uintptr(len(lpFileSystemNameBuffer))) - if driveret == 0 { - if typeret == 5 || typeret == 2 { - continue //device is not ready will happen if there is no disk in the drive - } - return ret, err - } - opts := "rw" - if lpFileSystemFlags&FileReadOnlyVolume != 0 { - opts = "ro" + + var errLogicalDrives error + retChan := make(chan PartitionStat) + quitChan := make(chan struct{}) + defer close(quitChan) + + getPartitions := func() { + defer close(retChan) + + lpBuffer := make([]byte, 254) + + diskret, _, err := procGetLogicalDriveStringsW.Call( + uintptr(len(lpBuffer)), + uintptr(unsafe.Pointer(&lpBuffer[0]))) + if diskret == 0 { + errLogicalDrives = err + return + } + for _, v := range lpBuffer { + if v >= 65 && v <= 90 { + path := string(v) + ":" + typepath, _ := windows.UTF16PtrFromString(path) + typeret, _, _ := procGetDriveType.Call(uintptr(unsafe.Pointer(typepath))) + if typeret == 0 { + err := windows.GetLastError() + warnings.Add(err) + continue } - if lpFileSystemFlags&FileFileCompression != 0 { - opts += ".compress" + // 2: DRIVE_REMOVABLE 3: DRIVE_FIXED 4: DRIVE_REMOTE 5: DRIVE_CDROM + + if typeret == 2 || typeret == 3 || typeret == 4 || typeret == 5 { + lpVolumeNameBuffer := make([]byte, 256) + lpVolumeSerialNumber := int64(0) + lpMaximumComponentLength := int64(0) + lpFileSystemFlags := int64(0) + lpFileSystemNameBuffer := make([]byte, 256) + volpath, _ := windows.UTF16PtrFromString(string(v) + ":/") + driveret, _, err := procGetVolumeInformation.Call( + uintptr(unsafe.Pointer(volpath)), + uintptr(unsafe.Pointer(&lpVolumeNameBuffer[0])), + uintptr(len(lpVolumeNameBuffer)), + uintptr(unsafe.Pointer(&lpVolumeSerialNumber)), + uintptr(unsafe.Pointer(&lpMaximumComponentLength)), + uintptr(unsafe.Pointer(&lpFileSystemFlags)), + uintptr(unsafe.Pointer(&lpFileSystemNameBuffer[0])), + uintptr(len(lpFileSystemNameBuffer))) + if driveret == 0 { + if typeret == 5 || typeret == 2 { + continue // device is not ready will happen if there is no disk in the drive + } + warnings.Add(err) + continue + } + opts := []string{"rw"} + if lpFileSystemFlags&fileReadOnlyVolume != 0 { + opts = []string{"ro"} + } + if lpFileSystemFlags&fileFileCompression != 0 { + opts = append(opts, "compress") + } + + select { + case retChan <- PartitionStat{ + Mountpoint: path, + Device: path, + Fstype: string(bytes.ReplaceAll(lpFileSystemNameBuffer, []byte("\x00"), []byte(""))), + Opts: opts, + }: + case <-quitChan: + return + } } + } + } + } + + go getPartitions() - d := PartitionStat{ - Mountpoint: path, - Device: path, - Fstype: string(bytes.Replace(lpFileSystemNameBuffer, []byte("\x00"), []byte(""), -1)), - Opts: opts, + var ret []PartitionStat + for { + select { + case p, ok := <-retChan: + if !ok { + if errLogicalDrives != nil { + return ret, errLogicalDrives } - ret = append(ret, d) + return ret, warnings.Reference() } + ret = append(ret, p) + case <-ctx.Done(): + return ret, ctx.Err() } } - return ret, nil } func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { @@ -181,3 +231,11 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC } return drivemap, nil } + +func SerialNumberWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} + +func LabelWithContext(ctx context.Context, name string) (string, error) { + return "", common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/disk/iostat_darwin.c b/vendor/github.com/shirou/gopsutil/v3/disk/iostat_darwin.c similarity index 96% rename from vendor/github.com/shirou/gopsutil/disk/iostat_darwin.c rename to vendor/github.com/shirou/gopsutil/v3/disk/iostat_darwin.c index 9619c6f47..8aab04f60 100644 --- a/vendor/github.com/shirou/gopsutil/disk/iostat_darwin.c +++ b/vendor/github.com/shirou/gopsutil/v3/disk/iostat_darwin.c @@ -16,19 +16,17 @@ static int getdrivestat(io_registry_entry_t d, DriveStats *stat); static int fillstat(io_registry_entry_t d, DriveStats *stat); int -readdrivestat(DriveStats a[], int n) +gopsutil_v3_readdrivestat(DriveStats a[], int n) { - mach_port_t port; CFMutableDictionaryRef match; io_iterator_t drives; io_registry_entry_t d; kern_return_t status; int na, rv; - IOMasterPort(bootstrap_port, &port); match = IOServiceMatching("IOMedia"); CFDictionaryAddValue(match, CFSTR(kIOMediaWholeKey), kCFBooleanTrue); - status = IOServiceGetMatchingServices(port, match, &drives); + status = IOServiceGetMatchingServices(0, match, &drives); if(status != KERN_SUCCESS) return -1; diff --git a/vendor/github.com/shirou/gopsutil/disk/iostat_darwin.h b/vendor/github.com/shirou/gopsutil/v3/disk/iostat_darwin.h similarity index 85% rename from vendor/github.com/shirou/gopsutil/disk/iostat_darwin.h rename to vendor/github.com/shirou/gopsutil/v3/disk/iostat_darwin.h index c7208499d..cb9ec7a0a 100644 --- a/vendor/github.com/shirou/gopsutil/disk/iostat_darwin.h +++ b/vendor/github.com/shirou/gopsutil/v3/disk/iostat_darwin.h @@ -29,5 +29,4 @@ struct CPUStats { natural_t idle; }; -extern int readdrivestat(DriveStats a[], int n); -extern int readcpustat(CPUStats *cpu); +extern int gopsutil_v3_readdrivestat(DriveStats a[], int n); diff --git a/vendor/github.com/shirou/gopsutil/host/host.go b/vendor/github.com/shirou/gopsutil/v3/host/host.go similarity index 78% rename from vendor/github.com/shirou/gopsutil/host/host.go rename to vendor/github.com/shirou/gopsutil/v3/host/host.go index 647cf0156..c7e84e3a5 100644 --- a/vendor/github.com/shirou/gopsutil/host/host.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host.go @@ -3,13 +3,16 @@ package host import ( "context" "encoding/json" + "errors" "os" "runtime" "time" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) +type Warnings = common.Warnings + var invoke common.Invoker = common.Invoke{} // A HostInfoStat describes the host status. @@ -27,7 +30,7 @@ type InfoStat struct { KernelArch string `json:"kernelArch"` // native cpu architecture queried at runtime, as returned by `uname -m` or empty string in case of error VirtualizationSystem string `json:"virtualizationSystem"` VirtualizationRole string `json:"virtualizationRole"` // guest or host - HostID string `json:"hostid"` // ex: uuid + HostID string `json:"hostId"` // ex: uuid } type UserStat struct { @@ -39,7 +42,9 @@ type UserStat struct { type TemperatureStat struct { SensorKey string `json:"sensorKey"` - Temperature float64 `json:"sensorTemperature"` + Temperature float64 `json:"temperature"` + High float64 `json:"sensorHigh"` + Critical float64 `json:"sensorCritical"` } func (h InfoStat) String() string { @@ -68,47 +73,47 @@ func InfoWithContext(ctx context.Context) (*InfoStat, error) { } ret.Hostname, err = os.Hostname() - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.Platform, ret.PlatformFamily, ret.PlatformVersion, err = PlatformInformationWithContext(ctx) - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.KernelVersion, err = KernelVersionWithContext(ctx) - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.KernelArch, err = KernelArch() - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.VirtualizationSystem, ret.VirtualizationRole, err = VirtualizationWithContext(ctx) - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.BootTime, err = BootTimeWithContext(ctx) - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.Uptime, err = UptimeWithContext(ctx) - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.Procs, err = numProcs(ctx) - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } ret.HostID, err = HostIDWithContext(ctx) - if err != nil && err != common.ErrNotImplementedError { + if err != nil && !errors.Is(err, common.ErrNotImplementedError) { return nil, err } @@ -152,3 +157,7 @@ func SensorsTemperatures() ([]TemperatureStat, error) { func timeSince(ts uint64) uint64 { return uint64(time.Now().Unix()) - ts } + +func timeSinceMillis(ts uint64) uint64 { + return uint64(time.Now().UnixMilli()) - ts +} diff --git a/vendor/github.com/shirou/gopsutil/host/host_bsd.go b/vendor/github.com/shirou/gopsutil/v3/host/host_bsd.go similarity index 94% rename from vendor/github.com/shirou/gopsutil/host/host_bsd.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_bsd.go index fc45b8770..4dc2bba58 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_bsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_bsd.go @@ -1,3 +1,4 @@ +//go:build darwin || freebsd || openbsd // +build darwin freebsd openbsd package host diff --git a/vendor/github.com/shirou/gopsutil/host/host_darwin.go b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin.go similarity index 83% rename from vendor/github.com/shirou/gopsutil/host/host_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_darwin.go index d3e23cff3..1be2e8533 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package host @@ -9,25 +10,20 @@ import ( "errors" "io/ioutil" "os" - "os/exec" "strings" "unsafe" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/process" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/process" ) // from utmpx.h -const USER_PROCESS = 7 +const user_PROCESS = 7 func HostIDWithContext(ctx context.Context) (string, error) { - ioreg, err := exec.LookPath("ioreg") - if err != nil { - return "", err - } - - out, err := invoke.CommandWithContext(ctx, ioreg, "-rd1", "-c", "IOPlatformExpertDevice") + out, err := invoke.CommandWithContext(ctx, "ioreg", "-rd1", "-c", "IOPlatformExpertDevice") if err != nil { return "", err } @@ -81,7 +77,7 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) { if err != nil { continue } - if u.Type != USER_PROCESS { + if u.Type != user_PROCESS { continue } user := UserStat{ @@ -94,7 +90,6 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) { } return ret, nil - } func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) { @@ -102,17 +97,12 @@ func PlatformInformationWithContext(ctx context.Context) (string, string, string family := "" pver := "" - sw_vers, err := exec.LookPath("sw_vers") - if err != nil { - return "", "", "", err - } - p, err := unix.Sysctl("kern.ostype") if err == nil { platform = strings.ToLower(p) } - out, err := invoke.CommandWithContext(ctx, sw_vers, "-productVersion") + out, err := invoke.CommandWithContext(ctx, "sw_vers", "-productVersion") if err == nil { pver = strings.ToLower(strings.TrimSpace(string(out))) } diff --git a/vendor/github.com/shirou/gopsutil/host/host_darwin_amd64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_amd64.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_darwin_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_darwin_amd64.go index c3596f9f5..8caeed2e8 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_darwin_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_amd64.go @@ -14,6 +14,7 @@ type Utmpx struct { Host [256]int8 Pad [16]uint32 } + type Timeval struct { Sec int32 } diff --git a/vendor/github.com/shirou/gopsutil/host/host_darwin_arm64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_arm64.go similarity index 86% rename from vendor/github.com/shirou/gopsutil/host/host_darwin_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_darwin_arm64.go index 74c28f2f7..293bd4df8 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_darwin_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_arm64.go @@ -1,5 +1,6 @@ -// +build darwin -// +build arm64 +//go:build darwin && arm64 +// +build darwin,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs host/types_darwin.go diff --git a/vendor/github.com/shirou/gopsutil/host/host_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_cgo.go similarity index 82% rename from vendor/github.com/shirou/gopsutil/host/host_darwin_cgo.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_darwin_cgo.go index d5ba4cde3..ffdc7b78f 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_darwin_cgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_cgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build cgo +//go:build darwin && cgo +// +build darwin,cgo package host @@ -34,13 +34,13 @@ func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, err } var temperatures []TemperatureStat - C.open_smc() - defer C.close_smc() + C.gopsutil_v3_open_smc() + defer C.gopsutil_v3_close_smc() for _, key := range temperatureKeys { temperatures = append(temperatures, TemperatureStat{ SensorKey: key, - Temperature: float64(C.get_temperature(C.CString(key))), + Temperature: float64(C.gopsutil_v3_get_temperature(C.CString(key))), }) } return temperatures, nil diff --git a/vendor/github.com/shirou/gopsutil/host/host_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_nocgo.go similarity index 65% rename from vendor/github.com/shirou/gopsutil/host/host_darwin_nocgo.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_darwin_nocgo.go index 784899bc0..6285ba94d 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_darwin_nocgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_darwin_nocgo.go @@ -1,12 +1,12 @@ -// +build darwin -// +build !cgo +//go:build darwin && !cgo +// +build darwin,!cgo package host import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/host/host_fallback.go b/vendor/github.com/shirou/gopsutil/v3/host/host_fallback.go similarity index 90% rename from vendor/github.com/shirou/gopsutil/host/host_fallback.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_fallback.go index db697a5a5..585250f9a 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_fallback.go @@ -1,3 +1,4 @@ +//go:build !darwin && !linux && !freebsd && !openbsd && !solaris && !windows // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows package host @@ -5,7 +6,7 @@ package host import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func HostIDWithContext(ctx context.Context) (string, error) { diff --git a/vendor/github.com/shirou/gopsutil/host/host_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/host/host_freebsd.go similarity index 96% rename from vendor/github.com/shirou/gopsutil/host/host_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_freebsd.go index 583a1f9e3..2c9aa9d0d 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd // +build freebsd package host @@ -12,8 +13,8 @@ import ( "strings" "unsafe" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/process" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/process" "golang.org/x/sys/unix" ) @@ -81,7 +82,6 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) { } return ret, nil - } func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) { diff --git a/vendor/github.com/shirou/gopsutil/host/host_freebsd_386.go b/vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_386.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/host/host_freebsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_386.go diff --git a/vendor/github.com/shirou/gopsutil/host/host_freebsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_amd64.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/host/host_freebsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_amd64.go diff --git a/vendor/github.com/shirou/gopsutil/host/host_freebsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_arm.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/host/host_freebsd_arm.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_arm.go diff --git a/vendor/github.com/shirou/gopsutil/host/host_freebsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_arm64.go similarity index 54% rename from vendor/github.com/shirou/gopsutil/host/host_freebsd_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_arm64.go index 88dc11fca..41bec3c11 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_freebsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_freebsd_arm64.go @@ -1,24 +1,25 @@ -// +build freebsd -// +build arm64 +//go:build freebsd && arm64 +// +build freebsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs host/types_freebsd.go package host const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 - sizeOfUtmpx = 0xc5 + sizeofPtr = 0x8 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x8 + sizeofLongLong = 0x8 + sizeOfUtmpx = 0xc5 ) type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 + _C_short int16 + _C_int int32 + _C_long int64 + _C_long_long int64 ) type Utmp struct { diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux.go similarity index 60% rename from vendor/github.com/shirou/gopsutil/host/host_linux.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux.go index ad630db1f..e6ac63a39 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package host @@ -9,17 +10,17 @@ import ( "fmt" "io/ioutil" "os" - "os/exec" "path/filepath" "regexp" "strconv" "strings" - "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" ) -type LSB struct { +type lsbStruct struct { ID string Release string Codename string @@ -27,12 +28,16 @@ type LSB struct { } // from utmp.h -const USER_PROCESS = 7 +const ( + user_PROCESS = 7 + + hostTemperatureScale = 1000.0 +) func HostIDWithContext(ctx context.Context) (string, error) { - sysProductUUID := common.HostSys("class/dmi/id/product_uuid") - machineID := common.HostEtc("machine-id") - procSysKernelRandomBootID := common.HostProc("sys/kernel/random/boot_id") + sysProductUUID := common.HostSysWithContext(ctx, "class/dmi/id/product_uuid") + machineID := common.HostEtcWithContext(ctx, "machine-id") + procSysKernelRandomBootID := common.HostProcWithContext(ctx, "sys/kernel/random/boot_id") switch { // In order to read this file, needs to be supported by kernel/arch and run as root // so having fallback is important @@ -62,7 +67,7 @@ func HostIDWithContext(ctx context.Context) (string, error) { } func numProcs(ctx context.Context) (uint64, error) { - return common.NumProcs() + return common.NumProcsWithContext(ctx) } func BootTimeWithContext(ctx context.Context) (uint64, error) { @@ -78,7 +83,7 @@ func UptimeWithContext(ctx context.Context) (uint64, error) { } func UsersWithContext(ctx context.Context) ([]UserStat, error) { - utmpfile := common.HostVar("run/utmp") + utmpfile := common.HostVarWithContext(ctx, "run/utmp") file, err := os.Open(utmpfile) if err != nil { @@ -104,7 +109,7 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) { if err != nil { continue } - if u.Type != USER_PROCESS { + if u.Type != user_PROCESS { continue } user := UserStat{ @@ -117,13 +122,12 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) { } return ret, nil - } -func getLSB() (*LSB, error) { - ret := &LSB{} - if common.PathExists(common.HostEtc("lsb-release")) { - contents, err := common.ReadLines(common.HostEtc("lsb-release")) +func getlsbStruct(ctx context.Context) (*lsbStruct, error) { + ret := &lsbStruct{} + if common.PathExists(common.HostEtcWithContext(ctx, "lsb-release")) { + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "lsb-release")) if err != nil { return ret, err // return empty } @@ -134,21 +138,17 @@ func getLSB() (*LSB, error) { } switch field[0] { case "DISTRIB_ID": - ret.ID = field[1] + ret.ID = strings.ReplaceAll(field[1], `"`, ``) case "DISTRIB_RELEASE": - ret.Release = field[1] + ret.Release = strings.ReplaceAll(field[1], `"`, ``) case "DISTRIB_CODENAME": - ret.Codename = field[1] + ret.Codename = strings.ReplaceAll(field[1], `"`, ``) case "DISTRIB_DESCRIPTION": - ret.Description = field[1] + ret.Description = strings.ReplaceAll(field[1], `"`, ``) } } } else if common.PathExists("/usr/bin/lsb_release") { - lsb_release, err := exec.LookPath("lsb_release") - if err != nil { - return ret, err - } - out, err := invoke.Command(lsb_release) + out, err := invoke.Command("/usr/bin/lsb_release") if err != nil { return ret, err } @@ -159,13 +159,13 @@ func getLSB() (*LSB, error) { } switch field[0] { case "Distributor ID": - ret.ID = field[1] + ret.ID = strings.ReplaceAll(field[1], `"`, ``) case "Release": - ret.Release = field[1] + ret.Release = strings.ReplaceAll(field[1], `"`, ``) case "Codename": - ret.Codename = field[1] + ret.Codename = strings.ReplaceAll(field[1], `"`, ``) case "Description": - ret.Description = field[1] + ret.Description = strings.ReplaceAll(field[1], `"`, ``) } } @@ -175,84 +175,96 @@ func getLSB() (*LSB, error) { } func PlatformInformationWithContext(ctx context.Context) (platform string, family string, version string, err error) { - lsb, err := getLSB() + lsb, err := getlsbStruct(ctx) if err != nil { - lsb = &LSB{} + lsb = &lsbStruct{} } - if common.PathExists(common.HostEtc("oracle-release")) { + if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "oracle-release")) { platform = "oracle" - contents, err := common.ReadLines(common.HostEtc("oracle-release")) + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "oracle-release")) if err == nil { version = getRedhatishVersion(contents) } - } else if common.PathExists(common.HostEtc("enterprise-release")) { + } else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "enterprise-release")) { platform = "oracle" - contents, err := common.ReadLines(common.HostEtc("enterprise-release")) + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "enterprise-release")) if err == nil { version = getRedhatishVersion(contents) } - } else if common.PathExists(common.HostEtc("slackware-version")) { + } else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "slackware-version")) { platform = "slackware" - contents, err := common.ReadLines(common.HostEtc("slackware-version")) + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "slackware-version")) if err == nil { version = getSlackwareVersion(contents) } - } else if common.PathExists(common.HostEtc("debian_version")) { + } else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "debian_version")) { if lsb.ID == "Ubuntu" { platform = "ubuntu" version = lsb.Release } else if lsb.ID == "LinuxMint" { platform = "linuxmint" version = lsb.Release + } else if lsb.ID == "Kylin" { + platform = "Kylin" + version = lsb.Release + } else if lsb.ID == `"Cumulus Linux"` { + platform = "cumuluslinux" + version = lsb.Release } else { - if common.PathExists("/usr/bin/raspi-config") { + if common.PathExistsWithContents("/usr/bin/raspi-config") { platform = "raspbian" } else { platform = "debian" } - contents, err := common.ReadLines(common.HostEtc("debian_version")) + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "debian_version")) if err == nil && len(contents) > 0 && contents[0] != "" { version = contents[0] } } - } else if common.PathExists(common.HostEtc("redhat-release")) { - contents, err := common.ReadLines(common.HostEtc("redhat-release")) + } else if common.PathExists(common.HostEtcWithContext(ctx, "neokylin-release")) { + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "neokylin-release")) + if err == nil { + version = getRedhatishVersion(contents) + platform = getRedhatishPlatform(contents) + } + } else if common.PathExists(common.HostEtcWithContext(ctx, "redhat-release")) { + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "redhat-release")) if err == nil { version = getRedhatishVersion(contents) platform = getRedhatishPlatform(contents) } - } else if common.PathExists(common.HostEtc("system-release")) { - contents, err := common.ReadLines(common.HostEtc("system-release")) + } else if common.PathExists(common.HostEtcWithContext(ctx, "system-release")) { + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "system-release")) if err == nil { version = getRedhatishVersion(contents) platform = getRedhatishPlatform(contents) } - } else if common.PathExists(common.HostEtc("gentoo-release")) { + } else if common.PathExists(common.HostEtcWithContext(ctx, "gentoo-release")) { platform = "gentoo" - contents, err := common.ReadLines(common.HostEtc("gentoo-release")) + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "gentoo-release")) if err == nil { version = getRedhatishVersion(contents) } - } else if common.PathExists(common.HostEtc("SuSE-release")) { - contents, err := common.ReadLines(common.HostEtc("SuSE-release")) + } else if common.PathExists(common.HostEtcWithContext(ctx, "SuSE-release")) { + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "SuSE-release")) if err == nil { version = getSuseVersion(contents) platform = getSusePlatform(contents) } // TODO: slackware detecion - } else if common.PathExists(common.HostEtc("arch-release")) { + } else if common.PathExists(common.HostEtcWithContext(ctx, "arch-release")) { platform = "arch" version = lsb.Release - } else if common.PathExists(common.HostEtc("alpine-release")) { + } else if common.PathExists(common.HostEtcWithContext(ctx, "alpine-release")) { platform = "alpine" - contents, err := common.ReadLines(common.HostEtc("alpine-release")) + contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "alpine-release")) if err == nil && len(contents) > 0 && contents[0] != "" { version = contents[0] } - } else if common.PathExists(common.HostEtc("os-release")) { - p, v, err := common.GetOSRelease() + } else if common.PathExists(common.HostEtcWithContext(ctx, "os-release")) { + p, v, err := common.GetOSReleaseWithContext(ctx) if err == nil { platform = p version = v @@ -274,12 +286,14 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil version = lsb.Release } + platform = strings.Trim(platform, `"`) + switch platform { - case "debian", "ubuntu", "linuxmint", "raspbian": + case "debian", "ubuntu", "linuxmint", "raspbian", "Kylin", "cumuluslinux": family = "debian" case "fedora": family = "fedora" - case "oracle", "centos", "redhat", "scientific", "enterpriseenterprise", "amazon", "xenserver", "cloudlinux", "ibm_powerkvm", "rocky": + case "oracle", "centos", "redhat", "scientific", "enterpriseenterprise", "amazon", "xenserver", "cloudlinux", "ibm_powerkvm", "rocky", "almalinux": family = "rhel" case "suse", "opensuse", "opensuse-leap", "opensuse-tumbleweed", "opensuse-tumbleweed-kubic", "sles", "sled", "caasp": family = "suse" @@ -297,10 +311,11 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil family = "coreos" case "solus": family = "solus" + case "neokylin": + family = "neokylin" } return platform, family, version, nil - } func KernelVersionWithContext(ctx context.Context) (version string, err error) { @@ -309,7 +324,7 @@ func KernelVersionWithContext(ctx context.Context) (version string, err error) { if err != nil { return "", err } - return string(utsname.Release[:bytes.IndexByte(utsname.Release[:], 0)]), nil + return unix.ByteSliceToString(utsname.Release[:]), nil } func getSlackwareVersion(contents []string) string { @@ -324,7 +339,7 @@ func getRedhatishVersion(contents []string) string { if strings.Contains(c, "rawhide") { return "rawhide" } - if matches := regexp.MustCompile(`release (\d[\d.]*)`).FindStringSubmatch(c); matches != nil { + if matches := regexp.MustCompile(`release (\w[\d.]*)`).FindStringSubmatch(c); matches != nil { return matches[1] } return "" @@ -366,23 +381,31 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) { } func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, error) { - var temperatures []TemperatureStat - files, err := filepath.Glob(common.HostSys("/class/hwmon/hwmon*/temp*_*")) - if err != nil { + var err error + + var files []string + + temperatures := make([]TemperatureStat, 0) + + // Only the temp*_input file provides current temperature + // value in millidegree Celsius as reported by the temperature to the device: + // https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface + if files, err = filepath.Glob(common.HostSysWithContext(ctx, "/class/hwmon/hwmon*/temp*_input")); err != nil { return temperatures, err } + if len(files) == 0 { // CentOS has an intermediate /device directory: // https://github.com/giampaolo/psutil/issues/971 - files, err = filepath.Glob(common.HostSys("/class/hwmon/hwmon*/device/temp*_*")) - if err != nil { + if files, err = filepath.Glob(common.HostSysWithContext(ctx, "/class/hwmon/hwmon*/device/temp*_input")); err != nil { return temperatures, err } } + var warns Warnings if len(files) == 0 { // handle distributions without hwmon, like raspbian #391, parse legacy thermal_zone files - files, err = filepath.Glob(common.HostSys("/class/thermal/thermal_zone*/")) + files, err = filepath.Glob(common.HostSysWithContext(ctx, "/class/thermal/thermal_zone*/")) if err != nil { return temperatures, err } @@ -413,6 +436,8 @@ func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, err return temperatures, warns.Reference() } + temperatures = make([]TemperatureStat, 0, len(files)) + // example directory // device/ temp1_crit_alarm temp2_crit_alarm temp3_crit_alarm temp4_crit_alarm temp5_crit_alarm temp6_crit_alarm temp7_crit_alarm // name temp1_input temp2_input temp3_input temp4_input temp5_input temp6_input temp7_input @@ -420,44 +445,81 @@ func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, err // subsystem/ temp1_max temp2_max temp3_max temp4_max temp5_max temp6_max temp7_max // temp1_crit temp2_crit temp3_crit temp4_crit temp5_crit temp6_crit temp7_crit uevent for _, file := range files { - filename := strings.Split(filepath.Base(file), "_") - if filename[1] == "label" { - // Do not try to read the temperature of the label file - continue - } + var raw []byte + + var temperature float64 + + // Get the base directory location + directory := filepath.Dir(file) + + // Get the base filename prefix like temp1 + basename := strings.Split(filepath.Base(file), "_")[0] + + // Get the base path like /temp1 + basepath := filepath.Join(directory, basename) // Get the label of the temperature you are reading - var label string - c, _ := ioutil.ReadFile(filepath.Join(filepath.Dir(file), filename[0]+"_label")) - if c != nil { - //format the label from "Core 0" to "core0_" - label = fmt.Sprintf("%s_", strings.Join(strings.Split(strings.TrimSpace(strings.ToLower(string(c))), " "), "")) + label := "" + + if raw, _ = ioutil.ReadFile(basepath + "_label"); len(raw) != 0 { + // Format the label from "Core 0" to "core_0" + label = strings.Join(strings.Split(strings.TrimSpace(strings.ToLower(string(raw))), " "), "_") } // Get the name of the temperature you are reading - name, err := ioutil.ReadFile(filepath.Join(filepath.Dir(file), "name")) - if err != nil { + if raw, err = ioutil.ReadFile(filepath.Join(directory, "name")); err != nil { warns.Add(err) continue } + name := strings.TrimSpace(string(raw)) + + if label != "" { + name = name + "_" + label + } + // Get the temperature reading - current, err := ioutil.ReadFile(file) - if err != nil { + if raw, err = ioutil.ReadFile(file); err != nil { warns.Add(err) continue } - temperature, err := strconv.ParseFloat(strings.TrimSpace(string(current)), 64) - if err != nil { + + if temperature, err = strconv.ParseFloat(strings.TrimSpace(string(raw)), 64); err != nil { warns.Add(err) continue } - tempName := strings.TrimSpace(strings.ToLower(string(strings.Join(filename[1:], "")))) + // Add discovered temperature sensor to the list temperatures = append(temperatures, TemperatureStat{ - SensorKey: fmt.Sprintf("%s_%s%s", strings.TrimSpace(string(name)), label, tempName), - Temperature: temperature / 1000.0, + SensorKey: name, + Temperature: temperature / hostTemperatureScale, + High: optionalValueReadFromFile(basepath+"_max") / hostTemperatureScale, + Critical: optionalValueReadFromFile(basepath+"_crit") / hostTemperatureScale, }) } + return temperatures, warns.Reference() } + +func optionalValueReadFromFile(filename string) float64 { + var raw []byte + + var err error + + var value float64 + + // Check if file exists + if _, err := os.Stat(filename); os.IsNotExist(err) { + return 0 + } + + if raw, err = ioutil.ReadFile(filename); err != nil { + return 0 + } + + if value, err = strconv.ParseFloat(strings.TrimSpace(string(raw)), 64); err != nil { + return 0 + } + + return value +} diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_386.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_386.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_386.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_386.go index 79b5cb5d3..46e0c5d5a 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_386.go @@ -35,10 +35,12 @@ type utmp struct { Addr_v6 [4]int32 X__unused [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type UtTv struct { Sec int32 Usec int32 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_amd64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_amd64.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_amd64.go index 9a69652f5..1e574482f 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_amd64.go @@ -33,10 +33,12 @@ type utmp struct { Addr_v6 [4]int32 X__glibc_reserved [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int64 Usec int64 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_arm.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_arm.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_arm.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_arm.go index e2cf44850..7abbbb8a3 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_arm.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_arm.go @@ -33,10 +33,12 @@ type utmp struct { Addr_v6 [4]int32 X__glibc_reserved [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int32 Usec int32 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_arm64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_arm64.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_arm64.go index 37dbe5c8c..eebef55cd 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_arm64.go @@ -33,10 +33,12 @@ type utmp struct { Addr_v6 [4]int32 X__glibc_reserved [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int64 Usec int64 diff --git a/vendor/github.com/shirou/gopsutil/v3/host/host_linux_loong64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_loong64.go new file mode 100644 index 000000000..edf1be597 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_loong64.go @@ -0,0 +1,48 @@ +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs host/types_linux.go + +//go:build linux && loong64 +// +build linux,loong64 + +package host + +const ( + sizeofPtr = 0x8 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x8 + sizeofLongLong = 0x8 + sizeOfUtmp = 0x190 +) + +type ( + _C_short int16 + _C_int int32 + _C_long int64 + _C_long_long int64 +) + +type ( + utmp struct { + Type int16 + Pid int32 + Line [32]int8 + Id [4]int8 + User [32]int8 + Host [256]int8 + Exit exit_status + Session int64 + Tv timeval + Addr_v6 [4]int32 + X__glibc_reserved [20]int8 + Pad_cgo_0 [4]byte + } + exit_status struct { + Termination int16 + Exit int16 + } + timeval struct { + Sec int64 + Usec int64 + } +) diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_mips.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_mips.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips.go index b0fca0939..50207e5bc 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_mips.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips.go @@ -33,10 +33,12 @@ type utmp struct { Addr_v6 [4]int32 X__unused [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int32 Usec int32 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_mips64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips64.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_mips64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips64.go index b0fca0939..50207e5bc 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_mips64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips64.go @@ -33,10 +33,12 @@ type utmp struct { Addr_v6 [4]int32 X__unused [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int32 Usec int32 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_mips64le.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips64le.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_mips64le.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips64le.go index b0fca0939..50207e5bc 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_mips64le.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mips64le.go @@ -33,10 +33,12 @@ type utmp struct { Addr_v6 [4]int32 X__unused [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int32 Usec int32 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_mipsle.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mipsle.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_mipsle.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_mipsle.go index b0fca0939..50207e5bc 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_mipsle.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_mipsle.go @@ -33,10 +33,12 @@ type utmp struct { Addr_v6 [4]int32 X__unused [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int32 Usec int32 diff --git a/vendor/github.com/shirou/gopsutil/v3/host/host_linux_ppc64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_ppc64.go new file mode 100644 index 000000000..5b324effa --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_ppc64.go @@ -0,0 +1,48 @@ +//go:build linux && ppc64 +// +build linux,ppc64 + +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs types_linux.go + +package host + +const ( + sizeofPtr = 0x8 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x8 + sizeofLongLong = 0x8 + sizeOfUtmp = 0x180 +) + +type ( + _C_short int16 + _C_int int32 + _C_long int64 + _C_long_long int64 +) + +type utmp struct { + Type int16 + Pad_cgo_0 [2]byte + Pid int32 + Line [32]int8 + Id [4]int8 + User [32]int8 + Host [256]int8 + Exit exit_status + Session int32 + Tv timeval + Addr_v6 [4]int32 + X__glibc_reserved [20]int8 +} + +type exit_status struct { + Termination int16 + Exit int16 +} + +type timeval struct { + Sec int64 + Usec int64 +} diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_ppc64le.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_ppc64le.go similarity index 93% rename from vendor/github.com/shirou/gopsutil/host/host_linux_ppc64le.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_ppc64le.go index d081a0819..51f5bee11 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_ppc64le.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_ppc64le.go @@ -1,5 +1,6 @@ -// +build linux -// +build ppc64le +//go:build linux && ppc64le +// +build linux,ppc64le + // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.go @@ -35,10 +36,12 @@ type utmp struct { Addr_v6 [4]int32 X__glibc_reserved [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int64 Usec int64 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_riscv64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_riscv64.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_linux_riscv64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_riscv64.go index 79a077d66..bb03a0b39 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_riscv64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_riscv64.go @@ -32,10 +32,12 @@ type utmp struct { Addr_v6 [4]int32 X__glibc_reserved [20]uint8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int64 Usec int64 diff --git a/vendor/github.com/shirou/gopsutil/host/host_linux_s390x.go b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_s390x.go similarity index 93% rename from vendor/github.com/shirou/gopsutil/host/host_linux_s390x.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_linux_s390x.go index 083fbf924..6ea432a61 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_linux_s390x.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_linux_s390x.go @@ -1,5 +1,6 @@ -// +build linux -// +build s390x +//go:build linux && s390x +// +build linux,s390x + // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.go @@ -35,10 +36,12 @@ type utmp struct { Addr_v6 [4]int32 X__glibc_reserved [20]int8 } + type exit_status struct { Termination int16 Exit int16 } + type timeval struct { Sec int64 Usec int64 diff --git a/vendor/github.com/shirou/gopsutil/host/host_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd.go similarity index 95% rename from vendor/github.com/shirou/gopsutil/host/host_openbsd.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_openbsd.go index 4b9b04b82..569de4abd 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package host @@ -11,8 +12,8 @@ import ( "strings" "unsafe" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/process" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/process" "golang.org/x/sys/unix" ) diff --git a/vendor/github.com/shirou/gopsutil/host/host_openbsd_386.go b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_386.go similarity index 90% rename from vendor/github.com/shirou/gopsutil/host/host_openbsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_386.go index af0d855d3..b299d7ae4 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_openbsd_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_386.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build 386 +//go:build openbsd && 386 +// +build openbsd,386 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs host/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/host/host_openbsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_amd64.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/host/host_openbsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_amd64.go index afe0943e7..2d23b9b71 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_openbsd_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_amd64.go @@ -25,6 +25,7 @@ type Utmp struct { Host [256]int8 Time int64 } + type Timeval struct { Sec int64 Usec int64 diff --git a/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_arm.go new file mode 100644 index 000000000..f0ac57d0b --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_arm.go @@ -0,0 +1,34 @@ +//go:build openbsd && arm +// +build openbsd,arm + +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs host/types_openbsd.go + +package host + +const ( + sizeofPtr = 0x4 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x4 + sizeofLongLong = 0x8 + sizeOfUtmp = 0x130 +) + +type ( + _C_short int16 + _C_int int32 + _C_long int32 + _C_long_long int64 +) + +type Utmp struct { + Line [8]int8 + Name [32]int8 + Host [256]int8 + Time int64 +} +type Timeval struct { + Sec int64 + Usec int32 +} diff --git a/vendor/github.com/shirou/gopsutil/host/host_openbsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_arm64.go similarity index 89% rename from vendor/github.com/shirou/gopsutil/host/host_openbsd_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_arm64.go index 3efc44ecf..20fb42dd7 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_openbsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_openbsd_arm64.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build arm64 +//go:build openbsd && arm64 +// +build openbsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs host/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/v3/host/host_posix.go b/vendor/github.com/shirou/gopsutil/v3/host/host_posix.go new file mode 100644 index 000000000..24529f19f --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_posix.go @@ -0,0 +1,15 @@ +//go:build linux || freebsd || openbsd || darwin || solaris +// +build linux freebsd openbsd darwin solaris + +package host + +import "golang.org/x/sys/unix" + +func KernelArch() (string, error) { + var utsname unix.Utsname + err := unix.Uname(&utsname) + if err != nil { + return "", err + } + return unix.ByteSliceToString(utsname.Machine[:]), nil +} diff --git a/vendor/github.com/shirou/gopsutil/host/host_solaris.go b/vendor/github.com/shirou/gopsutil/v3/host/host_solaris.go similarity index 70% rename from vendor/github.com/shirou/gopsutil/host/host_solaris.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_solaris.go index 9180db5a6..7d3625acb 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_solaris.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_solaris.go @@ -4,15 +4,16 @@ import ( "bufio" "bytes" "context" + "encoding/csv" "fmt" + "io" "io/ioutil" "os" - "os/exec" "regexp" "strconv" "strings" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func HostIDWithContext(ctx context.Context) (string, error) { @@ -23,23 +24,20 @@ func HostIDWithContext(ctx context.Context) (string, error) { if platform == "SmartOS" { // If everything works, use the current zone ID as the HostID if present. - zonename, err := exec.LookPath("zonename") + out, err := invoke.CommandWithContext(ctx, "zonename") if err == nil { - out, err := invoke.CommandWithContext(ctx, zonename) - if err == nil { - sc := bufio.NewScanner(bytes.NewReader(out)) - for sc.Scan() { - line := sc.Text() - - // If we're in the global zone, rely on the hostname. - if line == "global" { - hostname, err := os.Hostname() - if err == nil { - return hostname, nil - } - } else { - return strings.TrimSpace(line), nil + sc := bufio.NewScanner(bytes.NewReader(out)) + for sc.Scan() { + line := sc.Text() + + // If we're in the global zone, rely on the hostname. + if line == "global" { + hostname, err := os.Hostname() + if err == nil { + return hostname, nil } + } else { + return strings.TrimSpace(line), nil } } } @@ -48,15 +46,12 @@ func HostIDWithContext(ctx context.Context) (string, error) { // If HostID is still unknown, use hostid(1), which can lie to callers but at // this point there are no hardware facilities available. This behavior // matches that of other supported OSes. - hostID, err := exec.LookPath("hostid") + out, err := invoke.CommandWithContext(ctx, "hostid") if err == nil { - out, err := invoke.CommandWithContext(ctx, hostID) - if err == nil { - sc := bufio.NewScanner(bytes.NewReader(out)) - for sc.Scan() { - line := sc.Text() - return strings.TrimSpace(line), nil - } + sc := bufio.NewScanner(bytes.NewReader(out)) + for sc.Scan() { + line := sc.Text() + return strings.TrimSpace(line), nil } } @@ -75,12 +70,7 @@ func numProcs(ctx context.Context) (uint64, error) { var kstatMatch = regexp.MustCompile(`([^\s]+)[\s]+([^\s]*)`) func BootTimeWithContext(ctx context.Context) (uint64, error) { - kstat, err := exec.LookPath("kstat") - if err != nil { - return 0, err - } - - out, err := invoke.CommandWithContext(ctx, kstat, "-p", "unix:0:system_misc:boot_time") + out, err := invoke.CommandWithContext(ctx, "kstat", "-p", "unix:0:system_misc:boot_time") if err != nil { return 0, err } @@ -106,7 +96,40 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) { } func SensorsTemperaturesWithContext(ctx context.Context) ([]TemperatureStat, error) { - return []TemperatureStat{}, common.ErrNotImplementedError + var ret []TemperatureStat + + out, err := invoke.CommandWithContext(ctx, "ipmitool", "-c", "sdr", "list") + if err != nil { + return ret, err + } + + r := csv.NewReader(strings.NewReader(string(out))) + // Output may contain errors, e.g. "bmc_send_cmd: Permission denied", don't expect a consistent number of records + r.FieldsPerRecord = -1 + for { + record, err := r.Read() + if err == io.EOF { + break + } + if err != nil { + return ret, err + } + // CPU1 Temp,40,degrees C,ok + if len(record) < 3 || record[1] == "" || record[2] != "degrees C" { + continue + } + v, err := strconv.ParseFloat(record[1], 64) + if err != nil { + return ret, err + } + ts := TemperatureStat{ + SensorKey: strings.TrimSuffix(record[0], " Temp"), + Temperature: v, + } + ret = append(ret, ts) + } + + return ret, nil } func VirtualizationWithContext(ctx context.Context) (string, string, error) { @@ -146,12 +169,7 @@ func parseReleaseFile() (string, error) { // parseUnameOutput returns platformFamily, kernelVersion and platformVersion func parseUnameOutput(ctx context.Context) (string, string, string, error) { - uname, err := exec.LookPath("uname") - if err != nil { - return "", "", "", err - } - - out, err := invoke.CommandWithContext(ctx, uname, "-srv") + out, err := invoke.CommandWithContext(ctx, "uname", "-srv") if err != nil { return "", "", "", err } diff --git a/vendor/github.com/shirou/gopsutil/host/host_windows.go b/vendor/github.com/shirou/gopsutil/v3/host/host_windows.go similarity index 90% rename from vendor/github.com/shirou/gopsutil/host/host_windows.go rename to vendor/github.com/shirou/gopsutil/v3/host/host_windows.go index 5873d6a1a..1fe0551b3 100644 --- a/vendor/github.com/shirou/gopsutil/host/host_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/host/host_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package host @@ -13,8 +14,8 @@ import ( "time" "unsafe" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/process" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/process" "github.com/yusufpapurcu/wmi" "golang.org/x/sys/windows" ) @@ -102,6 +103,14 @@ func numProcs(ctx context.Context) (uint64, error) { } func UptimeWithContext(ctx context.Context) (uint64, error) { + up, err := uptimeMillis() + if err != nil { + return 0, err + } + return uint64((time.Duration(up) * time.Millisecond).Seconds()), nil +} + +func uptimeMillis() (uint64, error) { procGetTickCount := procGetTickCount64 err := procGetTickCount64.Find() if err != nil { @@ -111,7 +120,7 @@ func UptimeWithContext(ctx context.Context) (uint64, error) { if lastErr != 0 { return 0, lastErr } - return uint64((time.Duration(r1) * time.Millisecond).Seconds()), nil + return uint64(r1), nil } // cachedBootTime must be accessed via atomic.Load/StoreUint64 @@ -122,11 +131,11 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) { if t != 0 { return t, nil } - up, err := Uptime() + up, err := uptimeMillis() if err != nil { return 0, err } - t = timeSince(up) + t = uint64((time.Duration(timeSinceMillis(up)) * time.Millisecond).Seconds()) atomic.StoreUint64(&cachedBootTime, t) return t, nil } @@ -187,6 +196,14 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil } } + var UBR uint32 // Update Build Revision + err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`UBR`), nil, &valType, nil, &bufLen) + if err == nil { + regBuf := make([]byte, 4) + err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`UBR`), nil, &valType, (*byte)(unsafe.Pointer(®Buf[0])), &bufLen) + copy((*[4]byte)(unsafe.Pointer(&UBR))[:], regBuf) + } + // PlatformFamily switch osInfo.wProductType { case 1: @@ -198,7 +215,9 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil } // Platform Version - version = fmt.Sprintf("%d.%d.%d Build %d", osInfo.dwMajorVersion, osInfo.dwMinorVersion, osInfo.dwBuildNumber, osInfo.dwBuildNumber) + version = fmt.Sprintf("%d.%d.%d.%d Build %d.%d", + osInfo.dwMajorVersion, osInfo.dwMinorVersion, osInfo.dwBuildNumber, UBR, + osInfo.dwBuildNumber, UBR) return platform, family, version, nil } diff --git a/vendor/github.com/shirou/gopsutil/host/smc_darwin.c b/vendor/github.com/shirou/gopsutil/v3/host/smc_darwin.c similarity index 93% rename from vendor/github.com/shirou/gopsutil/host/smc_darwin.c rename to vendor/github.com/shirou/gopsutil/v3/host/smc_darwin.c index aedea8be9..0197d95b4 100644 --- a/vendor/github.com/shirou/gopsutil/host/smc_darwin.c +++ b/vendor/github.com/shirou/gopsutil/v3/host/smc_darwin.c @@ -68,12 +68,11 @@ typedef struct { static const int SMC_KEY_SIZE = 4; // number of characters in an SMC key. static io_connect_t conn; // our connection to the SMC. -kern_return_t open_smc(void) { +kern_return_t gopsutil_v3_open_smc(void) { kern_return_t result; io_service_t service; - service = IOServiceGetMatchingService(kIOMasterPortDefault, - IOServiceMatching(IOSERVICE_SMC)); + service = IOServiceGetMatchingService(0, IOServiceMatching(IOSERVICE_SMC)); if (service == 0) { // Note: IOServiceMatching documents 0 on failure printf("ERROR: %s NOT FOUND\n", IOSERVICE_SMC); @@ -86,7 +85,7 @@ kern_return_t open_smc(void) { return result; } -kern_return_t close_smc(void) { return IOServiceClose(conn); } +kern_return_t gopsutil_v3_close_smc(void) { return IOServiceClose(conn); } static uint32_t to_uint32(char *key) { uint32_t ans = 0; @@ -155,7 +154,7 @@ static kern_return_t read_smc(char *key, smc_return_t *result_smc) { return result; } -double get_temperature(char *key) { +double gopsutil_v3_get_temperature(char *key) { kern_return_t result; smc_return_t result_smc; diff --git a/vendor/github.com/shirou/gopsutil/host/smc_darwin.h b/vendor/github.com/shirou/gopsutil/v3/host/smc_darwin.h similarity index 87% rename from vendor/github.com/shirou/gopsutil/host/smc_darwin.h rename to vendor/github.com/shirou/gopsutil/v3/host/smc_darwin.h index ab51ed9f7..e3013abdb 100644 --- a/vendor/github.com/shirou/gopsutil/host/smc_darwin.h +++ b/vendor/github.com/shirou/gopsutil/v3/host/smc_darwin.h @@ -25,8 +25,8 @@ #define THUNDERBOLT_1 "TI1P" #define WIRELESS_MODULE "TW0P" -kern_return_t open_smc(void); -kern_return_t close_smc(void); -double get_temperature(char *); +kern_return_t gopsutil_v3_open_smc(void); +kern_return_t gopsutil_v3_close_smc(void); +double gopsutil_v3_get_temperature(char *); #endif // __SMC_H__ diff --git a/vendor/github.com/shirou/gopsutil/internal/common/binary.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/binary.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/internal/common/binary.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/binary.go index bf385fd4f..5e8d43db8 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/binary.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/binary.go @@ -21,6 +21,7 @@ package common // high-performance serialization, especially for large data structures, // should look at more advanced solutions such as the encoding/gob // package or protocol buffers. + import ( "errors" "io" @@ -253,7 +254,7 @@ func Write(w io.Writer, order ByteOrder, data interface{}) error { b[0] = *v case uint8: bs = b[:1] - b[0] = v + b[0] = byte(v) case []uint8: bs = v case *int16: @@ -388,8 +389,10 @@ type coder struct { buf []byte } -type decoder coder -type encoder coder +type ( + decoder coder + encoder coder +) func (d *decoder) uint8() uint8 { x := d.buf[0] diff --git a/vendor/github.com/shirou/gopsutil/internal/common/common.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common.go similarity index 70% rename from vendor/github.com/shirou/gopsutil/internal/common/common.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/common.go index 63462885e..7a31d251b 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/common.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common.go @@ -6,12 +6,14 @@ package common // - linux (amd64, arm) // - freebsd (amd64) // - windows (amd64) + import ( "bufio" "bytes" "context" "errors" "fmt" + "io" "io/ioutil" "net/url" "os" @@ -23,6 +25,8 @@ import ( "strconv" "strings" "time" + + "github.com/shirou/gopsutil/v3/common" ) var ( @@ -63,7 +67,7 @@ func (i Invoke) CommandWithContext(ctx context.Context, name string, arg ...stri type FakeInvoke struct { Suffix string // Suffix species expected file name suffix such as "fail" - Error error // If Error specfied, return the error. + Error error // If Error specified, return the error. } // Command in FakeInvoke returns from expected file if exists. @@ -94,10 +98,9 @@ func (i FakeInvoke) CommandWithContext(ctx context.Context, name string, arg ... var ErrNotImplementedError = errors.New("not implemented yet") -// ReadFile reads contents from a file. +// ReadFile reads contents from a file func ReadFile(filename string) (string, error) { content, err := ioutil.ReadFile(filename) - if err != nil { return "", err } @@ -111,11 +114,35 @@ func ReadLines(filename string) ([]string, error) { return ReadLinesOffsetN(filename, 0, -1) } +// ReadLine reads a file and returns the first occurrence of a line that is prefixed with prefix. +func ReadLine(filename string, prefix string) (string, error) { + f, err := os.Open(filename) + if err != nil { + return "", err + } + defer f.Close() + r := bufio.NewReader(f) + for { + line, err := r.ReadString('\n') + if err != nil { + if err == io.EOF { + break + } + return "", err + } + if strings.HasPrefix(line, prefix) { + return line, nil + } + } + + return "", nil +} + // ReadLinesOffsetN reads contents from file and splits them by new line. // The offset tells at which line number to start. // The count determines the number of lines to read (starting from offset): -// n >= 0: at most n lines -// n < 0: whole file +// n >= 0: at most n lines +// n < 0: whole file func ReadLinesOffsetN(filename string, offset uint, n int) ([]string, error) { f, err := os.Open(filename) if err != nil { @@ -129,6 +156,9 @@ func ReadLinesOffsetN(filename string, offset uint, n int) ([]string, error) { for i := 0; i < n+int(offset) || n < 0; i++ { line, err := r.ReadString('\n') if err != nil { + if err == io.EOF && len(line) > 0 { + ret = append(ret, strings.Trim(line, "\n")) + } break } if i < int(offset) { @@ -165,7 +195,7 @@ func UintToString(orig []uint8) string { size = i break } - ret[i] = o + ret[i] = byte(o) } if size == -1 { size = len(orig) @@ -224,31 +254,31 @@ func ReadInts(filename string) ([]int64, error) { return ret, nil } -// HexToUint32 parses Hex to uint32 without error. +// Parse Hex to uint32 without error func HexToUint32(hex string) uint32 { vv, _ := strconv.ParseUint(hex, 16, 32) return uint32(vv) } -// mustParseInt32 parses to int32 without error. +// Parse to int32 without error func mustParseInt32(val string) int32 { vv, _ := strconv.ParseInt(val, 10, 32) return int32(vv) } -// mustParseUint64 parses to uint64 without error. +// Parse to uint64 without error func mustParseUint64(val string) uint64 { vv, _ := strconv.ParseInt(val, 10, 64) return uint64(vv) } -// mustParseFloat64 parses to Float64 without error. +// Parse to Float64 without error func mustParseFloat64(val string) float64 { vv, _ := strconv.ParseFloat(val, 64) return vv } -// StringsHas checks the target string slice contains src or not. +// StringsHas checks the target string slice contains src or not func StringsHas(target []string, src string) bool { for _, t := range target { if strings.TrimSpace(t) == src { @@ -258,7 +288,7 @@ func StringsHas(target []string, src string) bool { return false } -// StringsContains checks the src in any string of the target string slice. +// StringsContains checks the src in any string of the target string slice func StringsContains(target []string, src string) bool { for _, t := range target { if strings.Contains(t, src) { @@ -308,6 +338,32 @@ func PathExists(filename string) bool { return false } +// PathExistsWithContents returns the filename exists and it is not empty +func PathExistsWithContents(filename string) bool { + info, err := os.Stat(filename) + if err != nil { + return false + } + return info.Size() > 4 // at least 4 bytes +} + +// GetEnvWithContext retrieves the environment variable key. If it does not exist it returns the default. +// The context may optionally contain a map superseding os.EnvKey. +func GetEnvWithContext(ctx context.Context, key string, dfault string, combineWith ...string) string { + var value string + if env, ok := ctx.Value(common.EnvKey).(common.EnvMap); ok { + value = env[common.EnvKeyType(key)] + } + if value == "" { + value = os.Getenv(key) + } + if value == "" { + value = dfault + } + + return combine(value, combineWith) +} + // GetEnv retrieves the environment variable key. If it does not exist it returns the default. func GetEnv(key string, dfault string, combineWith ...string) string { value := os.Getenv(key) @@ -315,6 +371,10 @@ func GetEnv(key string, dfault string, combineWith ...string) string { value = dfault } + return combine(value, combineWith) +} + +func combine(value string, combineWith []string) string { switch len(combineWith) { case 0: return value @@ -352,14 +412,40 @@ func HostDev(combineWith ...string) string { return GetEnv("HOST_DEV", "/dev", combineWith...) } -// MockEnv set environment variable and return revert function. -// MockEnv should be used testing only. -func MockEnv(key string, value string) func() { - original := os.Getenv(key) - os.Setenv(key, value) - return func() { - os.Setenv(key, original) - } +func HostRoot(combineWith ...string) string { + return GetEnv("HOST_ROOT", "/", combineWith...) +} + +func HostProcWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_PROC", "/proc", combineWith...) +} + +func HostProcMountInfoWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_PROC_MOUNTINFO", "", combineWith...) +} + +func HostSysWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_SYS", "/sys", combineWith...) +} + +func HostEtcWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_ETC", "/etc", combineWith...) +} + +func HostVarWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_VAR", "/var", combineWith...) +} + +func HostRunWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_RUN", "/run", combineWith...) +} + +func HostDevWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_DEV", "/dev", combineWith...) +} + +func HostRootWithContext(ctx context.Context, combineWith ...string) string { + return GetEnvWithContext(ctx, "HOST_ROOT", "/", combineWith...) } // getSysctrlEnv sets LC_ALL=C in a list of env vars for use when running diff --git a/vendor/github.com/shirou/gopsutil/internal/common/common_darwin.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_darwin.go similarity index 91% rename from vendor/github.com/shirou/gopsutil/internal/common/common_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/common_darwin.go index be46af3d9..f1a784597 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/common_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package common @@ -13,11 +14,7 @@ import ( ) func DoSysctrlWithContext(ctx context.Context, mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.CommandContext(ctx, sysctl, "-n", mib) + cmd := exec.CommandContext(ctx, "sysctl", "-n", mib) cmd.Env = getSysctrlEnv(os.Environ()) out, err := cmd.Output() if err != nil { diff --git a/vendor/github.com/shirou/gopsutil/internal/common/common_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_freebsd.go similarity index 92% rename from vendor/github.com/shirou/gopsutil/internal/common/common_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/common_freebsd.go index 85bda0e22..f590e2e67 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/common_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd || openbsd // +build freebsd openbsd package common @@ -28,11 +29,7 @@ func SysctlUint(mib string) (uint64, error) { } func DoSysctrl(mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.Command(sysctl, "-n", mib) + cmd := exec.Command("sysctl", "-n", mib) cmd.Env = getSysctrlEnv(os.Environ()) out, err := cmd.Output() if err != nil { diff --git a/vendor/github.com/shirou/gopsutil/internal/common/common_linux.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_linux.go similarity index 62% rename from vendor/github.com/shirou/gopsutil/internal/common/common_linux.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/common_linux.go index ca01c7557..a644687ba 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/common_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package common @@ -11,29 +12,30 @@ import ( "strconv" "strings" "sync" + "syscall" "time" ) func DoSysctrl(mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.Command(sysctl, "-n", mib) + cmd := exec.Command("sysctl", "-n", mib) cmd.Env = getSysctrlEnv(os.Environ()) out, err := cmd.Output() if err != nil { return []string{}, err } v := strings.Replace(string(out), "{ ", "", 1) - v = strings.Replace(v, " }", "", 1) - values := strings.Fields(v) + v = strings.Replace(string(v), " }", "", 1) + values := strings.Fields(string(v)) return values, nil } func NumProcs() (uint64, error) { - f, err := os.Open(HostProc()) + return NumProcsWithContext(context.Background()) +} + +func NumProcsWithContext(ctx context.Context) (uint64, error) { + f, err := os.Open(HostProcWithContext(ctx)) if err != nil { return 0, err } @@ -55,55 +57,75 @@ func NumProcs() (uint64, error) { } func BootTimeWithContext(ctx context.Context) (uint64, error) { - system, role, err := Virtualization() + system, role, err := VirtualizationWithContext(ctx) if err != nil { return 0, err } - statFile := "stat" + useStatFile := true if system == "lxc" && role == "guest" { // if lxc, /proc/uptime is used. - statFile = "uptime" + useStatFile = false } else if system == "docker" && role == "guest" { // also docker, guest - statFile = "uptime" + useStatFile = false } - filename := HostProc(statFile) + if useStatFile { + return readBootTimeStat(ctx) + } + + filename := HostProcWithContext(ctx, "uptime") lines, err := ReadLines(filename) + if err != nil { + return handleBootTimeFileReadErr(err) + } + if len(lines) != 1 { + return 0, fmt.Errorf("wrong uptime format") + } + f := strings.Fields(lines[0]) + b, err := strconv.ParseFloat(f[0], 64) if err != nil { return 0, err } + currentTime := float64(time.Now().UnixNano()) / float64(time.Second) + t := currentTime - b + return uint64(t), nil +} - if statFile == "uptime" { - if len(lines) != 1 { - return 0, fmt.Errorf("wrong uptime format") - } - f := strings.Fields(lines[0]) - b, err := strconv.ParseFloat(f[0], 64) +func handleBootTimeFileReadErr(err error) (uint64, error) { + if os.IsPermission(err) { + var info syscall.Sysinfo_t + err := syscall.Sysinfo(&info) if err != nil { return 0, err } - t := uint64(time.Now().Unix()) - uint64(b) - return t, nil + + currentTime := time.Now().UnixNano() / int64(time.Second) + t := currentTime - int64(info.Uptime) + return uint64(t), nil } - if statFile == "stat" { - for _, line := range lines { - if strings.HasPrefix(line, "btime") { - f := strings.Fields(line) - if len(f) != 2 { - return 0, fmt.Errorf("wrong btime format") - } - b, err := strconv.ParseInt(f[1], 10, 64) - if err != nil { - return 0, err - } - t := uint64(b) - return t, nil - } + return 0, err +} + +func readBootTimeStat(ctx context.Context) (uint64, error) { + filename := HostProcWithContext(ctx, "stat") + line, err := ReadLine(filename, "btime") + if err != nil { + return handleBootTimeFileReadErr(err) + } + if strings.HasPrefix(line, "btime") { + f := strings.Fields(line) + if len(f) != 2 { + return 0, fmt.Errorf("wrong btime format") + } + b, err := strconv.ParseInt(f[1], 10, 64) + if err != nil { + return 0, err } + t := uint64(b) + return t, nil } - return 0, fmt.Errorf("could not find btime") } @@ -111,7 +133,7 @@ func Virtualization() (string, string, error) { return VirtualizationWithContext(context.Background()) } -// required variables for concurrency safe virtualization caching. +// required variables for concurrency safe virtualization caching var ( cachedVirtMap map[string]string cachedVirtMutex sync.RWMutex @@ -130,41 +152,45 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) { } cachedVirtMutex.RUnlock() - filename := HostProc("xen") + filename := HostProcWithContext(ctx, "xen") if PathExists(filename) { system = "xen" role = "guest" // assume guest if PathExists(filepath.Join(filename, "capabilities")) { contents, err := ReadLines(filepath.Join(filename, "capabilities")) - if err == nil && StringsContains(contents, "control_d") { - role = "host" + if err == nil { + if StringsContains(contents, "control_d") { + role = "host" + } } } } - filename = HostProc("modules") + filename = HostProcWithContext(ctx, "modules") if PathExists(filename) { contents, err := ReadLines(filename) if err == nil { - switch { - case StringsContains(contents, "kvm"): + if StringsContains(contents, "kvm") { system = "kvm" role = "host" - case StringsContains(contents, "vboxdrv"): + } else if StringsContains(contents, "hv_util") { + system = "hyperv" + role = "guest" + } else if StringsContains(contents, "vboxdrv") { system = "vbox" role = "host" - case StringsContains(contents, "vboxguest"): + } else if StringsContains(contents, "vboxguest") { system = "vbox" role = "guest" - case StringsContains(contents, "vmware"): + } else if StringsContains(contents, "vmware") { system = "vmware" role = "guest" } } } - filename = HostProc("cpuinfo") + filename = HostProcWithContext(ctx, "cpuinfo") if PathExists(filename) { contents, err := ReadLines(filename) if err == nil { @@ -177,7 +203,7 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) { } } - filename = HostProc("bus/pci/devices") + filename = HostProcWithContext(ctx, "bus/pci/devices") if PathExists(filename) { contents, err := ReadLines(filename) if err == nil { @@ -187,7 +213,7 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) { } } - filename = HostProc() + filename = HostProcWithContext(ctx) if PathExists(filepath.Join(filename, "bc", "0")) { system = "openvz" role = "host" @@ -222,31 +248,35 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) { if PathExists(filepath.Join(filename, "self", "cgroup")) { contents, err := ReadLines(filepath.Join(filename, "self", "cgroup")) if err == nil { - switch { - case StringsContains(contents, "lxc"): + if StringsContains(contents, "lxc") { system = "lxc" role = "guest" - case StringsContains(contents, "docker"): + } else if StringsContains(contents, "docker") { system = "docker" role = "guest" - case StringsContains(contents, "machine-rkt"): + } else if StringsContains(contents, "machine-rkt") { system = "rkt" role = "guest" - case PathExists("/usr/bin/lxc-version"): + } else if PathExists("/usr/bin/lxc-version") { system = "lxc" role = "host" } } } - if PathExists(HostEtc("os-release")) { - p, _, err := GetOSRelease() + if PathExists(HostEtcWithContext(ctx, "os-release")) { + p, _, err := GetOSReleaseWithContext(ctx) if err == nil && p == "coreos" { system = "rkt" // Is it true? role = "host" } } + if PathExists(HostRootWithContext(ctx, ".dockerenv")) { + system = "docker" + role = "guest" + } + // before returning for the first time, cache the system and role cachedVirtOnce.Do(func() { cachedVirtMutex.Lock() @@ -261,7 +291,11 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) { } func GetOSRelease() (platform string, version string, err error) { - contents, err := ReadLines(HostEtc("os-release")) + return GetOSReleaseWithContext(context.Background()) +} + +func GetOSReleaseWithContext(ctx context.Context) (platform string, version string, err error) { + contents, err := ReadLines(HostEtcWithContext(ctx, "os-release")) if err != nil { return "", "", nil // return empty } @@ -277,10 +311,16 @@ func GetOSRelease() (platform string, version string, err error) { version = trimQuotes(field[1]) } } + + // cleanup amazon ID + if platform == "amzn" { + platform = "amazon" + } + return platform, version, nil } -// trimQuotes removes quotes in the source string. +// Remove quotes of the source string func trimQuotes(s string) string { if len(s) >= 2 { if s[0] == '"' && s[len(s)-1] == '"' { diff --git a/vendor/github.com/shirou/gopsutil/internal/common/common_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_openbsd.go similarity index 90% rename from vendor/github.com/shirou/gopsutil/internal/common/common_openbsd.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/common_openbsd.go index ba73a7eb5..58d76f334 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/common_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package common @@ -12,11 +13,7 @@ import ( ) func DoSysctrl(mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.Command(sysctl, "-n", mib) + cmd := exec.Command("sysctl", "-n", mib) cmd.Env = getSysctrlEnv(os.Environ()) out, err := cmd.Output() if err != nil { diff --git a/vendor/github.com/shirou/gopsutil/internal/common/common_unix.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_unix.go similarity index 75% rename from vendor/github.com/shirou/gopsutil/internal/common/common_unix.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/common_unix.go index 605202815..4af7e5c2a 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/common_unix.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_unix.go @@ -1,9 +1,11 @@ +//go:build linux || freebsd || darwin || openbsd // +build linux freebsd darwin openbsd package common import ( "context" + "errors" "os/exec" "strconv" "strings" @@ -17,12 +19,11 @@ func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args .. cmd = []string{"-a", "-n", "-P", "-p", strconv.Itoa(int(pid))} } cmd = append(cmd, args...) - lsof, err := exec.LookPath("lsof") - if err != nil { - return []string{}, err - } - out, err := invoke.CommandWithContext(ctx, lsof, cmd...) + out, err := invoke.CommandWithContext(ctx, "lsof", cmd...) if err != nil { + if errors.Is(err, exec.ErrNotFound) { + return []string{}, err + } // if no pid found, lsof returns code 1. if err.Error() == "exit status 1" && len(out) == 0 { return []string{}, nil @@ -41,12 +42,7 @@ func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args .. } func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) { - cmd := []string{"-P", strconv.Itoa(int(pid))} - pgrep, err := exec.LookPath("pgrep") - if err != nil { - return []int32{}, err - } - out, err := invoke.CommandWithContext(ctx, pgrep, cmd...) + out, err := invoke.CommandWithContext(ctx, "pgrep", "-P", strconv.Itoa(int(pid))) if err != nil { return []int32{}, err } @@ -56,7 +52,7 @@ func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int if len(l) == 0 { continue } - i, err := strconv.Atoi(l) + i, err := strconv.ParseInt(l, 10, 32) if err != nil { continue } diff --git a/vendor/github.com/shirou/gopsutil/internal/common/common_windows.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_windows.go similarity index 98% rename from vendor/github.com/shirou/gopsutil/internal/common/common_windows.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/common_windows.go index ba20136da..301b2315b 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/common_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package common @@ -162,7 +163,7 @@ func NewWin32PerformanceCounter(postName, counterName string) (*Win32Performance if err != nil { return nil, err } - var counter = Win32PerformanceCounter{ + counter := Win32PerformanceCounter{ Query: query, PostName: postName, CounterName: counterName, @@ -217,9 +218,12 @@ func WMIQueryWithContext(ctx context.Context, query string, dst interface{}, con } // Convert paths using native DOS format like: -// "\Device\HarddiskVolume1\Windows\systemew\file.txt" +// +// "\Device\HarddiskVolume1\Windows\systemew\file.txt" +// // into: -// "C:\Windows\systemew\file.txt" +// +// "C:\Windows\systemew\file.txt" func ConvertDOSPath(p string) string { rawDrive := strings.Join(strings.Split(p, `\`)[:3], `\`) diff --git a/vendor/github.com/shirou/gopsutil/v3/internal/common/endian.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/endian.go new file mode 100644 index 000000000..147cfdc4b --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/endian.go @@ -0,0 +1,10 @@ +package common + +import "unsafe" + +// IsLittleEndian checks if the current platform uses little-endian. +// copied from https://github.com/ntrrg/ntgo/blob/v0.8.0/runtime/infrastructure.go#L16 (MIT License) +func IsLittleEndian() bool { + var x int16 = 0x0011 + return *(*byte)(unsafe.Pointer(&x)) == 0x11 +} diff --git a/vendor/github.com/shirou/gopsutil/internal/common/sleep.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/sleep.go similarity index 79% rename from vendor/github.com/shirou/gopsutil/internal/common/sleep.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/sleep.go index ee27e54d4..9bed2419e 100644 --- a/vendor/github.com/shirou/gopsutil/internal/common/sleep.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/sleep.go @@ -8,9 +8,12 @@ import ( // Sleep awaits for provided interval. // Can be interrupted by context cancelation. func Sleep(ctx context.Context, interval time.Duration) error { - var timer = time.NewTimer(interval) + timer := time.NewTimer(interval) select { case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } return ctx.Err() case <-timer.C: return nil diff --git a/vendor/github.com/shirou/gopsutil/host/types.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/warnings.go similarity index 57% rename from vendor/github.com/shirou/gopsutil/host/types.go rename to vendor/github.com/shirou/gopsutil/v3/internal/common/warnings.go index 1eff4755e..a4aaadaf5 100644 --- a/vendor/github.com/shirou/gopsutil/host/types.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/warnings.go @@ -1,11 +1,10 @@ -package host +package common -import ( - "fmt" -) +import "fmt" type Warnings struct { - List []error + List []error + Verbose bool } func (w *Warnings) Add(err error) { @@ -15,11 +14,17 @@ func (w *Warnings) Add(err error) { func (w *Warnings) Reference() error { if len(w.List) > 0 { return w - } else { - return nil } + return nil } func (w *Warnings) Error() string { + if w.Verbose { + str := "" + for i, e := range w.List { + str += fmt.Sprintf("\tError %d: %s\n", i, e.Error()) + } + return str + } return fmt.Sprintf("Number of warnings: %v", len(w.List)) } diff --git a/vendor/github.com/shirou/gopsutil/load/load.go b/vendor/github.com/shirou/gopsutil/v3/load/load.go similarity index 92% rename from vendor/github.com/shirou/gopsutil/load/load.go rename to vendor/github.com/shirou/gopsutil/v3/load/load.go index a4926c21b..0da50904e 100644 --- a/vendor/github.com/shirou/gopsutil/load/load.go +++ b/vendor/github.com/shirou/gopsutil/v3/load/load.go @@ -3,7 +3,7 @@ package load import ( "encoding/json" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) var invoke common.Invoker = common.Invoke{} diff --git a/vendor/github.com/shirou/gopsutil/v3/load/load_aix.go b/vendor/github.com/shirou/gopsutil/v3/load/load_aix.go new file mode 100644 index 000000000..78b391280 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_aix.go @@ -0,0 +1,19 @@ +//go:build aix +// +build aix + +package load + +import ( + "context" +) + +func Avg() (*AvgStat, error) { + return AvgWithContext(context.Background()) +} + +// Misc returns miscellaneous host-wide statistics. +// darwin use ps command to get process running/blocked count. +// Almost same as Darwin implementation, but state is different. +func Misc() (*MiscStat, error) { + return MiscWithContext(context.Background()) +} diff --git a/vendor/github.com/shirou/gopsutil/v3/load/load_aix_cgo.go b/vendor/github.com/shirou/gopsutil/v3/load/load_aix_cgo.go new file mode 100644 index 000000000..bbbf287e2 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_aix_cgo.go @@ -0,0 +1,60 @@ +//go:build aix && cgo +// +build aix,cgo + +package load + +/* +#cgo LDFLAGS: -L/usr/lib -lperfstat + +#include +#include +*/ +import "C" + +import ( + "context" + "unsafe" + + "github.com/power-devops/perfstat" +) + +func AvgWithContext(ctx context.Context) (*AvgStat, error) { + c, err := perfstat.CpuTotalStat() + if err != nil { + return nil, err + } + ret := &AvgStat{ + Load1: float64(c.LoadAvg1), + Load5: float64(c.LoadAvg5), + Load15: float64(c.LoadAvg15), + } + + return ret, nil +} + +func MiscWithContext(ctx context.Context) (*MiscStat, error) { + info := C.struct_procentry64{} + cpid := C.pid_t(0) + + ret := MiscStat{} + for { + // getprocs first argument is a void* + num, err := C.getprocs64(unsafe.Pointer(&info), C.sizeof_struct_procentry64, nil, 0, &cpid, 1) + if err != nil { + return nil, err + } + + ret.ProcsTotal++ + switch info.pi_state { + case C.SACTIVE: + ret.ProcsRunning++ + case C.SSTOP: + ret.ProcsBlocked++ + } + + if num == 0 { + break + } + } + return &ret, nil +} diff --git a/vendor/github.com/shirou/gopsutil/v3/load/load_aix_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/load/load_aix_nocgo.go new file mode 100644 index 000000000..25d50ac18 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_aix_nocgo.go @@ -0,0 +1,66 @@ +//go:build aix && !cgo +// +build aix,!cgo + +package load + +import ( + "context" + "regexp" + "strconv" + "strings" + + "github.com/shirou/gopsutil/v3/internal/common" +) + +var separator = regexp.MustCompile(`,?\s+`) + +func AvgWithContext(ctx context.Context) (*AvgStat, error) { + line, err := invoke.CommandWithContext(ctx, "uptime") + if err != nil { + return nil, err + } + + idx := strings.Index(string(line), "load average:") + if idx < 0 { + return nil, common.ErrNotImplementedError + } + ret := &AvgStat{} + + p := separator.Split(string(line[idx:len(line)]), 5) + if 4 < len(p) && p[0] == "load" && p[1] == "average:" { + if t, err := strconv.ParseFloat(p[2], 64); err == nil { + ret.Load1 = t + } + if t, err := strconv.ParseFloat(p[3], 64); err == nil { + ret.Load5 = t + } + if t, err := strconv.ParseFloat(p[4], 64); err == nil { + ret.Load15 = t + } + return ret, nil + } + + return nil, common.ErrNotImplementedError +} + +func MiscWithContext(ctx context.Context) (*MiscStat, error) { + out, err := invoke.CommandWithContext(ctx, "ps", "-Ao", "state") + if err != nil { + return nil, err + } + + ret := &MiscStat{} + for _, line := range strings.Split(string(out), "\n") { + ret.ProcsTotal++ + switch line { + case "R": + case "A": + ret.ProcsRunning++ + case "T": + ret.ProcsBlocked++ + default: + continue + } + } + return ret, nil +} diff --git a/vendor/github.com/shirou/gopsutil/load/load_bsd.go b/vendor/github.com/shirou/gopsutil/v3/load/load_bsd.go similarity index 91% rename from vendor/github.com/shirou/gopsutil/load/load_bsd.go rename to vendor/github.com/shirou/gopsutil/v3/load/load_bsd.go index 9cb254a05..51d928682 100644 --- a/vendor/github.com/shirou/gopsutil/load/load_bsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_bsd.go @@ -1,10 +1,10 @@ +//go:build freebsd || openbsd // +build freebsd openbsd package load import ( "context" - "os/exec" "strings" "unsafe" @@ -51,11 +51,7 @@ func Misc() (*MiscStat, error) { } func MiscWithContext(ctx context.Context) (*MiscStat, error) { - bin, err := exec.LookPath("ps") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, bin, "axo", "state") + out, err := invoke.CommandWithContext(ctx, "ps", "axo", "state") if err != nil { return nil, err } diff --git a/vendor/github.com/shirou/gopsutil/load/load_darwin.go b/vendor/github.com/shirou/gopsutil/v3/load/load_darwin.go similarity index 87% rename from vendor/github.com/shirou/gopsutil/load/load_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/load/load_darwin.go index a205f2f8a..ce8018813 100644 --- a/vendor/github.com/shirou/gopsutil/load/load_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_darwin.go @@ -1,10 +1,10 @@ +//go:build darwin // +build darwin package load import ( "context" - "os/exec" "strings" "unsafe" @@ -38,7 +38,7 @@ func AvgWithContext(ctx context.Context) (*AvgStat, error) { return ret, nil } -// Misc returnes miscellaneous host-wide statistics. +// Misc returns miscellaneous host-wide statistics. // darwin use ps command to get process running/blocked count. // Almost same as FreeBSD implementation, but state is different. // U means 'Uninterruptible Sleep'. @@ -47,11 +47,7 @@ func Misc() (*MiscStat, error) { } func MiscWithContext(ctx context.Context) (*MiscStat, error) { - bin, err := exec.LookPath("ps") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, bin, "axo", "state") + out, err := invoke.CommandWithContext(ctx, "ps", "axo", "state") if err != nil { return nil, err } diff --git a/vendor/github.com/shirou/gopsutil/load/load_fallback.go b/vendor/github.com/shirou/gopsutil/v3/load/load_fallback.go similarity index 67% rename from vendor/github.com/shirou/gopsutil/load/load_fallback.go rename to vendor/github.com/shirou/gopsutil/v3/load/load_fallback.go index 4642b446f..3e41fd1ea 100644 --- a/vendor/github.com/shirou/gopsutil/load/load_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_fallback.go @@ -1,11 +1,12 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris +//go:build !darwin && !linux && !freebsd && !openbsd && !windows && !solaris && !aix +// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris,!aix package load import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func Avg() (*AvgStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/load/load_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/load/load_freebsd.go similarity index 83% rename from vendor/github.com/shirou/gopsutil/load/load_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/load/load_freebsd.go index bee8f554d..406980506 100644 --- a/vendor/github.com/shirou/gopsutil/load/load_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd // +build freebsd package load diff --git a/vendor/github.com/shirou/gopsutil/load/load_linux.go b/vendor/github.com/shirou/gopsutil/v3/load/load_linux.go similarity index 70% rename from vendor/github.com/shirou/gopsutil/load/load_linux.go rename to vendor/github.com/shirou/gopsutil/v3/load/load_linux.go index 08699f430..0298c8bed 100644 --- a/vendor/github.com/shirou/gopsutil/load/load_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/load/load_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package load @@ -9,7 +10,7 @@ import ( "strings" "syscall" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func Avg() (*AvgStat, error) { @@ -19,27 +20,28 @@ func Avg() (*AvgStat, error) { func AvgWithContext(ctx context.Context) (*AvgStat, error) { stat, err := fileAvgWithContext(ctx) if err != nil { - stat, err = sysinfoAvgWithContext(ctx) + stat, err = sysinfoAvgWithContext() } return stat, err } -func sysinfoAvgWithContext(ctx context.Context) (*AvgStat, error) { +func sysinfoAvgWithContext() (*AvgStat, error) { var info syscall.Sysinfo_t - if err := syscall.Sysinfo(&info); err != nil { + err := syscall.Sysinfo(&info) + if err != nil { return nil, err } - const siLoadShift = 16 + const si_load_shift = 16 return &AvgStat{ - Load1: float64(info.Loads[0]) / float64(1< 2 { + if t, err := strconv.ParseUint(p[1], 10, 64); err == nil { + vmem.Total = t * pagesize + } + if t, err := strconv.ParseUint(p[2], 10, 64); err == nil { + vmem.Used = t * pagesize + if vmem.Total > 0 { + vmem.UsedPercent = 100 * float64(vmem.Used) / float64(vmem.Total) + } + } + if t, err := strconv.ParseUint(p[3], 10, 64); err == nil { + vmem.Free = t * pagesize + } + } + } else if strings.HasPrefix(line, "pg space") { + p := whiteSpaces.Split(line, 4) + if len(p) > 3 { + if t, err := strconv.ParseUint(p[2], 10, 64); err == nil { + swap.Total = t * pagesize + } + if t, err := strconv.ParseUint(p[3], 10, 64); err == nil { + swap.Free = swap.Total - t*pagesize + } + } + break + } + } + return vmem, swap, nil +} diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_bsd.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_bsd.go similarity index 91% rename from vendor/github.com/shirou/gopsutil/mem/mem_bsd.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_bsd.go index 88db76209..ce930fbe4 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_bsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_bsd.go @@ -1,3 +1,4 @@ +//go:build freebsd || openbsd // +build freebsd openbsd package mem @@ -5,7 +6,6 @@ package mem import ( "context" "fmt" - "os/exec" "strconv" "strings" ) @@ -24,11 +24,7 @@ func SwapDevices() ([]*SwapDevice, error) { } func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - swapCommandPath, err := exec.LookPath(swapCommand) - if err != nil { - return nil, fmt.Errorf("could not find command %q: %w", swapCommand, err) - } - output, err := invoke.CommandWithContext(ctx, swapCommandPath, "-lk") + output, err := invoke.CommandWithContext(ctx, swapCommand, "-lk") if err != nil { return nil, fmt.Errorf("could not execute %q: %w", swapCommand, err) } diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_darwin.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin.go similarity index 95% rename from vendor/github.com/shirou/gopsutil/mem/mem_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin.go index 4b8f069d3..a05a0faba 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package mem @@ -7,8 +8,9 @@ import ( "fmt" "unsafe" - "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" ) func getHwMemsize() (uint64, error) { diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_cgo.go similarity index 93% rename from vendor/github.com/shirou/gopsutil/mem/mem_darwin_cgo.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_cgo.go index ade3cecd4..e5da7dcdb 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_darwin_cgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_cgo.go @@ -1,9 +1,11 @@ +//go:build darwin && cgo // +build darwin,cgo package mem /* #include +#include */ import "C" @@ -11,8 +13,6 @@ import ( "context" "fmt" "unsafe" - - "golang.org/x/sys/unix" ) // VirtualMemory returns VirtualmemoryStat. @@ -33,7 +33,7 @@ func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { return nil, fmt.Errorf("host_statistics error=%d", status) } - pageSize := uint64(unix.Getpagesize()) + pageSize := uint64(C.vm_kernel_page_size) total, err := getHwMemsize() if err != nil { return nil, err diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_nocgo.go similarity index 93% rename from vendor/github.com/shirou/gopsutil/mem/mem_darwin_nocgo.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_nocgo.go index 2e847cbe4..c93931680 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_darwin_nocgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_nocgo.go @@ -1,10 +1,10 @@ +//go:build darwin && !cgo // +build darwin,!cgo package mem import ( "context" - "os/exec" "strconv" "strings" @@ -13,11 +13,7 @@ import ( // Runs vm_stat and returns Free and inactive pages func getVMStat(vms *VirtualMemoryStat) error { - vm_stat, err := exec.LookPath("vm_stat") - if err != nil { - return err - } - out, err := invoke.Command(vm_stat) + out, err := invoke.Command("vm_stat") if err != nil { return err } diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_fallback.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_fallback.go similarity index 76% rename from vendor/github.com/shirou/gopsutil/mem/mem_fallback.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_fallback.go index 02e87d7a9..0b6c528f2 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_fallback.go @@ -1,11 +1,12 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows +//go:build !darwin && !linux && !freebsd && !openbsd && !solaris && !windows && !plan9 && !aix +// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!plan9,!aix package mem import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func VirtualMemory() (*VirtualMemoryStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_freebsd.go similarity index 98% rename from vendor/github.com/shirou/gopsutil/mem/mem_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_freebsd.go index f91efc9e3..9a56785b3 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd // +build freebsd package mem @@ -7,9 +8,8 @@ import ( "errors" "unsafe" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/unix" - - "github.com/shirou/gopsutil/internal/common" ) func VirtualMemory() (*VirtualMemoryStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_linux.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_linux.go similarity index 89% rename from vendor/github.com/shirou/gopsutil/mem/mem_linux.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_linux.go index cf3c64e9c..935331728 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package mem @@ -13,8 +14,9 @@ import ( "strconv" "strings" - "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" ) type VirtualMemoryExStat struct { @@ -55,14 +57,14 @@ func VirtualMemoryExWithContext(ctx context.Context) (*VirtualMemoryExStat, erro } func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *VirtualMemoryExStat, error) { - filename := common.HostProc("meminfo") + filename := common.HostProcWithContext(ctx, "meminfo") lines, _ := common.ReadLines(filename) // flag if MemAvailable is in /proc/meminfo (kernel 3.14+) memavail := false activeFile := false // "Active(file)" not available: 2.6.28 / Dec 2008 inactiveFile := false // "Inactive(file)" not available: 2.6.28 / Dec 2008 - sReclaimable := false // "SReclaimable:" not available: 2.6.19 / Nov 2006 + sReclaimable := false // "Sreclaimable:" not available: 2.6.19 / Nov 2006 ret := &VirtualMemoryStat{} retEx := &VirtualMemoryExStat{} @@ -157,13 +159,13 @@ func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *Virtu if err != nil { return ret, retEx, err } - ret.Writeback = t * 1024 + ret.WriteBack = t * 1024 case "WritebackTmp": t, err := strconv.ParseUint(value, 10, 64) if err != nil { return ret, retEx, err } - ret.WritebackTmp = t * 1024 + ret.WriteBackTmp = t * 1024 case "Dirty": t, err := strconv.ParseUint(value, 10, 64) if err != nil { @@ -188,13 +190,13 @@ func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *Virtu return ret, retEx, err } sReclaimable = true - ret.SReclaimable = t * 1024 + ret.Sreclaimable = t * 1024 case "SUnreclaim": t, err := strconv.ParseUint(value, 10, 64) if err != nil { return ret, retEx, err } - ret.SUnreclaim = t * 1024 + ret.Sunreclaim = t * 1024 case "PageTables": t, err := strconv.ParseUint(value, 10, 64) if err != nil { @@ -266,19 +268,19 @@ func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *Virtu if err != nil { return ret, retEx, err } - ret.VMallocTotal = t * 1024 + ret.VmallocTotal = t * 1024 case "VmallocUsed": t, err := strconv.ParseUint(value, 10, 64) if err != nil { return ret, retEx, err } - ret.VMallocUsed = t * 1024 + ret.VmallocUsed = t * 1024 case "VmallocChunk": t, err := strconv.ParseUint(value, 10, 64) if err != nil { return ret, retEx, err } - ret.VMallocChunk = t * 1024 + ret.VmallocChunk = t * 1024 case "HugePages_Total": t, err := strconv.ParseUint(value, 10, 64) if err != nil { @@ -291,6 +293,18 @@ func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *Virtu return ret, retEx, err } ret.HugePagesFree = t + case "HugePages_Rsvd": + t, err := strconv.ParseUint(value, 10, 64) + if err != nil { + return ret, retEx, err + } + ret.HugePagesRsvd = t + case "HugePages_Surp": + t, err := strconv.ParseUint(value, 10, 64) + if err != nil { + return ret, retEx, err + } + ret.HugePagesSurp = t case "Hugepagesize": t, err := strconv.ParseUint(value, 10, 64) if err != nil { @@ -300,11 +314,11 @@ func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *Virtu } } - ret.Cached += ret.SReclaimable + ret.Cached += ret.Sreclaimable if !memavail { if activeFile && inactiveFile && sReclaimable { - ret.Available = calcuateAvailVmem(ret, retEx) + ret.Available = calculateAvailVmem(ctx, ret, retEx) } else { ret.Available = ret.Cached + ret.Free } @@ -331,13 +345,13 @@ func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { Free: uint64(sysinfo.Freeswap) * uint64(sysinfo.Unit), } ret.Used = ret.Total - ret.Free - //check Infinity + // check Infinity if ret.Total != 0 { ret.UsedPercent = float64(ret.Total-ret.Free) / float64(ret.Total) * 100.0 } else { ret.UsedPercent = 0 } - filename := common.HostProc("vmstat") + filename := common.HostProcWithContext(ctx, "vmstat") lines, _ := common.ReadLines(filename) for _, l := range lines { fields := strings.Fields(l) @@ -386,15 +400,14 @@ func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { return ret, nil } -// calcuateAvailVmem is a fallback under kernel 3.14 where /proc/meminfo does not provide +// calculateAvailVmem is a fallback under kernel 3.14 where /proc/meminfo does not provide // "MemAvailable:" column. It reimplements an algorithm from the link below // https://github.com/giampaolo/psutil/pull/890 -func calcuateAvailVmem(ret *VirtualMemoryStat, retEx *VirtualMemoryExStat) uint64 { +func calculateAvailVmem(ctx context.Context, ret *VirtualMemoryStat, retEx *VirtualMemoryExStat) uint64 { var watermarkLow uint64 - fn := common.HostProc("zoneinfo") + fn := common.HostProcWithContext(ctx, "zoneinfo") lines, err := common.ReadLines(fn) - if err != nil { return ret.Free + ret.Cached // fallback under kernel 2.6.13 } @@ -407,7 +420,6 @@ func calcuateAvailVmem(ret *VirtualMemoryStat, retEx *VirtualMemoryExStat) uint6 if strings.HasPrefix(fields[0], "low") { lowValue, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { lowValue = 0 } @@ -421,7 +433,7 @@ func calcuateAvailVmem(ret *VirtualMemoryStat, retEx *VirtualMemoryExStat) uint6 pageCache := retEx.ActiveFile + retEx.InactiveFile pageCache -= uint64(math.Min(float64(pageCache/2), float64(watermarkLow))) availMemory += pageCache - availMemory += ret.SReclaimable - uint64(math.Min(float64(ret.SReclaimable/2.0), float64(watermarkLow))) + availMemory += ret.Sreclaimable - uint64(math.Min(float64(ret.Sreclaimable/2.0), float64(watermarkLow))) if availMemory < 0 { availMemory = 0 @@ -446,18 +458,18 @@ func SwapDevices() ([]*SwapDevice, error) { } func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - swapsFilePath := common.HostProc(swapsFilename) + swapsFilePath := common.HostProcWithContext(ctx, swapsFilename) f, err := os.Open(swapsFilePath) if err != nil { return nil, err } defer f.Close() - return parseSwapsFile(f) + return parseSwapsFile(ctx, f) } -func parseSwapsFile(r io.Reader) ([]*SwapDevice, error) { - swapsFilePath := common.HostProc(swapsFilename) +func parseSwapsFile(ctx context.Context, r io.Reader) ([]*SwapDevice, error) { + swapsFilePath := common.HostProcWithContext(ctx, swapsFilename) scanner := bufio.NewScanner(r) if !scanner.Scan() { if err := scanner.Err(); err != nil { diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd.go similarity index 91% rename from vendor/github.com/shirou/gopsutil/mem/mem_openbsd.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd.go index 7ecdae9fd..e37d5abe0 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package mem @@ -8,9 +9,8 @@ import ( "encoding/binary" "errors" "fmt" - "os/exec" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/unix" ) @@ -75,12 +75,7 @@ func SwapMemory() (*SwapMemoryStat, error) { } func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - swapctl, err := exec.LookPath("swapctl") - if err != nil { - return nil, err - } - - out, err := invoke.CommandWithContext(ctx, swapctl, "-sk") + out, err := invoke.CommandWithContext(ctx, "swapctl", "-sk") if err != nil { return &SwapMemoryStat{}, nil } diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_386.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_386.go similarity index 96% rename from vendor/github.com/shirou/gopsutil/mem/mem_openbsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_386.go index 0fa65d9c7..de2b26ca4 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_386.go @@ -1,3 +1,4 @@ +//go:build openbsd && 386 // +build openbsd,386 // Code generated by cmd/cgo -godefs; DO NOT EDIT. diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_amd64.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/mem/mem_openbsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_amd64.go diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm.go new file mode 100644 index 000000000..2488f1851 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm.go @@ -0,0 +1,38 @@ +//go:build openbsd && arm +// +build openbsd,arm + +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs mem/types_openbsd.go + +package mem + +const ( + CTLVfs = 10 + VfsGeneric = 0 + VfsBcacheStat = 3 +) + +const ( + sizeOfBcachestats = 0x90 +) + +type Bcachestats struct { + Numbufs int64 + Numbufpages int64 + Numdirtypages int64 + Numcleanpages int64 + Pendingwrites int64 + Pendingreads int64 + Numwrites int64 + Numreads int64 + Cachehits int64 + Busymapped int64 + Dmapages int64 + Highpages int64 + Delwribufs int64 + Kvaslots int64 + Avail int64 + Highflips int64 + Highflops int64 + Dmaflips int64 +} diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm64.go similarity index 95% rename from vendor/github.com/shirou/gopsutil/mem/mem_openbsd_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm64.go index 35f8517b6..3661b16fb 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm64.go @@ -1,3 +1,4 @@ +//go:build openbsd && arm64 // +build openbsd,arm64 // Code generated by cmd/cgo -godefs; DO NOT EDIT. diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_plan9.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_plan9.go new file mode 100644 index 000000000..b5259f844 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_plan9.go @@ -0,0 +1,68 @@ +//go:build plan9 +// +build plan9 + +package mem + +import ( + "context" + "os" + + stats "github.com/lufia/plan9stats" + "github.com/shirou/gopsutil/v3/internal/common" +) + +func SwapMemory() (*SwapMemoryStat, error) { + return SwapMemoryWithContext(context.Background()) +} + +func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { + root := os.Getenv("HOST_ROOT") + m, err := stats.ReadMemStats(ctx, stats.WithRootDir(root)) + if err != nil { + return nil, err + } + u := 0.0 + if m.SwapPages.Avail != 0 { + u = float64(m.SwapPages.Used) / float64(m.SwapPages.Avail) * 100.0 + } + return &SwapMemoryStat{ + Total: uint64(m.SwapPages.Avail * m.PageSize), + Used: uint64(m.SwapPages.Used * m.PageSize), + Free: uint64(m.SwapPages.Free() * m.PageSize), + UsedPercent: u, + }, nil +} + +func VirtualMemory() (*VirtualMemoryStat, error) { + return VirtualMemoryWithContext(context.Background()) +} + +func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { + root := os.Getenv("HOST_ROOT") + m, err := stats.ReadMemStats(ctx, stats.WithRootDir(root)) + if err != nil { + return nil, err + } + u := 0.0 + if m.UserPages.Avail != 0 { + u = float64(m.UserPages.Used) / float64(m.UserPages.Avail) * 100.0 + } + return &VirtualMemoryStat{ + Total: uint64(m.Total), + Available: uint64(m.UserPages.Free() * m.PageSize), + Used: uint64(m.UserPages.Used * m.PageSize), + UsedPercent: u, + Free: uint64(m.UserPages.Free() * m.PageSize), + + SwapTotal: uint64(m.SwapPages.Avail * m.PageSize), + SwapFree: uint64(m.SwapPages.Free() * m.PageSize), + }, nil +} + +func SwapDevices() ([]*SwapDevice, error) { + return SwapDevicesWithContext(context.Background()) +} + +func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { + return nil, common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_solaris.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_solaris.go similarity index 82% rename from vendor/github.com/shirou/gopsutil/mem/mem_solaris.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_solaris.go index 8b549588a..c911267e1 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_solaris.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_solaris.go @@ -1,16 +1,18 @@ +//go:build solaris // +build solaris package mem import ( "context" + "errors" "fmt" - "os/exec" "regexp" "strconv" "strings" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/tklauser/go-sysconf" ) // VirtualMemory for Solaris is a minimal implementation which only returns @@ -33,6 +35,13 @@ func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { return nil, err } result.Total = cap + freemem, err := globalZoneFreeMemory(ctx) + if err != nil { + return nil, err + } + result.Available = freemem + result.Free = freemem + result.Used = result.Total - result.Free } else { cap, err := nonGlobalZoneMemoryCapacity() if err != nil { @@ -53,13 +62,8 @@ func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { } func zoneName() (string, error) { - zonename, err := exec.LookPath("zonename") - if err != nil { - return "", err - } - ctx := context.Background() - out, err := invoke.CommandWithContext(ctx, zonename) + out, err := invoke.CommandWithContext(ctx, "zonename") if err != nil { return "", err } @@ -70,20 +74,15 @@ func zoneName() (string, error) { var globalZoneMemoryCapacityMatch = regexp.MustCompile(`[Mm]emory size: (\d+) Megabytes`) func globalZoneMemoryCapacity() (uint64, error) { - prtconf, err := exec.LookPath("prtconf") - if err != nil { - return 0, err - } - ctx := context.Background() - out, err := invoke.CommandWithContext(ctx, prtconf) + out, err := invoke.CommandWithContext(ctx, "prtconf") if err != nil { return 0, err } match := globalZoneMemoryCapacityMatch.FindAllStringSubmatch(string(out), -1) if len(match) != 1 { - return 0, fmt.Errorf("memory size not contained in output of %q", prtconf) + return 0, errors.New("memory size not contained in output of prtconf") } totalMB, err := strconv.ParseUint(match[0][1], 10, 64) @@ -94,16 +93,30 @@ func globalZoneMemoryCapacity() (uint64, error) { return totalMB * 1024 * 1024, nil } -var kstatMatch = regexp.MustCompile(`(\S+)\s+(\S*)`) +func globalZoneFreeMemory(ctx context.Context) (uint64, error) { + output, err := invoke.CommandWithContext(ctx, "pagesize") + if err != nil { + return 0, err + } -func nonGlobalZoneMemoryCapacity() (uint64, error) { - kstat, err := exec.LookPath("kstat") + pagesize, err := strconv.ParseUint(strings.TrimSpace(string(output)), 10, 64) if err != nil { return 0, err } + free, err := sysconf.Sysconf(sysconf.SC_AVPHYS_PAGES) + if err != nil { + return 0, err + } + + return uint64(free) * pagesize, nil +} + +var kstatMatch = regexp.MustCompile(`(\S+)\s+(\S*)`) + +func nonGlobalZoneMemoryCapacity() (uint64, error) { ctx := context.Background() - out, err := invoke.CommandWithContext(ctx, kstat, "-p", "-c", "zone_memory_cap", "memory_cap:*:*:physcap") + out, err := invoke.CommandWithContext(ctx, "kstat", "-p", "-c", "zone_memory_cap", "memory_cap:*:*:physcap") if err != nil { return 0, err } @@ -140,11 +153,7 @@ func SwapDevices() ([]*SwapDevice, error) { } func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - swapCommandPath, err := exec.LookPath(swapCommand) - if err != nil { - return nil, fmt.Errorf("could not find command %q: %w", swapCommand, err) - } - output, err := invoke.CommandWithContext(ctx, swapCommandPath, "-l") + output, err := invoke.CommandWithContext(ctx, swapCommand, "-l") if err != nil { return nil, fmt.Errorf("could not execute %q: %w", swapCommand, err) } diff --git a/vendor/github.com/shirou/gopsutil/mem/mem_windows.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_windows.go similarity index 98% rename from vendor/github.com/shirou/gopsutil/mem/mem_windows.go rename to vendor/github.com/shirou/gopsutil/v3/mem/mem_windows.go index 7c2f3bc68..8c7fb1a13 100644 --- a/vendor/github.com/shirou/gopsutil/mem/mem_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package mem @@ -8,7 +9,7 @@ import ( "syscall" "unsafe" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/windows" ) diff --git a/vendor/github.com/shirou/gopsutil/net/net.go b/vendor/github.com/shirou/gopsutil/v3/net/net.go similarity index 67% rename from vendor/github.com/shirou/gopsutil/net/net.go rename to vendor/github.com/shirou/gopsutil/v3/net/net.go index f1f99dc3a..0f3a62f39 100644 --- a/vendor/github.com/shirou/gopsutil/net/net.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net.go @@ -5,7 +5,7 @@ import ( "encoding/json" "net" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) var invoke common.Invoker = common.Invoke{} @@ -22,7 +22,6 @@ type IOCountersStat struct { Dropout uint64 `json:"dropout"` // total number of outgoing packets which were dropped (always 0 on OSX and BSD) Fifoin uint64 `json:"fifoin"` // total number of FIFO buffers errors while receiving Fifoout uint64 `json:"fifoout"` // total number of FIFO buffers errors while sending - } // Addr is implemented compatibility to psutil @@ -53,39 +52,45 @@ type InterfaceAddr struct { Addr string `json:"addr"` } +// InterfaceAddrList is a list of InterfaceAddr +type InterfaceAddrList []InterfaceAddr + type InterfaceStat struct { - Index int `json:"index"` - MTU int `json:"mtu"` // maximum transmission unit - Name string `json:"name"` // e.g., "en0", "lo0", "eth0.100" - HardwareAddr string `json:"hardwareaddr"` // IEEE MAC-48, EUI-48 and EUI-64 form - Flags []string `json:"flags"` // e.g., FlagUp, FlagLoopback, FlagMulticast - Addrs []InterfaceAddr `json:"addrs"` + Index int `json:"index"` + MTU int `json:"mtu"` // maximum transmission unit + Name string `json:"name"` // e.g., "en0", "lo0", "eth0.100" + HardwareAddr string `json:"hardwareAddr"` // IEEE MAC-48, EUI-48 and EUI-64 form + Flags []string `json:"flags"` // e.g., FlagUp, FlagLoopback, FlagMulticast + Addrs InterfaceAddrList `json:"addrs"` } +// InterfaceStatList is a list of InterfaceStat +type InterfaceStatList []InterfaceStat + type FilterStat struct { - ConnTrackCount int64 `json:"conntrackCount"` - ConnTrackMax int64 `json:"conntrackMax"` + ConnTrackCount int64 `json:"connTrackCount"` + ConnTrackMax int64 `json:"connTrackMax"` } // ConntrackStat has conntrack summary info type ConntrackStat struct { - Entries uint32 `json:"entries"` // Number of entries in the conntrack table - Searched uint32 `json:"searched"` // Number of conntrack table lookups performed - Found uint32 `json:"found"` // Number of searched entries which were successful - New uint32 `json:"new"` // Number of entries added which were not expected before - Invalid uint32 `json:"invalid"` // Number of packets seen which can not be tracked - Ignore uint32 `json:"ignore"` // Packets seen which are already connected to an entry - Delete uint32 `json:"delete"` // Number of entries which were removed - DeleteList uint32 `json:"delete_list"` // Number of entries which were put to dying list - Insert uint32 `json:"insert"` // Number of entries inserted into the list - InsertFailed uint32 `json:"insert_failed"` // # insertion attempted but failed (same entry exists) - Drop uint32 `json:"drop"` // Number of packets dropped due to conntrack failure. - EarlyDrop uint32 `json:"early_drop"` // Dropped entries to make room for new ones, if maxsize reached - IcmpError uint32 `json:"icmp_error"` // Subset of invalid. Packets that can't be tracked d/t error - ExpectNew uint32 `json:"expect_new"` // Entries added after an expectation was already present - ExpectCreate uint32 `json:"expect_create"` // Expectations added - ExpectDelete uint32 `json:"expect_delete"` // Expectations deleted - SearchRestart uint32 `json:"search_restart"` // Conntrack table lookups restarted due to hashtable resizes + Entries uint32 `json:"entries"` // Number of entries in the conntrack table + Searched uint32 `json:"searched"` // Number of conntrack table lookups performed + Found uint32 `json:"found"` // Number of searched entries which were successful + New uint32 `json:"new"` // Number of entries added which were not expected before + Invalid uint32 `json:"invalid"` // Number of packets seen which can not be tracked + Ignore uint32 `json:"ignore"` // Packets seen which are already connected to an entry + Delete uint32 `json:"delete"` // Number of entries which were removed + DeleteList uint32 `json:"deleteList"` // Number of entries which were put to dying list + Insert uint32 `json:"insert"` // Number of entries inserted into the list + InsertFailed uint32 `json:"insertFailed"` // # insertion attempted but failed (same entry exists) + Drop uint32 `json:"drop"` // Number of packets dropped due to conntrack failure. + EarlyDrop uint32 `json:"earlyDrop"` // Dropped entries to make room for new ones, if maxsize reached + IcmpError uint32 `json:"icmpError"` // Subset of invalid. Packets that can't be tracked d/t error + ExpectNew uint32 `json:"expectNew"` // Entries added after an expectation was already present + ExpectCreate uint32 `json:"expectCreate"` // Expectations added + ExpectDelete uint32 `json:"expectDelete"` // Expectations deleted + SearchRestart uint32 `json:"searchRestart"` // Conntrack table lookups restarted due to hashtable resizes } func NewConntrackStat(e uint32, s uint32, f uint32, n uint32, inv uint32, ign uint32, del uint32, dlst uint32, ins uint32, insfail uint32, drop uint32, edrop uint32, ie uint32, en uint32, ec uint32, ed uint32, sr uint32) *ConntrackStat { @@ -125,7 +130,7 @@ func (l *ConntrackStatList) Append(c *ConntrackStat) { } func (l *ConntrackStatList) Items() []ConntrackStat { - items := make([]ConntrackStat, len(l.items), len(l.items)) + items := make([]ConntrackStat, len(l.items)) for i, el := range l.items { items[i] = *el } @@ -182,6 +187,11 @@ func (n InterfaceStat) String() string { return string(s) } +func (l InterfaceStatList) String() string { + s, _ := json.Marshal(l) + return string(s) +} + func (n InterfaceAddr) String() string { s, _ := json.Marshal(n) return string(s) @@ -192,16 +202,16 @@ func (n ConntrackStat) String() string { return string(s) } -func Interfaces() ([]InterfaceStat, error) { +func Interfaces() (InterfaceStatList, error) { return InterfacesWithContext(context.Background()) } -func InterfacesWithContext(ctx context.Context) ([]InterfaceStat, error) { +func InterfacesWithContext(ctx context.Context) (InterfaceStatList, error) { is, err := net.Interfaces() if err != nil { return nil, err } - ret := make([]InterfaceStat, 0, len(is)) + ret := make(InterfaceStatList, 0, len(is)) for _, ifi := range is { var flags []string @@ -230,7 +240,7 @@ func InterfacesWithContext(ctx context.Context) ([]InterfaceStat, error) { } addrs, err := ifi.Addrs() if err == nil { - r.Addrs = make([]InterfaceAddr, 0, len(addrs)) + r.Addrs = make(InterfaceAddrList, 0, len(addrs)) for _, addr := range addrs { r.Addrs = append(r.Addrs, InterfaceAddr{ Addr: addr.String(), diff --git a/vendor/github.com/shirou/gopsutil/net/net_aix.go b/vendor/github.com/shirou/gopsutil/v3/net/net_aix.go similarity index 79% rename from vendor/github.com/shirou/gopsutil/net/net_aix.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_aix.go index 4ac849701..81feaa8d7 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_aix.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_aix.go @@ -1,3 +1,4 @@ +//go:build aix // +build aix package net @@ -5,107 +6,19 @@ package net import ( "context" "fmt" - "os/exec" "regexp" "strconv" "strings" "syscall" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) -func parseNetstatI(output string) ([]IOCountersStat, error) { - lines := strings.Split(string(output), "\n") - ret := make([]IOCountersStat, 0, len(lines)-1) - exists := make([]string, 0, len(ret)) - - // Check first line is header - if len(lines) > 0 && strings.Fields(lines[0])[0] != "Name" { - return nil, fmt.Errorf("not a 'netstat -i' output") - } - - for _, line := range lines[1:] { - values := strings.Fields(line) - if len(values) < 1 || values[0] == "Name" { - continue - } - if common.StringsHas(exists, values[0]) { - // skip if already get - continue - } - exists = append(exists, values[0]) - - if len(values) < 9 { - continue - } - - base := 1 - // sometimes Address is omitted - if len(values) < 10 { - base = 0 - } - - parsed := make([]uint64, 0, 5) - vv := []string{ - values[base+3], // Ipkts == PacketsRecv - values[base+4], // Ierrs == Errin - values[base+5], // Opkts == PacketsSent - values[base+6], // Oerrs == Errout - values[base+8], // Drops == Dropout - } - - for _, target := range vv { - if target == "-" { - parsed = append(parsed, 0) - continue - } - - t, err := strconv.ParseUint(target, 10, 64) - if err != nil { - return nil, err - } - parsed = append(parsed, t) - } - - n := IOCountersStat{ - Name: values[0], - PacketsRecv: parsed[0], - Errin: parsed[1], - PacketsSent: parsed[2], - Errout: parsed[3], - Dropout: parsed[4], - } - ret = append(ret, n) - } - return ret, nil -} - func IOCounters(pernic bool) ([]IOCountersStat, error) { return IOCountersWithContext(context.Background(), pernic) } -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, "-idn") - if err != nil { - return nil, err - } - - iocounters, err := parseNetstatI(string(out)) - if err != nil { - return nil, err - } - if pernic == false { - return getIOCountersAll(iocounters) - } - return iocounters, nil - -} - -// NetIOCountersByFile is an method which is added just a compatibility for linux. +// IOCountersByFile exists just for compatibility with Linux. func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { return IOCountersByFileWithContext(context.Background(), pernic, filename) } @@ -335,7 +248,6 @@ func parseNetstatA(output string, kind string) ([]ConnectionStat, error) { } return ret, nil - } func Connections(kind string) ([]ConnectionStat, error) { @@ -343,7 +255,6 @@ func Connections(kind string) ([]ConnectionStat, error) { } func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - args := []string{"-na"} switch strings.ToLower(kind) { default: @@ -362,12 +273,7 @@ func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, args = append(args, "-funix") } - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, args...) - + out, err := invoke.CommandWithContext(ctx, "netstat", args...) if err != nil { return nil, err } @@ -378,7 +284,6 @@ func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, } return ret, nil - } func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_aix_cgo.go b/vendor/github.com/shirou/gopsutil/v3/net/net_aix_cgo.go new file mode 100644 index 000000000..8c34f881c --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_aix_cgo.go @@ -0,0 +1,36 @@ +//go:build aix && cgo +// +build aix,cgo + +package net + +import ( + "context" + + "github.com/power-devops/perfstat" +) + +func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { + ifs, err := perfstat.NetIfaceStat() + if err != nil { + return nil, err + } + + iocounters := make([]IOCountersStat, 0, len(ifs)) + for _, netif := range ifs { + n := IOCountersStat{ + Name: netif.Name, + BytesSent: uint64(netif.OBytes), + BytesRecv: uint64(netif.IBytes), + PacketsSent: uint64(netif.OPackets), + PacketsRecv: uint64(netif.IPackets), + Errin: uint64(netif.OErrors), + Errout: uint64(netif.IErrors), + Dropout: uint64(netif.XmitDrops), + } + iocounters = append(iocounters, n) + } + if pernic == false { + return getIOCountersAll(iocounters) + } + return iocounters, nil +} diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_aix_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/net/net_aix_nocgo.go new file mode 100644 index 000000000..e3fce9021 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_aix_nocgo.go @@ -0,0 +1,95 @@ +//go:build aix && !cgo +// +build aix,!cgo + +package net + +import ( + "context" + "fmt" + "strconv" + "strings" + + "github.com/shirou/gopsutil/v3/internal/common" +) + +func parseNetstatI(output string) ([]IOCountersStat, error) { + lines := strings.Split(string(output), "\n") + ret := make([]IOCountersStat, 0, len(lines)-1) + exists := make([]string, 0, len(ret)) + + // Check first line is header + if len(lines) > 0 && strings.Fields(lines[0])[0] != "Name" { + return nil, fmt.Errorf("not a 'netstat -i' output") + } + + for _, line := range lines[1:] { + values := strings.Fields(line) + if len(values) < 1 || values[0] == "Name" { + continue + } + if common.StringsHas(exists, values[0]) { + // skip if already get + continue + } + exists = append(exists, values[0]) + + if len(values) < 9 { + continue + } + + base := 1 + // sometimes Address is omitted + if len(values) < 10 { + base = 0 + } + + parsed := make([]uint64, 0, 5) + vv := []string{ + values[base+3], // Ipkts == PacketsRecv + values[base+4], // Ierrs == Errin + values[base+5], // Opkts == PacketsSent + values[base+6], // Oerrs == Errout + values[base+8], // Drops == Dropout + } + + for _, target := range vv { + if target == "-" { + parsed = append(parsed, 0) + continue + } + + t, err := strconv.ParseUint(target, 10, 64) + if err != nil { + return nil, err + } + parsed = append(parsed, t) + } + + n := IOCountersStat{ + Name: values[0], + PacketsRecv: parsed[0], + Errin: parsed[1], + PacketsSent: parsed[2], + Errout: parsed[3], + Dropout: parsed[4], + } + ret = append(ret, n) + } + return ret, nil +} + +func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { + out, err := invoke.CommandWithContext(ctx, "netstat", "-idn") + if err != nil { + return nil, err + } + + iocounters, err := parseNetstatI(string(out)) + if err != nil { + return nil, err + } + if pernic == false { + return getIOCountersAll(iocounters) + } + return iocounters, nil +} diff --git a/vendor/github.com/shirou/gopsutil/net/net_darwin.go b/vendor/github.com/shirou/gopsutil/v3/net/net_darwin.go similarity index 95% rename from vendor/github.com/shirou/gopsutil/net/net_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_darwin.go index 8e6e7f953..8a7b63744 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package net @@ -6,11 +7,12 @@ import ( "context" "errors" "fmt" - "github.com/shirou/gopsutil/internal/common" "os/exec" "regexp" "strconv" "strings" + + "github.com/shirou/gopsutil/v3/internal/common" ) var ( @@ -205,11 +207,7 @@ func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, } } else { // duplicated interface, list all interfaces - ifconfig, err := exec.LookPath("ifconfig") - if err != nil { - return nil, err - } - if out, err = invoke.CommandWithContext(ctx, ifconfig, "-l"); err != nil { + if out, err = invoke.CommandWithContext(ctx, "ifconfig", "-l"); err != nil { return nil, err } interfaceNames := strings.Fields(strings.TrimRight(string(out), endOfLine)) @@ -255,13 +253,13 @@ func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, return ret, nil } -// NetIOCountersByFile is an method which is added just a compatibility for linux. +// IOCountersByFile exists just for compatibility with Linux. func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { return IOCountersByFileWithContext(context.Background(), pernic, filename) } func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) { - return IOCounters(pernic) + return IOCountersWithContext(ctx, pernic) } func FilterCounters() ([]FilterStat, error) { @@ -280,7 +278,7 @@ func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackSta return nil, common.ErrNotImplementedError } -// NetProtoCounters returns network statistics for the entire system +// ProtoCounters returns network statistics for the entire system // If protocols is empty then all protocols are returned, otherwise // just the protocols in the list are returned. // Not Implemented for Darwin diff --git a/vendor/github.com/shirou/gopsutil/net/net_fallback.go b/vendor/github.com/shirou/gopsutil/v3/net/net_fallback.go similarity index 94% rename from vendor/github.com/shirou/gopsutil/net/net_fallback.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_fallback.go index 7d9a26591..e136be1ba 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_fallback.go @@ -1,11 +1,12 @@ -// +build !aix,!darwin,!linux,!freebsd,!openbsd,!windows +//go:build !aix && !darwin && !linux && !freebsd && !openbsd && !windows && !solaris +// +build !aix,!darwin,!linux,!freebsd,!openbsd,!windows,!solaris package net import ( "context" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func IOCounters(pernic bool) ([]IOCountersStat, error) { diff --git a/vendor/github.com/shirou/gopsutil/net/net_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/net/net_freebsd.go similarity index 89% rename from vendor/github.com/shirou/gopsutil/net/net_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_freebsd.go index 1204f5977..bf8baf094 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_freebsd.go @@ -1,14 +1,14 @@ +//go:build freebsd // +build freebsd package net import ( "context" - "os/exec" "strconv" "strings" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) func IOCounters(pernic bool) ([]IOCountersStat, error) { @@ -16,11 +16,7 @@ func IOCounters(pernic bool) ([]IOCountersStat, error) { } func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, "-ibdnW") + out, err := invoke.CommandWithContext(ctx, "netstat", "-ibdnW") if err != nil { return nil, err } @@ -94,7 +90,7 @@ func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, return ret, nil } -// NetIOCountersByFile is an method which is added just a compatibility for linux. +// IOCountersByFile exists just for compatibility with Linux. func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { return IOCountersByFileWithContext(context.Background(), pernic, filename) } @@ -119,7 +115,7 @@ func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackSta return nil, common.ErrNotImplementedError } -// NetProtoCounters returns network statistics for the entire system +// ProtoCounters returns network statistics for the entire system // If protocols is empty then all protocols are returned, otherwise // just the protocols in the list are returned. // Not Implemented for FreeBSD diff --git a/vendor/github.com/shirou/gopsutil/net/net_linux.go b/vendor/github.com/shirou/gopsutil/v3/net/net_linux.go similarity index 81% rename from vendor/github.com/shirou/gopsutil/net/net_linux.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_linux.go index ed5d027b8..de0ea7345 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package net @@ -16,30 +17,30 @@ import ( "strings" "syscall" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) const ( // Conntrack Column numbers - CT_ENTRIES = iota - CT_SEARCHED - CT_FOUND - CT_NEW - CT_INVALID - CT_IGNORE - CT_DELETE - CT_DELETE_LIST - CT_INSERT - CT_INSERT_FAILED - CT_DROP - CT_EARLY_DROP - CT_ICMP_ERROR - CT_EXPECT_NEW - CT_EXPECT_CREATE - CT_EXPECT_DELETE - CT_SEARCH_RESTART + ctENTRIES = iota + ctSEARCHED + ctFOUND + ctNEW + ctINVALID + ctIGNORE + ctDELETE + ctDELETE_LIST + ctINSERT + ctINSERT_FAILED + ctDROP + ctEARLY_DROP + ctICMP_ERROR + CT_EXPEctNEW + ctEXPECT_CREATE + CT_EXPEctDELETE + ctSEARCH_RESTART ) -// NetIOCounters returnes network I/O statistics for every network +// NetIOCounters returns network I/O statistics for every network // interface installed on the system. If pernic argument is false, // return only sum of all information (which name is 'all'). If true, // every network interface installed on the system is returned @@ -49,7 +50,7 @@ func IOCounters(pernic bool) ([]IOCountersStat, error) { } func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - filename := common.HostProc("net/dev") + filename := common.HostProcWithContext(ctx, "net/dev") return IOCountersByFileWithContext(ctx, pernic, filename) } @@ -140,7 +141,7 @@ func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename stri ret = append(ret, nic) } - if pernic == false { + if !pernic { return getIOCountersAll(ret) } @@ -156,11 +157,11 @@ var netProtocols = []string{ "udplite", } -// NetProtoCounters returns network statistics for the entire system +// ProtoCounters returns network statistics for the entire system // If protocols is empty then all protocols are returned, otherwise // just the protocols in the list are returned. // Available protocols: -// ip,icmp,icmpmsg,tcp,udp,udplite +// [ip,icmp,icmpmsg,tcp,udp,udplite] func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { return ProtoCountersWithContext(context.Background(), protocols) } @@ -176,7 +177,7 @@ func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoC protos[p] = true } - filename := common.HostProc("net/snmp") + filename := common.HostProcWithContext(ctx, "net/snmp") lines, err := common.ReadLines(filename) if err != nil { return nil, err @@ -187,7 +188,7 @@ func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoC line := lines[i] r := strings.IndexRune(line, ':') if r == -1 { - return nil, errors.New(filename + " is not fomatted correctly, expected ':'.") + return nil, errors.New(filename + " is not formatted correctly, expected ':'.") } proto := strings.ToLower(line[:r]) if !protos[proto] { @@ -203,7 +204,7 @@ func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoC i++ statValues := strings.Split(lines[i][r+2:], " ") if len(statNames) != len(statValues) { - return nil, errors.New(filename + " is not fomatted correctly, expected same number of columns.") + return nil, errors.New(filename + " is not formatted correctly, expected same number of columns.") } stat := ProtoCountersStat{ Protocol: proto, @@ -229,11 +230,10 @@ func FilterCounters() ([]FilterStat, error) { } func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - countfile := common.HostProc("sys/net/netfilter/nf_conntrack_count") - maxfile := common.HostProc("sys/net/netfilter/nf_conntrack_max") + countfile := common.HostProcWithContext(ctx, "sys/net/netfilter/nf_conntrack_count") + maxfile := common.HostProcWithContext(ctx, "sys/net/netfilter/nf_conntrack_max") count, err := common.ReadInts(countfile) - if err != nil { return nil, err } @@ -260,7 +260,7 @@ func ConntrackStats(percpu bool) ([]ConntrackStat, error) { // ConntrackStatsWithContext returns more detailed info about the conntrack table func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return conntrackStatsFromFile(common.HostProc("net/stat/nf_conntrack"), percpu) + return conntrackStatsFromFile(common.HostProcWithContext(ctx, "net/stat/nf_conntrack"), percpu) } // conntrackStatsFromFile returns more detailed info about the conntrack table @@ -278,23 +278,23 @@ func conntrackStatsFromFile(filename string, percpu bool) ([]ConntrackStat, erro fields := strings.Fields(line) if len(fields) == 17 && fields[0] != "entries" { statlist.Append(NewConntrackStat( - common.HexToUint32(fields[CT_ENTRIES]), - common.HexToUint32(fields[CT_SEARCHED]), - common.HexToUint32(fields[CT_FOUND]), - common.HexToUint32(fields[CT_NEW]), - common.HexToUint32(fields[CT_INVALID]), - common.HexToUint32(fields[CT_IGNORE]), - common.HexToUint32(fields[CT_DELETE]), - common.HexToUint32(fields[CT_DELETE_LIST]), - common.HexToUint32(fields[CT_INSERT]), - common.HexToUint32(fields[CT_INSERT_FAILED]), - common.HexToUint32(fields[CT_DROP]), - common.HexToUint32(fields[CT_EARLY_DROP]), - common.HexToUint32(fields[CT_ICMP_ERROR]), - common.HexToUint32(fields[CT_EXPECT_NEW]), - common.HexToUint32(fields[CT_EXPECT_CREATE]), - common.HexToUint32(fields[CT_EXPECT_DELETE]), - common.HexToUint32(fields[CT_SEARCH_RESTART]), + common.HexToUint32(fields[ctENTRIES]), + common.HexToUint32(fields[ctSEARCHED]), + common.HexToUint32(fields[ctFOUND]), + common.HexToUint32(fields[ctNEW]), + common.HexToUint32(fields[ctINVALID]), + common.HexToUint32(fields[ctIGNORE]), + common.HexToUint32(fields[ctDELETE]), + common.HexToUint32(fields[ctDELETE_LIST]), + common.HexToUint32(fields[ctINSERT]), + common.HexToUint32(fields[ctINSERT_FAILED]), + common.HexToUint32(fields[ctDROP]), + common.HexToUint32(fields[ctEARLY_DROP]), + common.HexToUint32(fields[ctICMP_ERROR]), + common.HexToUint32(fields[CT_EXPEctNEW]), + common.HexToUint32(fields[ctEXPECT_CREATE]), + common.HexToUint32(fields[CT_EXPEctDELETE]), + common.HexToUint32(fields[ctSEARCH_RESTART]), )) } } @@ -306,7 +306,7 @@ func conntrackStatsFromFile(filename string, percpu bool) ([]ConntrackStat, erro } // http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h -var TCPStatuses = map[string]string{ +var tcpStatuses = map[string]string{ "01": "ESTABLISHED", "02": "SYN_SENT", "03": "SYN_RECV", @@ -331,21 +331,25 @@ var kindTCP4 = netConnectionKindType{ sockType: syscall.SOCK_STREAM, filename: "tcp", } + var kindTCP6 = netConnectionKindType{ family: syscall.AF_INET6, sockType: syscall.SOCK_STREAM, filename: "tcp6", } + var kindUDP4 = netConnectionKindType{ family: syscall.AF_INET, sockType: syscall.SOCK_DGRAM, filename: "udp", } + var kindUDP6 = netConnectionKindType{ family: syscall.AF_INET6, sockType: syscall.SOCK_DGRAM, filename: "udp6", } + var kindUNIX = netConnectionKindType{ family: syscall.AF_UNIX, filename: "unix", @@ -388,7 +392,7 @@ func Connections(kind string) ([]ConnectionStat, error) { } func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsPid(kind, 0) + return ConnectionsPidWithContext(ctx, kind, 0) } // Return a list of network connections opened returning at most `max` @@ -398,7 +402,7 @@ func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) { } func ConnectionsMaxWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return ConnectionsPidMax(kind, 0, max) + return ConnectionsPidMaxWithContext(ctx, kind, 0, max) } // Return a list of network connections opened, omitting `Uids`. @@ -455,11 +459,11 @@ func connectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, p if !ok { return nil, fmt.Errorf("invalid kind, %s", kind) } - root := common.HostProc() + root := common.HostProcWithContext(ctx) var err error var inodes map[string][]inodeMap if pid == 0 { - inodes, err = getProcInodesAll(root, max) + inodes, err = getProcInodesAllWithContext(ctx, root, max) } else { inodes, err = getProcInodes(root, pid, max) if len(inodes) == 0 { @@ -468,12 +472,16 @@ func connectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, p } } if err != nil { - return nil, fmt.Errorf("cound not get pid(s), %d: %s", pid, err) + return nil, fmt.Errorf("cound not get pid(s), %d: %w", pid, err) } - return statsFromInodes(root, pid, tmap, inodes, skipUids) + return statsFromInodesWithContext(ctx, root, pid, tmap, inodes, skipUids) } func statsFromInodes(root string, pid int32, tmap []netConnectionKindType, inodes map[string][]inodeMap, skipUids bool) ([]ConnectionStat, error) { + return statsFromInodesWithContext(context.Background(), root, pid, tmap, inodes, skipUids) +} + +func statsFromInodesWithContext(ctx context.Context, root string, pid int32, tmap []netConnectionKindType, inodes map[string][]inodeMap, skipUids bool) ([]ConnectionStat, error) { dupCheckMap := make(map[string]struct{}) var ret []ConnectionStat @@ -489,7 +497,7 @@ func statsFromInodes(root string, pid int32, tmap []netConnectionKindType, inode } switch t.family { case syscall.AF_INET, syscall.AF_INET6: - ls, err = processInet(path, t, inodes, pid) + ls, err = processInetWithContext(ctx, path, t, inodes, pid) case syscall.AF_UNIX: ls, err = processUnix(path, t, inodes, pid) } @@ -523,7 +531,7 @@ func statsFromInodes(root string, pid int32, tmap []netConnectionKindType, inode if !skipUids { // fetch process owner Real, effective, saved set, and filesystem UIDs proc := process{Pid: conn.Pid} - conn.Uids, _ = proc.getUids() + conn.Uids, _ = proc.getUids(ctx) } ret = append(ret, conn) @@ -535,7 +543,7 @@ func statsFromInodes(root string, pid int32, tmap []netConnectionKindType, inode return ret, nil } -// getProcInodes returnes fd of the pid. +// getProcInodes returns fd of the pid. func getProcInodes(root string, pid int32, max int) (map[string][]inodeMap, error) { ret := make(map[string][]inodeMap) @@ -545,12 +553,12 @@ func getProcInodes(root string, pid int32, max int) (map[string][]inodeMap, erro return ret, err } defer f.Close() - files, err := f.Readdir(max) + dirEntries, err := readDir(f, max) if err != nil { return ret, err } - for _, fd := range files { - inodePath := fmt.Sprintf("%s/%d/fd/%s", root, pid, fd.Name()) + for _, dirEntry := range dirEntries { + inodePath := fmt.Sprintf("%s/%d/fd/%s", root, pid, dirEntry.Name()) inode, err := os.Readlink(inodePath) if err != nil { @@ -566,7 +574,7 @@ func getProcInodes(root string, pid int32, max int) (map[string][]inodeMap, erro if !ok { ret[inode] = make([]inodeMap, 0) } - fd, err := strconv.Atoi(fd.Name()) + fd, err := strconv.Atoi(dirEntry.Name()) if err != nil { continue } @@ -591,7 +599,7 @@ func Pids() ([]int32, error) { func PidsWithContext(ctx context.Context) ([]int32, error) { var ret []int32 - d, err := os.Open(common.HostProc()) + d, err := os.Open(common.HostProcWithContext(ctx)) if err != nil { return nil, err } @@ -623,8 +631,8 @@ type process struct { } // Uids returns user ids of the process as a slice of the int -func (p *process) getUids() ([]int32, error) { - err := p.fillFromStatus() +func (p *process) getUids(ctx context.Context) ([]int32, error) { + err := p.fillFromStatus(ctx) if err != nil { return []int32{}, err } @@ -632,9 +640,9 @@ func (p *process) getUids() ([]int32, error) { } // Get status from /proc/(pid)/status -func (p *process) fillFromStatus() error { +func (p *process) fillFromStatus(ctx context.Context) error { pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "status") + statPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "status") contents, err := ioutil.ReadFile(statPath) if err != nil { return err @@ -662,7 +670,11 @@ func (p *process) fillFromStatus() error { } func getProcInodesAll(root string, max int) (map[string][]inodeMap, error) { - pids, err := Pids() + return getProcInodesAllWithContext(context.Background(), root, max) +} + +func getProcInodesAllWithContext(ctx context.Context, root string, max int) (map[string][]inodeMap, error) { + pids, err := PidsWithContext(ctx) if err != nil { return nil, err } @@ -672,7 +684,7 @@ func getProcInodesAll(root string, max int) (map[string][]inodeMap, error) { t, err := getProcInodes(root, pid, max) if err != nil { // skip if permission error or no longer exists - if os.IsPermission(err) || os.IsNotExist(err) || err == io.EOF { + if os.IsPermission(err) || os.IsNotExist(err) || errors.Is(err, io.EOF) { continue } return ret, err @@ -691,6 +703,10 @@ func getProcInodesAll(root string, max int) (map[string][]inodeMap, error) { // "0500000A:0016" -> "10.0.0.5", 22 // "0085002452100113070057A13F025401:0035" -> "2400:8500:1301:1052:a157:7:154:23f", 53 func decodeAddress(family uint32, src string) (Addr, error) { + return decodeAddressWithContext(context.Background(), family, src) +} + +func decodeAddressWithContext(ctx context.Context, family uint32, src string) (Addr, error) { t := strings.Split(src, ":") if len(t) != 2 { return Addr{}, fmt.Errorf("does not contain port, %s", src) @@ -702,14 +718,18 @@ func decodeAddress(family uint32, src string) (Addr, error) { } decoded, err := hex.DecodeString(addr) if err != nil { - return Addr{}, fmt.Errorf("decode error, %s", err) + return Addr{}, fmt.Errorf("decode error, %w", err) } var ip net.IP - // Assumes this is little_endian + if family == syscall.AF_INET { - ip = net.IP(Reverse(decoded)) + if common.IsLittleEndian() { + ip = net.IP(ReverseWithContext(ctx, decoded)) + } else { + ip = net.IP(decoded) + } } else { // IPv6 - ip, err = parseIPv6HexString(decoded) + ip, err = parseIPv6HexStringWithContext(ctx, decoded) if err != nil { return Addr{}, err } @@ -734,20 +754,27 @@ func ReverseWithContext(ctx context.Context, s []byte) []byte { // parseIPv6HexString parse array of bytes to IPv6 string func parseIPv6HexString(src []byte) (net.IP, error) { + return parseIPv6HexStringWithContext(context.Background(), src) +} + +func parseIPv6HexStringWithContext(ctx context.Context, src []byte) (net.IP, error) { if len(src) != 16 { return nil, fmt.Errorf("invalid IPv6 string") } buf := make([]byte, 0, 16) for i := 0; i < len(src); i += 4 { - r := Reverse(src[i : i+4]) + r := ReverseWithContext(ctx, src[i:i+4]) buf = append(buf, r...) } return net.IP(buf), nil } func processInet(file string, kind netConnectionKindType, inodes map[string][]inodeMap, filterPid int32) ([]connTmp, error) { + return processInetWithContext(context.Background(), file, kind, inodes, filterPid) +} +func processInetWithContext(ctx context.Context, file string, kind netConnectionKindType, inodes map[string][]inodeMap, filterPid int32) ([]connTmp, error) { if strings.HasSuffix(file, "6") && !common.PathExists(file) { // IPv6 not supported, return empty. return []connTmp{}, nil @@ -786,15 +813,15 @@ func processInet(file string, kind netConnectionKindType, inodes map[string][]in continue } if kind.sockType == syscall.SOCK_STREAM { - status = TCPStatuses[status] + status = tcpStatuses[status] } else { status = "NONE" } - la, err := decodeAddress(kind.family, laddr) + la, err := decodeAddressWithContext(ctx, kind.family, laddr) if err != nil { continue } - ra, err := decodeAddress(kind.family, raddr) + ra, err := decodeAddressWithContext(ctx, kind.family, raddr) if err != nil { continue } diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_linux_111.go b/vendor/github.com/shirou/gopsutil/v3/net/net_linux_111.go new file mode 100644 index 000000000..bd5c95871 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_linux_111.go @@ -0,0 +1,12 @@ +//go:build !go1.16 +// +build !go1.16 + +package net + +import ( + "os" +) + +func readDir(f *os.File, max int) ([]os.FileInfo, error) { + return f.Readdir(max) +} diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_linux_116.go b/vendor/github.com/shirou/gopsutil/v3/net/net_linux_116.go new file mode 100644 index 000000000..a45072e92 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_linux_116.go @@ -0,0 +1,12 @@ +//go:build go1.16 +// +build go1.16 + +package net + +import ( + "os" +) + +func readDir(f *os.File, max int) ([]os.DirEntry, error) { + return f.ReadDir(max) +} diff --git a/vendor/github.com/shirou/gopsutil/net/net_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/net/net_openbsd.go similarity index 97% rename from vendor/github.com/shirou/gopsutil/net/net_openbsd.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_openbsd.go index cfed2bee4..cf48f53e7 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package net @@ -11,7 +12,7 @@ import ( "strings" "syscall" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) var portMatch = regexp.MustCompile(`(.*)\.(\d+)$`) @@ -138,7 +139,7 @@ func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, return ret, nil } -// NetIOCountersByFile is an method which is added just a compatibility for linux. +// IOCountersByFile exists just for compatibility with Linux. func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { return IOCountersByFileWithContext(context.Background(), pernic, filename) } @@ -163,7 +164,7 @@ func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackSta return nil, common.ErrNotImplementedError } -// NetProtoCounters returns network statistics for the entire system +// ProtoCounters returns network statistics for the entire system // If protocols is empty then all protocols are returned, otherwise // just the protocols in the list are returned. // Not Implemented for OpenBSD @@ -298,7 +299,6 @@ func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, return nil, err } out, err := invoke.CommandWithContext(ctx, netstat, args...) - if err != nil { return nil, err } diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_solaris.go b/vendor/github.com/shirou/gopsutil/v3/net/net_solaris.go new file mode 100644 index 000000000..7f1f5c86f --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_solaris.go @@ -0,0 +1,143 @@ +//go:build solaris +// +build solaris + +package net + +import ( + "context" + "fmt" + "regexp" + "runtime" + "strconv" + "strings" + + "github.com/shirou/gopsutil/v3/internal/common" +) + +// NetIOCounters returnes network I/O statistics for every network +// interface installed on the system. If pernic argument is false, +// return only sum of all information (which name is 'all'). If true, +// every network interface installed on the system is returned +// separately. +func IOCounters(pernic bool) ([]IOCountersStat, error) { + return IOCountersWithContext(context.Background(), pernic) +} + +func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { + // collect all the net class's links with below statistics + filterstr := "/^(?!vnic)/::phys:/^rbytes64$|^ipackets64$|^idrops64$|^ierrors$|^obytes64$|^opackets64$|^odrops64$|^oerrors$/" + if runtime.GOOS == "illumos" { + filterstr = "/[^vnic]/::mac:/^rbytes64$|^ipackets64$|^idrops64$|^ierrors$|^obytes64$|^opackets64$|^odrops64$|^oerrors$/" + } + kstatSysOut, err := invoke.CommandWithContext(ctx, "kstat", "-c", "net", "-p", filterstr) + if err != nil { + return nil, fmt.Errorf("cannot execute kstat: %w", err) + } + + lines := strings.Split(strings.TrimSpace(string(kstatSysOut)), "\n") + if len(lines) == 0 { + return nil, fmt.Errorf("no interface found") + } + rbytes64arr := make(map[string]uint64) + ipackets64arr := make(map[string]uint64) + idrops64arr := make(map[string]uint64) + ierrorsarr := make(map[string]uint64) + obytes64arr := make(map[string]uint64) + opackets64arr := make(map[string]uint64) + odrops64arr := make(map[string]uint64) + oerrorsarr := make(map[string]uint64) + + re := regexp.MustCompile(`[:\s]+`) + for _, line := range lines { + fields := re.Split(line, -1) + interfaceName := fields[0] + instance := fields[1] + switch fields[3] { + case "rbytes64": + rbytes64arr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse rbytes64: %w", err) + } + case "ipackets64": + ipackets64arr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse ipackets64: %w", err) + } + case "idrops64": + idrops64arr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse idrops64: %w", err) + } + case "ierrors": + ierrorsarr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse ierrors: %w", err) + } + case "obytes64": + obytes64arr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse obytes64: %w", err) + } + case "opackets64": + opackets64arr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse opackets64: %w", err) + } + case "odrops64": + odrops64arr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse odrops64: %w", err) + } + case "oerrors": + oerrorsarr[interfaceName+instance], err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, fmt.Errorf("cannot parse oerrors: %w", err) + } + } + } + ret := make([]IOCountersStat, 0) + for k := range rbytes64arr { + nic := IOCountersStat{ + Name: k, + BytesRecv: rbytes64arr[k], + PacketsRecv: ipackets64arr[k], + Errin: ierrorsarr[k], + Dropin: idrops64arr[k], + BytesSent: obytes64arr[k], + PacketsSent: opackets64arr[k], + Errout: oerrorsarr[k], + Dropout: odrops64arr[k], + } + ret = append(ret, nic) + } + + if !pernic { + return getIOCountersAll(ret) + } + + return ret, nil +} + +func Connections(kind string) ([]ConnectionStat, error) { + return ConnectionsWithContext(context.Background(), kind) +} + +func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { + return []ConnectionStat{}, common.ErrNotImplementedError +} + +func FilterCounters() ([]FilterStat, error) { + return FilterCountersWithContext(context.Background()) +} + +func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { + return []FilterStat{}, common.ErrNotImplementedError +} + +func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { + return ProtoCountersWithContext(context.Background(), protocols) +} + +func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { + return []ProtoCountersStat{}, common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/net/net_unix.go b/vendor/github.com/shirou/gopsutil/v3/net/net_unix.go similarity index 97% rename from vendor/github.com/shirou/gopsutil/net/net_unix.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_unix.go index abe25c4ed..cb846e28a 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_unix.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_unix.go @@ -1,3 +1,4 @@ +//go:build freebsd || darwin // +build freebsd darwin package net @@ -10,7 +11,7 @@ import ( "strings" "syscall" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" ) // Return a list of network connections opened. @@ -19,7 +20,7 @@ func Connections(kind string) ([]ConnectionStat, error) { } func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsPid(kind, 0) + return ConnectionsPidWithContext(ctx, kind, 0) } // Return a list of network connections opened returning at most `max` @@ -80,7 +81,6 @@ func ConnectionsPidWithContext(ctx context.Context, kind string, pid int32) ([]C } n, err := parseNetLine(rr) if err != nil { - continue } diff --git a/vendor/github.com/shirou/gopsutil/net/net_windows.go b/vendor/github.com/shirou/gopsutil/v3/net/net_windows.go similarity index 97% rename from vendor/github.com/shirou/gopsutil/net/net_windows.go rename to vendor/github.com/shirou/gopsutil/v3/net/net_windows.go index bdc928798..5d384342f 100644 --- a/vendor/github.com/shirou/gopsutil/net/net_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package net @@ -10,7 +11,7 @@ import ( "syscall" "unsafe" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/windows" ) @@ -44,16 +45,19 @@ var kindTCP4 = netConnectionKindType{ sockType: syscall.SOCK_STREAM, filename: "tcp", } + var kindTCP6 = netConnectionKindType{ family: syscall.AF_INET6, sockType: syscall.SOCK_STREAM, filename: "tcp6", } + var kindUDP4 = netConnectionKindType{ family: syscall.AF_INET, sockType: syscall.SOCK_DGRAM, filename: "udp", } + var kindUDP6 = netConnectionKindType{ family: syscall.AF_INET6, sockType: syscall.SOCK_DGRAM, @@ -196,7 +200,7 @@ func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, return counters, nil } -// NetIOCountersByFile is an method which is added just a compatibility for linux. +// IOCountersByFile exists just for compatibility with Linux. func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { return IOCountersByFileWithContext(context.Background(), pernic, filename) } @@ -207,7 +211,8 @@ func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename stri // Return a list of network connections // Available kind: -// reference to netConnectionKindMap +// +// reference to netConnectionKindMap func Connections(kind string) ([]ConnectionStat, error) { return ConnectionsWithContext(context.Background(), kind) } @@ -333,8 +338,7 @@ func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackSta return nil, common.ErrNotImplementedError } - -// NetProtoCounters returns network statistics for the entire system +// ProtoCounters returns network statistics for the entire system // If protocols is empty then all protocols are returned, otherwise // just the protocols in the list are returned. // Not Implemented for Windows @@ -525,9 +529,7 @@ func getUDPConnections(family uint32) ([]ConnectionStat, error) { buf = make([]byte, size) } - var ( - index, step, length int - ) + var index, step, length int stats := make([]ConnectionStat, 0) switch family { @@ -694,8 +696,10 @@ type mibTCP6TableOwnerPid struct { Table [anySize]mibTCP6RowOwnerPid } -type pmibTCPTableOwnerPidAll *mibTCPTableOwnerPid -type pmibTCP6TableOwnerPidAll *mibTCP6TableOwnerPid +type ( + pmibTCPTableOwnerPidAll *mibTCPTableOwnerPid + pmibTCP6TableOwnerPidAll *mibTCP6TableOwnerPid +) // UDP @@ -750,8 +754,10 @@ type mibUDP6TableOwnerPid struct { Table [anySize]mibUDP6RowOwnerPid } -type pmibUDPTableOwnerPid *mibUDPTableOwnerPid -type pmibUDP6TableOwnerPid *mibUDP6TableOwnerPid +type ( + pmibUDPTableOwnerPid *mibUDPTableOwnerPid + pmibUDP6TableOwnerPid *mibUDP6TableOwnerPid +) func decodePort(port uint32) uint16 { return syscall.Ntohs(uint16(port)) diff --git a/vendor/github.com/shirou/gopsutil/process/process.go b/vendor/github.com/shirou/gopsutil/v3/process/process.go similarity index 83% rename from vendor/github.com/shirou/gopsutil/process/process.go rename to vendor/github.com/shirou/gopsutil/v3/process/process.go index fc1c5f4cb..1a7fe1b80 100644 --- a/vendor/github.com/shirou/gopsutil/process/process.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process.go @@ -7,19 +7,19 @@ import ( "runtime" "sort" "sync" - "syscall" "time" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/mem" - "github.com/shirou/gopsutil/net" + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/mem" + "github.com/shirou/gopsutil/v3/net" ) var ( invoke common.Invoker = common.Invoke{} ErrorNoChildren = errors.New("process does not have children") ErrorProcessNotRunning = errors.New("process does not exist") + ErrorNotPermitted = errors.New("operation not permitted") ) type Process struct { @@ -43,6 +43,34 @@ type Process struct { tgid int32 } +// Process status +const ( + // Running marks a task a running or runnable (on the run queue) + Running = "running" + // Blocked marks a task waiting on a short, uninterruptible operation (usually I/O) + Blocked = "blocked" + // Idle marks a task sleeping for more than about 20 seconds + Idle = "idle" + // Lock marks a task waiting to acquire a lock + Lock = "lock" + // Sleep marks task waiting for short, interruptible operation + Sleep = "sleep" + // Stop marks a stopped process + Stop = "stop" + // Wait marks an idle interrupt thread (or paging in pre 2.6.xx Linux) + Wait = "wait" + // Zombie marks a defunct process, terminated but not reaped by its parent + Zombie = "zombie" + + // Solaris states. See https://github.com/collectd/collectd/blob/1da3305c10c8ff9a63081284cf3d4bb0f6daffd8/src/processes.c#L2115 + Daemon = "daemon" + Detached = "detached" + System = "system" + Orphan = "orphan" + + UnknownState = "" +) + type OpenFilesStat struct { Path string `json:"path"` Fd uint64 `json:"fd"` @@ -68,8 +96,8 @@ type SignalInfoStat struct { type RlimitStat struct { Resource int32 `json:"resource"` - Soft int32 `json:"soft"` //TODO too small. needs to be uint64 - Hard int32 `json:"hard"` //TODO too small. needs to be uint64 + Soft uint64 `json:"soft"` + Hard uint64 `json:"hard"` Used uint64 `json:"used"` } @@ -202,7 +230,7 @@ func (p *Process) BackgroundWithContext(ctx context.Context) (bool, error) { } // If interval is 0, return difference from last call(non-blocking). -// If interval > 0, wait interval sec and return diffrence between start and end. +// If interval > 0, wait interval sec and return difference between start and end. func (p *Process) Percent(interval time.Duration) (float64, error) { return p.PercentWithContext(context.Background(), interval) } @@ -253,7 +281,7 @@ func (p *Process) IsRunningWithContext(ctx context.Context) (bool, error) { return false, err } p2, err := NewProcessWithContext(ctx, p.Pid) - if err == ErrorProcessNotRunning { + if errors.Is(err, ErrorProcessNotRunning) { return false, nil } createTime2, err := p2.CreateTimeWithContext(ctx) @@ -307,7 +335,7 @@ func (p *Process) MemoryPercentWithContext(ctx context.Context) (float32, error) return (100 * float32(used) / float32(total)), nil } -// CPU_Percent returns how many percent of the CPU time this process uses +// CPUPercent returns how many percent of the CPU time this process uses func (p *Process) CPUPercent() (float64, error) { return p.CPUPercentWithContext(context.Background()) } @@ -374,12 +402,21 @@ func (p *Process) Parent() (*Process, error) { return p.ParentWithContext(context.Background()) } +// ParentWithContext returns parent Process of the process. +func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { + ppid, err := p.PpidWithContext(ctx) + if err != nil { + return nil, err + } + return NewProcessWithContext(ctx, ppid) +} + // Status returns the process status. // Return value could be one of these. // R: Running S: Sleep T: Stop I: Idle // Z: Zombie W: Wait L: Lock // The character is same within all supported platforms. -func (p *Process) Status() (string, error) { +func (p *Process) Status() ([]string, error) { return p.StatusWithContext(context.Background()) } @@ -470,7 +507,7 @@ func (p *Process) MemoryInfoEx() (*MemoryInfoExStat, error) { return p.MemoryInfoExWithContext(context.Background()) } -// PageFaultsInfo returns the process's page fault counters. +// PageFaults returns the process's page fault counters. func (p *Process) PageFaults() (*PageFaultsStat, error) { return p.PageFaultsWithContext(context.Background()) } @@ -493,16 +530,11 @@ func (p *Process) Connections() ([]net.ConnectionStat, error) { return p.ConnectionsWithContext(context.Background()) } -// Connections returns a slice of net.ConnectionStat used by the process at most `max`. +// ConnectionsMax returns a slice of net.ConnectionStat used by the process at most `max`. func (p *Process) ConnectionsMax(max int) ([]net.ConnectionStat, error) { return p.ConnectionsMaxWithContext(context.Background(), max) } -// NetIOCounters returns NetIOCounters of the process. -func (p *Process) NetIOCounters(pernic bool) ([]net.IOCountersStat, error) { - return p.NetIOCountersWithContext(context.Background(), pernic) -} - // MemoryMaps get memory maps from /proc/(pid)/smaps func (p *Process) MemoryMaps(grouped bool) (*[]MemoryMapsStat, error) { return p.MemoryMapsWithContext(context.Background(), grouped) @@ -514,7 +546,7 @@ func (p *Process) Tgid() (int32, error) { } // SendSignal sends a unix.Signal to the process. -func (p *Process) SendSignal(sig syscall.Signal) error { +func (p *Process) SendSignal(sig Signal) error { return p.SendSignalWithContext(context.Background(), sig) } @@ -547,3 +579,42 @@ func (p *Process) Username() (string, error) { func (p *Process) Environ() ([]string, error) { return p.EnvironWithContext(context.Background()) } + +// convertStatusChar as reported by the ps command across different platforms. +func convertStatusChar(letter string) string { + // Sources + // Darwin: http://www.mywebuniversity.com/Man_Pages/Darwin/man_ps.html + // FreeBSD: https://www.freebsd.org/cgi/man.cgi?ps + // Linux https://man7.org/linux/man-pages/man1/ps.1.html + // OpenBSD: https://man.openbsd.org/ps.1#state + // Solaris: https://github.com/collectd/collectd/blob/1da3305c10c8ff9a63081284cf3d4bb0f6daffd8/src/processes.c#L2115 + switch letter { + case "A": + return Daemon + case "D", "U": + return Blocked + case "E": + return Detached + case "I": + return Idle + case "L": + return Lock + case "O": + return Orphan + case "R": + return Running + case "S": + return Sleep + case "T", "t": + // "t" is used by Linux to signal stopped by the debugger during tracing + return Stop + case "W": + return Wait + case "Y": + return System + case "Z": + return Zombie + default: + return UnknownState + } +} diff --git a/vendor/github.com/shirou/gopsutil/process/process_bsd.go b/vendor/github.com/shirou/gopsutil/v3/process/process_bsd.go similarity index 84% rename from vendor/github.com/shirou/gopsutil/process/process_bsd.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_bsd.go index 545e44f31..263829ffa 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_bsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_bsd.go @@ -1,3 +1,4 @@ +//go:build darwin || freebsd || openbsd // +build darwin freebsd openbsd package process @@ -7,9 +8,8 @@ import ( "context" "encoding/binary" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" ) type MemoryInfoExStat struct{} @@ -20,10 +20,6 @@ func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { return 0, common.ErrNotImplementedError } -func (p *Process) CwdWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { return 0, common.ErrNotImplementedError } @@ -60,10 +56,6 @@ func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, er return nil, common.ErrNotImplementedError } -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { return nil, common.ErrNotImplementedError } diff --git a/vendor/github.com/shirou/gopsutil/process/process_darwin.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin.go similarity index 53% rename from vendor/github.com/shirou/gopsutil/process/process_darwin.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_darwin.go index 383e0994d..176661cbd 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package process @@ -5,17 +6,15 @@ package process import ( "context" "fmt" - "os/exec" "path/filepath" "strconv" "strings" - "time" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" "github.com/tklauser/go-sysconf" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/net" ) // copied from sys/sysctl.h @@ -28,13 +27,13 @@ const ( KernProcPathname = 12 // path to executable ) -var ClockTicks = 100 // default value +var clockTicks = 100 // default value func init() { clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) // ignore errors if err == nil { - ClockTicks = int(clkTck) + clockTicks = int(clkTck) } } @@ -45,34 +44,25 @@ type _Ctype_struct___0 struct { func pidsWithContext(ctx context.Context) ([]int32, error) { var ret []int32 - pids, err := callPsWithContext(ctx, "pid", 0, false, false) + kprocs, err := unix.SysctlKinfoProcSlice("kern.proc.all") if err != nil { return ret, err } - for _, pid := range pids { - v, err := strconv.Atoi(pid[0]) - if err != nil { - return ret, err - } - ret = append(ret, int32(v)) + for _, proc := range kprocs { + ret = append(ret, int32(proc.Proc.P_pid)) } return ret, nil } func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - r, err := callPsWithContext(ctx, "ppid", p.Pid, false, false) - if err != nil { - return 0, err - } - - v, err := strconv.Atoi(r[0][0]) + k, err := p.getKProc() if err != nil { return 0, err } - return int32(v), err + return k.Eproc.Ppid, nil } func (p *Process) NameWithContext(ctx context.Context) (string, error) { @@ -80,7 +70,8 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) { if err != nil { return "", err } - name := common.IntToString(k.Proc.P_comm[:]) + + name := common.ByteToString(k.Proc.P_comm[:]) if len(name) >= 15 { cmdName, err := p.cmdNameWithContext(ctx) @@ -88,11 +79,9 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) { return "", err } if len(cmdName) > 0 { - extendedName := filepath.Base(cmdName[0]) + extendedName := filepath.Base(cmdName) if strings.HasPrefix(extendedName, p.name) { name = extendedName - } else { - name = cmdName[0] } } } @@ -100,101 +89,28 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) { return name, nil } -func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { - r, err := callPsWithContext(ctx, "command", p.Pid, false, false) - if err != nil { - return "", err - } - return strings.Join(r[0], " "), err -} - -// cmdNameWithContext returns the command name (including spaces) without any arguments -func (p *Process) cmdNameWithContext(ctx context.Context) ([]string, error) { - r, err := callPsWithContext(ctx, "command", p.Pid, false, true) - if err != nil { - return nil, err - } - return r[0], err -} - -// CmdlineSliceWithContext returns the command line arguments of the process as a slice with each -// element being an argument. Because of current deficiencies in the way that the command -// line arguments are found, single arguments that have spaces in the will actually be -// reported as two separate items. In order to do something better CGO would be needed -// to use the native darwin functions. -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - r, err := callPsWithContext(ctx, "command", p.Pid, false, false) - if err != nil { - return nil, err - } - return r[0], err -} - func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - r, err := callPsWithContext(ctx, "etime", p.Pid, false, false) + k, err := p.getKProc() if err != nil { return 0, err } - elapsedSegments := strings.Split(strings.Replace(r[0][0], "-", ":", 1), ":") - var elapsedDurations []time.Duration - for i := len(elapsedSegments) - 1; i >= 0; i-- { - p, err := strconv.ParseInt(elapsedSegments[i], 10, 0) - if err != nil { - return 0, err - } - elapsedDurations = append(elapsedDurations, time.Duration(p)) - } - - var elapsed = time.Duration(elapsedDurations[0]) * time.Second - if len(elapsedDurations) > 1 { - elapsed += time.Duration(elapsedDurations[1]) * time.Minute - } - if len(elapsedDurations) > 2 { - elapsed += time.Duration(elapsedDurations[2]) * time.Hour - } - if len(elapsedDurations) > 3 { - elapsed += time.Duration(elapsedDurations[3]) * time.Hour * 24 - } - - start := time.Now().Add(-elapsed) - return start.Unix() * 1000, nil + return k.Proc.P_starttime.Sec*1000 + int64(k.Proc.P_starttime.Usec)/1000, nil } -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - out, err := common.CallLsofWithContext(ctx, invoke, p.Pid, "-FR") - if err != nil { - return nil, err - } - for _, line := range out { - if len(line) >= 1 && line[0] == 'R' { - v, err := strconv.Atoi(line[1:]) - if err != nil { - return nil, err - } - return NewProcessWithContext(ctx, int32(v)) - } - } - return nil, fmt.Errorf("could not find parent line") -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { r, err := callPsWithContext(ctx, "state", p.Pid, false, false) if err != nil { - return "", err + return []string{""}, err } - - return r[0][0][0:1], err + status := convertStatusChar(r[0][0][0:1]) + return []string{status}, err } func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details pid := p.Pid - ps, err := exec.LookPath("ps") - if err != nil { - return false, err - } - out, err := invoke.CommandWithContext(ctx, ps, "-o", "stat=", "-p", strconv.Itoa(int(pid))) + out, err := invoke.CommandWithContext(ctx, "ps", "-o", "stat=", "-p", strconv.Itoa(int(pid))) if err != nil { return false, err } @@ -208,7 +124,7 @@ func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { } // See: http://unix.superglobalmegacorp.com/Net2/newsrc/sys/ucred.h.html - userEffectiveUID := int32(k.Eproc.Ucred.UID) + userEffectiveUID := int32(k.Eproc.Ucred.Uid) return []int32{userEffectiveUID}, nil } @@ -220,7 +136,7 @@ func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { } gids := make([]int32, 0, 3) - gids = append(gids, int32(k.Eproc.Pcred.P_rgid), int32(k.Eproc.Ucred.Ngroups), int32(k.Eproc.Pcred.P_svgid)) + gids = append(gids, int32(k.Eproc.Pcred.P_rgid), int32(k.Eproc.Pcred.P_rgid), int32(k.Eproc.Pcred.P_svgid)) return gids, nil } @@ -270,14 +186,6 @@ func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, e return nil, common.ErrNotImplementedError } -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - r, err := callPsWithContext(ctx, "utime,stime", p.Pid, true, false) - if err != nil { - return 0, err - } - return int32(len(r)), nil -} - func convertCPUTimes(s string) (ret float64, err error) { var t int var _tmp string @@ -289,20 +197,20 @@ func convertCPUTimes(s string) (ret float64, err error) { if err != nil { return ret, err } - t += hour * 60 * 60 * ClockTicks + t += hour * 60 * 60 * clockTicks mins, err := strconv.Atoi(_t[1]) if err != nil { return ret, err } - t += mins * 60 * ClockTicks + t += mins * 60 * clockTicks _tmp = _t[2] case 2: mins, err := strconv.Atoi(_t[0]) if err != nil { return ret, err } - t += mins * 60 * ClockTicks + t += mins * 60 * clockTicks _tmp = _t[1] case 1, 0: _tmp = s @@ -318,61 +226,10 @@ func convertCPUTimes(s string) (ret float64, err error) { return ret, err } h, err := strconv.Atoi(_t[0]) - t += h * ClockTicks + t += h * clockTicks h, err = strconv.Atoi(_t[1]) t += h - return float64(t) / float64(ClockTicks), nil -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - r, err := callPsWithContext(ctx, "utime,stime", p.Pid, false, false) - - if err != nil { - return nil, err - } - - utime, err := convertCPUTimes(r[0][0]) - if err != nil { - return nil, err - } - stime, err := convertCPUTimes(r[0][1]) - if err != nil { - return nil, err - } - - ret := &cpu.TimesStat{ - CPU: "cpu", - User: utime, - System: stime, - } - return ret, nil -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - r, err := callPsWithContext(ctx, "rss,vsize,pagein", p.Pid, false, false) - if err != nil { - return nil, err - } - rss, err := strconv.Atoi(r[0][0]) - if err != nil { - return nil, err - } - vms, err := strconv.Atoi(r[0][1]) - if err != nil { - return nil, err - } - pagein, err := strconv.Atoi(r[0][2]) - if err != nil { - return nil, err - } - - ret := &MemoryInfoStat{ - RSS: uint64(rss) * 1024, - VMS: uint64(vms) * 1024, - Swap: uint64(pagein), - } - - return ret, nil + return float64(t) / float64(clockTicks), nil } func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { @@ -420,29 +277,15 @@ func ProcessesWithContext(ctx context.Context) ([]*Process, error) { // Returns a proc as defined here: // http://unix.superglobalmegacorp.com/Net2/newsrc/sys/kinfo_proc.h.html -func (p *Process) getKProc() (*KinfoProc, error) { - buf, err := unix.SysctlRaw("kern.proc.pid", int(p.Pid)) - if err != nil { - return nil, err - } - k, err := parseKinfoProc(buf) - if err != nil { - return nil, err - } - - return &k, nil +func (p *Process) getKProc() (*unix.KinfoProc, error) { + return unix.SysctlKinfoProc("kern.proc.pid", int(p.Pid)) } // call ps command. // Return value deletes Header line(you must not input wrong arg). -// And split by space. Caller have responsibility to manage. +// And splited by Space. Caller have responsibility to manage. // If passed arg pid is 0, get information from all process. func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption bool, nameOption bool) ([][]string, error) { - bin, err := exec.LookPath("ps") - if err != nil { - return [][]string{}, err - } - var cmd []string if pid == 0 { // will get from all processes. cmd = []string{"-ax", "-o", arg} @@ -451,11 +294,10 @@ func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption } else { cmd = []string{"-x", "-o", arg, "-p", strconv.Itoa(int(pid))} } - if nameOption { cmd = append(cmd, "-c") } - out, err := invoke.CommandWithContext(ctx, bin, cmd...) + out, err := invoke.CommandWithContext(ctx, "ps", cmd...) if err != nil { return [][]string{}, err } @@ -463,7 +305,6 @@ func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption var ret [][]string for _, l := range lines[1:] { - var lr []string if nameOption { lr = append(lr, l) @@ -475,7 +316,6 @@ func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption lr = append(lr, strings.TrimSpace(r)) } } - if len(lr) != 0 { ret = append(ret, lr) } diff --git a/vendor/github.com/shirou/gopsutil/process/process_darwin_amd64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_amd64.go similarity index 99% rename from vendor/github.com/shirou/gopsutil/process/process_darwin_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_darwin_amd64.go index f8e922385..b353e5eac 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_darwin_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_amd64.go @@ -218,10 +218,12 @@ type AuditinfoAddr struct { Asid int32 Flags uint64 } + type AuMask struct { Success uint32 Failure uint32 } + type AuTidAddr struct { Port int32 Type uint32 diff --git a/vendor/github.com/shirou/gopsutil/process/process_darwin_arm64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_arm64.go similarity index 98% rename from vendor/github.com/shirou/gopsutil/process/process_darwin_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_darwin_arm64.go index 92bd4259b..cbd6bdc79 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_darwin_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_arm64.go @@ -1,5 +1,6 @@ -// +build darwin -// +build arm64 +//go:build darwin && arm64 +// +build darwin,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs process/types_darwin.go diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_cgo.go new file mode 100644 index 000000000..858f08e7a --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_cgo.go @@ -0,0 +1,222 @@ +//go:build darwin && cgo +// +build darwin,cgo + +package process + +// #include +// #include +// #include +// #include +// #include +// #include +// #include +import "C" + +import ( + "bytes" + "context" + "fmt" + "strings" + "syscall" + "unsafe" + + "github.com/shirou/gopsutil/v3/cpu" +) + +var ( + argMax int + timescaleToNanoSeconds float64 +) + +func init() { + argMax = getArgMax() + timescaleToNanoSeconds = getTimeScaleToNanoSeconds() +} + +func getArgMax() int { + var ( + mib = [...]C.int{C.CTL_KERN, C.KERN_ARGMAX} + argmax C.int + size C.size_t = C.ulong(unsafe.Sizeof(argmax)) + ) + retval := C.sysctl(&mib[0], 2, unsafe.Pointer(&argmax), &size, C.NULL, 0) + if retval == 0 { + return int(argmax) + } + return 0 +} + +func getTimeScaleToNanoSeconds() float64 { + var timeBaseInfo C.struct_mach_timebase_info + + C.mach_timebase_info(&timeBaseInfo) + + return float64(timeBaseInfo.numer) / float64(timeBaseInfo.denom) +} + +func (p *Process) ExeWithContext(ctx context.Context) (string, error) { + var c C.char // need a var for unsafe.Sizeof need a var + const bufsize = C.PROC_PIDPATHINFO_MAXSIZE * unsafe.Sizeof(c) + buffer := (*C.char)(C.malloc(C.size_t(bufsize))) + defer C.free(unsafe.Pointer(buffer)) + + ret, err := C.proc_pidpath(C.int(p.Pid), unsafe.Pointer(buffer), C.uint32_t(bufsize)) + if err != nil { + return "", err + } + if ret <= 0 { + return "", fmt.Errorf("unknown error: proc_pidpath returned %d", ret) + } + + return C.GoString(buffer), nil +} + +// CwdWithContext retrieves the Current Working Directory for the given process. +// It uses the proc_pidinfo from libproc and will only work for processes the +// EUID can access. Otherwise "operation not permitted" will be returned as the +// error. +// Note: This might also work for other *BSD OSs. +func (p *Process) CwdWithContext(ctx context.Context) (string, error) { + const vpiSize = C.sizeof_struct_proc_vnodepathinfo + vpi := (*C.struct_proc_vnodepathinfo)(C.malloc(vpiSize)) + defer C.free(unsafe.Pointer(vpi)) + ret, err := C.proc_pidinfo(C.int(p.Pid), C.PROC_PIDVNODEPATHINFO, 0, unsafe.Pointer(vpi), vpiSize) + if err != nil { + // fmt.Printf("ret: %d %T\n", ret, err) + if err == syscall.EPERM { + return "", ErrorNotPermitted + } + return "", err + } + if ret <= 0 { + return "", fmt.Errorf("unknown error: proc_pidinfo returned %d", ret) + } + if ret != C.sizeof_struct_proc_vnodepathinfo { + return "", fmt.Errorf("too few bytes; expected %d, got %d", vpiSize, ret) + } + return C.GoString(&vpi.pvi_cdir.vip_path[0]), err +} + +func procArgs(pid int32) ([]byte, int, error) { + var ( + mib = [...]C.int{C.CTL_KERN, C.KERN_PROCARGS2, C.int(pid)} + size C.size_t = C.ulong(argMax) + nargs C.int + result []byte + ) + procargs := (*C.char)(C.malloc(C.ulong(argMax))) + defer C.free(unsafe.Pointer(procargs)) + retval, err := C.sysctl(&mib[0], 3, unsafe.Pointer(procargs), &size, C.NULL, 0) + if retval == 0 { + C.memcpy(unsafe.Pointer(&nargs), unsafe.Pointer(procargs), C.sizeof_int) + result = C.GoBytes(unsafe.Pointer(procargs), C.int(size)) + // fmt.Printf("size: %d %d\n%s\n", size, nargs, hex.Dump(result)) + return result, int(nargs), nil + } + return nil, 0, err +} + +func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { + return p.cmdlineSliceWithContext(ctx, true) +} + +func (p *Process) cmdlineSliceWithContext(ctx context.Context, fallback bool) ([]string, error) { + pargs, nargs, err := procArgs(p.Pid) + if err != nil { + return nil, err + } + // The first bytes hold the nargs int, skip it. + args := bytes.Split((pargs)[C.sizeof_int:], []byte{0}) + var argStr string + // The first element is the actual binary/command path. + // command := args[0] + var argSlice []string + // var envSlice []string + // All other, non-zero elements are arguments. The first "nargs" elements + // are the arguments. Everything else in the slice is then the environment + // of the process. + for _, arg := range args[1:] { + argStr = string(arg[:]) + if len(argStr) > 0 { + if nargs > 0 { + argSlice = append(argSlice, argStr) + nargs-- + continue + } + break + // envSlice = append(envSlice, argStr) + } + } + return argSlice, err +} + +// cmdNameWithContext returns the command name (including spaces) without any arguments +func (p *Process) cmdNameWithContext(ctx context.Context) (string, error) { + r, err := p.cmdlineSliceWithContext(ctx, false) + if err != nil { + return "", err + } + + if len(r) == 0 { + return "", nil + } + + return r[0], err +} + +func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { + r, err := p.CmdlineSliceWithContext(ctx) + if err != nil { + return "", err + } + return strings.Join(r, " "), err +} + +func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { + const tiSize = C.sizeof_struct_proc_taskinfo + ti := (*C.struct_proc_taskinfo)(C.malloc(tiSize)) + defer C.free(unsafe.Pointer(ti)) + + _, err := C.proc_pidinfo(C.int(p.Pid), C.PROC_PIDTASKINFO, 0, unsafe.Pointer(ti), tiSize) + if err != nil { + return 0, err + } + + return int32(ti.pti_threadnum), nil +} + +func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { + const tiSize = C.sizeof_struct_proc_taskinfo + ti := (*C.struct_proc_taskinfo)(C.malloc(tiSize)) + defer C.free(unsafe.Pointer(ti)) + + _, err := C.proc_pidinfo(C.int(p.Pid), C.PROC_PIDTASKINFO, 0, unsafe.Pointer(ti), tiSize) + if err != nil { + return nil, err + } + + ret := &cpu.TimesStat{ + CPU: "cpu", + User: float64(ti.pti_total_user) * timescaleToNanoSeconds / 1e9, + System: float64(ti.pti_total_system) * timescaleToNanoSeconds / 1e9, + } + return ret, nil +} + +func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { + const tiSize = C.sizeof_struct_proc_taskinfo + ti := (*C.struct_proc_taskinfo)(C.malloc(tiSize)) + defer C.free(unsafe.Pointer(ti)) + + _, err := C.proc_pidinfo(C.int(p.Pid), C.PROC_PIDTASKINFO, 0, unsafe.Pointer(ti), tiSize) + if err != nil { + return nil, err + } + + ret := &MemoryInfoStat{ + RSS: uint64(ti.pti_resident_size), + VMS: uint64(ti.pti_virtual_size), + Swap: uint64(ti.pti_pageins), + } + return ret, nil +} diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_nocgo.go new file mode 100644 index 000000000..bc1d357df --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_nocgo.go @@ -0,0 +1,127 @@ +//go:build darwin && !cgo +// +build darwin,!cgo + +package process + +import ( + "context" + "fmt" + "strconv" + "strings" + + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" +) + +func (p *Process) CwdWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + +func (p *Process) ExeWithContext(ctx context.Context) (string, error) { + out, err := invoke.CommandWithContext(ctx, "lsof", "-p", strconv.Itoa(int(p.Pid)), "-Fpfn") + if err != nil { + return "", fmt.Errorf("bad call to lsof: %s", err) + } + txtFound := 0 + lines := strings.Split(string(out), "\n") + for i := 1; i < len(lines); i++ { + if lines[i] == "ftxt" { + txtFound++ + if txtFound == 2 { + return lines[i-1][1:], nil + } + } + } + return "", fmt.Errorf("missing txt data returned by lsof") +} + +func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { + r, err := callPsWithContext(ctx, "command", p.Pid, false, false) + if err != nil { + return "", err + } + return strings.Join(r[0], " "), err +} + +func (p *Process) cmdNameWithContext(ctx context.Context) (string, error) { + r, err := callPsWithContext(ctx, "command", p.Pid, false, true) + if err != nil { + return "", err + } + if len(r) > 0 && len(r[0]) > 0 { + return r[0][0], err + } + + return "", err +} + +// CmdlineSliceWithContext returns the command line arguments of the process as a slice with each +// element being an argument. Because of current deficiencies in the way that the command +// line arguments are found, single arguments that have spaces in the will actually be +// reported as two separate items. In order to do something better CGO would be needed +// to use the native darwin functions. +func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { + r, err := callPsWithContext(ctx, "command", p.Pid, false, false) + if err != nil { + return nil, err + } + return r[0], err +} + +func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { + r, err := callPsWithContext(ctx, "utime,stime", p.Pid, true, false) + if err != nil { + return 0, err + } + return int32(len(r)), nil +} + +func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { + r, err := callPsWithContext(ctx, "utime,stime", p.Pid, false, false) + if err != nil { + return nil, err + } + + utime, err := convertCPUTimes(r[0][0]) + if err != nil { + return nil, err + } + stime, err := convertCPUTimes(r[0][1]) + if err != nil { + return nil, err + } + + ret := &cpu.TimesStat{ + CPU: "cpu", + User: utime, + System: stime, + } + return ret, nil +} + +func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { + r, err := callPsWithContext(ctx, "rss,vsize,pagein", p.Pid, false, false) + if err != nil { + return nil, err + } + rss, err := strconv.Atoi(r[0][0]) + if err != nil { + return nil, err + } + vms, err := strconv.Atoi(r[0][1]) + if err != nil { + return nil, err + } + pagein, err := strconv.Atoi(r[0][2]) + if err != nil { + return nil, err + } + + ret := &MemoryInfoStat{ + RSS: uint64(rss) * 1024, + VMS: uint64(vms) * 1024, + Swap: uint64(pagein), + } + + return ret, nil +} diff --git a/vendor/github.com/shirou/gopsutil/process/process_fallback.go b/vendor/github.com/shirou/gopsutil/v3/process/process_fallback.go similarity index 90% rename from vendor/github.com/shirou/gopsutil/process/process_fallback.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_fallback.go index 0d54900b1..1a5d0c4b4 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_fallback.go @@ -1,4 +1,5 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris +//go:build !darwin && !linux && !freebsd && !openbsd && !windows && !solaris && !plan9 +// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris,!plan9 package process @@ -6,11 +7,13 @@ import ( "context" "syscall" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/net" ) +type Signal = syscall.Signal + type MemoryMapsStat struct { Path string `json:"path"` Rss uint64 `json:"rss"` @@ -25,8 +28,7 @@ type MemoryMapsStat struct { Swap uint64 `json:"swap"` } -type MemoryInfoExStat struct { -} +type MemoryInfoExStat struct{} func pidsWithContext(ctx context.Context) ([]int32, error) { return nil, common.ErrNotImplementedError @@ -72,12 +74,8 @@ func (p *Process) CwdWithContext(ctx context.Context) (string, error) { return "", common.ErrNotImplementedError } -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { + return []string{""}, common.ErrNotImplementedError } func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { @@ -172,15 +170,11 @@ func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net return nil, common.ErrNotImplementedError } -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { return nil, common.ErrNotImplementedError } -func (p *Process) SendSignalWithContext(ctx context.Context, sig syscall.Signal) error { +func (p *Process) SendSignalWithContext(ctx context.Context, sig Signal) error { return common.ErrNotImplementedError } diff --git a/vendor/github.com/shirou/gopsutil/process/process_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd.go similarity index 89% rename from vendor/github.com/shirou/gopsutil/process/process_freebsd.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_freebsd.go index 0666e7f42..85134b7ee 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd // +build freebsd package process @@ -5,14 +6,13 @@ package process import ( "bytes" "context" - "os/exec" "path/filepath" "strconv" "strings" - cpu "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - net "github.com/shirou/gopsutil/net" + cpu "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + net "github.com/shirou/gopsutil/v3/net" "golang.org/x/sys/unix" ) @@ -55,8 +55,6 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) { extendedName := filepath.Base(cmdlineSlice[0]) if strings.HasPrefix(extendedName, p.name) { name = extendedName - } else { - name = cmdlineSlice[0] } } } @@ -64,10 +62,20 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) { return name, nil } -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { +func (p *Process) CwdWithContext(ctx context.Context) (string, error) { return "", common.ErrNotImplementedError } +func (p *Process) ExeWithContext(ctx context.Context) (string, error) { + mib := []int32{CTLKern, KernProc, KernProcPathname, p.Pid} + buf, _, err := common.CallSyscall(mib) + if err != nil { + return "", err + } + + return strings.Trim(string(buf), "\x00"), nil +} + func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { mib := []int32{CTLKern, KernProc, KernProcArgs, p.Pid} buf, _, err := common.CallSyscall(mib) @@ -106,47 +114,43 @@ func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) } func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError + k, err := p.getKProc() + if err != nil { + return 0, err + } + return int64(k.Start.Sec)*1000 + int64(k.Start.Usec)/1000, nil } -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { k, err := p.getKProc() if err != nil { - return "", err + return []string{""}, err } var s string switch k.Stat { case SIDL: - s = "I" + s = Idle case SRUN: - s = "R" + s = Running case SSLEEP: - s = "S" + s = Sleep case SSTOP: - s = "T" + s = Stop case SZOMB: - s = "Z" + s = Zombie case SWAIT: - s = "W" + s = Wait case SLOCK: - s = "L" + s = Lock } - return s, nil + return []string{s}, nil } func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details pid := p.Pid - ps, err := exec.LookPath("ps") - if err != nil { - return false, err - } - out, err := invoke.CommandWithContext(ctx, ps, "-o", "stat=", "-p", strconv.Itoa(int(pid))) + out, err := invoke.CommandWithContext(ctx, "ps", "-o", "stat=", "-p", strconv.Itoa(int(pid))) if err != nil { return false, err } diff --git a/vendor/github.com/shirou/gopsutil/process/process_freebsd_386.go b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_386.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/process/process_freebsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_386.go diff --git a/vendor/github.com/shirou/gopsutil/process/process_freebsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_amd64.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/process/process_freebsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_amd64.go diff --git a/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/process/process_freebsd_arm.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm.go diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm64.go new file mode 100644 index 000000000..effd470a0 --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm64.go @@ -0,0 +1,202 @@ +//go:build freebsd && arm64 +// +build freebsd,arm64 + +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs process/types_freebsd.go + +package process + +const ( + CTLKern = 1 + KernProc = 14 + KernProcPID = 1 + KernProcProc = 8 + KernProcPathname = 12 + KernProcArgs = 7 +) + +const ( + sizeofPtr = 0x8 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x8 + sizeofLongLong = 0x8 +) + +const ( + sizeOfKinfoVmentry = 0x488 + sizeOfKinfoProc = 0x440 +) + +const ( + SIDL = 1 + SRUN = 2 + SSLEEP = 3 + SSTOP = 4 + SZOMB = 5 + SWAIT = 6 + SLOCK = 7 +) + +type ( + _C_short int16 + _C_int int32 + _C_long int64 + _C_long_long int64 +) + +type Timespec struct { + Sec int64 + Nsec int64 +} + +type Timeval struct { + Sec int64 + Usec int64 +} + +type Rusage struct { + Utime Timeval + Stime Timeval + Maxrss int64 + Ixrss int64 + Idrss int64 + Isrss int64 + Minflt int64 + Majflt int64 + Nswap int64 + Inblock int64 + Oublock int64 + Msgsnd int64 + Msgrcv int64 + Nsignals int64 + Nvcsw int64 + Nivcsw int64 +} + +type Rlimit struct { + Cur int64 + Max int64 +} + +type KinfoProc struct { + Structsize int32 + Layout int32 + Args *int64 /* pargs */ + Paddr *int64 /* proc */ + Addr *int64 /* user */ + Tracep *int64 /* vnode */ + Textvp *int64 /* vnode */ + Fd *int64 /* filedesc */ + Vmspace *int64 /* vmspace */ + Wchan *byte + Pid int32 + Ppid int32 + Pgid int32 + Tpgid int32 + Sid int32 + Tsid int32 + Jobc int16 + Spare_short1 int16 + Tdev_freebsd11 uint32 + Siglist [16]byte /* sigset */ + Sigmask [16]byte /* sigset */ + Sigignore [16]byte /* sigset */ + Sigcatch [16]byte /* sigset */ + Uid uint32 + Ruid uint32 + Svuid uint32 + Rgid uint32 + Svgid uint32 + Ngroups int16 + Spare_short2 int16 + Groups [16]uint32 + Size uint64 + Rssize int64 + Swrss int64 + Tsize int64 + Dsize int64 + Ssize int64 + Xstat uint16 + Acflag uint16 + Pctcpu uint32 + Estcpu uint32 + Slptime uint32 + Swtime uint32 + Cow uint32 + Runtime uint64 + Start Timeval + Childtime Timeval + Flag int64 + Kiflag int64 + Traceflag int32 + Stat uint8 + Nice int8 + Lock uint8 + Rqindex uint8 + Oncpu_old uint8 + Lastcpu_old uint8 + Tdname [17]uint8 + Wmesg [9]uint8 + Login [18]uint8 + Lockname [9]uint8 + Comm [20]int8 + Emul [17]uint8 + Loginclass [18]uint8 + Moretdname [4]uint8 + Sparestrings [46]uint8 + Spareints [2]int32 + Tdev uint64 + Oncpu int32 + Lastcpu int32 + Tracer int32 + Flag2 int32 + Fibnum int32 + Cr_flags uint32 + Jid int32 + Numthreads int32 + Tid int32 + Pri Priority + Rusage Rusage + Rusage_ch Rusage + Pcb *int64 /* pcb */ + Kstack *byte + Udata *byte + Tdaddr *int64 /* thread */ + Spareptrs [6]*byte + Sparelongs [12]int64 + Sflag int64 + Tdflags int64 +} + +type Priority struct { + Class uint8 + Level uint8 + Native uint8 + User uint8 +} + +type KinfoVmentry struct { + Structsize int32 + Type int32 + Start uint64 + End uint64 + Offset uint64 + Vn_fileid uint64 + Vn_fsid_freebsd11 uint32 + Flags int32 + Resident int32 + Private_resident int32 + Protection int32 + Ref_count int32 + Shadow_count int32 + Vn_type int32 + Vn_size uint64 + Vn_rdev_freebsd11 uint32 + Vn_mode uint16 + Status uint16 + Vn_fsid uint64 + Vn_rdev uint64 + X_kve_ispare [8]int32 + Path [1024]uint8 +} diff --git a/vendor/github.com/shirou/gopsutil/process/process_linux.go b/vendor/github.com/shirou/gopsutil/v3/process/process_linux.go similarity index 88% rename from vendor/github.com/shirou/gopsutil/process/process_linux.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_linux.go index de742fbde..37cb7ca44 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package process @@ -15,24 +16,25 @@ import ( "strconv" "strings" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" "github.com/tklauser/go-sysconf" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/net" ) -var PageSize = uint64(os.Getpagesize()) +var pageSize = uint64(os.Getpagesize()) -const PrioProcess = 0 // linux/resource.h +const prioProcess = 0 // linux/resource.h -var ClockTicks = 100 // default value +var clockTicks = 100 // default value func init() { clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) // ignore errors if err == nil { - ClockTicks = int(clkTck) + clockTicks = int(clkTck) } } @@ -122,29 +124,18 @@ func (p *Process) CwdWithContext(ctx context.Context) (string, error) { return p.fillFromCwdWithContext(ctx) } -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { err := p.fillFromStatusWithContext(ctx) if err != nil { - return nil, err - } - if p.parent == 0 { - return nil, fmt.Errorf("wrong number of parents") - } - return NewProcessWithContext(ctx, p.parent) -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return "", err + return []string{""}, err } - return p.status, nil + return []string{p.status}, nil } func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "stat") + statPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "stat") contents, err := ioutil.ReadFile(statPath) if err != nil { return false, err @@ -251,7 +242,7 @@ func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ( case RLIMIT_AS: rs.Used = uint64(p.memInfo.VMS) case RLIMIT_LOCKS: - //TODO we can get the used value from /proc/$pid/locks. But linux doesn't enforce it, so not a high priority. + // TODO we can get the used value from /proc/$pid/locks. But linux doesn't enforce it, so not a high priority. case RLIMIT_SIGPENDING: rs.Used = p.sigInfo.PendingProcess case RLIMIT_NICE: @@ -293,7 +284,7 @@ func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { ret := make(map[int32]*cpu.TimesStat) - taskPath := common.HostProc(strconv.Itoa(int(p.Pid)), "task") + taskPath := common.HostProcWithContext(ctx, strconv.Itoa(int(p.Pid)), "task") tids, err := readPidsFromDir(taskPath) if err != nil { @@ -345,17 +336,16 @@ func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, e return nil, err } return pageFaults, nil - } func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { pids, err := common.CallPgrepWithContext(ctx, invoke, p.Pid) if err != nil { - if len(pids) == 0 { - return nil, ErrorNoChildren - } return nil, err } + if len(pids) == 0 { + return nil, ErrorNoChildren + } ret := make([]*Process, 0, len(pids)) for _, pid := range pids { np, err := NewProcessWithContext(ctx, pid) @@ -388,18 +378,19 @@ func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net return net.ConnectionsPidMaxWithContext(ctx, "all", p.Pid, max) } -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - filename := common.HostProc(strconv.Itoa(int(p.Pid)), "net/dev") - return net.IOCountersByFileWithContext(ctx, pernic, filename) -} - func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { pid := p.Pid var ret []MemoryMapsStat + smapsPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "smaps") if grouped { ret = make([]MemoryMapsStat, 1) + // If smaps_rollup exists (require kernel >= 4.15), then we will use it + // for pre-summed memory information for a process. + smapsRollupPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "smaps_rollup") + if _, err := os.Stat(smapsRollupPath); !os.IsNotExist(err) { + smapsPath = smapsRollupPath + } } - smapsPath := common.HostProc(strconv.Itoa(int(pid)), "smaps") contents, err := ioutil.ReadFile(smapsPath) if err != nil { return nil, err @@ -454,9 +445,9 @@ func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]M var firstLine []string blocks := make([]string, 0, 16) + for i, line := range lines { fields := strings.Fields(line) - if (len(fields) > 0 && !strings.HasSuffix(fields[0], ":")) || i == len(lines)-1 { // new block section if len(firstLine) > 0 && len(blocks) > 0 { @@ -491,7 +482,7 @@ func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]M } func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { - environPath := common.HostProc(strconv.Itoa(int(p.Pid)), "environ") + environPath := common.HostProcWithContext(ctx, strconv.Itoa(int(p.Pid)), "environ") environContent, err := ioutil.ReadFile(environPath) if err != nil { @@ -505,44 +496,21 @@ func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { ** Internal functions **/ -func limitToInt(val string) (int32, error) { +func limitToUint(val string) (uint64, error) { if val == "unlimited" { - return math.MaxInt32, nil - } else { - res, err := strconv.ParseInt(val, 10, 32) - if err != nil { - return 0, err - } - return int32(res), nil + return math.MaxUint64, nil } -} - -// Get name from /proc/(pid)/comm or /proc/(pid)/status -func (p *Process) fillNameWithContext(ctx context.Context) error { - err := p.fillFromCommWithContext(ctx) - if err == nil && p.name != "" && len(p.name) < 15 { - return nil - } - return p.fillFromStatusWithContext(ctx) -} - -// Get name from /proc/(pid)/comm -func (p *Process) fillFromCommWithContext(ctx context.Context) error { - pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "comm") - contents, err := ioutil.ReadFile(statPath) + res, err := strconv.ParseUint(val, 10, 64) if err != nil { - return err + return 0, err } - - p.name = strings.TrimSuffix(string(contents), "\n") - return nil + return res, nil } // Get num_fds from /proc/(pid)/limits func (p *Process) fillFromLimitsWithContext(ctx context.Context) ([]RlimitStat, error) { pid := p.Pid - limitsFile := common.HostProc(strconv.Itoa(int(pid)), "limits") + limitsFile := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "limits") d, err := os.Open(limitsFile) if err != nil { return nil, err @@ -563,11 +531,11 @@ func (p *Process) fillFromLimitsWithContext(ctx context.Context) ([]RlimitStat, } // Assert that last item is a Hard limit - statItem.Hard, err = limitToInt(str[len(str)-1]) + statItem.Hard, err = limitToUint(str[len(str)-1]) if err != nil { - // On error remove last item an try once again since it can be unit or header line + // On error remove last item and try once again since it can be unit or header line str = str[:len(str)-1] - statItem.Hard, err = limitToInt(str[len(str)-1]) + statItem.Hard, err = limitToUint(str[len(str)-1]) if err != nil { return nil, err } @@ -575,15 +543,15 @@ func (p *Process) fillFromLimitsWithContext(ctx context.Context) ([]RlimitStat, // Remove last item from string str = str[:len(str)-1] - //Now last item is a Soft limit - statItem.Soft, err = limitToInt(str[len(str)-1]) + // Now last item is a Soft limit + statItem.Soft, err = limitToUint(str[len(str)-1]) if err != nil { return nil, err } // Remove last item from string str = str[:len(str)-1] - //The rest is a stats name + // The rest is a stats name resourceName := strings.Join(str, " ") switch resourceName { case "Max cpu time": @@ -635,7 +603,7 @@ func (p *Process) fillFromLimitsWithContext(ctx context.Context) ([]RlimitStat, // Get list of /proc/(pid)/fd files func (p *Process) fillFromfdListWithContext(ctx context.Context) (string, []string, error) { pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "fd") + statPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "fd") d, err := os.Open(statPath) if err != nil { return statPath, []string{}, err @@ -677,7 +645,7 @@ func (p *Process) fillFromfdWithContext(ctx context.Context) (int32, []*OpenFile // Get cwd from /proc/(pid)/cwd func (p *Process) fillFromCwdWithContext(ctx context.Context) (string, error) { pid := p.Pid - cwdPath := common.HostProc(strconv.Itoa(int(pid)), "cwd") + cwdPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "cwd") cwd, err := os.Readlink(cwdPath) if err != nil { return "", err @@ -688,7 +656,7 @@ func (p *Process) fillFromCwdWithContext(ctx context.Context) (string, error) { // Get exe from /proc/(pid)/exe func (p *Process) fillFromExeWithContext(ctx context.Context) (string, error) { pid := p.Pid - exePath := common.HostProc(strconv.Itoa(int(pid)), "exe") + exePath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "exe") exe, err := os.Readlink(exePath) if err != nil { return "", err @@ -699,7 +667,7 @@ func (p *Process) fillFromExeWithContext(ctx context.Context) (string, error) { // Get cmdline from /proc/(pid)/cmdline func (p *Process) fillFromCmdlineWithContext(ctx context.Context) (string, error) { pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") + cmdPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "cmdline") cmdline, err := ioutil.ReadFile(cmdPath) if err != nil { return "", err @@ -713,7 +681,7 @@ func (p *Process) fillFromCmdlineWithContext(ctx context.Context) (string, error func (p *Process) fillSliceFromCmdlineWithContext(ctx context.Context) ([]string, error) { pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") + cmdPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "cmdline") cmdline, err := ioutil.ReadFile(cmdPath) if err != nil { return nil, err @@ -721,9 +689,9 @@ func (p *Process) fillSliceFromCmdlineWithContext(ctx context.Context) ([]string if len(cmdline) == 0 { return nil, nil } - if cmdline[len(cmdline)-1] == 0 { - cmdline = cmdline[:len(cmdline)-1] - } + + cmdline = bytes.TrimRight(cmdline, "\x00") + parts := bytes.Split(cmdline, []byte{0}) var strParts []string for _, p := range parts { @@ -736,7 +704,7 @@ func (p *Process) fillSliceFromCmdlineWithContext(ctx context.Context) ([]string // Get IO status from /proc/(pid)/io func (p *Process) fillFromIOWithContext(ctx context.Context) (*IOCountersStat, error) { pid := p.Pid - ioPath := common.HostProc(strconv.Itoa(int(pid)), "io") + ioPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "io") ioline, err := ioutil.ReadFile(ioPath) if err != nil { return nil, err @@ -753,10 +721,7 @@ func (p *Process) fillFromIOWithContext(ctx context.Context) (*IOCountersStat, e if err != nil { return nil, err } - param := field[0] - if strings.HasSuffix(param, ":") { - param = param[:len(param)-1] - } + param := strings.TrimSuffix(field[0], ":") switch param { case "syscr": ret.ReadCount = t @@ -775,7 +740,7 @@ func (p *Process) fillFromIOWithContext(ctx context.Context) (*IOCountersStat, e // Get memory info from /proc/(pid)/statm func (p *Process) fillFromStatmWithContext(ctx context.Context) (*MemoryInfoStat, *MemoryInfoExStat, error) { pid := p.Pid - memPath := common.HostProc(strconv.Itoa(int(pid)), "statm") + memPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "statm") contents, err := ioutil.ReadFile(memPath) if err != nil { return nil, nil, err @@ -791,8 +756,8 @@ func (p *Process) fillFromStatmWithContext(ctx context.Context) (*MemoryInfoStat return nil, nil, err } memInfo := &MemoryInfoStat{ - RSS: rss * PageSize, - VMS: vms * PageSize, + RSS: rss * pageSize, + VMS: vms * pageSize, } shared, err := strconv.ParseUint(fields[2], 10, 64) @@ -813,21 +778,47 @@ func (p *Process) fillFromStatmWithContext(ctx context.Context) (*MemoryInfoStat } memInfoEx := &MemoryInfoExStat{ - RSS: rss * PageSize, - VMS: vms * PageSize, - Shared: shared * PageSize, - Text: text * PageSize, - Lib: lib * PageSize, - Dirty: dirty * PageSize, + RSS: rss * pageSize, + VMS: vms * pageSize, + Shared: shared * pageSize, + Text: text * pageSize, + Lib: lib * pageSize, + Dirty: dirty * pageSize, } return memInfo, memInfoEx, nil } +// Get name from /proc/(pid)/comm or /proc/(pid)/status +func (p *Process) fillNameWithContext(ctx context.Context) error { + err := p.fillFromCommWithContext(ctx) + if err == nil && p.name != "" && len(p.name) < 15 { + return nil + } + return p.fillFromStatusWithContext(ctx) +} + +// Get name from /proc/(pid)/comm +func (p *Process) fillFromCommWithContext(ctx context.Context) error { + pid := p.Pid + statPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "comm") + contents, err := ioutil.ReadFile(statPath) + if err != nil { + return err + } + + p.name = strings.TrimSuffix(string(contents), "\n") + return nil +} + // Get various status from /proc/(pid)/status +func (p *Process) fillFromStatus() error { + return p.fillFromStatusWithContext(context.Background()) +} + func (p *Process) fillFromStatusWithContext(ctx context.Context) error { pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "status") + statPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "status") contents, err := ioutil.ReadFile(statPath) if err != nil { return err @@ -846,7 +837,7 @@ func (p *Process) fillFromStatusWithContext(ctx context.Context) error { case "Name": p.name = strings.Trim(value, " \t") if len(p.name) >= 15 { - cmdlineSlice, err := p.CmdlineSlice() + cmdlineSlice, err := p.CmdlineSliceWithContext(ctx) if err != nil { return err } @@ -854,15 +845,13 @@ func (p *Process) fillFromStatusWithContext(ctx context.Context) error { extendedName := filepath.Base(cmdlineSlice[0]) if strings.HasPrefix(extendedName, p.name) { p.name = extendedName - } else { - p.name = cmdlineSlice[0] } } } // Ensure we have a copy and not reference into slice p.name = string([]byte(p.name)) case "State": - p.status = value[0:1] + p.status = convertStatusChar(value[0:1]) // Ensure we have a copy and not reference into slice p.status = string([]byte(p.status)) case "PPid", "Ppid": @@ -1023,14 +1012,18 @@ func (p *Process) fillFromStatusWithContext(ctx context.Context) error { return nil } +func (p *Process) fillFromTIDStat(tid int32) (uint64, int32, *cpu.TimesStat, int64, uint32, int32, *PageFaultsStat, error) { + return p.fillFromTIDStatWithContext(context.Background(), tid) +} + func (p *Process) fillFromTIDStatWithContext(ctx context.Context, tid int32) (uint64, int32, *cpu.TimesStat, int64, uint32, int32, *PageFaultsStat, error) { pid := p.Pid var statPath string if tid == -1 { - statPath = common.HostProc(strconv.Itoa(int(pid)), "stat") + statPath = common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "stat") } else { - statPath = common.HostProc(strconv.Itoa(int(pid)), "task", strconv.Itoa(int(tid)), "stat") + statPath = common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "task", strconv.Itoa(int(tid)), "stat") } contents, err := ioutil.ReadFile(statPath) @@ -1074,9 +1067,9 @@ func (p *Process) fillFromTIDStatWithContext(ctx context.Context, tid int32) (ui cpuTimes := &cpu.TimesStat{ CPU: "cpu", - User: utime / float64(ClockTicks), - System: stime / float64(ClockTicks), - Iowait: iotime / float64(ClockTicks), + User: utime / float64(clockTicks), + System: stime / float64(clockTicks), + Iowait: iotime / float64(clockTicks), } bootTime, _ := common.BootTimeWithContext(ctx) @@ -1084,7 +1077,7 @@ func (p *Process) fillFromTIDStatWithContext(ctx context.Context, tid int32) (ui if err != nil { return 0, 0, nil, 0, 0, 0, nil, err } - ctime := (t / uint64(ClockTicks)) + uint64(bootTime) + ctime := (t / uint64(clockTicks)) + uint64(bootTime) createTime := int64(ctime * 1000) rtpriority, err := strconv.ParseInt(fields[18], 10, 32) @@ -1099,7 +1092,7 @@ func (p *Process) fillFromTIDStatWithContext(ctx context.Context, tid int32) (ui // p.Nice = mustParseInt32(fields[18]) // use syscall instead of parse Stat file - snice, _ := unix.Getpriority(PrioProcess, int(pid)) + snice, _ := unix.Getpriority(prioProcess, int(pid)) nice := int32(snice) // FIXME: is this true? minFault, err := strconv.ParseUint(fields[10], 10, 64) @@ -1134,7 +1127,7 @@ func (p *Process) fillFromStatWithContext(ctx context.Context) (uint64, int32, * } func pidsWithContext(ctx context.Context) ([]int32, error) { - return readPidsFromDir(common.HostProc()) + return readPidsFromDir(common.HostProcWithContext(ctx)) } func ProcessesWithContext(ctx context.Context) ([]*Process, error) { diff --git a/vendor/github.com/shirou/gopsutil/process/process_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd.go similarity index 92% rename from vendor/github.com/shirou/gopsutil/process/process_openbsd.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_openbsd.go index 902664b06..a58c5eb11 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package process @@ -8,16 +9,15 @@ import ( "encoding/binary" "fmt" "io" - "os/exec" "path/filepath" "strconv" "strings" "unsafe" - cpu "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - mem "github.com/shirou/gopsutil/mem" - net "github.com/shirou/gopsutil/net" + cpu "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + mem "github.com/shirou/gopsutil/v3/mem" + net "github.com/shirou/gopsutil/v3/net" "golang.org/x/sys/unix" ) @@ -60,8 +60,6 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) { extendedName := filepath.Base(cmdlineSlice[0]) if strings.HasPrefix(extendedName, p.name) { name = extendedName - } else { - name = cmdlineSlice[0] } } } @@ -69,6 +67,10 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) { return name, nil } +func (p *Process) CwdWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + func (p *Process) ExeWithContext(ctx context.Context) (string, error) { return "", common.ErrNotImplementedError } @@ -76,7 +78,6 @@ func (p *Process) ExeWithContext(ctx context.Context) (string, error) { func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { mib := []int32{CTLKern, KernProcArgs, p.Pid, KernProcArgv} buf, _, err := common.CallSyscall(mib) - if err != nil { return nil, err } @@ -138,40 +139,32 @@ func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { return 0, common.ErrNotImplementedError } -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { k, err := p.getKProc() if err != nil { - return "", err + return []string{""}, err } var s string switch k.Stat { case SIDL: case SRUN: case SONPROC: - s = "R" + s = Running case SSLEEP: - s = "S" + s = Sleep case SSTOP: - s = "T" + s = Stop case SDEAD: - s = "Z" + s = Zombie } - return s, nil + return []string{s}, nil } func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details pid := p.Pid - ps, err := exec.LookPath("ps") - if err != nil { - return false, err - } - out, err := invoke.CommandWithContext(ctx, ps, "-o", "stat=", "-p", strconv.Itoa(int(pid))) + out, err := invoke.CommandWithContext(ctx, "ps", "-o", "stat=", "-p", strconv.Itoa(int(pid))) if err != nil { return false, err } @@ -314,7 +307,6 @@ func ProcessesWithContext(ctx context.Context) ([]*Process, error) { results := []*Process{} buf, length, err := callKernProcSyscall(KernProcAll, 0) - if err != nil { return results, err } diff --git a/vendor/github.com/shirou/gopsutil/process/process_openbsd_386.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_386.go similarity index 98% rename from vendor/github.com/shirou/gopsutil/process/process_openbsd_386.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_386.go index b89fb8dc2..f4ed02491 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_openbsd_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_386.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build 386 +//go:build openbsd && 386 +// +build openbsd,386 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs process/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/process/process_openbsd_amd64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_amd64.go similarity index 100% rename from vendor/github.com/shirou/gopsutil/process/process_openbsd_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_amd64.go diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm.go new file mode 100644 index 000000000..b94429f2e --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm.go @@ -0,0 +1,202 @@ +//go:build openbsd && arm +// +build openbsd,arm + +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs process/types_openbsd.go + +package process + +const ( + CTLKern = 1 + KernProc = 66 + KernProcAll = 0 + KernProcPID = 1 + KernProcProc = 8 + KernProcPathname = 12 + KernProcArgs = 55 + KernProcArgv = 1 + KernProcEnv = 3 +) + +const ( + ArgMax = 256 * 1024 +) + +const ( + sizeofPtr = 0x4 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x4 + sizeofLongLong = 0x8 +) + +const ( + sizeOfKinfoVmentry = 0x38 + sizeOfKinfoProc = 0x264 +) + +const ( + SIDL = 1 + SRUN = 2 + SSLEEP = 3 + SSTOP = 4 + SZOMB = 5 + SDEAD = 6 + SONPROC = 7 +) + +type ( + _C_short int16 + _C_int int32 + _C_long int32 + _C_long_long int64 +) + +type Timespec struct { + Sec int64 + Nsec int32 +} + +type Timeval struct { + Sec int64 + Usec int32 +} + +type Rusage struct { + Utime Timeval + Stime Timeval + Maxrss int32 + Ixrss int32 + Idrss int32 + Isrss int32 + Minflt int32 + Majflt int32 + Nswap int32 + Inblock int32 + Oublock int32 + Msgsnd int32 + Msgrcv int32 + Nsignals int32 + Nvcsw int32 + Nivcsw int32 +} + +type Rlimit struct { + Cur uint64 + Max uint64 +} + +type KinfoProc struct { + Forw uint64 + Back uint64 + Paddr uint64 + Addr uint64 + Fd uint64 + Stats uint64 + Limit uint64 + Vmspace uint64 + Sigacts uint64 + Sess uint64 + Tsess uint64 + Ru uint64 + Eflag int32 + Exitsig int32 + Flag int32 + Pid int32 + Ppid int32 + Sid int32 + X_pgid int32 + Tpgid int32 + Uid uint32 + Ruid uint32 + Gid uint32 + Rgid uint32 + Groups [16]uint32 + Ngroups int16 + Jobc int16 + Tdev uint32 + Estcpu uint32 + Rtime_sec uint32 + Rtime_usec uint32 + Cpticks int32 + Pctcpu uint32 + Swtime uint32 + Slptime uint32 + Schedflags int32 + Uticks uint64 + Sticks uint64 + Iticks uint64 + Tracep uint64 + Traceflag int32 + Holdcnt int32 + Siglist int32 + Sigmask uint32 + Sigignore uint32 + Sigcatch uint32 + Stat int8 + Priority uint8 + Usrpri uint8 + Nice uint8 + Xstat uint16 + Acflag uint16 + Comm [24]int8 + Wmesg [8]int8 + Wchan uint64 + Login [32]int8 + Vm_rssize int32 + Vm_tsize int32 + Vm_dsize int32 + Vm_ssize int32 + Uvalid int64 + Ustart_sec uint64 + Ustart_usec uint32 + Uutime_sec uint32 + Uutime_usec uint32 + Ustime_sec uint32 + Ustime_usec uint32 + Uru_maxrss uint64 + Uru_ixrss uint64 + Uru_idrss uint64 + Uru_isrss uint64 + Uru_minflt uint64 + Uru_majflt uint64 + Uru_nswap uint64 + Uru_inblock uint64 + Uru_oublock uint64 + Uru_msgsnd uint64 + Uru_msgrcv uint64 + Uru_nsignals uint64 + Uru_nvcsw uint64 + Uru_nivcsw uint64 + Uctime_sec uint32 + Uctime_usec uint32 + Psflags int32 + Spare int32 + Svuid uint32 + Svgid uint32 + Emul [8]int8 + Rlim_rss_cur uint64 + Cpuid uint64 + Vm_map_size uint64 + Tid int32 + Rtableid uint32 +} + +type Priority struct{} + +type KinfoVmentry struct { + Start uint32 + End uint32 + Guard uint32 + Fspace uint32 + Fspace_augment uint32 + Offset uint64 + Wired_count int32 + Etype int32 + Protection int32 + Max_protection int32 + Advice int32 + Inheritance int32 + Flags uint8 + Pad_cgo_0 [3]byte +} diff --git a/vendor/github.com/shirou/gopsutil/process/process_openbsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm64.go similarity index 98% rename from vendor/github.com/shirou/gopsutil/process/process_openbsd_arm64.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm64.go index 2d97fbc5c..a3291b8ca 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_openbsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm64.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build arm64 +//go:build openbsd && arm64 +// +build openbsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs process/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_plan9.go b/vendor/github.com/shirou/gopsutil/v3/process/process_plan9.go new file mode 100644 index 000000000..bc4bc062a --- /dev/null +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_plan9.go @@ -0,0 +1,203 @@ +//go:build plan9 +// +build plan9 + +package process + +import ( + "context" + "syscall" + + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/net" +) + +type Signal = syscall.Note + +type MemoryMapsStat struct { + Path string `json:"path"` + Rss uint64 `json:"rss"` + Size uint64 `json:"size"` + Pss uint64 `json:"pss"` + SharedClean uint64 `json:"sharedClean"` + SharedDirty uint64 `json:"sharedDirty"` + PrivateClean uint64 `json:"privateClean"` + PrivateDirty uint64 `json:"privateDirty"` + Referenced uint64 `json:"referenced"` + Anonymous uint64 `json:"anonymous"` + Swap uint64 `json:"swap"` +} + +type MemoryInfoExStat struct{} + +func pidsWithContext(ctx context.Context) ([]int32, error) { + return nil, common.ErrNotImplementedError +} + +func ProcessesWithContext(ctx context.Context) ([]*Process, error) { + return nil, common.ErrNotImplementedError +} + +func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { + return false, common.ErrNotImplementedError +} + +func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { + return 0, common.ErrNotImplementedError +} + +func (p *Process) NameWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + +func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { + return 0, common.ErrNotImplementedError +} + +func (p *Process) ExeWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + +func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + +func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { + return 0, common.ErrNotImplementedError +} + +func (p *Process) CwdWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { + return []string{""}, common.ErrNotImplementedError +} + +func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { + return false, common.ErrNotImplementedError +} + +func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + +func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { + return 0, common.ErrNotImplementedError +} + +func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { + return 0, common.ErrNotImplementedError +} + +func (p *Process) RlimitWithContext(ctx context.Context) ([]RlimitStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ([]RlimitStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) NumCtxSwitchesWithContext(ctx context.Context) (*NumCtxSwitchesStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) NumFDsWithContext(ctx context.Context) (int32, error) { + return 0, common.ErrNotImplementedError +} + +func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { + return 0, common.ErrNotImplementedError +} + +func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) CPUAffinityWithContext(ctx context.Context) ([]int32, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) MemoryInfoExWithContext(ctx context.Context) (*MemoryInfoExStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { + return nil, common.ErrNotImplementedError +} + +func (p *Process) SendSignalWithContext(ctx context.Context, sig Signal) error { + return common.ErrNotImplementedError +} + +func (p *Process) SuspendWithContext(ctx context.Context) error { + return common.ErrNotImplementedError +} + +func (p *Process) ResumeWithContext(ctx context.Context) error { + return common.ErrNotImplementedError +} + +func (p *Process) TerminateWithContext(ctx context.Context) error { + return common.ErrNotImplementedError +} + +func (p *Process) KillWithContext(ctx context.Context) error { + return common.ErrNotImplementedError +} + +func (p *Process) UsernameWithContext(ctx context.Context) (string, error) { + return "", common.ErrNotImplementedError +} + +func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { + return nil, common.ErrNotImplementedError +} diff --git a/vendor/github.com/shirou/gopsutil/process/process_posix.go b/vendor/github.com/shirou/gopsutil/v3/process/process_posix.go similarity index 87% rename from vendor/github.com/shirou/gopsutil/process/process_posix.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_posix.go index 45e6d1389..a01f9ecfc 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_posix.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_posix.go @@ -1,9 +1,11 @@ +//go:build linux || freebsd || openbsd || darwin || solaris // +build linux freebsd openbsd darwin solaris package process import ( "context" + "errors" "fmt" "os" "os/user" @@ -12,10 +14,13 @@ import ( "strings" "syscall" - "github.com/shirou/gopsutil/internal/common" "golang.org/x/sys/unix" + + "github.com/shirou/gopsutil/v3/internal/common" ) +type Signal = syscall.Signal + // POSIX func getTerminalMap() (map[uint64]string, error) { ret := make(map[uint64]string) @@ -80,7 +85,7 @@ func isMount(path string) bool { if err != nil { return false } - if fileInfo.Mode() & os.ModeSymlink != 0 { + if fileInfo.Mode()&os.ModeSymlink != 0 { return false } var stat1 unix.Stat_t @@ -104,8 +109,8 @@ func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { return false, err } - if isMount(common.HostProc()) { // if //proc exists and is mounted, check if //proc/ folder exists - _, err := os.Stat(common.HostProc(strconv.Itoa(int(pid)))) + if isMount(common.HostProcWithContext(ctx)) { // if //proc exists and is mounted, check if //proc/ folder exists + _, err := os.Stat(common.HostProcWithContext(ctx, strconv.Itoa(int(pid)))) if os.IsNotExist(err) { return false, nil } @@ -117,11 +122,11 @@ func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { if err == nil { return true, nil } - if err.Error() == "os: process already finished" { + if errors.Is(err, os.ErrProcessDone) { return false, nil } - errno, ok := err.(syscall.Errno) - if !ok { + var errno syscall.Errno + if !errors.As(err, &errno) { return false, err } switch errno { diff --git a/vendor/github.com/shirou/gopsutil/process/process_solaris.go b/vendor/github.com/shirou/gopsutil/v3/process/process_solaris.go similarity index 88% rename from vendor/github.com/shirou/gopsutil/process/process_solaris.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_solaris.go index f24a327b1..ad1c3cfc1 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_solaris.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_solaris.go @@ -8,9 +8,9 @@ import ( "strconv" "strings" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/net" ) type MemoryMapsStat struct { @@ -27,11 +27,10 @@ type MemoryMapsStat struct { Swap uint64 `json:"swap"` } -type MemoryInfoExStat struct { -} +type MemoryInfoExStat struct{} func pidsWithContext(ctx context.Context) ([]int32, error) { - return readPidsFromDir(common.HostProc()) + return readPidsFromDir(common.HostProcWithContext(ctx)) } func ProcessesWithContext(ctx context.Context) ([]*Process, error) { @@ -89,12 +88,8 @@ func (p *Process) CwdWithContext(ctx context.Context) (string, error) { return p.fillFromPathCwdWithContext(ctx) } -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { + return []string{""}, common.ErrNotImplementedError } func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { @@ -190,10 +185,6 @@ func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net return nil, common.ErrNotImplementedError } -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { return nil, common.ErrNotImplementedError } @@ -208,7 +199,7 @@ func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { func (p *Process) fillFromfdListWithContext(ctx context.Context) (string, []string, error) { pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "fd") + statPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "fd") d, err := os.Open(statPath) if err != nil { return statPath, []string{}, err @@ -220,7 +211,7 @@ func (p *Process) fillFromfdListWithContext(ctx context.Context) (string, []stri func (p *Process) fillFromPathCwdWithContext(ctx context.Context) (string, error) { pid := p.Pid - cwdPath := common.HostProc(strconv.Itoa(int(pid)), "path", "cwd") + cwdPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "path", "cwd") cwd, err := os.Readlink(cwdPath) if err != nil { return "", err @@ -230,7 +221,7 @@ func (p *Process) fillFromPathCwdWithContext(ctx context.Context) (string, error func (p *Process) fillFromPathAOutWithContext(ctx context.Context) (string, error) { pid := p.Pid - cwdPath := common.HostProc(strconv.Itoa(int(pid)), "path", "a.out") + cwdPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "path", "a.out") exe, err := os.Readlink(cwdPath) if err != nil { return "", err @@ -240,7 +231,7 @@ func (p *Process) fillFromPathAOutWithContext(ctx context.Context) (string, erro func (p *Process) fillFromExecnameWithContext(ctx context.Context) (string, error) { pid := p.Pid - execNamePath := common.HostProc(strconv.Itoa(int(pid)), "execname") + execNamePath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "execname") exe, err := ioutil.ReadFile(execNamePath) if err != nil { return "", err @@ -250,7 +241,7 @@ func (p *Process) fillFromExecnameWithContext(ctx context.Context) (string, erro func (p *Process) fillFromCmdlineWithContext(ctx context.Context) (string, error) { pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") + cmdPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "cmdline") cmdline, err := ioutil.ReadFile(cmdPath) if err != nil { return "", err @@ -267,7 +258,7 @@ func (p *Process) fillFromCmdlineWithContext(ctx context.Context) (string, error func (p *Process) fillSliceFromCmdlineWithContext(ctx context.Context) ([]string, error) { pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") + cmdPath := common.HostProcWithContext(ctx, strconv.Itoa(int(pid)), "cmdline") cmdline, err := ioutil.ReadFile(cmdPath) if err != nil { return nil, err diff --git a/vendor/github.com/shirou/gopsutil/process/process_windows.go b/vendor/github.com/shirou/gopsutil/v3/process/process_windows.go similarity index 88% rename from vendor/github.com/shirou/gopsutil/process/process_windows.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_windows.go index e410a0eb1..14ed0309f 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package process @@ -9,6 +10,7 @@ import ( "fmt" "io" "os" + "path/filepath" "reflect" "strings" "syscall" @@ -16,12 +18,14 @@ import ( "unicode/utf16" "unsafe" - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" + "github.com/shirou/gopsutil/v3/cpu" + "github.com/shirou/gopsutil/v3/internal/common" + "github.com/shirou/gopsutil/v3/net" "golang.org/x/sys/windows" ) +type Signal = syscall.Signal + var ( modntdll = windows.NewLazySystemDLL("ntdll.dll") procNtResumeProcess = modntdll.NewProc("NtResumeProcess") @@ -45,21 +49,6 @@ var ( const processQueryInformation = windows.PROCESS_QUERY_LIMITED_INFORMATION -type SystemProcessInformation struct { - NextEntryOffset uint64 - NumberOfThreads uint64 - Reserved1 [48]byte - Reserved2 [3]byte - UniqueProcessID uintptr - Reserved3 uintptr - HandleCount uint64 - Reserved4 [4]byte - Reserved5 [11]byte - PeakPagefileUsage uint64 - PrivatePageCount uint64 - Reserved6 [6]uint64 -} - type systemProcessorInformation struct { ProcessorArchitecture uint16 ProcessorLevel uint16 @@ -71,7 +60,7 @@ type systemProcessorInformation struct { type systemInfo struct { wProcessorArchitecture uint16 wReserved uint16 - dwPageSize uint32 + dwpageSize uint32 lpMinimumApplicationAddress uintptr lpMaximumApplicationAddress uintptr dwActiveProcessorMask uintptr @@ -83,11 +72,9 @@ type systemInfo struct { } // Memory_info_ex is different between OSes -type MemoryInfoExStat struct { -} +type MemoryInfoExStat struct{} -type MemoryMapsStat struct { -} +type MemoryMapsStat struct{} // ioCounters is an equivalent representation of IO_COUNTERS in the Windows API. // https://docs.microsoft.com/windows/win32/api/winnt/ns-winnt-io_counters @@ -140,54 +127,54 @@ type processEnvironmentBlock64 struct { } type rtlUserProcessParameters32 struct { - Reserved1 [16]uint8 - ConsoleHandle uint32 - ConsoleFlags uint32 - StdInputHandle uint32 - StdOutputHandle uint32 - StdErrorHandle uint32 + Reserved1 [16]uint8 + ConsoleHandle uint32 + ConsoleFlags uint32 + StdInputHandle uint32 + StdOutputHandle uint32 + StdErrorHandle uint32 CurrentDirectoryPathNameLength uint16 - _ uint16 // Max Length - CurrentDirectoryPathAddress uint32 - CurrentDirectoryHandle uint32 - DllPathNameLength uint16 - _ uint16 // Max Length - DllPathAddress uint32 - ImagePathNameLength uint16 - _ uint16 // Max Length - ImagePathAddress uint32 - CommandLineLength uint16 - _ uint16 // Max Length - CommandLineAddress uint32 - EnvironmentAddress uint32 + _ uint16 // Max Length + CurrentDirectoryPathAddress uint32 + CurrentDirectoryHandle uint32 + DllPathNameLength uint16 + _ uint16 // Max Length + DllPathAddress uint32 + ImagePathNameLength uint16 + _ uint16 // Max Length + ImagePathAddress uint32 + CommandLineLength uint16 + _ uint16 // Max Length + CommandLineAddress uint32 + EnvironmentAddress uint32 // More fields which we don't use so far } type rtlUserProcessParameters64 struct { - Reserved1 [16]uint8 - ConsoleHandle uint64 - ConsoleFlags uint64 - StdInputHandle uint64 - StdOutputHandle uint64 - StdErrorHandle uint64 + Reserved1 [16]uint8 + ConsoleHandle uint64 + ConsoleFlags uint64 + StdInputHandle uint64 + StdOutputHandle uint64 + StdErrorHandle uint64 CurrentDirectoryPathNameLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - CurrentDirectoryPathAddress uint64 - CurrentDirectoryHandle uint64 - DllPathNameLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - DllPathAddress uint64 - ImagePathNameLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - ImagePathAddress uint64 - CommandLineLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - CommandLineAddress uint64 - EnvironmentAddress uint64 + _ uint16 // Max Length + _ uint32 // Padding + CurrentDirectoryPathAddress uint64 + CurrentDirectoryHandle uint64 + DllPathNameLength uint16 + _ uint16 // Max Length + _ uint32 // Padding + DllPathAddress uint64 + ImagePathNameLength uint16 + _ uint16 // Max Length + _ uint32 // Padding + ImagePathAddress uint64 + CommandLineLength uint16 + _ uint16 // Max Length + _ uint32 // Padding + CommandLineAddress uint64 + EnvironmentAddress uint64 // More fields which we don't use so far } @@ -203,13 +190,15 @@ type winLUIDAndAttributes struct { } // TOKEN_PRIVILEGES -type winTokenPriviledges struct { +type winTokenPrivileges struct { PrivilegeCount winDWord Privileges [1]winLUIDAndAttributes } -type winLong int32 -type winDWord uint32 +type ( + winLong int32 + winDWord uint32 +) func init() { var systemInfo systemInfo @@ -230,23 +219,23 @@ func init() { } defer token.Close() - tokenPriviledges := winTokenPriviledges{PrivilegeCount: 1} + tokenPrivileges := winTokenPrivileges{PrivilegeCount: 1} lpName := syscall.StringToUTF16("SeDebugPrivilege") ret, _, _ := procLookupPrivilegeValue.Call( 0, uintptr(unsafe.Pointer(&lpName[0])), - uintptr(unsafe.Pointer(&tokenPriviledges.Privileges[0].Luid))) + uintptr(unsafe.Pointer(&tokenPrivileges.Privileges[0].Luid))) if ret == 0 { return } - tokenPriviledges.Privileges[0].Attributes = 0x00000002 // SE_PRIVILEGE_ENABLED + tokenPrivileges.Privileges[0].Attributes = 0x00000002 // SE_PRIVILEGE_ENABLED procAdjustTokenPrivileges.Call( uintptr(token), 0, - uintptr(unsafe.Pointer(&tokenPriviledges)), - uintptr(unsafe.Sizeof(tokenPriviledges)), + uintptr(unsafe.Pointer(&tokenPrivileges)), + uintptr(unsafe.Sizeof(tokenPrivileges)), 0, 0) } @@ -274,7 +263,6 @@ func pidsWithContext(ctx context.Context) ([]int32, error) { return ret, nil } - } func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { @@ -298,8 +286,7 @@ func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { } return false, err } - const STILL_ACTIVE = 259 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess - h, err := windows.OpenProcess(processQueryInformation, false, uint32(pid)) + h, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid)) if err == windows.ERROR_ACCESS_DENIED { return true, nil } @@ -309,10 +296,9 @@ func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { if err != nil { return false, err } - defer syscall.CloseHandle(syscall.Handle(h)) - var exitCode uint32 - err = windows.GetExitCodeProcess(h, &exitCode) - return exitCode == STILL_ACTIVE, err + defer windows.CloseHandle(h) + event, err := windows.WaitForSingleObject(h, 0) + return event == uint32(windows.WAIT_TIMEOUT), err } func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { @@ -334,18 +320,19 @@ func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { } func (p *Process) NameWithContext(ctx context.Context) (string, error) { - ppid, _, name, err := getFromSnapProcess(p.Pid) - if err != nil { - return "", fmt.Errorf("could not get Name: %s", err) + if p.Pid == 0 { + return "System Idle Process", nil + } + if p.Pid == 4 { + return "System", nil } - // if no errors and not cached already, cache ppid - p.parent = ppid - if 0 == p.getPpid() { - p.setPpid(ppid) + exe, err := p.ExeWithContext(ctx) + if err != nil { + return "", fmt.Errorf("could not get Name: %s", err) } - return name, nil + return filepath.Base(exe), nil } func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { @@ -423,7 +410,7 @@ func (p *Process) CwdWithContext(_ context.Context) (string, error) { } if userProcParams.CurrentDirectoryPathNameLength > 0 { cwd := readProcessMemory(syscall.Handle(h), procIs32Bits, uint64(userProcParams.CurrentDirectoryPathAddress), uint(userProcParams.CurrentDirectoryPathNameLength)) - if len(cwd) != int(userProcParams.CurrentDirectoryPathAddress) { + if len(cwd) != int(userProcParams.CurrentDirectoryPathNameLength) { return "", errors.New("cannot read current working directory") } @@ -444,21 +431,12 @@ func (p *Process) CwdWithContext(_ context.Context) (string, error) { } } - //if we reach here, we have no cwd + // if we reach here, we have no cwd return "", nil } -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - ppid, err := p.PpidWithContext(ctx) - if err != nil { - return nil, fmt.Errorf("could not get ParentProcessID: %s", err) - } - - return NewProcessWithContext(ctx, ppid) -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError +func (p *Process) StatusWithContext(ctx context.Context) ([]string, error) { + return []string{""}, common.ErrNotImplementedError } func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { @@ -716,8 +694,11 @@ func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, er 0, true, windows.DUPLICATE_SAME_ACCESS) != nil { continue } - fileType, _ := windows.GetFileType(windows.Handle(file)) - if fileType != windows.FILE_TYPE_DISK { + // release the new handle + defer windows.CloseHandle(windows.Handle(file)) + + fileType, err := windows.GetFileType(windows.Handle(file)) + if err != nil || fileType != windows.FILE_TYPE_DISK { continue } @@ -739,8 +720,8 @@ func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, er case <-time.NewTimer(100 * time.Millisecond).C: continue case <-ch: - fileInfo, _ := os.Stat(fileName) - if fileInfo.IsDir() { + fileInfo, err := os.Stat(fileName) + if err != nil || fileInfo.IsDir() { continue } @@ -767,10 +748,6 @@ func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net return nil, common.ErrNotImplementedError } -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { return nil, common.ErrNotImplementedError } @@ -1012,15 +989,9 @@ func is32BitProcess(h windows.Handle) bool { var procIs32Bits bool switch processorArchitecture { - case PROCESSOR_ARCHITECTURE_INTEL: - fallthrough - case PROCESSOR_ARCHITECTURE_ARM: + case PROCESSOR_ARCHITECTURE_INTEL, PROCESSOR_ARCHITECTURE_ARM: procIs32Bits = true - case PROCESSOR_ARCHITECTURE_ARM64: - fallthrough - case PROCESSOR_ARCHITECTURE_IA64: - fallthrough - case PROCESSOR_ARCHITECTURE_AMD64: + case PROCESSOR_ARCHITECTURE_ARM64, PROCESSOR_ARCHITECTURE_IA64, PROCESSOR_ARCHITECTURE_AMD64: var wow64 uint ret, _, _ := common.ProcNtQueryInformationProcess.Call( @@ -1035,14 +1006,14 @@ func is32BitProcess(h windows.Handle) bool { procIs32Bits = true } } else { - //if the OS does not support the call, we fallback into the bitness of the app + // if the OS does not support the call, we fallback into the bitness of the app if unsafe.Sizeof(wow64) == 4 { procIs32Bits = true } } default: - //for other unknown platforms, we rely on process platform + // for other unknown platforms, we rely on process platform if unsafe.Sizeof(processorArchitecture) == 8 { procIs32Bits = false } else { @@ -1176,7 +1147,7 @@ func getProcessCommandLine(pid int32) (string, error) { } } - //if we reach here, we have no command line + // if we reach here, we have no command line return "", nil } diff --git a/vendor/github.com/shirou/gopsutil/process/process_windows_386.go b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_32bit.go similarity index 77% rename from vendor/github.com/shirou/gopsutil/process/process_windows_386.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_windows_32bit.go index 71d4b2ff1..db4d45334 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_windows_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_32bit.go @@ -1,4 +1,5 @@ -// +build windows +//go:build (windows && 386) || (windows && arm) +// +build windows,386 windows,arm package process @@ -7,7 +8,7 @@ import ( "syscall" "unsafe" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/windows" ) @@ -26,7 +27,7 @@ type PROCESS_MEMORY_COUNTERS struct { func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { if is32BitProcess { - //we are on a 32-bit process reading an external 32-bit process + // we are on a 32-bit process reading an external 32-bit process var info processBasicInformation32 ret, _, _ := common.ProcNtQueryInformationProcess.Call( @@ -42,8 +43,8 @@ func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, er return 0, windows.NTStatus(ret) } } else { - //we are on a 32-bit process reading an external 64-bit process - if common.ProcNtWow64QueryInformationProcess64.Find() == nil { //avoid panic + // we are on a 32-bit process reading an external 64-bit process + if common.ProcNtWow64QueryInformationProcess64.Find() == nil { // avoid panic var info processBasicInformation64 ret, _, _ := common.ProcNtWow64QueryInformationProcess64.Call( @@ -81,19 +82,19 @@ func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, si return buffer[:read] } } else { - //reading a 64-bit process from a 32-bit one - if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { //avoid panic + // reading a 64-bit process from a 32-bit one + if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { // avoid panic var read uint64 buffer := make([]byte, size) ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call( uintptr(h), - uintptr(address & 0xFFFFFFFF), //the call expects a 64-bit value - uintptr(address >> 32), + uintptr(address&0xFFFFFFFF), // the call expects a 64-bit value + uintptr(address>>32), uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), //the call expects a 64-bit value - uintptr(0), //but size is 32-bit so pass zero as the high dword + uintptr(size), // the call expects a 64-bit value + uintptr(0), // but size is 32-bit so pass zero as the high dword uintptr(unsafe.Pointer(&read)), ) if int(ret) >= 0 && read > 0 { @@ -102,6 +103,6 @@ func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, si } } - //if we reach here, an error happened + // if we reach here, an error happened return nil } diff --git a/vendor/github.com/shirou/gopsutil/process/process_windows_amd64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_64bit.go similarity index 86% rename from vendor/github.com/shirou/gopsutil/process/process_windows_amd64.go rename to vendor/github.com/shirou/gopsutil/v3/process/process_windows_64bit.go index 14308e4d3..74c6212cf 100644 --- a/vendor/github.com/shirou/gopsutil/process/process_windows_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_64bit.go @@ -1,4 +1,5 @@ -// +build windows +//go:build (windows && amd64) || (windows && arm64) +// +build windows,amd64 windows,arm64 package process @@ -6,7 +7,7 @@ import ( "syscall" "unsafe" - "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/windows" ) @@ -25,7 +26,7 @@ type PROCESS_MEMORY_COUNTERS struct { func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { if is32BitProcess { - //we are on a 64-bit process reading an external 32-bit process + // we are on a 64-bit process reading an external 32-bit process var wow64 uint ret, _, _ := common.ProcNtQueryInformationProcess.Call( @@ -41,7 +42,7 @@ func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, er return 0, windows.NTStatus(ret) } } else { - //we are on a 64-bit process reading an external 64-bit process + // we are on a 64-bit process reading an external 64-bit process var info processBasicInformation64 ret, _, _ := common.ProcNtQueryInformationProcess.Call( diff --git a/vendor/github.com/shoenig/go-m1cpu/.golangci.yaml b/vendor/github.com/shoenig/go-m1cpu/.golangci.yaml new file mode 100644 index 000000000..dc6fefb97 --- /dev/null +++ b/vendor/github.com/shoenig/go-m1cpu/.golangci.yaml @@ -0,0 +1,12 @@ +run: + timeout: 5m +linters: + enable: + - gofmt + - errcheck + - errname + - errorlint + - bodyclose + - durationcheck + - whitespace + diff --git a/vendor/github.com/shoenig/go-m1cpu/LICENSE b/vendor/github.com/shoenig/go-m1cpu/LICENSE new file mode 100644 index 000000000..e87a115e4 --- /dev/null +++ b/vendor/github.com/shoenig/go-m1cpu/LICENSE @@ -0,0 +1,363 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. "Contributor" + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. "Contributor Version" + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the terms of + a Secondary License. + +1.6. "Executable Form" + + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + + means a work that combines Covered Software with other material, in a + separate file or files, that is not Covered Software. + +1.8. "License" + + means this document. + +1.9. "Licensable" + + means having the right to grant, to the maximum extent possible, whether + at the time of the initial grant or subsequently, any and all of the + rights conveyed by this License. + +1.10. "Modifications" + + means any of the following: + + a. any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. "Patent Claims" of a Contributor + + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the License, + by the making, using, selling, offering for sale, having made, import, + or transfer of either its Contributions or its Contributor Version. + +1.12. "Secondary License" + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. "Source Code Form" + + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, "control" means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution + become effective for each Contribution on the date the Contributor first + distributes such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under + this License. No additional rights or licenses will be implied from the + distribution or licensing of Covered Software under this License. + Notwithstanding Section 2.1(b) above, no patent license is granted by a + Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of + its Contributions. + + This License does not grant any rights in the trademarks, service marks, + or logos of any Contributor (except as may be necessary to comply with + the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this + License (see Section 10.2) or under the terms of a Secondary License (if + permitted under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its + Contributions are its original creation(s) or it has sufficient rights to + grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under + applicable copyright doctrines of fair use, fair dealing, or other + equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under + the terms of this License. You must inform recipients that the Source + Code Form of the Covered Software is governed by the terms of this + License, and how they can obtain a copy of this License. You may not + attempt to alter or restrict the recipients' rights in the Source Code + Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter the + recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for + the Covered Software. If the Larger Work is a combination of Covered + Software with a work governed by one or more Secondary Licenses, and the + Covered Software is not Incompatible With Secondary Licenses, this + License permits You to additionally distribute such Covered Software + under the terms of such Secondary License(s), so that the recipient of + the Larger Work may, at their option, further distribute the Covered + Software under the terms of either this License or such Secondary + License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices + (including copyright notices, patent notices, disclaimers of warranty, or + limitations of liability) contained within the Source Code Form of the + Covered Software, except that You may alter any license notices to the + extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on + behalf of any Contributor. You must make it absolutely clear that any + such warranty, support, indemnity, or liability obligation is offered by + You alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, + judicial order, or regulation then You must: (a) comply with the terms of + this License to the maximum extent possible; and (b) describe the + limitations and the code they affect. Such description must be placed in a + text file included with all distributions of the Covered Software under + this License. Except to the extent prohibited by statute or regulation, + such description must be sufficiently detailed for a recipient of ordinary + skill to be able to understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing + basis, if such Contributor fails to notify You of the non-compliance by + some reasonable means prior to 60 days after You have come back into + compliance. Moreover, Your grants from a particular Contributor are + reinstated on an ongoing basis if such Contributor notifies You of the + non-compliance by some reasonable means, this is the first time You have + received notice of non-compliance with this License from such + Contributor, and You become compliant prior to 30 days after Your receipt + of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, + counter-claims, and cross-claims) alleging that a Contributor Version + directly or indirectly infringes any patent, then the rights granted to + You by any and all Contributors for the Covered Software under Section + 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an "as is" basis, + without warranty of any kind, either expressed, implied, or statutory, + including, without limitation, warranties that the Covered Software is free + of defects, merchantable, fit for a particular purpose or non-infringing. + The entire risk as to the quality and performance of the Covered Software + is with You. Should any Covered Software prove defective in any respect, + You (not any Contributor) assume the cost of any necessary servicing, + repair, or correction. This disclaimer of warranty constitutes an essential + part of this License. No use of any Covered Software is authorized under + this License except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from + such party's negligence to the extent applicable law prohibits such + limitation. Some jurisdictions do not allow the exclusion or limitation of + incidental or consequential damages, so this exclusion and limitation may + not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts + of a jurisdiction where the defendant maintains its principal place of + business and such litigation shall be governed by laws of that + jurisdiction, without reference to its conflict-of-law provisions. Nothing + in this Section shall prevent a party's ability to bring cross-claims or + counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. Any law or regulation which provides that + the language of a contract shall be construed against the drafter shall not + be used to construe this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version + of the License under which You originally received the Covered Software, + or under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a + modified version of this License if you rename the license and remove + any references to the name of the license steward (except to note that + such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary + Licenses If You choose to distribute Source Code Form that is + Incompatible With Secondary Licenses under the terms of this version of + the License, the notice described in Exhibit B of this License must be + attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, +then You may include the notice in a location (such as a LICENSE file in a +relevant directory) where a recipient would be likely to look for such a +notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice + + This Source Code Form is "Incompatible + With Secondary Licenses", as defined by + the Mozilla Public License, v. 2.0. + diff --git a/vendor/github.com/shoenig/go-m1cpu/Makefile b/vendor/github.com/shoenig/go-m1cpu/Makefile new file mode 100644 index 000000000..28d786397 --- /dev/null +++ b/vendor/github.com/shoenig/go-m1cpu/Makefile @@ -0,0 +1,12 @@ +SHELL = bash + +default: test + +.PHONY: test +test: + @echo "--> Running Tests ..." + @go test -v -race ./... + +vet: + @echo "--> Vet Go sources ..." + @go vet ./... diff --git a/vendor/github.com/shoenig/go-m1cpu/README.md b/vendor/github.com/shoenig/go-m1cpu/README.md new file mode 100644 index 000000000..399657acf --- /dev/null +++ b/vendor/github.com/shoenig/go-m1cpu/README.md @@ -0,0 +1,66 @@ +# m1cpu + +[![Go Reference](https://pkg.go.dev/badge/github.com/shoenig/go-m1cpu.svg)](https://pkg.go.dev/github.com/shoenig/go-m1cpu) +[![MPL License](https://img.shields.io/github/license/shoenig/go-m1cpu?color=g&style=flat-square)](https://github.com/shoenig/go-m1cpu/blob/main/LICENSE) +[![Run CI Tests](https://github.com/shoenig/go-m1cpu/actions/workflows/ci.yaml/badge.svg)](https://github.com/shoenig/go-m1cpu/actions/workflows/ci.yaml) + +The `go-m1cpu` module is a library for inspecting Apple Silicon CPUs in Go. + +Use the `m1cpu` Go package for looking up the CPU frequency for Apple M1 and M2 CPUs. + +# Install + +```shell +go get github.com/shoenig/go-m1cpu@latest +``` + +# CGO + +This package requires the use of [CGO](https://go.dev/blog/cgo). + +Extracting the CPU properties is done via Apple's [IOKit](https://developer.apple.com/documentation/iokit?language=objc) +framework, which is accessible only through system C libraries. + +# Example + +Simple Go program to print Apple Silicon M1/M2 CPU speeds. + +```go +package main + +import ( + "fmt" + + "github.com/shoenig/go-m1cpu" +) + +func main() { + fmt.Println("Apple Silicon", m1cpu.IsAppleSilicon()) + + fmt.Println("pCore GHz", m1cpu.PCoreGHz()) + fmt.Println("eCore GHz", m1cpu.ECoreGHz()) + + fmt.Println("pCore Hz", m1cpu.PCoreHz()) + fmt.Println("eCore Hz", m1cpu.ECoreHz()) +} +``` + +Using `go test` to print out available information. + +``` +➜ go test -v -run Show +=== RUN Test_Show + cpu_test.go:42: pCore Hz 3504000000 + cpu_test.go:43: eCore Hz 2424000000 + cpu_test.go:44: pCore GHz 3.504 + cpu_test.go:45: eCore GHz 2.424 + cpu_test.go:46: pCore count 8 + cpu_test.go:47: eCoreCount 4 + cpu_test.go:50: pCore Caches 196608 131072 16777216 + cpu_test.go:53: eCore Caches 131072 65536 4194304 +--- PASS: Test_Show (0.00s) +``` + +# License + +Open source under the [MPL](LICENSE) diff --git a/vendor/github.com/shoenig/go-m1cpu/cpu.go b/vendor/github.com/shoenig/go-m1cpu/cpu.go new file mode 100644 index 000000000..502a8cce9 --- /dev/null +++ b/vendor/github.com/shoenig/go-m1cpu/cpu.go @@ -0,0 +1,213 @@ +//go:build darwin && arm64 && cgo + +package m1cpu + +// #cgo LDFLAGS: -framework CoreFoundation -framework IOKit +// #include +// #include +// #include +// #include +// +// #if !defined(MAC_OS_VERSION_12_0) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0 +// #define kIOMainPortDefault kIOMasterPortDefault +// #endif +// +// #define HzToGHz(hz) ((hz) / 1000000000.0) +// +// UInt64 global_pCoreHz; +// UInt64 global_eCoreHz; +// int global_pCoreCount; +// int global_eCoreCount; +// int global_pCoreL1InstCacheSize; +// int global_eCoreL1InstCacheSize; +// int global_pCoreL1DataCacheSize; +// int global_eCoreL1DataCacheSize; +// int global_pCoreL2CacheSize; +// int global_eCoreL2CacheSize; +// char global_brand[32]; +// +// UInt64 getFrequency(CFTypeRef typeRef) { +// CFDataRef cfData = typeRef; +// +// CFIndex size = CFDataGetLength(cfData); +// UInt8 buf[size]; +// CFDataGetBytes(cfData, CFRangeMake(0, size), buf); +// +// UInt8 b1 = buf[size-5]; +// UInt8 b2 = buf[size-6]; +// UInt8 b3 = buf[size-7]; +// UInt8 b4 = buf[size-8]; +// +// UInt64 pCoreHz = 0x00000000FFFFFFFF & ((b1<<24) | (b2 << 16) | (b3 << 8) | (b4)); +// return pCoreHz; +// } +// +// int sysctl_int(const char * name) { +// int value = -1; +// size_t size = 8; +// sysctlbyname(name, &value, &size, NULL, 0); +// return value; +// } +// +// void sysctl_string(const char * name, char * dest) { +// size_t size = 32; +// sysctlbyname(name, dest, &size, NULL, 0); +// } +// +// void initialize() { +// global_pCoreCount = sysctl_int("hw.perflevel0.physicalcpu"); +// global_eCoreCount = sysctl_int("hw.perflevel1.physicalcpu"); +// global_pCoreL1InstCacheSize = sysctl_int("hw.perflevel0.l1icachesize"); +// global_eCoreL1InstCacheSize = sysctl_int("hw.perflevel1.l1icachesize"); +// global_pCoreL1DataCacheSize = sysctl_int("hw.perflevel0.l1dcachesize"); +// global_eCoreL1DataCacheSize = sysctl_int("hw.perflevel1.l1dcachesize"); +// global_pCoreL2CacheSize = sysctl_int("hw.perflevel0.l2cachesize"); +// global_eCoreL2CacheSize = sysctl_int("hw.perflevel1.l2cachesize"); +// sysctl_string("machdep.cpu.brand_string", global_brand); +// +// CFMutableDictionaryRef matching = IOServiceMatching("AppleARMIODevice"); +// io_iterator_t iter; +// IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iter); +// +// const size_t bufsize = 512; +// io_object_t obj; +// while ((obj = IOIteratorNext(iter))) { +// char class[bufsize]; +// IOObjectGetClass(obj, class); +// char name[bufsize]; +// IORegistryEntryGetName(obj, name); +// +// if (strncmp(name, "pmgr", bufsize) == 0) { +// CFTypeRef pCoreRef = IORegistryEntryCreateCFProperty(obj, CFSTR("voltage-states5-sram"), kCFAllocatorDefault, 0); +// CFTypeRef eCoreRef = IORegistryEntryCreateCFProperty(obj, CFSTR("voltage-states1-sram"), kCFAllocatorDefault, 0); +// +// long long pCoreHz = getFrequency(pCoreRef); +// long long eCoreHz = getFrequency(eCoreRef); +// +// global_pCoreHz = pCoreHz; +// global_eCoreHz = eCoreHz; +// return; +// } +// } +// } +// +// UInt64 eCoreHz() { +// return global_eCoreHz; +// } +// +// UInt64 pCoreHz() { +// return global_pCoreHz; +// } +// +// Float64 eCoreGHz() { +// return HzToGHz(global_eCoreHz); +// } +// +// Float64 pCoreGHz() { +// return HzToGHz(global_pCoreHz); +// } +// +// int pCoreCount() { +// return global_pCoreCount; +// } +// +// int eCoreCount() { +// return global_eCoreCount; +// } +// +// int pCoreL1InstCacheSize() { +// return global_pCoreL1InstCacheSize; +// } +// +// int pCoreL1DataCacheSize() { +// return global_pCoreL1DataCacheSize; +// } +// +// int pCoreL2CacheSize() { +// return global_pCoreL2CacheSize; +// } +// +// int eCoreL1InstCacheSize() { +// return global_eCoreL1InstCacheSize; +// } +// +// int eCoreL1DataCacheSize() { +// return global_eCoreL1DataCacheSize; +// } +// +// int eCoreL2CacheSize() { +// return global_eCoreL2CacheSize; +// } +// +// char * modelName() { +// return global_brand; +// } +import "C" + +func init() { + C.initialize() +} + +// IsAppleSilicon returns true on this platform. +func IsAppleSilicon() bool { + return true +} + +// PCoreHZ returns the max frequency in Hertz of the P-Core of an Apple Silicon CPU. +func PCoreHz() uint64 { + return uint64(C.pCoreHz()) +} + +// ECoreHZ returns the max frequency in Hertz of the E-Core of an Apple Silicon CPU. +func ECoreHz() uint64 { + return uint64(C.eCoreHz()) +} + +// PCoreGHz returns the max frequency in Gigahertz of the P-Core of an Apple Silicon CPU. +func PCoreGHz() float64 { + return float64(C.pCoreGHz()) +} + +// ECoreGHz returns the max frequency in Gigahertz of the E-Core of an Apple Silicon CPU. +func ECoreGHz() float64 { + return float64(C.eCoreGHz()) +} + +// PCoreCount returns the number of physical P (performance) cores. +func PCoreCount() int { + return int(C.pCoreCount()) +} + +// ECoreCount returns the number of physical E (efficiency) cores. +func ECoreCount() int { + return int(C.eCoreCount()) +} + +// PCoreCacheSize returns the sizes of the P (performance) core cache sizes +// in the order of +// +// - L1 instruction cache +// - L1 data cache +// - L2 cache +func PCoreCache() (int, int, int) { + return int(C.pCoreL1InstCacheSize()), + int(C.pCoreL1DataCacheSize()), + int(C.pCoreL2CacheSize()) +} + +// ECoreCacheSize returns the sizes of the E (efficiency) core cache sizes +// in the order of +// +// - L1 instruction cache +// - L1 data cache +// - L2 cache +func ECoreCache() (int, int, int) { + return int(C.eCoreL1InstCacheSize()), + int(C.eCoreL1DataCacheSize()), + int(C.eCoreL2CacheSize()) +} + +// ModelName returns the model name of the CPU. +func ModelName() string { + return C.GoString(C.modelName()) +} diff --git a/vendor/github.com/shoenig/go-m1cpu/incompatible.go b/vendor/github.com/shoenig/go-m1cpu/incompatible.go new file mode 100644 index 000000000..d425025aa --- /dev/null +++ b/vendor/github.com/shoenig/go-m1cpu/incompatible.go @@ -0,0 +1,53 @@ +//go:build !darwin || !arm64 || !cgo + +package m1cpu + +// IsAppleSilicon return false on this platform. +func IsAppleSilicon() bool { + return false +} + +// PCoreHZ requires darwin/arm64 +func PCoreHz() uint64 { + panic("m1cpu: not a darwin/arm64 system") +} + +// ECoreHZ requires darwin/arm64 +func ECoreHz() uint64 { + panic("m1cpu: not a darwin/arm64 system") +} + +// PCoreGHz requires darwin/arm64 +func PCoreGHz() float64 { + panic("m1cpu: not a darwin/arm64 system") +} + +// ECoreGHz requires darwin/arm64 +func ECoreGHz() float64 { + panic("m1cpu: not a darwin/arm64 system") +} + +// PCoreCount requires darwin/arm64 +func PCoreCount() int { + panic("m1cpu: not a darwin/arm64 system") +} + +// ECoreCount requires darwin/arm64 +func ECoreCount() int { + panic("m1cpu: not a darwin/arm64 system") +} + +// PCoreCacheSize requires darwin/arm64 +func PCoreCache() (int, int, int) { + panic("m1cpu: not a darwin/arm64 system") +} + +// ECoreCacheSize requires darwin/arm64 +func ECoreCache() (int, int, int) { + panic("m1cpu: not a darwin/arm64 system") +} + +// ModelName requires darwin/arm64 +func ModelName() string { + panic("m1cpu: not a darwin/arm64 system") +} diff --git a/vendor/github.com/tklauser/go-sysconf/.cirrus.yml b/vendor/github.com/tklauser/go-sysconf/.cirrus.yml index 6be2c3548..1b27f1962 100644 --- a/vendor/github.com/tklauser/go-sysconf/.cirrus.yml +++ b/vendor/github.com/tklauser/go-sysconf/.cirrus.yml @@ -1,6 +1,6 @@ env: CIRRUS_CLONE_DEPTH: 1 - GO_VERSION: go1.19.1 + GO_VERSION: go1.20 freebsd_12_task: freebsd_instance: diff --git a/vendor/github.com/tklauser/go-sysconf/sysconf_darwin.go b/vendor/github.com/tklauser/go-sysconf/sysconf_darwin.go index 4a5197b2f..3f5d83f69 100644 --- a/vendor/github.com/tklauser/go-sysconf/sysconf_darwin.go +++ b/vendor/github.com/tklauser/go-sysconf/sysconf_darwin.go @@ -5,6 +5,10 @@ package sysconf import ( + "strconv" + "strings" + "sync" + "golang.org/x/sys/unix" ) @@ -14,8 +18,14 @@ const ( _SYMLOOP_MAX = _MAXSYMLINKS ) -// sysconf implements sysconf(3) as in the Darwin libc, version 1244.30.3 -// (derived from the FreeBSD libc). +var uname struct { + sync.Once + macOSMajor int +} + +// sysconf implements sysconf(4) as in the Darwin libc (derived from the FreeBSD +// libc), version 1534.81.1. +// See https://github.com/apple-oss-distributions/Libc/tree/Libc-1534.81.1. func sysconf(name int) (int64, error) { switch name { case SC_AIO_LISTIO_MAX: @@ -54,12 +64,16 @@ func sysconf(name int) (int64, error) { return sysctl32("kern.ngroups"), nil case SC_OPEN_MAX, SC_STREAM_MAX: var rlim unix.Rlimit - if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlim); err == nil { - if rlim.Cur != unix.RLIM_INFINITY { - return int64(rlim.Cur), nil - } + if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlim); err != nil { + return -1, nil } - return -1, nil + if rlim.Cur > unix.RLIM_INFINITY { + return -1, nil + } + if rlim.Cur > _LONG_MAX { + return -1, unix.EOVERFLOW + } + return int64(rlim.Cur), nil case SC_RTSIG_MAX: return -1, nil case SC_SEM_NSEMS_MAX: @@ -126,7 +140,22 @@ func sysconf(name int) (int64, error) { } return _POSIX_SEMAPHORES, nil case SC_SPAWN: - return _POSIX_SPAWN, nil + uname.Once.Do(func() { + var u unix.Utsname + err := unix.Uname(&u) + if err != nil { + return + } + rel := unix.ByteSliceToString(u.Release[:]) + ver := strings.Split(rel, ".") + maj, _ := strconv.Atoi(ver[0]) + uname.macOSMajor = maj + }) + if uname.macOSMajor < 22 { + return -1, nil + } + // macOS 13 (Ventura) and later + return 200112, nil case SC_SPIN_LOCKS: return _POSIX_SPIN_LOCKS, nil case SC_SPORADIC_SERVER: diff --git a/vendor/github.com/tklauser/go-sysconf/zsysconf_defs_darwin.go b/vendor/github.com/tklauser/go-sysconf/zsysconf_defs_darwin.go index 6fa7fde8a..6fadf3db1 100644 --- a/vendor/github.com/tklauser/go-sysconf/zsysconf_defs_darwin.go +++ b/vendor/github.com/tklauser/go-sysconf/zsysconf_defs_darwin.go @@ -181,7 +181,6 @@ const ( _POSIX_SHARED_MEMORY_OBJECTS = -0x1 _POSIX_SHELL = 0x30db0 _POSIX_SIGQUEUE_MAX = 0x20 - _POSIX_SPAWN = -0x1 _POSIX_SPIN_LOCKS = -0x1 _POSIX_SPORADIC_SERVER = -0x1 _POSIX_SS_REPL_MAX = 0x4 @@ -248,7 +247,8 @@ const ( const ( _CHAR_BIT = 0x8 - _INT_MAX = 0x7fffffff + _INT_MAX = 0x7fffffff + _LONG_MAX = 0x7fffffffffffffff sizeofOffT = 0x8 ) diff --git a/vendor/github.com/tklauser/numcpus/.cirrus.yml b/vendor/github.com/tklauser/numcpus/.cirrus.yml index 53c0110b5..69c6ced5c 100644 --- a/vendor/github.com/tklauser/numcpus/.cirrus.yml +++ b/vendor/github.com/tklauser/numcpus/.cirrus.yml @@ -1,6 +1,6 @@ env: CIRRUS_CLONE_DEPTH: 1 - GO_VERSION: go1.19.1 + GO_VERSION: go1.20 freebsd_12_task: freebsd_instance: diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 0c4d14929..8f775fafa 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -624,7 +624,7 @@ ccflags="$@" $2 ~ /^MEM/ || $2 ~ /^WG/ || $2 ~ /^FIB_RULE_/ || - $2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)} + $2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE|IOMIN$|IOOPT$|ALIGNOFF$|DISCARD|ROTATIONAL$|ZEROOUT$|GETDISKSEQ$)/ {printf("\t%s = C.%s\n", $2, $2)} $2 ~ /^__WCOREFLAG$/ {next} $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} diff --git a/vendor/golang.org/x/sys/unix/mmap_nomremap.go b/vendor/golang.org/x/sys/unix/mmap_nomremap.go new file mode 100644 index 000000000..ca0513632 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/mmap_nomremap.go @@ -0,0 +1,14 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build aix || darwin || dragonfly || freebsd || openbsd || solaris +// +build aix darwin dragonfly freebsd openbsd solaris + +package unix + +var mapper = &mmapper{ + active: make(map[*byte][]byte), + mmap: mmap, + munmap: munmap, +} diff --git a/vendor/golang.org/x/sys/unix/mremap.go b/vendor/golang.org/x/sys/unix/mremap.go index 86213c05d..fa93d0aa9 100644 --- a/vendor/golang.org/x/sys/unix/mremap.go +++ b/vendor/golang.org/x/sys/unix/mremap.go @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build linux -// +build linux +//go:build linux || netbsd +// +build linux netbsd package unix @@ -14,8 +14,17 @@ type mremapMmapper struct { mremap func(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (xaddr uintptr, err error) } +var mapper = &mremapMmapper{ + mmapper: mmapper{ + active: make(map[*byte][]byte), + mmap: mmap, + munmap: munmap, + }, + mremap: mremap, +} + func (m *mremapMmapper) Mremap(oldData []byte, newLength int, flags int) (data []byte, err error) { - if newLength <= 0 || len(oldData) == 0 || len(oldData) != cap(oldData) || flags&MREMAP_FIXED != 0 { + if newLength <= 0 || len(oldData) == 0 || len(oldData) != cap(oldData) || flags&mremapFixed != 0 { return nil, EINVAL } @@ -32,9 +41,13 @@ func (m *mremapMmapper) Mremap(oldData []byte, newLength int, flags int) (data [ } bNew := unsafe.Slice((*byte)(unsafe.Pointer(newAddr)), newLength) pNew := &bNew[cap(bNew)-1] - if flags&MREMAP_DONTUNMAP == 0 { + if flags&mremapDontunmap == 0 { delete(m.active, pOld) } m.active[pNew] = bNew return bNew, nil } + +func Mremap(oldData []byte, newLength int, flags int) (data []byte, err error) { + return mapper.Mremap(oldData, newLength, flags) +} diff --git a/vendor/golang.org/x/sys/unix/syscall_aix.go b/vendor/golang.org/x/sys/unix/syscall_aix.go index c406ae00f..9a6e5acac 100644 --- a/vendor/golang.org/x/sys/unix/syscall_aix.go +++ b/vendor/golang.org/x/sys/unix/syscall_aix.go @@ -535,21 +535,6 @@ func Fsync(fd int) error { //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = nsendmsg //sys munmap(addr uintptr, length uintptr) (err error) - -var mapper = &mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, -} - -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} - //sys Madvise(b []byte, advice int) (err error) //sys Mprotect(b []byte, prot int) (err error) //sys Mlock(b []byte) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go index 7705c3270..4217de518 100644 --- a/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -601,20 +601,6 @@ func Poll(fds []PollFd, timeout int) (n int, err error) { // Gethostuuid(uuid *byte, timeout *Timespec) (err error) // Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error) -var mapper = &mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, -} - -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} - //sys Madvise(b []byte, behav int) (err error) //sys Mlock(b []byte) (err error) //sys Mlockall(flags int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 206921504..135cc3cd7 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -510,30 +510,36 @@ func SysctlKinfoProcSlice(name string, args ...int) ([]KinfoProc, error) { return nil, err } - // Find size. - n := uintptr(0) - if err := sysctl(mib, nil, &n, nil, 0); err != nil { - return nil, err - } - if n == 0 { - return nil, nil - } - if n%SizeofKinfoProc != 0 { - return nil, fmt.Errorf("sysctl() returned a size of %d, which is not a multiple of %d", n, SizeofKinfoProc) - } + for { + // Find size. + n := uintptr(0) + if err := sysctl(mib, nil, &n, nil, 0); err != nil { + return nil, err + } + if n == 0 { + return nil, nil + } + if n%SizeofKinfoProc != 0 { + return nil, fmt.Errorf("sysctl() returned a size of %d, which is not a multiple of %d", n, SizeofKinfoProc) + } - // Read into buffer of that size. - buf := make([]KinfoProc, n/SizeofKinfoProc) - if err := sysctl(mib, (*byte)(unsafe.Pointer(&buf[0])), &n, nil, 0); err != nil { - return nil, err - } - if n%SizeofKinfoProc != 0 { - return nil, fmt.Errorf("sysctl() returned a size of %d, which is not a multiple of %d", n, SizeofKinfoProc) - } + // Read into buffer of that size. + buf := make([]KinfoProc, n/SizeofKinfoProc) + if err := sysctl(mib, (*byte)(unsafe.Pointer(&buf[0])), &n, nil, 0); err != nil { + if err == ENOMEM { + // Process table grew. Try again. + continue + } + return nil, err + } + if n%SizeofKinfoProc != 0 { + return nil, fmt.Errorf("sysctl() returned a size of %d, which is not a multiple of %d", n, SizeofKinfoProc) + } - // The actual call may return less than the original reported required - // size so ensure we deal with that. - return buf[:n/SizeofKinfoProc], nil + // The actual call may return less than the original reported required + // size so ensure we deal with that. + return buf[:n/SizeofKinfoProc], nil + } } //sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 39de5f143..a730878e4 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1885,7 +1885,7 @@ func Getpgrp() (pid int) { //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) -//sys Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6 +//sys pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Removexattr(path string, attr string) (err error) //sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) @@ -2125,28 +2125,6 @@ func writevRacedetect(iovecs []Iovec, n int) { // mmap varies by architecture; see syscall_linux_*.go. //sys munmap(addr uintptr, length uintptr) (err error) //sys mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (xaddr uintptr, err error) - -var mapper = &mremapMmapper{ - mmapper: mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, - }, - mremap: mremap, -} - -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} - -func Mremap(oldData []byte, newLength int, flags int) (data []byte, err error) { - return mapper.Mremap(oldData, newLength, flags) -} - //sys Madvise(b []byte, advice int) (err error) //sys Mprotect(b []byte, prot int) (err error) //sys Mlock(b []byte) (err error) @@ -2155,6 +2133,12 @@ func Mremap(oldData []byte, newLength int, flags int) (data []byte, err error) { //sys Munlock(b []byte) (err error) //sys Munlockall() (err error) +const ( + mremapFixed = MREMAP_FIXED + mremapDontunmap = MREMAP_DONTUNMAP + mremapMaymove = MREMAP_MAYMOVE +) + // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd, // using the specified flags. func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) { @@ -2454,6 +2438,39 @@ func Getresgid() (rgid, egid, sgid int) { return int(r), int(e), int(s) } +// Pselect is a wrapper around the Linux pselect6 system call. +// This version does not modify the timeout argument. +func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { + // Per https://man7.org/linux/man-pages/man2/select.2.html#NOTES, + // The Linux pselect6() system call modifies its timeout argument. + // [Not modifying the argument] is the behavior required by POSIX.1-2001. + var mutableTimeout *Timespec + if timeout != nil { + mutableTimeout = new(Timespec) + *mutableTimeout = *timeout + } + + // The final argument of the pselect6() system call is not a + // sigset_t * pointer, but is instead a structure + var kernelMask *sigset_argpack + if sigmask != nil { + wordBits := 32 << (^uintptr(0) >> 63) // see math.intSize + + // A sigset stores one bit per signal, + // offset by 1 (because signal 0 does not exist). + // So the number of words needed is ⌈__C_NSIG - 1 / wordBits⌉. + sigsetWords := (_C__NSIG - 1 + wordBits - 1) / (wordBits) + + sigsetBytes := uintptr(sigsetWords * (wordBits / 8)) + kernelMask = &sigset_argpack{ + ss: sigmask, + ssLen: sigsetBytes, + } + } + + return pselect6(nfd, r, w, e, mutableTimeout, kernelMask) +} + /* * Unimplemented */ diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go index 5b21fcfd7..70601ce36 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go @@ -40,7 +40,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err if timeout != nil { ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} } - return Pselect(nfd, r, w, e, ts, nil) + return pselect6(nfd, r, w, e, ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index a81f5742b..f5266689a 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -33,7 +33,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err if timeout != nil { ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} } - return Pselect(nfd, r, w, e, ts, nil) + return pselect6(nfd, r, w, e, ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go index 69d2d7c3d..f6ab02ec1 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go @@ -28,7 +28,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err if timeout != nil { ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} } - return Pselect(nfd, r, w, e, ts, nil) + return pselect6(nfd, r, w, e, ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go index 76d564095..93fe59d25 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go @@ -31,7 +31,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err if timeout != nil { ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} } - return Pselect(nfd, r, w, e, ts, nil) + return pselect6(nfd, r, w, e, ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go index 35851ef70..5e6ceee12 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go @@ -32,7 +32,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err if timeout != nil { ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} } - return Pselect(nfd, r, w, e, ts, nil) + return pselect6(nfd, r, w, e, ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) @@ -177,3 +177,14 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error } return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) } + +//sys riscvHWProbe(pairs []RISCVHWProbePairs, cpuCount uintptr, cpus *CPUSet, flags uint) (err error) + +func RISCVHWProbe(pairs []RISCVHWProbePairs, set *CPUSet, flags uint) (err error) { + var setSize uintptr + + if set != nil { + setSize = uintptr(unsafe.Sizeof(*set)) + } + return riscvHWProbe(pairs, setSize, set, flags) +} diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 018d7d478..ddd1ac853 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -360,6 +360,18 @@ func Statvfs(path string, buf *Statvfs_t) (err error) { //sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) +const ( + mremapFixed = MAP_FIXED + mremapDontunmap = 0 + mremapMaymove = 0 +) + +//sys mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) = SYS_MREMAP + +func mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (uintptr, error) { + return mremapNetBSD(oldaddr, oldlength, newaddr, newlength, flags) +} + /* * Unimplemented */ @@ -564,7 +576,6 @@ func Statvfs(path string, buf *Statvfs_t) (err error) { // mq_timedreceive // mq_timedsend // mq_unlink -// mremap // msgget // msgrcv // msgsnd diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go index b600a289d..72d23575f 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -716,20 +716,6 @@ func writelen(fd int, buf *byte, nbuf int) (n int, err error) { return } -var mapper = &mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, -} - -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} - // Event Ports type fileObjCookie struct { diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index 8e48c29ec..8bb30e7ce 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -147,6 +147,14 @@ func (m *mmapper) Munmap(data []byte) (err error) { return nil } +func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { + return mapper.Mmap(fd, offset, length, prot, flags) +} + +func Munmap(b []byte) (err error) { + return mapper.Munmap(b) +} + func Read(fd int, p []byte) (n int, err error) { n, err = read(fd, p) if raceenabled { diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index d3d49ec3e..44e72edb4 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -285,25 +285,11 @@ func Close(fd int) (err error) { return } -var mapper = &mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, -} - // Dummy function: there are no semantics for Madvise on z/OS func Madvise(b []byte, advice int) (err error) { return } -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} - //sys Gethostname(buf []byte) (err error) = SYS___GETHOSTNAME_A //sysnb Getegid() (egid int) //sysnb Geteuid() (uid int) diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index a46df0f1e..cfb143001 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x127a BLKBSZGET = 0x80041270 BLKBSZSET = 0x40041271 + BLKDISCARD = 0x1277 + BLKDISCARDZEROES = 0x127c BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 + BLKGETDISKSEQ = 0x80081280 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80041272 + BLKIOMIN = 0x1278 + BLKIOOPT = 0x1279 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d + BLKROTATIONAL = 0x127e BLKRRPART = 0x125f + BLKSECDISCARD = 0x127d BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 + BLKZEROOUT = 0x127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 6cd4a3ea9..df64f2d59 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x127a BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 + BLKDISCARD = 0x1277 + BLKDISCARDZEROES = 0x127c BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 + BLKGETDISKSEQ = 0x80081280 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 + BLKIOMIN = 0x1278 + BLKIOOPT = 0x1279 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d + BLKROTATIONAL = 0x127e BLKRRPART = 0x125f + BLKSECDISCARD = 0x127d BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 + BLKZEROOUT = 0x127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index c7ebee24d..3025cd5b2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x127a BLKBSZGET = 0x80041270 BLKBSZSET = 0x40041271 + BLKDISCARD = 0x1277 + BLKDISCARDZEROES = 0x127c BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 + BLKGETDISKSEQ = 0x80081280 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80041272 + BLKIOMIN = 0x1278 + BLKIOOPT = 0x1279 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d + BLKROTATIONAL = 0x127e BLKRRPART = 0x125f + BLKSECDISCARD = 0x127d BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 + BLKZEROOUT = 0x127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 12a9a1389..09e1ffbef 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x127a BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 + BLKDISCARD = 0x1277 + BLKDISCARDZEROES = 0x127c BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 + BLKGETDISKSEQ = 0x80081280 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 + BLKIOMIN = 0x1278 + BLKIOOPT = 0x1279 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d + BLKROTATIONAL = 0x127e BLKRRPART = 0x125f + BLKSECDISCARD = 0x127d BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 + BLKZEROOUT = 0x127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index f26a164f4..a45723540 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x127a BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 + BLKDISCARD = 0x1277 + BLKDISCARDZEROES = 0x127c BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 + BLKGETDISKSEQ = 0x80081280 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 + BLKIOMIN = 0x1278 + BLKIOOPT = 0x1279 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d + BLKROTATIONAL = 0x127e BLKRRPART = 0x125f + BLKSECDISCARD = 0x127d BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 + BLKZEROOUT = 0x127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 890bc3c9b..fee7dfb81 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40041270 BLKBSZSET = 0x80041271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40041272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 549f26ac6..a5b2373ae 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index e0365e32c..5dde82c98 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index fdccce15c..2e80ea6b3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40041270 BLKBSZSET = 0x80041271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40041272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index b2205c83f..a65dcd7cb 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -27,22 +27,31 @@ const ( B57600 = 0x10 B576000 = 0x15 B921600 = 0x16 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40041270 BLKBSZSET = 0x80041271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40041272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1f BS1 = 0x8000 BSDLY = 0x8000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 81aa5ad0f..cbd34e3d8 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -27,22 +27,31 @@ const ( B57600 = 0x10 B576000 = 0x15 B921600 = 0x16 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1f BS1 = 0x8000 BSDLY = 0x8000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 76807a1fd..e4afa7a31 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -27,22 +27,31 @@ const ( B57600 = 0x10 B576000 = 0x15 B921600 = 0x16 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1f BS1 = 0x8000 BSDLY = 0x8000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index d4a5ab9e4..44f45a039 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x127a BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 + BLKDISCARD = 0x1277 + BLKDISCARDZEROES = 0x127c BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 + BLKGETDISKSEQ = 0x80081280 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 + BLKIOMIN = 0x1278 + BLKIOOPT = 0x1279 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d + BLKROTATIONAL = 0x127e BLKRRPART = 0x125f + BLKSECDISCARD = 0x127d BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 + BLKZEROOUT = 0x127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 66e65db95..74733e260 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -27,22 +27,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x127a BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 + BLKDISCARD = 0x1277 + BLKDISCARDZEROES = 0x127c BLKFLSBUF = 0x1261 BLKFRAGET = 0x1265 BLKFRASET = 0x1264 + BLKGETDISKSEQ = 0x80081280 BLKGETSIZE = 0x1260 BLKGETSIZE64 = 0x80081272 + BLKIOMIN = 0x1278 + BLKIOOPT = 0x1279 BLKPBSZGET = 0x127b BLKRAGET = 0x1263 BLKRASET = 0x1262 BLKROGET = 0x125e BLKROSET = 0x125d + BLKROTATIONAL = 0x127e BLKRRPART = 0x125f + BLKSECDISCARD = 0x127d BLKSECTGET = 0x1267 BLKSECTSET = 0x1266 BLKSSZGET = 0x1268 + BLKZEROOUT = 0x127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 48984202c..f5f3934b1 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -30,22 +30,31 @@ const ( B57600 = 0x1001 B576000 = 0x1006 B921600 = 0x1007 + BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 + BLKDISCARD = 0x20001277 + BLKDISCARDZEROES = 0x2000127c BLKFLSBUF = 0x20001261 BLKFRAGET = 0x20001265 BLKFRASET = 0x20001264 + BLKGETDISKSEQ = 0x40081280 BLKGETSIZE = 0x20001260 BLKGETSIZE64 = 0x40081272 + BLKIOMIN = 0x20001278 + BLKIOOPT = 0x20001279 BLKPBSZGET = 0x2000127b BLKRAGET = 0x20001263 BLKRASET = 0x20001262 BLKROGET = 0x2000125e BLKROSET = 0x2000125d + BLKROTATIONAL = 0x2000127e BLKRRPART = 0x2000125f + BLKSECDISCARD = 0x2000127d BLKSECTGET = 0x20001267 BLKSECTSET = 0x20001266 BLKSSZGET = 0x20001268 + BLKZEROOUT = 0x2000127f BOTHER = 0x1000 BS1 = 0x2000 BSDLY = 0x2000 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 7ceec233f..a07321bed 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -1356,7 +1356,7 @@ func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { +func pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go index 0b2923958..0ab4f2ed7 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go @@ -531,3 +531,19 @@ func kexecFileLoad(kernelFd int, initrdFd int, cmdlineLen int, cmdline string, f } return } + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func riscvHWProbe(pairs []RISCVHWProbePairs, cpuCount uintptr, cpus *CPUSet, flags uint) (err error) { + var _p0 unsafe.Pointer + if len(pairs) > 0 { + _p0 = unsafe.Pointer(&pairs[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS_RISCV_HWPROBE, uintptr(_p0), uintptr(len(pairs)), uintptr(cpuCount), uintptr(unsafe.Pointer(cpus)), uintptr(flags), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go index cdb2af5ae..35f499b32 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -1858,3 +1858,14 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error } return } + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go index 9d25f76b0..3cda65b0d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -1858,3 +1858,14 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error } return } + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go index d3f803516..1e1fea902 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -1858,3 +1858,14 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error } return } + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go index 887188a52..3b77da110 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go @@ -1858,3 +1858,14 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error } return } + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mremapNetBSD(oldp uintptr, oldsize uintptr, newp uintptr, newsize uintptr, flags int) (xaddr uintptr, err error) { + r0, _, e1 := Syscall6(SYS_MREMAP, uintptr(oldp), uintptr(oldsize), uintptr(newp), uintptr(newsize), uintptr(flags), 0) + xaddr = uintptr(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 3e594a8c0..ef285c567 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -251,6 +251,8 @@ const ( SYS_ACCEPT4 = 242 SYS_RECVMMSG = 243 SYS_ARCH_SPECIFIC_SYSCALL = 244 + SYS_RISCV_HWPROBE = 258 + SYS_RISCV_FLUSH_ICACHE = 259 SYS_WAIT4 = 260 SYS_PRLIMIT64 = 261 SYS_FANOTIFY_INIT = 262 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 02e2462c8..26ef52aaf 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -866,6 +866,11 @@ const ( POLLNVAL = 0x20 ) +type sigset_argpack struct { + ss *Sigset_t + ssLen uintptr +} + type SignalfdSiginfo struct { Signo uint32 Errno int32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index 9ea54b7b8..83c69c119 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -718,3 +718,26 @@ type SysvShmDesc struct { _ uint64 _ uint64 } + +type RISCVHWProbePairs struct { + Key int64 + Value uint64 +} + +const ( + RISCV_HWPROBE_KEY_MVENDORID = 0x0 + RISCV_HWPROBE_KEY_MARCHID = 0x1 + RISCV_HWPROBE_KEY_MIMPID = 0x2 + RISCV_HWPROBE_KEY_BASE_BEHAVIOR = 0x3 + RISCV_HWPROBE_BASE_BEHAVIOR_IMA = 0x1 + RISCV_HWPROBE_KEY_IMA_EXT_0 = 0x4 + RISCV_HWPROBE_IMA_FD = 0x1 + RISCV_HWPROBE_IMA_C = 0x2 + RISCV_HWPROBE_KEY_CPUPERF_0 = 0x5 + RISCV_HWPROBE_MISALIGNED_UNKNOWN = 0x0 + RISCV_HWPROBE_MISALIGNED_EMULATED = 0x1 + RISCV_HWPROBE_MISALIGNED_SLOW = 0x2 + RISCV_HWPROBE_MISALIGNED_FAST = 0x3 + RISCV_HWPROBE_MISALIGNED_UNSUPPORTED = 0x4 + RISCV_HWPROBE_MISALIGNED_MASK = 0x7 +) diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 964590075..373d16388 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -135,14 +135,14 @@ func Getpagesize() int { return 4096 } // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention. // This is useful when interoperating with Windows code requiring callbacks. -// The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. +// The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. func NewCallback(fn interface{}) uintptr { return syscall.NewCallback(fn) } // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention. // This is useful when interoperating with Windows code requiring callbacks. -// The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. +// The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr. func NewCallbackCDecl(fn interface{}) uintptr { return syscall.NewCallbackCDecl(fn) } diff --git a/vendor/modules.txt b/vendor/modules.txt index 658245a0f..4f471521a 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -203,6 +203,9 @@ github.com/josharian/intern # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go +# github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 +## explicit; go 1.16 +github.com/lufia/plan9stats # github.com/mailru/easyjson v0.7.7 ## explicit; go 1.12 github.com/mailru/easyjson/buffer @@ -275,6 +278,9 @@ github.com/pborman/uuid # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib +# github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c +## explicit; go 1.14 +github.com/power-devops/perfstat # github.com/prometheus/client_golang v1.16.0 ## explicit; go 1.17 github.com/prometheus/client_golang/prometheus @@ -294,16 +300,20 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/shirou/gopsutil v3.21.11+incompatible -## explicit -github.com/shirou/gopsutil/cpu -github.com/shirou/gopsutil/disk -github.com/shirou/gopsutil/host -github.com/shirou/gopsutil/internal/common -github.com/shirou/gopsutil/load -github.com/shirou/gopsutil/mem -github.com/shirou/gopsutil/net -github.com/shirou/gopsutil/process +# github.com/shirou/gopsutil/v3 v3.23.8 +## explicit; go 1.15 +github.com/shirou/gopsutil/v3/common +github.com/shirou/gopsutil/v3/cpu +github.com/shirou/gopsutil/v3/disk +github.com/shirou/gopsutil/v3/host +github.com/shirou/gopsutil/v3/internal/common +github.com/shirou/gopsutil/v3/load +github.com/shirou/gopsutil/v3/mem +github.com/shirou/gopsutil/v3/net +github.com/shirou/gopsutil/v3/process +# github.com/shoenig/go-m1cpu v0.1.6 +## explicit; go 1.20 +github.com/shoenig/go-m1cpu # github.com/sirupsen/logrus v1.8.1 ## explicit; go 1.13 github.com/sirupsen/logrus @@ -316,10 +326,10 @@ github.com/stretchr/testify/assert github.com/stretchr/testify/require # github.com/tedsuo/ifrit v0.0.0-20230516164442-7862c310ad26 ## explicit; go 1.16 -# github.com/tklauser/go-sysconf v0.3.11 +# github.com/tklauser/go-sysconf v0.3.12 ## explicit; go 1.13 github.com/tklauser/go-sysconf -# github.com/tklauser/numcpus v0.6.0 +# github.com/tklauser/numcpus v0.6.1 ## explicit; go 1.13 github.com/tklauser/numcpus # github.com/yusufpapurcu/wmi v1.2.3 @@ -381,7 +391,7 @@ golang.org/x/oauth2/jwt # golang.org/x/sync v0.3.0 ## explicit; go 1.17 golang.org/x/sync/semaphore -# golang.org/x/sys v0.10.0 +# golang.org/x/sys v0.11.0 ## explicit; go 1.17 golang.org/x/sys/cpu golang.org/x/sys/internal/unsafeheader