newrelic.go 7.2 KB

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