-
-
Notifications
You must be signed in to change notification settings - Fork 233
/
stat_linux.go
111 lines (94 loc) · 1.94 KB
/
stat_linux.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
package main
import (
"fmt"
"net"
"os"
"sort"
"sync"
"time"
"github.com/kevwan/tproxy/display"
"github.com/olekukonko/tablewriter"
)
type StatPrinter struct {
duration time.Duration
conns map[string]*net.TCPConn
prev map[string]*TcpInfo
lock sync.RWMutex
}
func NewStatPrinter(duration time.Duration) Stater {
if !settings.Stat {
return NilPrinter{}
}
return &StatPrinter{
duration: duration,
conns: make(map[string]*net.TCPConn),
}
}
func (p *StatPrinter) AddConn(key string, conn *net.TCPConn) {
p.lock.Lock()
defer p.lock.Unlock()
p.conns[key] = conn
}
func (p *StatPrinter) DelConn(key string) {
p.lock.Lock()
defer p.lock.Unlock()
delete(p.conns, key)
}
func (p *StatPrinter) Start() {
ticker := time.NewTicker(p.duration)
defer ticker.Stop()
for range ticker.C {
p.print()
}
}
func (p *StatPrinter) Stop() {
p.print()
}
func (p *StatPrinter) buildRows() [][]string {
var keys []string
infos := make(map[string]*TcpInfo)
p.lock.RLock()
prev := p.prev
for k, v := range p.conns {
info, err := GetTcpInfo(v)
if err != nil {
display.PrintfWithTime("GetTcpInfo: %v\n", err)
continue
}
keys = append(keys, k)
infos[k] = info
}
p.prev = infos
p.lock.RUnlock()
var rows [][]string
now := time.Now().Format(display.TimeFormat)
sort.Strings(keys)
for _, k := range keys {
v, ok := infos[k]
if !ok {
continue
}
var rate string
pinfo, ok := prev[k]
if ok {
rate = fmt.Sprintf("%.2f", GetRetransRate(pinfo, v))
} else {
rate = "-"
}
rtt, rttv := v.GetRTT()
rows = append(rows, []string{now, k, rate, fmt.Sprint(rtt), fmt.Sprint(rttv)})
}
return rows
}
func (p *StatPrinter) print() {
rows := p.buildRows()
if len(rows) == 0 {
return
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Timestamp", "Connection", "RetransRate(%)", "RTT(ms)", "RTT/Variance(ms)"})
table.SetBorder(false)
table.AppendBulk(rows)
table.Render()
fmt.Println()
}