metrics.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package snowflake_proxy
  2. import (
  3. "net/http"
  4. "github.com/prometheus/client_golang/prometheus"
  5. "github.com/prometheus/client_golang/prometheus/promhttp"
  6. )
  7. const (
  8. // metricNamespace represent prometheus namespace
  9. metricNamespace = "tor_snowflake_proxy"
  10. )
  11. type Metrics struct {
  12. totalInBoundTraffic prometheus.Counter
  13. totalOutBoundTraffic prometheus.Counter
  14. totalConnections prometheus.Counter
  15. }
  16. func NewMetrics() *Metrics {
  17. return &Metrics{
  18. totalConnections: prometheus.NewCounter(prometheus.CounterOpts{
  19. Namespace: metricNamespace,
  20. Name: "connections_total",
  21. Help: "The total number of connections handled by the snowflake proxy",
  22. }),
  23. totalInBoundTraffic: prometheus.NewCounter(prometheus.CounterOpts{
  24. Namespace: metricNamespace,
  25. Name: "traffic_inbound_bytes_total",
  26. Help: "The total in bound traffic by the snowflake proxy (KB)",
  27. }),
  28. totalOutBoundTraffic: prometheus.NewCounter(prometheus.CounterOpts{
  29. Namespace: metricNamespace,
  30. Name: "traffic_outbound_bytes_total",
  31. Help: "The total out bound traffic by the snowflake proxy (KB)",
  32. }),
  33. }
  34. }
  35. // Start register the metrics server and serve them on the given address
  36. func (m *Metrics) Start(addr string) error {
  37. go func() {
  38. http.Handle("/internal/metrics", promhttp.Handler())
  39. if err := http.ListenAndServe(addr, nil); err != nil {
  40. panic(err)
  41. }
  42. }()
  43. return prometheus.Register(m)
  44. }
  45. func (m *Metrics) Collect(ch chan<- prometheus.Metric) {
  46. m.totalConnections.Collect(ch)
  47. m.totalInBoundTraffic.Collect(ch)
  48. m.totalOutBoundTraffic.Collect(ch)
  49. }
  50. func (m *Metrics) Describe(descs chan<- *prometheus.Desc) {
  51. prometheus.DescribeByCollect(m, descs)
  52. }
  53. // TrackInBoundTraffic counts the received traffic by the snowflake proxy
  54. func (m *Metrics) TrackInBoundTraffic(value int64) {
  55. m.totalInBoundTraffic.Add(float64(value))
  56. }
  57. // TrackOutBoundTraffic counts the transmitted traffic by the snowflake proxy
  58. func (m *Metrics) TrackOutBoundTraffic(value int64) {
  59. m.totalOutBoundTraffic.Add(float64(value))
  60. }
  61. // TrackNewConnection counts the new connections
  62. func (m *Metrics) TrackNewConnection() {
  63. m.totalConnections.Inc()
  64. }