4
0

monitoring.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package monitoring
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/newrelic/go-agent/v3/newrelic"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/logging"
  11. )
  12. // Middleware is a function returns another http.Handler that wraps the given
  13. // handler.
  14. type Middleware func(next http.Handler) http.Handler
  15. // Monitoring is the type holding a middleware that traces the request to an
  16. // application.
  17. type Monitoring struct {
  18. middleware Middleware
  19. }
  20. // monitoring config represents the JSON attributes used for configuration. At
  21. // this moment only fields for NewRelic are supported.
  22. type monitoringConfig struct {
  23. Type string `json:"type,omitempty"`
  24. Name string `json:"name"`
  25. Key string `json:"key"`
  26. }
  27. // New initializes the monitoring with the given configuration.
  28. // Right now it only supports newrelic as the monitoring backend.
  29. func New(raw json.RawMessage) (*Monitoring, error) {
  30. var config monitoringConfig
  31. if err := json.Unmarshal(raw, &config); err != nil {
  32. return nil, errors.Wrap(err, "error unmarshalling monitoring attribute")
  33. }
  34. m := new(Monitoring)
  35. switch strings.ToLower(config.Type) {
  36. case "", "newrelic":
  37. app, err := newrelic.NewApplication(
  38. newrelic.ConfigAppName(config.Name),
  39. newrelic.ConfigLicense(config.Key),
  40. )
  41. if err != nil {
  42. return nil, errors.Wrap(err, "error loading New Relic application")
  43. }
  44. m.middleware = newRelicMiddleware(app)
  45. default:
  46. return nil, errors.Errorf("unsupported monitoring.type '%s'", config.Type)
  47. }
  48. return m, nil
  49. }
  50. // Middleware is an HTTP middleware that traces the request with the configured
  51. // monitoring backednd.
  52. func (m *Monitoring) Middleware(next http.Handler) http.Handler {
  53. return m.middleware(next)
  54. }
  55. func newRelicMiddleware(app *newrelic.Application) Middleware {
  56. return func(next http.Handler) http.Handler {
  57. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  58. // Start transaction
  59. txn := app.StartTransaction(transactionName(r))
  60. defer txn.End()
  61. w = txn.SetWebResponse(w)
  62. txn.SetWebRequestHTTP(r)
  63. // Wrap request writer if necessary
  64. rw := logging.NewResponseLogger(w)
  65. // Call next handler
  66. next.ServeHTTP(rw, r)
  67. // Report status (using same key NewRelic uses by default)
  68. status := rw.StatusCode()
  69. txn.AddAttribute("httpResponseCode", strconv.Itoa(status))
  70. // Add custom attributes
  71. if v, ok := logging.GetRequestID(r.Context()); ok {
  72. txn.AddAttribute("request.id", v)
  73. }
  74. // Report errors if necessary
  75. if status >= http.StatusBadRequest {
  76. var errorNoticed bool
  77. if fields := rw.Fields(); fields != nil {
  78. if v, ok := fields["error"]; ok {
  79. if err, ok := v.(error); ok {
  80. txn.NoticeError(err)
  81. errorNoticed = true
  82. }
  83. }
  84. }
  85. if !errorNoticed {
  86. txn.NoticeError(fmt.Errorf("request failed with status code %d", status))
  87. }
  88. }
  89. })
  90. }
  91. }
  92. func transactionName(r *http.Request) string {
  93. // From https://github.com/gorilla/handlers
  94. uri := r.RequestURI
  95. // Requests using the CONNECT method over HTTP/2.0 must use
  96. // the authority field (aka r.Host) to identify the target.
  97. // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
  98. if r.ProtoMajor == 2 && r.Method == "CONNECT" {
  99. uri = r.Host
  100. }
  101. if uri == "" {
  102. uri = r.URL.RequestURI()
  103. }
  104. return uri
  105. }