You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

251 lines
7.8 KiB

  1. // Copyright (c) 2015-2024 MinIO, Inc.
  2. //
  3. // This file is part of MinIO Object Storage stack
  4. //
  5. // This program is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. package cmd
  18. import (
  19. "encoding/json"
  20. "fmt"
  21. "net/http"
  22. "slices"
  23. "strings"
  24. "sync"
  25. "github.com/minio/minio/internal/config"
  26. "github.com/minio/minio/internal/mcontext"
  27. "github.com/minio/mux"
  28. "github.com/minio/pkg/v3/env"
  29. "github.com/prometheus/client_golang/prometheus"
  30. "github.com/prometheus/client_golang/prometheus/promhttp"
  31. )
  32. type promLogger struct{}
  33. func (p promLogger) Println(v ...interface{}) {
  34. metricsLogIf(GlobalContext, fmt.Errorf("metrics handler error: %v", v))
  35. }
  36. type metricsV3Server struct {
  37. registry *prometheus.Registry
  38. opts promhttp.HandlerOpts
  39. auth func(http.Handler) http.Handler
  40. metricsData *metricsV3Collection
  41. }
  42. var (
  43. globalMetricsV3CollectorPaths []collectorPath
  44. globalMetricsV3Once sync.Once
  45. )
  46. func newMetricsV3Server(auth func(h http.Handler) http.Handler) *metricsV3Server {
  47. registry := prometheus.NewRegistry()
  48. metricGroups := newMetricGroups(registry)
  49. globalMetricsV3Once.Do(func() {
  50. globalMetricsV3CollectorPaths = metricGroups.collectorPaths
  51. })
  52. return &metricsV3Server{
  53. registry: registry,
  54. opts: promhttp.HandlerOpts{
  55. ErrorLog: promLogger{},
  56. ErrorHandling: promhttp.ContinueOnError,
  57. Registry: registry,
  58. MaxRequestsInFlight: 2,
  59. EnableOpenMetrics: env.Get(EnvPrometheusOpenMetrics, config.EnableOff) == config.EnableOn,
  60. ProcessStartTime: globalBootTime,
  61. },
  62. auth: auth,
  63. metricsData: metricGroups,
  64. }
  65. }
  66. // metricDisplay - contains info on a metric for display purposes.
  67. type metricDisplay struct {
  68. Name string `json:"name"`
  69. Help string `json:"help"`
  70. Type string `json:"type"`
  71. Labels []string `json:"labels"`
  72. }
  73. func (md metricDisplay) String() string {
  74. return fmt.Sprintf("Name: %s\nType: %s\nHelp: %s\nLabels: {%s}\n", md.Name, md.Type, md.Help, strings.Join(md.Labels, ","))
  75. }
  76. func (md metricDisplay) TableRow() string {
  77. labels := strings.Join(md.Labels, ",")
  78. if labels == "" {
  79. labels = ""
  80. } else {
  81. labels = "`" + labels + "`"
  82. }
  83. return fmt.Sprintf("| `%s` | `%s` | %s | %s |\n", md.Name, md.Type, md.Help, labels)
  84. }
  85. // listMetrics - returns a handler that lists all the metrics that could be
  86. // returned for the requested path.
  87. //
  88. // FIXME: It currently only lists `minio_` prefixed metrics.
  89. func (h *metricsV3Server) listMetrics(path string) http.Handler {
  90. // First collect all matching MetricsGroup's
  91. matchingMG := make(map[collectorPath]*MetricsGroup)
  92. for _, collPath := range h.metricsData.collectorPaths {
  93. if collPath.isDescendantOf(path) {
  94. if v, ok := h.metricsData.mgMap[collPath]; ok {
  95. matchingMG[collPath] = v
  96. } else if v, ok := h.metricsData.bucketMGMap[collPath]; ok {
  97. matchingMG[collPath] = v
  98. }
  99. }
  100. }
  101. if len(matchingMG) == 0 {
  102. return nil
  103. }
  104. var metrics []metricDisplay
  105. for _, collectorPath := range h.metricsData.collectorPaths {
  106. if mg, ok := matchingMG[collectorPath]; ok {
  107. var commonLabels []string
  108. for k := range mg.ExtraLabels {
  109. commonLabels = append(commonLabels, k)
  110. }
  111. for _, d := range mg.Descriptors {
  112. labels := slices.Clone(d.VariableLabels)
  113. labels = append(labels, commonLabels...)
  114. metric := metricDisplay{
  115. Name: mg.MetricFQN(d.Name),
  116. Help: d.Help,
  117. Type: d.Type.String(),
  118. Labels: labels,
  119. }
  120. metrics = append(metrics, metric)
  121. }
  122. }
  123. }
  124. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  125. contentType := r.Header.Get("Content-Type")
  126. if contentType == "application/json" {
  127. w.Header().Set("Content-Type", "application/json")
  128. jsonEncoder := json.NewEncoder(w)
  129. jsonEncoder.Encode(metrics)
  130. return
  131. }
  132. // If not JSON, return plain text. We format it as a markdown table for
  133. // readability.
  134. w.Header().Set("Content-Type", "text/plain")
  135. var b strings.Builder
  136. b.WriteString("| Name | Type | Help | Labels |\n")
  137. b.WriteString("| ---- | ---- | ---- | ------ |\n")
  138. for _, metric := range metrics {
  139. b.WriteString(metric.TableRow())
  140. }
  141. w.Write([]byte(b.String()))
  142. })
  143. }
  144. func (h *metricsV3Server) handle(path string, isListingRequest bool, buckets []string) http.Handler {
  145. var notFoundHandler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  146. http.Error(w, "Metrics Resource Not found", http.StatusNotFound)
  147. })
  148. // Require that metrics path has one component at least.
  149. if path == "/" {
  150. return notFoundHandler
  151. }
  152. if isListingRequest {
  153. handler := h.listMetrics(path)
  154. if handler == nil {
  155. return notFoundHandler
  156. }
  157. return handler
  158. }
  159. // In each of the following cases, we check if the collect path is a
  160. // descendant of `path`, and if so, we add the corresponding gatherer to
  161. // the list of gatherers. This way, /api/a will return all metrics returned
  162. // by /api/a/b and /api/a/c (and any other matching descendant collector
  163. // paths).
  164. var gatherers []prometheus.Gatherer
  165. for _, collectorPath := range h.metricsData.collectorPaths {
  166. if collectorPath.isDescendantOf(path) {
  167. gatherer := h.metricsData.mgGatherers[collectorPath]
  168. // For Bucket metrics we need to set the buckets argument inside the
  169. // metric group, so that it will affect collection. If no buckets
  170. // are provided, we will not return bucket metrics.
  171. if bmg, ok := h.metricsData.bucketMGMap[collectorPath]; ok {
  172. if len(buckets) == 0 {
  173. continue
  174. }
  175. unLocker := bmg.LockAndSetBuckets(buckets)
  176. defer unLocker()
  177. }
  178. gatherers = append(gatherers, gatherer)
  179. }
  180. }
  181. if len(gatherers) == 0 {
  182. return notFoundHandler
  183. }
  184. return promhttp.HandlerFor(prometheus.Gatherers(gatherers), h.opts)
  185. }
  186. // ServeHTTP - implements http.Handler interface.
  187. //
  188. // When the `list` query parameter is provided (its value is ignored), the
  189. // server lists all metrics that could be returned for the requested path.
  190. //
  191. // The (repeatable) `buckets` query parameter is a list of bucket names (or it
  192. // could be a comma separated value) to return metrics with a bucket label.
  193. // Bucket metrics will be returned only for the provided buckets. If no buckets
  194. // parameter is provided, no bucket metrics are returned.
  195. func (h *metricsV3Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  196. pathComponents := mux.Vars(r)["pathComps"]
  197. isListingRequest := r.Form.Has("list")
  198. var buckets []string
  199. if strings.HasPrefix(pathComponents, "/bucket/") {
  200. // bucket specific metrics, extract the bucket name from the path.
  201. // it's the last part of the path. e.g. /bucket/api/<bucket-name>
  202. bucketIdx := strings.LastIndex(pathComponents, "/")
  203. buckets = append(buckets, pathComponents[bucketIdx+1:])
  204. // remove bucket from pathComponents as it is dyanamic and
  205. // hence not included in the collector path.
  206. pathComponents = pathComponents[:bucketIdx]
  207. }
  208. innerHandler := h.handle(pathComponents, isListingRequest, buckets)
  209. // Add tracing to the prom. handler
  210. tracedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  211. tc, ok := r.Context().Value(mcontext.ContextTraceKey).(*mcontext.TraceCtxt)
  212. if ok {
  213. tc.FuncName = "handler.MetricsV3"
  214. tc.ResponseRecorder.LogErrBody = true
  215. }
  216. innerHandler.ServeHTTP(w, r)
  217. })
  218. // Add authentication
  219. h.auth(tracedHandler).ServeHTTP(w, r)
  220. }