1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-29 10:45:22 +00:00
v2fly/app/stats/stats.go

97 lines
1.9 KiB
Go
Raw Normal View History

2018-03-30 17:56:59 +00:00
package stats
2018-09-30 21:08:41 +00:00
//go:generate errorgen
2018-03-30 17:56:59 +00:00
import (
"context"
"sync"
"sync/atomic"
"v2ray.com/core"
)
2018-04-03 22:29:30 +00:00
// Counter is an implementation of core.StatCounter.
2018-03-30 17:56:59 +00:00
type Counter struct {
value int64
}
2018-04-03 22:29:30 +00:00
// Value implements core.StatCounter.
2018-03-30 17:56:59 +00:00
func (c *Counter) Value() int64 {
return atomic.LoadInt64(&c.value)
}
2018-04-03 22:29:30 +00:00
// Set implements core.StatCounter.
2018-03-30 21:17:28 +00:00
func (c *Counter) Set(newValue int64) int64 {
2018-03-30 17:56:59 +00:00
return atomic.SwapInt64(&c.value, newValue)
}
2018-04-03 22:29:30 +00:00
// Add implements core.StatCounter.
2018-03-30 17:56:59 +00:00
func (c *Counter) Add(delta int64) int64 {
return atomic.AddInt64(&c.value, delta)
}
2018-04-03 22:29:30 +00:00
// Manager is an implementation of core.StatManager.
2018-03-30 17:56:59 +00:00
type Manager struct {
access sync.RWMutex
counters map[string]*Counter
}
func NewManager(ctx context.Context, config *Config) (*Manager, error) {
2018-03-31 08:30:12 +00:00
m := &Manager{
2018-03-30 17:56:59 +00:00
counters: make(map[string]*Counter),
2018-03-31 08:30:12 +00:00
}
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
2018-03-30 17:56:59 +00:00
}
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.")
}
2018-03-31 08:30:12 +00:00
newError("create new counter ", name).AtDebug().WriteToLog()
2018-03-30 17:56:59 +00:00
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
}
2018-07-10 21:40:58 +00:00
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
}
}
}
2018-05-25 21:20:24 +00:00
// Start implements common.Runnable.
2018-03-30 17:56:59 +00:00
func (m *Manager) Start() error {
return nil
}
2018-05-25 21:20:24 +00:00
// Close implement common.Closable.
2018-03-30 17:56:59 +00:00
func (m *Manager) Close() error {
return nil
}