newrelic.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. if stringer, ok := value.(fmt.Stringer); ok {
  114. span.AddAttribute(key, stringer.String())
  115. return
  116. }
  117. rv := reflect.ValueOf(value)
  118. switch {
  119. case rv.Kind() == reflect.String || rv.Kind() == reflect.Bool:
  120. span.AddAttribute(key, value)
  121. case rv.CanInt():
  122. span.AddAttribute(key, rv.Int())
  123. case rv.CanUint():
  124. span.AddAttribute(key, rv.Uint())
  125. case rv.CanFloat():
  126. span.AddAttribute(key, rv.Float())
  127. case rv.Kind() == reflect.Map && rv.Type().Key().Kind() == reflect.String:
  128. for _, k := range rv.MapKeys() {
  129. setMetadata(span, key+"."+k.String(), rv.MapIndex(k).Interface())
  130. }
  131. default:
  132. span.AddAttribute(key, fmt.Sprintf("%v", value))
  133. }
  134. }
  135. func SetMetadata(ctx context.Context, key string, value interface{}) {
  136. if !enabled {
  137. return
  138. }
  139. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  140. setMetadata(txn, key, value)
  141. }
  142. }
  143. func StartSegment(ctx context.Context, name string, meta map[string]any) context.CancelFunc {
  144. if !enabled {
  145. return func() {}
  146. }
  147. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  148. segment := txn.StartSegment(name)
  149. for k, v := range meta {
  150. setMetadata(segment, k, v)
  151. }
  152. return func() { segment.End() }
  153. }
  154. return func() {}
  155. }
  156. func SendError(ctx context.Context, errType string, err error) {
  157. if !enabled {
  158. return
  159. }
  160. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  161. txn.NoticeError(newrelic.Error{
  162. Message: err.Error(),
  163. Class: errformat.FormatErrType(errType, err),
  164. })
  165. }
  166. }
  167. func AddGaugeFunc(name string, f GaugeFunc) {
  168. gaugeFuncsMutex.Lock()
  169. defer gaugeFuncsMutex.Unlock()
  170. gaugeFuncs["imgproxy."+name] = f
  171. }
  172. func ObserveBufferSize(t string, size int) {
  173. if enabledHarvester {
  174. bufferSummariesMutex.Lock()
  175. defer bufferSummariesMutex.Unlock()
  176. summary, ok := bufferSummaries[t]
  177. if !ok {
  178. summary = &telemetry.Summary{
  179. Name: "imgproxy.buffer.size",
  180. Attributes: map[string]interface{}{"buffer_type": t},
  181. Timestamp: time.Now(),
  182. }
  183. bufferSummaries[t] = summary
  184. }
  185. sizef := float64(size)
  186. summary.Count += 1
  187. summary.Sum += sizef
  188. summary.Min = math.Min(summary.Min, sizef)
  189. summary.Max = math.Max(summary.Max, sizef)
  190. }
  191. }
  192. func SetBufferDefaultSize(t string, size int) {
  193. if enabledHarvester {
  194. harvester.RecordMetric(telemetry.Gauge{
  195. Name: "imgproxy.buffer.default_size",
  196. Value: float64(size),
  197. Attributes: map[string]interface{}{"buffer_type": t},
  198. Timestamp: time.Now(),
  199. })
  200. }
  201. }
  202. func SetBufferMaxSize(t string, size int) {
  203. if enabledHarvester {
  204. harvester.RecordMetric(telemetry.Gauge{
  205. Name: "imgproxy.buffer.max_size",
  206. Value: float64(size),
  207. Attributes: map[string]interface{}{"buffer_type": t},
  208. Timestamp: time.Now(),
  209. })
  210. }
  211. }
  212. func runMetricsCollector() {
  213. tick := time.NewTicker(interval)
  214. defer tick.Stop()
  215. for {
  216. select {
  217. case <-tick.C:
  218. func() {
  219. gaugeFuncsMutex.RLock()
  220. defer gaugeFuncsMutex.RUnlock()
  221. for name, f := range gaugeFuncs {
  222. harvester.RecordMetric(telemetry.Gauge{
  223. Name: name,
  224. Value: f(),
  225. Timestamp: time.Now(),
  226. })
  227. }
  228. }()
  229. func() {
  230. bufferSummariesMutex.RLock()
  231. defer bufferSummariesMutex.RUnlock()
  232. now := time.Now()
  233. for _, summary := range bufferSummaries {
  234. summary.Interval = now.Sub(summary.Timestamp)
  235. harvester.RecordMetric(*summary)
  236. summary.Timestamp = now
  237. summary.Count = 0
  238. summary.Sum = 0
  239. summary.Min = 0
  240. summary.Max = 0
  241. }
  242. }()
  243. harvester.RecordMetric(telemetry.Gauge{
  244. Name: "imgproxy.workers",
  245. Value: float64(config.Workers),
  246. Timestamp: time.Now(),
  247. })
  248. harvester.RecordMetric(telemetry.Gauge{
  249. Name: "imgproxy.requests_in_progress",
  250. Value: stats.RequestsInProgress(),
  251. Timestamp: time.Now(),
  252. })
  253. harvester.RecordMetric(telemetry.Gauge{
  254. Name: "imgproxy.images_in_progress",
  255. Value: stats.ImagesInProgress(),
  256. Timestamp: time.Now(),
  257. })
  258. harvester.RecordMetric(telemetry.Gauge{
  259. Name: "imgproxy.workers_utilization",
  260. Value: stats.WorkersUtilization(),
  261. Timestamp: time.Now(),
  262. })
  263. harvester.HarvestNow(harvesterCtx)
  264. case <-harvesterCtx.Done():
  265. return
  266. }
  267. }
  268. }