newrelic.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package newrelic
  2. import (
  3. "context"
  4. "fmt"
  5. "math"
  6. "net/http"
  7. "regexp"
  8. "sync"
  9. "time"
  10. "github.com/newrelic/go-agent/v3/newrelic"
  11. "github.com/newrelic/newrelic-telemetry-sdk-go/telemetry"
  12. log "github.com/sirupsen/logrus"
  13. "github.com/imgproxy/imgproxy/v3/config"
  14. "github.com/imgproxy/imgproxy/v3/metrics/errformat"
  15. "github.com/imgproxy/imgproxy/v3/metrics/stats"
  16. )
  17. type transactionCtxKey struct{}
  18. type GaugeFunc func() float64
  19. const (
  20. defaultMetricURL = "https://metric-api.newrelic.com/metric/v1"
  21. euMetricURL = "https://metric-api.eu.newrelic.com/metric/v1"
  22. )
  23. var (
  24. enabled = false
  25. enabledHarvester = false
  26. app *newrelic.Application
  27. harvester *telemetry.Harvester
  28. harvesterCtx context.Context
  29. harvesterCtxCancel context.CancelFunc
  30. gaugeFuncs = make(map[string]GaugeFunc)
  31. gaugeFuncsMutex sync.RWMutex
  32. bufferSummaries = make(map[string]*telemetry.Summary)
  33. bufferSummariesMutex sync.RWMutex
  34. interval = 10 * time.Second
  35. licenseEuRegex = regexp.MustCompile(`(^eu.+?)x`)
  36. )
  37. func Init() error {
  38. if len(config.NewRelicKey) == 0 {
  39. return nil
  40. }
  41. name := config.NewRelicAppName
  42. if len(name) == 0 {
  43. name = "imgproxy"
  44. }
  45. var err error
  46. app, err = newrelic.NewApplication(
  47. newrelic.ConfigAppName(name),
  48. newrelic.ConfigLicense(config.NewRelicKey),
  49. func(c *newrelic.Config) {
  50. if len(config.NewRelicLabels) > 0 {
  51. c.Labels = config.NewRelicLabels
  52. }
  53. },
  54. )
  55. if err != nil {
  56. return fmt.Errorf("Can't init New Relic agent: %s", err)
  57. }
  58. harvesterAttributes := map[string]interface{}{"appName": name}
  59. for k, v := range config.NewRelicLabels {
  60. harvesterAttributes[k] = v
  61. }
  62. metricsURL := defaultMetricURL
  63. if licenseEuRegex.MatchString(config.NewRelicKey) {
  64. metricsURL = euMetricURL
  65. }
  66. harvester, err = telemetry.NewHarvester(
  67. telemetry.ConfigAPIKey(config.NewRelicKey),
  68. telemetry.ConfigCommonAttributes(harvesterAttributes),
  69. telemetry.ConfigHarvestPeriod(0), // Don't harvest automatically
  70. telemetry.ConfigMetricsURLOverride(metricsURL),
  71. telemetry.ConfigBasicErrorLogger(log.StandardLogger().WithField("from", "newrelic").WriterLevel(log.WarnLevel)),
  72. )
  73. if err == nil {
  74. harvesterCtx, harvesterCtxCancel = context.WithCancel(context.Background())
  75. enabledHarvester = true
  76. go runMetricsCollector()
  77. } else {
  78. log.Warnf("Can't init New Relic telemetry harvester: %s", err)
  79. }
  80. enabled = true
  81. return nil
  82. }
  83. func Stop() {
  84. if enabled {
  85. app.Shutdown(5 * time.Second)
  86. if enabledHarvester {
  87. harvesterCtxCancel()
  88. harvester.HarvestNow(context.Background())
  89. }
  90. }
  91. }
  92. func Enabled() bool {
  93. return enabled
  94. }
  95. func StartTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
  96. if !enabled {
  97. return ctx, func() {}, rw
  98. }
  99. txn := app.StartTransaction("request")
  100. txn.SetWebRequestHTTP(r)
  101. newRw := txn.SetWebResponse(rw)
  102. cancel := func() { txn.End() }
  103. return context.WithValue(ctx, transactionCtxKey{}, txn), cancel, newRw
  104. }
  105. func StartSegment(ctx context.Context, name string) context.CancelFunc {
  106. if !enabled {
  107. return func() {}
  108. }
  109. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  110. segment := txn.StartSegment(name)
  111. return func() { segment.End() }
  112. }
  113. return func() {}
  114. }
  115. func SendError(ctx context.Context, errType string, err error) {
  116. if !enabled {
  117. return
  118. }
  119. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  120. txn.NoticeError(newrelic.Error{
  121. Message: err.Error(),
  122. Class: errformat.FormatErrType(errType, err),
  123. })
  124. }
  125. }
  126. func AddGaugeFunc(name string, f GaugeFunc) {
  127. gaugeFuncsMutex.Lock()
  128. defer gaugeFuncsMutex.Unlock()
  129. gaugeFuncs["imgproxy."+name] = f
  130. }
  131. func ObserveBufferSize(t string, size int) {
  132. if enabledHarvester {
  133. bufferSummariesMutex.Lock()
  134. defer bufferSummariesMutex.Unlock()
  135. summary, ok := bufferSummaries[t]
  136. if !ok {
  137. summary = &telemetry.Summary{
  138. Name: "imgproxy.buffer.size",
  139. Attributes: map[string]interface{}{"buffer_type": t},
  140. Timestamp: time.Now(),
  141. }
  142. bufferSummaries[t] = summary
  143. }
  144. sizef := float64(size)
  145. summary.Count += 1
  146. summary.Sum += sizef
  147. summary.Min = math.Min(summary.Min, sizef)
  148. summary.Max = math.Max(summary.Max, sizef)
  149. }
  150. }
  151. func SetBufferDefaultSize(t string, size int) {
  152. if enabledHarvester {
  153. harvester.RecordMetric(telemetry.Gauge{
  154. Name: "imgproxy.buffer.default_size",
  155. Value: float64(size),
  156. Attributes: map[string]interface{}{"buffer_type": t},
  157. Timestamp: time.Now(),
  158. })
  159. }
  160. }
  161. func SetBufferMaxSize(t string, size int) {
  162. if enabledHarvester {
  163. harvester.RecordMetric(telemetry.Gauge{
  164. Name: "imgproxy.buffer.max_size",
  165. Value: float64(size),
  166. Attributes: map[string]interface{}{"buffer_type": t},
  167. Timestamp: time.Now(),
  168. })
  169. }
  170. }
  171. func runMetricsCollector() {
  172. tick := time.NewTicker(interval)
  173. defer tick.Stop()
  174. for {
  175. select {
  176. case <-tick.C:
  177. func() {
  178. gaugeFuncsMutex.RLock()
  179. defer gaugeFuncsMutex.RUnlock()
  180. for name, f := range gaugeFuncs {
  181. harvester.RecordMetric(telemetry.Gauge{
  182. Name: name,
  183. Value: f(),
  184. Timestamp: time.Now(),
  185. })
  186. }
  187. }()
  188. func() {
  189. bufferSummariesMutex.RLock()
  190. defer bufferSummariesMutex.RUnlock()
  191. now := time.Now()
  192. for _, summary := range bufferSummaries {
  193. summary.Interval = now.Sub(summary.Timestamp)
  194. harvester.RecordMetric(*summary)
  195. summary.Timestamp = now
  196. summary.Count = 0
  197. summary.Sum = 0
  198. summary.Min = 0
  199. summary.Max = 0
  200. }
  201. }()
  202. harvester.RecordMetric(telemetry.Gauge{
  203. Name: "imgproxy.requests_in_progress",
  204. Value: stats.RequestsInProgress(),
  205. Timestamp: time.Now(),
  206. })
  207. harvester.RecordMetric(telemetry.Gauge{
  208. Name: "imgproxy.images_in_progress",
  209. Value: stats.ImagesInProgress(),
  210. Timestamp: time.Now(),
  211. })
  212. harvester.HarvestNow(harvesterCtx)
  213. case <-harvesterCtx.Done():
  214. return
  215. }
  216. }
  217. }