-
Notifications
You must be signed in to change notification settings - Fork 0
/
ifstat.go
185 lines (149 loc) · 2.78 KB
/
ifstat.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"regexp"
"time"
)
const (
kb = 1 << (10 * (iota + 1))
mb
)
type readPair struct {
rx string
tx string
}
type (
netSpeed int
pair struct {
rx netSpeed
tx netSpeed
}
)
const printFormat = "%v %v\n"
type ifStat struct {
path []readPair
delay time.Duration
out io.Writer
}
func (speed netSpeed) String() (res string) {
switch {
case speed < kb:
res += fmt.Sprintf("%7.1fB ", float32(speed))
case speed >= kb && speed < mb:
res += fmt.Sprintf("%7.1fKb", float32(speed)/float32(kb))
case speed >= mb:
res += fmt.Sprintf("%7.1fMb", float32(speed)/float32(mb))
}
return
}
func newStat(accumulate time.Duration, names ...string) *ifStat {
path := make([]readPair, 0, len(names))
for _, ifname := range names {
if err := checkIfaceExists(ifname); err != nil {
log.Println(err)
continue
}
prefix := filepath.Join("/sys/class/net", ifname, "statistics")
path = append(path,
readPair{
rx: filepath.Join(prefix, "rx_bytes"),
tx: filepath.Join(prefix, "tx_bytes"),
})
}
return &ifStat{
path: path,
delay: accumulate,
out: os.Stdout,
}
}
func checkIfaceExists(name string) error {
check, err := regexp.Compile(`^\s*` + name + ": .*$")
if err != nil {
return err
}
file, err := os.Open("/proc/net/dev")
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if check.MatchString(scanner.Text()) {
return nil
}
}
return fmt.Errorf("interface not exists: %s", name)
}
func (i *ifStat) Run() func() {
var (
ctx, cancel = context.WithCancel(context.Background())
last = i.readDetached(ctx)
)
go i.printDetached(last)
return cancel
}
func (i *ifStat) readDetached(ctx context.Context) (status <-chan pair) {
var (
last = make(chan pair)
ticker = time.NewTicker(i.delay)
)
go func() {
last <- i.read()
for {
select {
case <-ticker.C:
last <- i.read()
case <-ctx.Done():
close(last)
return
}
}
}()
return last
}
func (i *ifStat) printDetached(last <-chan pair) {
var (
prod = netSpeed(time.Second / i.delay)
prev = <-last
)
for curr := range last {
var (
rxInt = (curr.rx - prev.rx) * prod
txInt = (curr.tx - prev.tx) * prod
)
_, err := fmt.Fprintf(i.out, printFormat, rxInt, txInt)
if err != nil {
log.Print(err)
}
prev = curr
}
}
func mustGetInt(r string) (res netSpeed) {
file, err := os.Open(r)
if err != nil {
return
}
_, err = fmt.Fscan(file, &res)
if err != nil {
log.Print(err)
return
}
err = file.Close()
if err != nil {
log.Print(err)
}
return
}
func (i *ifStat) read() (res pair) {
for _, ifpath := range i.path {
res.rx += mustGetInt(ifpath.rx)
res.tx += mustGetInt(ifpath.tx)
}
return
}