stats.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // +build !confonly
  2. package stats
  3. //go:generate errorgen
  4. import (
  5. "context"
  6. "sync"
  7. "sync/atomic"
  8. "v2ray.com/core/features/stats"
  9. )
  10. // Counter is an implementation of stats.Counter.
  11. type Counter struct {
  12. value int64
  13. }
  14. // Value implements stats.Counter.
  15. func (c *Counter) Value() int64 {
  16. return atomic.LoadInt64(&c.value)
  17. }
  18. // Set implements stats.Counter.
  19. func (c *Counter) Set(newValue int64) int64 {
  20. return atomic.SwapInt64(&c.value, newValue)
  21. }
  22. // Add implements stats.Counter.
  23. func (c *Counter) Add(delta int64) int64 {
  24. return atomic.AddInt64(&c.value, delta)
  25. }
  26. // Manager is an implementation of stats.Manager.
  27. type Manager struct {
  28. access sync.RWMutex
  29. counters map[string]*Counter
  30. }
  31. func NewManager(ctx context.Context, config *Config) (*Manager, error) {
  32. m := &Manager{
  33. counters: make(map[string]*Counter),
  34. }
  35. return m, nil
  36. }
  37. func (*Manager) Type() interface{} {
  38. return stats.ManagerType()
  39. }
  40. func (m *Manager) RegisterCounter(name string) (stats.Counter, error) {
  41. m.access.Lock()
  42. defer m.access.Unlock()
  43. if _, found := m.counters[name]; found {
  44. return nil, newError("Counter ", name, " already registered.")
  45. }
  46. newError("create new counter ", name).AtDebug().WriteToLog()
  47. c := new(Counter)
  48. m.counters[name] = c
  49. return c, nil
  50. }
  51. func (m *Manager) GetCounter(name string) stats.Counter {
  52. m.access.RLock()
  53. defer m.access.RUnlock()
  54. if c, found := m.counters[name]; found {
  55. return c
  56. }
  57. return nil
  58. }
  59. func (m *Manager) Visit(visitor func(string, stats.Counter) bool) {
  60. m.access.RLock()
  61. defer m.access.RUnlock()
  62. for name, c := range m.counters {
  63. if !visitor(name, c) {
  64. break
  65. }
  66. }
  67. }
  68. // Start implements common.Runnable.
  69. func (m *Manager) Start() error {
  70. return nil
  71. }
  72. // Close implement common.Closable.
  73. func (m *Manager) Close() error {
  74. return nil
  75. }