1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 02:26:49 -05:00
v2fly/app/stats/stats.go

97 lines
2.0 KiB
Go
Raw Normal View History

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