stats.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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(m); err != nil {
  38. return nil, newError("failed to register StatManager").Base(err)
  39. }
  40. }
  41. return m, nil
  42. }
  43. func (*Manager) Type() interface{} {
  44. return stats.ManagerType()
  45. }
  46. func (m *Manager) RegisterCounter(name string) (stats.Counter, error) {
  47. m.access.Lock()
  48. defer m.access.Unlock()
  49. if _, found := m.counters[name]; found {
  50. return nil, newError("Counter ", name, " already registered.")
  51. }
  52. newError("create new counter ", name).AtDebug().WriteToLog()
  53. c := new(Counter)
  54. m.counters[name] = c
  55. return c, nil
  56. }
  57. func (m *Manager) GetCounter(name string) stats.Counter {
  58. m.access.RLock()
  59. defer m.access.RUnlock()
  60. if c, found := m.counters[name]; found {
  61. return c
  62. }
  63. return nil
  64. }
  65. func (m *Manager) Visit(visitor func(string, stats.Counter) bool) {
  66. m.access.RLock()
  67. defer m.access.RUnlock()
  68. for name, c := range m.counters {
  69. if !visitor(name, c) {
  70. break
  71. }
  72. }
  73. }
  74. // Start implements common.Runnable.
  75. func (m *Manager) Start() error {
  76. return nil
  77. }
  78. // Close implement common.Closable.
  79. func (m *Manager) Close() error {
  80. return nil
  81. }