standard.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package metrics
  2. import (
  3. "io"
  4. "net"
  5. "sync"
  6. "time"
  7. gometrics "github.com/coreos/etcd/third_party/github.com/rcrowley/go-metrics"
  8. )
  9. const (
  10. // RuntimeMemStatsSampleInterval is the interval in seconds at which the
  11. // Go runtime's memory statistics will be gathered.
  12. RuntimeMemStatsSampleInterval = time.Duration(2) * time.Second
  13. // GraphitePublishInterval is the interval in seconds at which all
  14. // gathered statistics will be published to a Graphite endpoint.
  15. GraphitePublishInterval = time.Duration(2) * time.Second
  16. )
  17. type standardBucket struct {
  18. sync.Mutex
  19. name string
  20. registry gometrics.Registry
  21. timers map[string]Timer
  22. gauges map[string]Gauge
  23. }
  24. func newStandardBucket(name string) standardBucket {
  25. registry := gometrics.NewRegistry()
  26. gometrics.RegisterRuntimeMemStats(registry)
  27. go gometrics.CaptureRuntimeMemStats(registry, RuntimeMemStatsSampleInterval)
  28. return standardBucket{
  29. name: name,
  30. registry: registry,
  31. timers: make(map[string]Timer),
  32. gauges: make(map[string]Gauge),
  33. }
  34. }
  35. func (smb standardBucket) Dump(w io.Writer) {
  36. gometrics.WriteOnce(smb.registry, w)
  37. return
  38. }
  39. func (smb standardBucket) Timer(name string) Timer {
  40. smb.Lock()
  41. defer smb.Unlock()
  42. timer, ok := smb.timers[name]
  43. if !ok {
  44. timer = gometrics.NewTimer()
  45. smb.timers[name] = timer
  46. smb.registry.Register(name, timer)
  47. }
  48. return timer
  49. }
  50. func (smb standardBucket) Gauge(name string) Gauge {
  51. smb.Lock()
  52. defer smb.Unlock()
  53. gauge, ok := smb.gauges[name]
  54. if !ok {
  55. gauge = gometrics.NewGauge()
  56. smb.gauges[name] = gauge
  57. smb.registry.Register(name, gauge)
  58. }
  59. return gauge
  60. }
  61. func (smb standardBucket) Publish(graphite_addr string) error {
  62. addr, err := net.ResolveTCPAddr("tcp", graphite_addr)
  63. if err != nil {
  64. return err
  65. }
  66. go gometrics.Graphite(smb.registry, GraphitePublishInterval, smb.name, addr)
  67. return nil
  68. }