tunnelsforha.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package origin
  2. import (
  3. "fmt"
  4. "sync"
  5. "github.com/prometheus/client_golang/prometheus"
  6. )
  7. // tunnelsForHA maps this cloudflared instance's HA connections to the tunnel IDs they serve.
  8. type tunnelsForHA struct {
  9. sync.Mutex
  10. metrics *prometheus.GaugeVec
  11. entries map[uint8]string
  12. }
  13. // NewTunnelsForHA initializes the Prometheus metrics etc for a tunnelsForHA.
  14. func NewTunnelsForHA() tunnelsForHA {
  15. metrics := prometheus.NewGaugeVec(
  16. prometheus.GaugeOpts{
  17. Name: "tunnel_ids",
  18. Help: "The ID of all tunnels (and their corresponding HA connection ID) running in this instance of cloudflared.",
  19. },
  20. []string{"tunnel_id", "ha_conn_id"},
  21. )
  22. prometheus.MustRegister(metrics)
  23. return tunnelsForHA{
  24. metrics: metrics,
  25. entries: make(map[uint8]string),
  26. }
  27. }
  28. // Track a new tunnel ID, removing the disconnected tunnel (if any) and update metrics.
  29. func (t *tunnelsForHA) AddTunnelID(haConn uint8, tunnelID string) {
  30. t.Lock()
  31. defer t.Unlock()
  32. haStr := fmt.Sprintf("%v", haConn)
  33. if oldTunnelID, ok := t.entries[haConn]; ok {
  34. t.metrics.WithLabelValues(oldTunnelID, haStr).Dec()
  35. }
  36. t.entries[haConn] = tunnelID
  37. t.metrics.WithLabelValues(tunnelID, haStr).Inc()
  38. }
  39. func (t *tunnelsForHA) String() string {
  40. t.Lock()
  41. defer t.Unlock()
  42. return fmt.Sprintf("%v", t.entries)
  43. }