newrelic.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package newrelic
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "math"
  7. "net/http"
  8. "reflect"
  9. "regexp"
  10. "sync"
  11. "time"
  12. "github.com/newrelic/go-agent/v3/newrelic"
  13. "github.com/newrelic/newrelic-telemetry-sdk-go/telemetry"
  14. "github.com/imgproxy/imgproxy/v3/config"
  15. "github.com/imgproxy/imgproxy/v3/monitoring/errformat"
  16. "github.com/imgproxy/imgproxy/v3/monitoring/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. errLogger := slog.NewLogLogger(
  71. slog.With("source", "newrelic").Handler(),
  72. slog.LevelWarn,
  73. )
  74. harvester, err = telemetry.NewHarvester(
  75. telemetry.ConfigAPIKey(config.NewRelicKey),
  76. telemetry.ConfigCommonAttributes(harvesterAttributes),
  77. telemetry.ConfigHarvestPeriod(0), // Don't harvest automatically
  78. telemetry.ConfigMetricsURLOverride(metricsURL),
  79. telemetry.ConfigBasicErrorLogger(errLogger.Writer()),
  80. )
  81. if err == nil {
  82. harvesterCtx, harvesterCtxCancel = context.WithCancel(context.Background())
  83. enabledHarvester = true
  84. go runMetricsCollector()
  85. } else {
  86. slog.Warn(fmt.Sprintf("Can't init New Relic telemetry harvester: %s", err))
  87. }
  88. enabled = true
  89. return nil
  90. }
  91. func Stop() {
  92. if enabled {
  93. app.Shutdown(5 * time.Second)
  94. if enabledHarvester {
  95. harvesterCtxCancel()
  96. harvester.HarvestNow(context.Background())
  97. }
  98. }
  99. }
  100. func Enabled() bool {
  101. return enabled
  102. }
  103. func StartTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
  104. if !enabled {
  105. return ctx, func() {}, rw
  106. }
  107. txn := app.StartTransaction("request")
  108. txn.SetWebRequestHTTP(r)
  109. newRw := txn.SetWebResponse(rw)
  110. cancel := func() { txn.End() }
  111. return context.WithValue(ctx, transactionCtxKey{}, txn), cancel, newRw
  112. }
  113. func setMetadata(span attributable, key string, value interface{}) {
  114. if len(key) == 0 || value == nil {
  115. return
  116. }
  117. if stringer, ok := value.(fmt.Stringer); ok {
  118. span.AddAttribute(key, stringer.String())
  119. return
  120. }
  121. rv := reflect.ValueOf(value)
  122. switch {
  123. case rv.Kind() == reflect.String || rv.Kind() == reflect.Bool:
  124. span.AddAttribute(key, value)
  125. case rv.CanInt():
  126. span.AddAttribute(key, rv.Int())
  127. case rv.CanUint():
  128. span.AddAttribute(key, rv.Uint())
  129. case rv.CanFloat():
  130. span.AddAttribute(key, rv.Float())
  131. case rv.Kind() == reflect.Map && rv.Type().Key().Kind() == reflect.String:
  132. for _, k := range rv.MapKeys() {
  133. setMetadata(span, key+"."+k.String(), rv.MapIndex(k).Interface())
  134. }
  135. default:
  136. span.AddAttribute(key, fmt.Sprintf("%v", value))
  137. }
  138. }
  139. func SetMetadata(ctx context.Context, key string, value interface{}) {
  140. if !enabled {
  141. return
  142. }
  143. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  144. setMetadata(txn, key, value)
  145. }
  146. }
  147. func StartSegment(ctx context.Context, name string, meta map[string]any) context.CancelFunc {
  148. if !enabled {
  149. return func() {}
  150. }
  151. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  152. segment := txn.NewGoroutine().StartSegment(name)
  153. for k, v := range meta {
  154. setMetadata(segment, k, v)
  155. }
  156. return func() { segment.End() }
  157. }
  158. return func() {}
  159. }
  160. func SendError(ctx context.Context, errType string, err error) {
  161. if !enabled {
  162. return
  163. }
  164. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  165. txn.NoticeError(newrelic.Error{
  166. Message: err.Error(),
  167. Class: errformat.FormatErrType(errType, err),
  168. })
  169. }
  170. }
  171. func AddGaugeFunc(name string, f GaugeFunc) {
  172. gaugeFuncsMutex.Lock()
  173. defer gaugeFuncsMutex.Unlock()
  174. gaugeFuncs["imgproxy."+name] = f
  175. }
  176. func ObserveBufferSize(t string, size int) {
  177. if enabledHarvester {
  178. bufferSummariesMutex.Lock()
  179. defer bufferSummariesMutex.Unlock()
  180. summary, ok := bufferSummaries[t]
  181. if !ok {
  182. summary = &telemetry.Summary{
  183. Name: "imgproxy.buffer.size",
  184. Attributes: map[string]interface{}{"buffer_type": t},
  185. Timestamp: time.Now(),
  186. }
  187. bufferSummaries[t] = summary
  188. }
  189. sizef := float64(size)
  190. summary.Count += 1
  191. summary.Sum += sizef
  192. summary.Min = math.Min(summary.Min, sizef)
  193. summary.Max = math.Max(summary.Max, sizef)
  194. }
  195. }
  196. func SetBufferDefaultSize(t string, size int) {
  197. if enabledHarvester {
  198. harvester.RecordMetric(telemetry.Gauge{
  199. Name: "imgproxy.buffer.default_size",
  200. Value: float64(size),
  201. Attributes: map[string]interface{}{"buffer_type": t},
  202. Timestamp: time.Now(),
  203. })
  204. }
  205. }
  206. func SetBufferMaxSize(t string, size int) {
  207. if enabledHarvester {
  208. harvester.RecordMetric(telemetry.Gauge{
  209. Name: "imgproxy.buffer.max_size",
  210. Value: float64(size),
  211. Attributes: map[string]interface{}{"buffer_type": t},
  212. Timestamp: time.Now(),
  213. })
  214. }
  215. }
  216. func runMetricsCollector() {
  217. tick := time.NewTicker(interval)
  218. defer tick.Stop()
  219. for {
  220. select {
  221. case <-tick.C:
  222. func() {
  223. gaugeFuncsMutex.RLock()
  224. defer gaugeFuncsMutex.RUnlock()
  225. for name, f := range gaugeFuncs {
  226. harvester.RecordMetric(telemetry.Gauge{
  227. Name: name,
  228. Value: f(),
  229. Timestamp: time.Now(),
  230. })
  231. }
  232. }()
  233. func() {
  234. bufferSummariesMutex.RLock()
  235. defer bufferSummariesMutex.RUnlock()
  236. now := time.Now()
  237. for _, summary := range bufferSummaries {
  238. summary.Interval = now.Sub(summary.Timestamp)
  239. harvester.RecordMetric(*summary)
  240. summary.Timestamp = now
  241. summary.Count = 0
  242. summary.Sum = 0
  243. summary.Min = 0
  244. summary.Max = 0
  245. }
  246. }()
  247. harvester.RecordMetric(telemetry.Gauge{
  248. Name: "imgproxy.workers",
  249. Value: float64(config.Workers),
  250. Timestamp: time.Now(),
  251. })
  252. harvester.RecordMetric(telemetry.Gauge{
  253. Name: "imgproxy.requests_in_progress",
  254. Value: stats.RequestsInProgress(),
  255. Timestamp: time.Now(),
  256. })
  257. harvester.RecordMetric(telemetry.Gauge{
  258. Name: "imgproxy.images_in_progress",
  259. Value: stats.ImagesInProgress(),
  260. Timestamp: time.Now(),
  261. })
  262. harvester.RecordMetric(telemetry.Gauge{
  263. Name: "imgproxy.workers_utilization",
  264. Value: stats.WorkersUtilization(),
  265. Timestamp: time.Now(),
  266. })
  267. harvester.HarvestNow(harvesterCtx)
  268. case <-harvesterCtx.Done():
  269. return
  270. }
  271. }
  272. }