stats.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package stats
  2. //go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg stats -path App,Stats
  3. import (
  4. "context"
  5. "sync"
  6. "sync/atomic"
  7. "v2ray.com/core"
  8. )
  9. type Counter struct {
  10. value int64
  11. }
  12. func (c *Counter) Value() int64 {
  13. return atomic.LoadInt64(&c.value)
  14. }
  15. func (c *Counter) Set(newValue int64) int64 {
  16. return atomic.SwapInt64(&c.value, newValue)
  17. }
  18. func (c *Counter) Add(delta int64) int64 {
  19. return atomic.AddInt64(&c.value, delta)
  20. }
  21. type Manager struct {
  22. access sync.RWMutex
  23. counters map[string]*Counter
  24. }
  25. func NewManager(ctx context.Context, config *Config) (*Manager, error) {
  26. m := &Manager{
  27. counters: make(map[string]*Counter),
  28. }
  29. v := core.FromContext(ctx)
  30. if v != nil {
  31. if err := v.RegisterFeature((*core.StatManager)(nil), m); err != nil {
  32. return nil, newError("failed to register StatManager").Base(err)
  33. }
  34. }
  35. return m, nil
  36. }
  37. func (m *Manager) RegisterCounter(name string) (core.StatCounter, error) {
  38. m.access.Lock()
  39. defer m.access.Unlock()
  40. if _, found := m.counters[name]; found {
  41. return nil, newError("Counter ", name, " already registered.")
  42. }
  43. newError("create new counter ", name).AtDebug().WriteToLog()
  44. c := new(Counter)
  45. m.counters[name] = c
  46. return c, nil
  47. }
  48. func (m *Manager) GetCounter(name string) core.StatCounter {
  49. m.access.RLock()
  50. defer m.access.RUnlock()
  51. if c, found := m.counters[name]; found {
  52. return c
  53. }
  54. return nil
  55. }
  56. func (m *Manager) Start() error {
  57. return nil
  58. }
  59. func (m *Manager) Close() error {
  60. return nil
  61. }