forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
96 lines (77 loc) · 1.88 KB
/
stats.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
package stats
//go:generate errorgen
import (
"context"
"sync"
"sync/atomic"
"v2ray.com/core"
)
// Counter is an implementation of core.StatCounter.
type Counter struct {
value int64
}
// Value implements core.StatCounter.
func (c *Counter) Value() int64 {
return atomic.LoadInt64(&c.value)
}
// Set implements core.StatCounter.
func (c *Counter) Set(newValue int64) int64 {
return atomic.SwapInt64(&c.value, newValue)
}
// Add implements core.StatCounter.
func (c *Counter) Add(delta int64) int64 {
return atomic.AddInt64(&c.value, delta)
}
// Manager is an implementation of core.StatManager.
type Manager struct {
access sync.RWMutex
counters map[string]*Counter
}
func NewManager(ctx context.Context, config *Config) (*Manager, error) {
m := &Manager{
counters: make(map[string]*Counter),
}
v := core.FromContext(ctx)
if v != nil {
if err := v.RegisterFeature((*core.StatManager)(nil), m); err != nil {
return nil, newError("failed to register StatManager").Base(err)
}
}
return m, nil
}
func (m *Manager) RegisterCounter(name string) (core.StatCounter, error) {
m.access.Lock()
defer m.access.Unlock()
if _, found := m.counters[name]; found {
return nil, newError("Counter ", name, " already registered.")
}
newError("create new counter ", name).AtDebug().WriteToLog()
c := new(Counter)
m.counters[name] = c
return c, nil
}
func (m *Manager) GetCounter(name string) core.StatCounter {
m.access.RLock()
defer m.access.RUnlock()
if c, found := m.counters[name]; found {
return c
}
return nil
}
func (m *Manager) Visit(visitor func(string, core.StatCounter) bool) {
m.access.RLock()
defer m.access.RUnlock()
for name, c := range m.counters {
if !visitor(name, c) {
break
}
}
}
// Start implements common.Runnable.
func (m *Manager) Start() error {
return nil
}
// Close implement common.Closable.
func (m *Manager) Close() error {
return nil
}