/
counter.go
122 lines (95 loc) · 2.27 KB
/
counter.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
/**
* counter.go - bandwidth counter
*
* @author Yaroslav Pogrebnyak <yyyaroslav@gmail.com>
*/
package counters
import (
"time"
"github.com/millken/tcpwder/core"
)
/**
* Count total bandwidth and bandwidth per second
*/
type BandwidthCounter struct {
/* Bandwidth Stats */
BandwidthStats
/* Last received total bytes */
RxTotalLast uint64
/* Last transmitted total bytes */
TxTotalLast uint64
/* Timeframe to calculate per-second bandwidth */
interval time.Duration
/* Ticker for per-second bandwidth calculation and pushing stats */
ticker *time.Ticker
/* Indicates that new bandwidth delta was received */
newTxRx bool
/* ----- channels ----- */
/* Input channel for bandwidth deltas */
Traffic chan core.ReadWriteCount
/* Stop channel */
stop chan bool
/* Output channel for bandwidth stats */
Out chan BandwidthStats
}
/**
* Create new BandwidthCounter
*/
func NewBandwidthCounter(interval time.Duration, out chan BandwidthStats) *BandwidthCounter {
return &BandwidthCounter{
interval: interval,
ticker: time.NewTicker(interval),
BandwidthStats: BandwidthStats{
RxTotal: 0,
TxTotal: 0,
},
TxTotalLast: 0,
RxTotalLast: 0,
Out: out,
Traffic: make(chan core.ReadWriteCount),
stop: make(chan bool),
}
}
/**
* Starts bandwidth counter
*/
func (this *BandwidthCounter) Start() {
go func() {
for {
select {
// Stop requested
case <-this.stop:
this.ticker.Stop()
close(this.Traffic)
return
// New counting cycle
case <-this.ticker.C:
if !this.newTxRx {
this.RxSecond = 0
this.TxSecond = 0
} else {
dRx := this.RxTotal - this.RxTotalLast
dTx := this.TxTotal - this.TxTotalLast
this.RxSecond = uint(dRx / uint64(this.interval.Seconds()))
this.TxSecond = uint(dTx / uint64(this.interval.Seconds()))
this.RxTotalLast = this.RxTotal
this.TxTotalLast = this.TxTotal
this.newTxRx = false
}
// Send results to out
this.Out <- this.BandwidthStats
// New traffic deltas available
case rwc := <-this.Traffic:
this.newTxRx = true
this.RxTotal += uint64(rwc.CountRead)
this.TxTotal += uint64(rwc.CountWrite)
}
}
}()
}
/**
* Stops bandwidth counter
*/
func (this *BandwidthCounter) Stop() {
this.stop <- true
}