prometheus.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package prometheus
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "github.com/felixge/httpsnoop"
  9. "github.com/prometheus/client_golang/prometheus"
  10. "github.com/prometheus/client_golang/prometheus/promhttp"
  11. log "github.com/sirupsen/logrus"
  12. "github.com/imgproxy/imgproxy/v3/config"
  13. "github.com/imgproxy/imgproxy/v3/metrics/stats"
  14. "github.com/imgproxy/imgproxy/v3/reuseport"
  15. )
  16. var (
  17. enabled = false
  18. requestsTotal prometheus.Counter
  19. statusCodesTotal *prometheus.CounterVec
  20. errorsTotal *prometheus.CounterVec
  21. requestDuration prometheus.Histogram
  22. requestSpanDuration *prometheus.HistogramVec
  23. downloadDuration prometheus.Histogram
  24. processingDuration prometheus.Histogram
  25. bufferSize *prometheus.HistogramVec
  26. bufferDefaultSize *prometheus.GaugeVec
  27. bufferMaxSize *prometheus.GaugeVec
  28. requestsInProgress prometheus.GaugeFunc
  29. imagesInProgress prometheus.GaugeFunc
  30. )
  31. func Init() {
  32. if len(config.PrometheusBind) == 0 {
  33. return
  34. }
  35. requestsTotal = prometheus.NewCounter(prometheus.CounterOpts{
  36. Namespace: config.PrometheusNamespace,
  37. Name: "requests_total",
  38. Help: "A counter of the total number of HTTP requests imgproxy processed.",
  39. })
  40. statusCodesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
  41. Namespace: config.PrometheusNamespace,
  42. Name: "status_codes_total",
  43. Help: "A counter of the response status codes.",
  44. }, []string{"status"})
  45. errorsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
  46. Namespace: config.PrometheusNamespace,
  47. Name: "errors_total",
  48. Help: "A counter of the occurred errors separated by type.",
  49. }, []string{"type"})
  50. requestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  51. Namespace: config.PrometheusNamespace,
  52. Name: "request_duration_seconds",
  53. Help: "A histogram of the response latency.",
  54. })
  55. requestSpanDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
  56. Namespace: config.PrometheusNamespace,
  57. Name: "request_span_duration_seconds",
  58. Help: "A histogram of the queue latency.",
  59. }, []string{"span"})
  60. downloadDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  61. Namespace: config.PrometheusNamespace,
  62. Name: "download_duration_seconds",
  63. Help: "A histogram of the source image downloading latency.",
  64. })
  65. processingDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  66. Namespace: config.PrometheusNamespace,
  67. Name: "processing_duration_seconds",
  68. Help: "A histogram of the image processing latency.",
  69. })
  70. bufferSize = prometheus.NewHistogramVec(prometheus.HistogramOpts{
  71. Namespace: config.PrometheusNamespace,
  72. Name: "buffer_size_bytes",
  73. Help: "A histogram of the buffer size in bytes.",
  74. Buckets: prometheus.ExponentialBuckets(1024, 2, 14),
  75. }, []string{"type"})
  76. bufferDefaultSize = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  77. Namespace: config.PrometheusNamespace,
  78. Name: "buffer_default_size_bytes",
  79. Help: "A gauge of the buffer default size in bytes.",
  80. }, []string{"type"})
  81. bufferMaxSize = prometheus.NewGaugeVec(prometheus.GaugeOpts{
  82. Namespace: config.PrometheusNamespace,
  83. Name: "buffer_max_size_bytes",
  84. Help: "A gauge of the buffer max size in bytes.",
  85. }, []string{"type"})
  86. requestsInProgress = prometheus.NewGaugeFunc(prometheus.GaugeOpts{
  87. Namespace: config.PrometheusNamespace,
  88. Name: "requests_in_progress",
  89. Help: "A gauge of the number of requests currently being in progress.",
  90. }, stats.RequestsInProgress)
  91. imagesInProgress = prometheus.NewGaugeFunc(prometheus.GaugeOpts{
  92. Namespace: config.PrometheusNamespace,
  93. Name: "images_in_progress",
  94. Help: "A gauge of the number of images currently being in progress.",
  95. }, stats.ImagesInProgress)
  96. prometheus.MustRegister(
  97. requestsTotal,
  98. statusCodesTotal,
  99. errorsTotal,
  100. requestDuration,
  101. requestSpanDuration,
  102. downloadDuration,
  103. processingDuration,
  104. bufferSize,
  105. bufferDefaultSize,
  106. bufferMaxSize,
  107. requestsInProgress,
  108. imagesInProgress,
  109. )
  110. enabled = true
  111. }
  112. func Enabled() bool {
  113. return enabled
  114. }
  115. func StartServer(cancel context.CancelFunc) error {
  116. if !enabled {
  117. return nil
  118. }
  119. s := http.Server{Handler: promhttp.Handler()}
  120. l, err := reuseport.Listen("tcp", config.PrometheusBind)
  121. if err != nil {
  122. return fmt.Errorf("Can't start Prometheus metrics server: %s", err)
  123. }
  124. go func() {
  125. log.Infof("Starting Prometheus server at %s", config.PrometheusBind)
  126. if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
  127. log.Error(err)
  128. }
  129. cancel()
  130. }()
  131. return nil
  132. }
  133. func StartRequest(rw http.ResponseWriter) (context.CancelFunc, http.ResponseWriter) {
  134. if !enabled {
  135. return func() {}, rw
  136. }
  137. requestsTotal.Inc()
  138. newRw := httpsnoop.Wrap(rw, httpsnoop.Hooks{
  139. WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
  140. return func(statusCode int) {
  141. statusCodesTotal.With(prometheus.Labels{"status": strconv.Itoa(statusCode)}).Inc()
  142. next(statusCode)
  143. }
  144. },
  145. })
  146. return startDuration(requestDuration), newRw
  147. }
  148. func StartQueueSegment() context.CancelFunc {
  149. if !enabled {
  150. return func() {}
  151. }
  152. return startDuration(requestSpanDuration.With(prometheus.Labels{"span": "queue"}))
  153. }
  154. func StartDownloadingSegment() context.CancelFunc {
  155. if !enabled {
  156. return func() {}
  157. }
  158. cancel := startDuration(requestSpanDuration.With(prometheus.Labels{"span": "downloading"}))
  159. cancelLegacy := startDuration(downloadDuration)
  160. return func() {
  161. cancel()
  162. cancelLegacy()
  163. }
  164. }
  165. func StartProcessingSegment() context.CancelFunc {
  166. if !enabled {
  167. return func() {}
  168. }
  169. cancel := startDuration(requestSpanDuration.With(prometheus.Labels{"span": "processing"}))
  170. cancelLegacy := startDuration(processingDuration)
  171. return func() {
  172. cancel()
  173. cancelLegacy()
  174. }
  175. }
  176. func StartStreamingSegment() context.CancelFunc {
  177. if !enabled {
  178. return func() {}
  179. }
  180. return startDuration(requestSpanDuration.With(prometheus.Labels{"span": "streaming"}))
  181. }
  182. func startDuration(m prometheus.Observer) context.CancelFunc {
  183. t := time.Now()
  184. return func() {
  185. m.Observe(time.Since(t).Seconds())
  186. }
  187. }
  188. func IncrementErrorsTotal(t string) {
  189. if enabled {
  190. errorsTotal.With(prometheus.Labels{"type": t}).Inc()
  191. }
  192. }
  193. func ObserveBufferSize(t string, size int) {
  194. if enabled {
  195. bufferSize.With(prometheus.Labels{"type": t}).Observe(float64(size))
  196. }
  197. }
  198. func SetBufferDefaultSize(t string, size int) {
  199. if enabled {
  200. bufferDefaultSize.With(prometheus.Labels{"type": t}).Set(float64(size))
  201. }
  202. }
  203. func SetBufferMaxSize(t string, size int) {
  204. if enabled {
  205. bufferMaxSize.With(prometheus.Labels{"type": t}).Set(float64(size))
  206. }
  207. }
  208. func AddGaugeFunc(name, help string, f func() float64) {
  209. if !enabled {
  210. return
  211. }
  212. gauge := prometheus.NewGaugeFunc(prometheus.GaugeOpts{
  213. Namespace: config.PrometheusNamespace,
  214. Name: name,
  215. Help: help,
  216. }, f)
  217. prometheus.MustRegister(gauge)
  218. }