|
| 1 | +package doorman |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + |
| 6 | + "github.com/prometheus/client_golang/prometheus" |
| 7 | +) |
| 8 | + |
| 9 | +type collector struct { |
| 10 | + server *Server |
| 11 | + mu sync.Mutex |
| 12 | + has *prometheus.GaugeVec |
| 13 | + wants *prometheus.GaugeVec |
| 14 | + count *prometheus.GaugeVec |
| 15 | +} |
| 16 | + |
| 17 | +// NewCollector returns a custom Prometheus collector that creates |
| 18 | +// metrics for how much capacity has been assigned |
| 19 | +// (doorman_server_sum_has), requested (doorman_server_sum_wants), and |
| 20 | +// the total number of clients (doorman_server_client_count), with the |
| 21 | +// resource id as the label. It has to be registered using |
| 22 | +// prometheus.Register. |
| 23 | +func NewCollector(server *Server) prometheus.Collector { |
| 24 | + labels := []string{"resource"} |
| 25 | + return &collector{ |
| 26 | + server: server, |
| 27 | + has: prometheus.NewGaugeVec(prometheus.GaugeOpts{ |
| 28 | + Namespace: "doorman", |
| 29 | + Subsystem: "server", |
| 30 | + Name: "sum_has", |
| 31 | + Help: "All capacity assigned to clients for a resource.", |
| 32 | + }, labels), |
| 33 | + wants: prometheus.NewGaugeVec(prometheus.GaugeOpts{ |
| 34 | + Namespace: "doorman", |
| 35 | + Subsystem: "server", |
| 36 | + Name: "sum_wants", |
| 37 | + Help: "All capacity requested by clients for a resource.", |
| 38 | + }, labels), |
| 39 | + count: prometheus.NewGaugeVec(prometheus.GaugeOpts{ |
| 40 | + Namespace: "doorman", |
| 41 | + Subsystem: "server", |
| 42 | + Name: "client_count", |
| 43 | + Help: "Number of clients requesting this resource.", |
| 44 | + }, labels), |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func (c *collector) Describe(ch chan<- *prometheus.Desc) { |
| 49 | + c.has.Describe(ch) |
| 50 | + c.wants.Describe(ch) |
| 51 | + c.count.Describe(ch) |
| 52 | +} |
| 53 | + |
| 54 | +func (c *collector) Collect(ch chan<- prometheus.Metric) { |
| 55 | + status := c.server.Status() |
| 56 | + c.mu.Lock() |
| 57 | + defer c.mu.Unlock() |
| 58 | + |
| 59 | + for id, res := range status.Resources { |
| 60 | + c.has.WithLabelValues(id).Set(res.SumHas) |
| 61 | + c.wants.WithLabelValues(id).Set(res.SumWants) |
| 62 | + c.count.WithLabelValues(id).Set(float64(res.Count)) |
| 63 | + } |
| 64 | + c.has.Collect(ch) |
| 65 | + c.wants.Collect(ch) |
| 66 | + c.count.Collect(ch) |
| 67 | + |
| 68 | + c.has.Reset() |
| 69 | + c.wants.Reset() |
| 70 | + c.count.Reset() |
| 71 | +} |
0 commit comments