-
-
Notifications
You must be signed in to change notification settings - Fork 238
/
Copy pathcounter.go
74 lines (63 loc) · 1.44 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
package main
import (
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"github.com/fatih/color"
)
type connCounter struct {
total int64
concurrent int64
max int64
conns map[string]time.Time
maxLifetime time.Duration
lock sync.Mutex
}
func NewConnCounter() Stater {
return &connCounter{
conns: make(map[string]time.Time),
}
}
func (c *connCounter) AddConn(key string, _ *net.TCPConn) {
atomic.AddInt64(&c.total, 1)
val := atomic.AddInt64(&c.concurrent, 1)
max := atomic.LoadInt64(&c.max)
if val > max {
atomic.CompareAndSwapInt64(&c.max, max, val)
}
c.lock.Lock()
defer c.lock.Unlock()
c.conns[key] = time.Now()
}
func (c *connCounter) DelConn(key string) {
atomic.AddInt64(&c.concurrent, -1)
c.lock.Lock()
defer c.lock.Unlock()
start, ok := c.conns[key]
delete(c.conns, key)
if ok {
lifetime := time.Since(start)
if lifetime > c.maxLifetime {
c.maxLifetime = lifetime
}
}
}
func (c *connCounter) Start() {
}
func (c *connCounter) Stop() {
c.lock.Lock()
for _, start := range c.conns {
lifetime := time.Since(start)
if lifetime > c.maxLifetime {
c.maxLifetime = lifetime
}
}
defer c.lock.Unlock()
fmt.Println()
color.HiWhite("Connection stats (client -> tproxy -> server):")
color.HiWhite(" Total connections: %d", atomic.LoadInt64(&c.total))
color.HiWhite(" Max concurrent connections: %d", atomic.LoadInt64(&c.max))
color.HiWhite(" Max connection lifetime: %s", c.maxLifetime)
}