stats.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package stats
  2. //go:generate errorgen
  3. import (
  4. "context"
  5. "sync"
  6. "sync/atomic"
  7. "v2ray.com/core"
  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. v := core.FromContext(ctx)
  36. if v != nil {
  37. if err := v.RegisterFeature((*stats.Manager)(nil), m); err != nil {
  38. return nil, newError("failed to register StatManager").Base(err)
  39. }
  40. }
  41. return m, nil
  42. }
  43. func (m *Manager) RegisterCounter(name string) (stats.Counter, error) {
  44. m.access.Lock()
  45. defer m.access.Unlock()
  46. if _, found := m.counters[name]; found {
  47. return nil, newError("Counter ", name, " already registered.")
  48. }
  49. newError("create new counter ", name).AtDebug().WriteToLog()
  50. c := new(Counter)
  51. m.counters[name] = c
  52. return c, nil
  53. }
  54. func (m *Manager) GetCounter(name string) stats.Counter {
  55. m.access.RLock()
  56. defer m.access.RUnlock()
  57. if c, found := m.counters[name]; found {
  58. return c
  59. }
  60. return nil
  61. }
  62. func (m *Manager) Visit(visitor func(string, stats.Counter) bool) {
  63. m.access.RLock()
  64. defer m.access.RUnlock()
  65. for name, c := range m.counters {
  66. if !visitor(name, c) {
  67. break
  68. }
  69. }
  70. }
  71. // Start implements common.Runnable.
  72. func (m *Manager) Start() error {
  73. return nil
  74. }
  75. // Close implement common.Closable.
  76. func (m *Manager) Close() error {
  77. return nil
  78. }