1
0

newrelic.go 6.4 KB

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