This repository has been archived by the owner on Mar 1, 2019. It is now read-only.
/
stat.go
81 lines (73 loc) · 1.43 KB
/
stat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
"log"
"strconv"
"github.com/shirou/gopsutil"
)
func init() {
commands["stat"] = FlagCommand{cmdStat, "netio"}
}
func cmdStat(args ...string) (err error) {
var usage = "Usage: airtoolbox stat ..."
return RunCmd(statCommands, usage, args)
}
var (
statCommands = map[string]FlagCommand{
"netio": {cmdStatNetio, "<pid|proc_name> stat net sent,recv"},
}
)
// convert name to pid
func name2pid(name string) (int32, error) {
pid, err := strconv.Atoi(name)
if err == nil {
return int32(pid), nil
}
pids, err := gopsutil.Pids()
if err != nil {
return 0, err
}
for _, pid := range pids {
p, er := gopsutil.NewProcess(pid)
if er != nil {
continue
}
pname, er := p.Name()
if er != nil {
continue
}
if pname == name {
fmt.Println(pid)
return pid, nil
}
}
return 0, fmt.Errorf("proc(%s) not found", name)
}
func cmdStatNetio(args ...string) (err error) {
if len(args) != 1 {
return ErrArguments
}
pid, err := name2pid(args[0])
if err != nil {
return
}
proc, err := gopsutil.NewProcess(pid)
if err != nil {
log.Fatal(err)
}
ncs, err := proc.NetIOCounters()
if err != nil {
log.Fatal(err)
}
var sent, recv uint64
for _, c := range ncs {
if c.Name == "lo" {
continue
}
sent += c.BytesSent
recv += c.BytesRecv
fmt.Printf("%s: sent:%d, recv:%d\n", c.Name, c.BytesSent, c.BytesRecv)
}
fmt.Printf("send: %dKB\nrecv: %dKB\n", sent>>10, recv>>10)
return nil
}