newrelic.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package newrelic
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "reflect"
  7. "time"
  8. "github.com/newrelic/go-agent/v3/newrelic"
  9. "github.com/imgproxy/imgproxy/v3/monitoring/errformat"
  10. "github.com/imgproxy/imgproxy/v3/monitoring/stats"
  11. "github.com/imgproxy/imgproxy/v3/vips"
  12. )
  13. // transactionCtxKey context key for storing New Relic transaction in context
  14. type transactionCtxKey struct{}
  15. // attributable is an interface for New Relic entities that can have attributes set on them
  16. type attributable interface {
  17. AddAttribute(key string, value any)
  18. }
  19. type NewRelic struct {
  20. stats *stats.Stats
  21. config *Config
  22. app *newrelic.Application
  23. metricsCtx context.Context
  24. metricsCtxCancel context.CancelFunc
  25. }
  26. func New(config *Config, stats *stats.Stats) (*NewRelic, error) {
  27. nl := &NewRelic{
  28. config: config,
  29. stats: stats,
  30. }
  31. if !config.Enabled() {
  32. return nl, nil
  33. }
  34. var err error
  35. // Initialize New Relic APM agent
  36. nl.app, err = newrelic.NewApplication(
  37. newrelic.ConfigAppName(config.AppName),
  38. newrelic.ConfigLicense(config.Key),
  39. func(c *newrelic.Config) {
  40. if len(config.Labels) > 0 {
  41. c.Labels = config.Labels
  42. }
  43. },
  44. )
  45. if err != nil {
  46. return nil, fmt.Errorf("can't init New Relic agent: %s", err)
  47. }
  48. nl.metricsCtx, nl.metricsCtxCancel = context.WithCancel(context.Background())
  49. go nl.runMetricsCollector()
  50. return nl, nil
  51. }
  52. // Enabled returns true if New Relic is enabled
  53. func (nl *NewRelic) Enabled() bool {
  54. return nl.config.Enabled()
  55. }
  56. // Stop stops the New Relic APM agent and Telemetry SDK harvester
  57. func (nl *NewRelic) Stop(ctx context.Context) {
  58. if nl.metricsCtxCancel != nil {
  59. nl.metricsCtxCancel()
  60. }
  61. if nl.app != nil {
  62. nl.app.Shutdown(5 * time.Second)
  63. }
  64. }
  65. func (nl *NewRelic) StartTransaction(ctx context.Context, rw http.ResponseWriter, r *http.Request) (context.Context, context.CancelFunc, http.ResponseWriter) {
  66. if !nl.Enabled() {
  67. return ctx, func() {}, rw
  68. }
  69. txn := nl.app.StartTransaction("request")
  70. txn.SetWebRequestHTTP(r)
  71. newRw := txn.SetWebResponse(rw)
  72. cancel := func() { txn.End() }
  73. return context.WithValue(ctx, transactionCtxKey{}, txn), cancel, newRw
  74. }
  75. func setMetadata(span attributable, key string, value interface{}) {
  76. if len(key) == 0 || value == nil {
  77. return
  78. }
  79. if stringer, ok := value.(fmt.Stringer); ok {
  80. span.AddAttribute(key, stringer.String())
  81. return
  82. }
  83. rv := reflect.ValueOf(value)
  84. switch {
  85. case rv.Kind() == reflect.String || rv.Kind() == reflect.Bool:
  86. span.AddAttribute(key, value)
  87. case rv.CanInt():
  88. span.AddAttribute(key, rv.Int())
  89. case rv.CanUint():
  90. span.AddAttribute(key, rv.Uint())
  91. case rv.CanFloat():
  92. span.AddAttribute(key, rv.Float())
  93. case rv.Kind() == reflect.Map && rv.Type().Key().Kind() == reflect.String:
  94. for _, k := range rv.MapKeys() {
  95. setMetadata(span, key+"."+k.String(), rv.MapIndex(k).Interface())
  96. }
  97. default:
  98. span.AddAttribute(key, fmt.Sprintf("%v", value))
  99. }
  100. }
  101. func (nl *NewRelic) SetMetadata(ctx context.Context, key string, value interface{}) {
  102. if !nl.Enabled() {
  103. return
  104. }
  105. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  106. setMetadata(txn, key, value)
  107. }
  108. }
  109. func (nl *NewRelic) StartSegment(ctx context.Context, name string, meta map[string]any) context.CancelFunc {
  110. if !nl.Enabled() {
  111. return func() {}
  112. }
  113. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  114. segment := txn.NewGoroutine().StartSegment(name)
  115. for k, v := range meta {
  116. setMetadata(segment, k, v)
  117. }
  118. return func() { segment.End() }
  119. }
  120. return func() {}
  121. }
  122. func (nl *NewRelic) SendError(ctx context.Context, errType string, err error) {
  123. if !nl.Enabled() {
  124. return
  125. }
  126. if txn, ok := ctx.Value(transactionCtxKey{}).(*newrelic.Transaction); ok {
  127. txn.NoticeError(newrelic.Error{
  128. Message: err.Error(),
  129. Class: errformat.FormatErrType(errType, err),
  130. })
  131. }
  132. }
  133. func (nl *NewRelic) runMetricsCollector() {
  134. tick := time.NewTicker(nl.config.MetricsInterval)
  135. defer tick.Stop()
  136. for {
  137. select {
  138. case <-tick.C:
  139. nl.app.RecordCustomMetric("imgproxy/workers", float64(nl.stats.WorkersNumber))
  140. nl.app.RecordCustomMetric("imgproxy/requests_in_progress", float64(nl.stats.RequestsInProgress()))
  141. nl.app.RecordCustomMetric("imgproxy/images_in_progress", float64(nl.stats.ImagesInProgress()))
  142. nl.app.RecordCustomMetric("imgproxy/workers_utilization", nl.stats.WorkersUtilization())
  143. nl.app.RecordCustomMetric("imgproxy/vips/memory", float64(vips.GetMem()))
  144. nl.app.RecordCustomMetric("imgproxy/vips/max_memory", float64(vips.GetMemHighwater()))
  145. nl.app.RecordCustomMetric("imgproxy/vips/allocs", float64(vips.GetAllocs()))
  146. case <-nl.metricsCtx.Done():
  147. return
  148. }
  149. }
  150. }