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