stats.go 1.7 KB

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