prometheus.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Copyright (C) 2024 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package servemetrics
  7. import (
  8. "reflect"
  9. "slices"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/prometheus/client_golang/prometheus"
  15. "github.com/syncthing/syncthing/lib/ur/contract"
  16. )
  17. const namePrefix = "syncthing_usage_"
  18. type metricsSet struct {
  19. srv *server
  20. gauges map[string]prometheus.Gauge
  21. gaugeVecs map[string]*prometheus.GaugeVec
  22. gaugeVecLabels map[string][]string
  23. summaries map[string]*metricSummary
  24. collectMut sync.Mutex
  25. }
  26. func newMetricsSet(srv *server) *metricsSet {
  27. s := &metricsSet{
  28. srv: srv,
  29. gauges: make(map[string]prometheus.Gauge),
  30. gaugeVecs: make(map[string]*prometheus.GaugeVec),
  31. gaugeVecLabels: make(map[string][]string),
  32. summaries: make(map[string]*metricSummary),
  33. }
  34. var initForType func(reflect.Type)
  35. initForType = func(t reflect.Type) {
  36. for i := 0; i < t.NumField(); i++ {
  37. field := t.Field(i)
  38. if field.Type.Kind() == reflect.Struct {
  39. initForType(field.Type)
  40. continue
  41. }
  42. name, typ, label := fieldNameTypeLabel(field)
  43. sname, labels := nameConstLabels(name)
  44. switch typ {
  45. case "gauge":
  46. s.gauges[name] = prometheus.NewGauge(prometheus.GaugeOpts{
  47. Name: namePrefix + sname,
  48. ConstLabels: labels,
  49. })
  50. case "summary":
  51. s.summaries[name] = newMetricSummary(namePrefix+sname, nil, labels)
  52. case "gaugeVec":
  53. s.gaugeVecLabels[name] = append(s.gaugeVecLabels[name], label)
  54. case "summaryVec":
  55. s.summaries[name] = newMetricSummary(namePrefix+sname, []string{label}, labels)
  56. }
  57. }
  58. }
  59. initForType(reflect.ValueOf(contract.Report{}).Type())
  60. for name, labels := range s.gaugeVecLabels {
  61. s.gaugeVecs[name] = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  62. Name: namePrefix + name,
  63. }, labels)
  64. }
  65. return s
  66. }
  67. func fieldNameTypeLabel(rf reflect.StructField) (string, string, string) {
  68. metric := rf.Tag.Get("metric")
  69. name, typ, ok := strings.Cut(metric, ",")
  70. if !ok {
  71. return "", "", ""
  72. }
  73. gv, label, ok := strings.Cut(typ, ":")
  74. if ok {
  75. typ = gv
  76. }
  77. return name, typ, label
  78. }
  79. func nameConstLabels(name string) (string, prometheus.Labels) {
  80. if name == "-" {
  81. return "", nil
  82. }
  83. name, labels, ok := strings.Cut(name, "{")
  84. if !ok {
  85. return name, nil
  86. }
  87. lls := strings.Split(labels[:len(labels)-1], ",")
  88. m := make(map[string]string)
  89. for _, l := range lls {
  90. k, v, _ := strings.Cut(l, "=")
  91. m[k] = v
  92. }
  93. return name, m
  94. }
  95. func (s *metricsSet) addReport(r *contract.Report) {
  96. gaugeVecs := make(map[string][]string)
  97. s.addReportStruct(reflect.ValueOf(r).Elem(), gaugeVecs)
  98. for name, lv := range gaugeVecs {
  99. s.gaugeVecs[name].WithLabelValues(lv...).Add(1)
  100. }
  101. }
  102. func (s *metricsSet) addReportStruct(v reflect.Value, gaugeVecs map[string][]string) {
  103. t := v.Type()
  104. for i := 0; i < v.NumField(); i++ {
  105. field := v.Field(i)
  106. if field.Kind() == reflect.Struct {
  107. s.addReportStruct(field, gaugeVecs)
  108. continue
  109. }
  110. name, typ, label := fieldNameTypeLabel(t.Field(i))
  111. switch typ {
  112. case "gauge":
  113. switch v := field.Interface().(type) {
  114. case int:
  115. s.gauges[name].Add(float64(v))
  116. case string:
  117. s.gaugeVecs[name].WithLabelValues(v).Add(1)
  118. case bool:
  119. if v {
  120. s.gauges[name].Add(1)
  121. }
  122. }
  123. case "gaugeVec":
  124. var labelValue string
  125. switch v := field.Interface().(type) {
  126. case string:
  127. labelValue = v
  128. case int:
  129. labelValue = strconv.Itoa(v)
  130. case map[string]int:
  131. for k, v := range v {
  132. labelValue = k
  133. field.SetInt(int64(v))
  134. break
  135. }
  136. }
  137. if _, ok := gaugeVecs[name]; !ok {
  138. gaugeVecs[name] = make([]string, len(s.gaugeVecLabels[name]))
  139. }
  140. for i, l := range s.gaugeVecLabels[name] {
  141. if l == label {
  142. gaugeVecs[name][i] = labelValue
  143. break
  144. }
  145. }
  146. case "summary", "summaryVec":
  147. switch v := field.Interface().(type) {
  148. case int:
  149. s.summaries[name].Observe("", float64(v))
  150. case float64:
  151. s.summaries[name].Observe("", v)
  152. case []int:
  153. for _, v := range v {
  154. s.summaries[name].Observe("", float64(v))
  155. }
  156. case map[string]int:
  157. for k, v := range v {
  158. if k == "" {
  159. // avoid empty string labels as those are the sign
  160. // of a non-vec summary
  161. k = "unknown"
  162. }
  163. s.summaries[name].Observe(k, float64(v))
  164. }
  165. }
  166. }
  167. }
  168. }
  169. func (s *metricsSet) Describe(c chan<- *prometheus.Desc) {
  170. for _, g := range s.gauges {
  171. g.Describe(c)
  172. }
  173. for _, g := range s.gaugeVecs {
  174. g.Describe(c)
  175. }
  176. for _, g := range s.summaries {
  177. g.Describe(c)
  178. }
  179. }
  180. func (s *metricsSet) Collect(c chan<- prometheus.Metric) {
  181. s.collectMut.Lock()
  182. defer s.collectMut.Unlock()
  183. t0 := time.Now()
  184. defer func() {
  185. metricsCollectSecondsTotal.Add(time.Since(t0).Seconds())
  186. metricsCollectsTotal.Inc()
  187. }()
  188. for _, g := range s.gauges {
  189. g.Set(0)
  190. }
  191. for _, g := range s.gaugeVecs {
  192. g.Reset()
  193. }
  194. for _, g := range s.summaries {
  195. g.Reset()
  196. }
  197. cutoff := time.Now().Add(-24 * time.Hour)
  198. s.srv.reports.Range(func(key string, r *contract.Report) bool {
  199. if r.Received.Before(cutoff) {
  200. s.srv.reports.Delete(key)
  201. return true
  202. }
  203. s.addReport(r)
  204. return true
  205. })
  206. for _, g := range s.gauges {
  207. c <- g
  208. }
  209. for _, g := range s.gaugeVecs {
  210. g.Collect(c)
  211. }
  212. for _, g := range s.summaries {
  213. g.Collect(c)
  214. }
  215. }
  216. type metricSummary struct {
  217. name string
  218. values map[string][]float64
  219. zeroes map[string]int
  220. qDesc *prometheus.Desc
  221. countDesc *prometheus.Desc
  222. sumDesc *prometheus.Desc
  223. zDesc *prometheus.Desc
  224. }
  225. func newMetricSummary(name string, labels []string, constLabels prometheus.Labels) *metricSummary {
  226. return &metricSummary{
  227. name: name,
  228. values: make(map[string][]float64),
  229. zeroes: make(map[string]int),
  230. qDesc: prometheus.NewDesc(name, "", append(labels, "quantile"), constLabels),
  231. countDesc: prometheus.NewDesc(name+"_nonzero_count", "", labels, constLabels),
  232. sumDesc: prometheus.NewDesc(name+"_sum", "", labels, constLabels),
  233. zDesc: prometheus.NewDesc(name+"_zero_count", "", labels, constLabels),
  234. }
  235. }
  236. func (q *metricSummary) Observe(labelValue string, v float64) {
  237. if v == 0 {
  238. q.zeroes[labelValue]++
  239. return
  240. }
  241. q.values[labelValue] = append(q.values[labelValue], v)
  242. }
  243. func (q *metricSummary) Describe(c chan<- *prometheus.Desc) {
  244. c <- q.qDesc
  245. c <- q.countDesc
  246. c <- q.sumDesc
  247. c <- q.zDesc
  248. }
  249. func (q *metricSummary) Collect(c chan<- prometheus.Metric) {
  250. for lv, vs := range q.values {
  251. var labelVals []string
  252. if lv != "" {
  253. labelVals = []string{lv}
  254. }
  255. c <- prometheus.MustNewConstMetric(q.countDesc, prometheus.GaugeValue, float64(len(vs)), labelVals...)
  256. c <- prometheus.MustNewConstMetric(q.zDesc, prometheus.GaugeValue, float64(q.zeroes[lv]), labelVals...)
  257. var sum float64
  258. for _, v := range vs {
  259. sum += v
  260. }
  261. c <- prometheus.MustNewConstMetric(q.sumDesc, prometheus.GaugeValue, sum, labelVals...)
  262. if len(vs) == 0 {
  263. return
  264. }
  265. slices.Sort(vs)
  266. c <- prometheus.MustNewConstMetric(q.qDesc, prometheus.GaugeValue, vs[0], append(labelVals, "0")...)
  267. c <- prometheus.MustNewConstMetric(q.qDesc, prometheus.GaugeValue, vs[len(vs)*5/100], append(labelVals, "0.05")...)
  268. c <- prometheus.MustNewConstMetric(q.qDesc, prometheus.GaugeValue, vs[len(vs)/2], append(labelVals, "0.5")...)
  269. c <- prometheus.MustNewConstMetric(q.qDesc, prometheus.GaugeValue, vs[len(vs)*9/10], append(labelVals, "0.9")...)
  270. c <- prometheus.MustNewConstMetric(q.qDesc, prometheus.GaugeValue, vs[len(vs)*95/100], append(labelVals, "0.95")...)
  271. c <- prometheus.MustNewConstMetric(q.qDesc, prometheus.GaugeValue, vs[len(vs)-1], append(labelVals, "1")...)
  272. }
  273. }
  274. func (q *metricSummary) Reset() {
  275. clear(q.values)
  276. clear(q.zeroes)
  277. }