4
0

monitoring.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package monitoring
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. newrelic "github.com/newrelic/go-agent"
  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(newrelic.NewConfig(config.Name, config.Key))
  38. if err != nil {
  39. return nil, errors.Wrap(err, "error loading New Relic application")
  40. }
  41. m.middleware = newRelicMiddleware(app)
  42. default:
  43. return nil, errors.Errorf("unsupported monitoring.type '%s'", config.Type)
  44. }
  45. return m, nil
  46. }
  47. // Middleware is an HTTP middleware that traces the request with the configured
  48. // monitoring backednd.
  49. func (m *Monitoring) Middleware(next http.Handler) http.Handler {
  50. return m.middleware(next)
  51. }
  52. func newRelicMiddleware(app newrelic.Application) Middleware {
  53. return func(next http.Handler) http.Handler {
  54. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  55. // Start transaction
  56. txn := app.StartTransaction(transactionName(r), w, r)
  57. defer txn.End()
  58. // Wrap request writer if necessary
  59. rw := logging.NewResponseLogger(w)
  60. // Call next handler
  61. next.ServeHTTP(rw, r)
  62. // Report status (using same key NewRelic uses by default)
  63. status := rw.StatusCode()
  64. txn.AddAttribute("httpResponseCode", strconv.Itoa(status))
  65. // Add custom attributes
  66. if v, ok := logging.GetRequestID(r.Context()); ok {
  67. txn.AddAttribute("request.id", v)
  68. }
  69. // Report errors if necessary
  70. if status >= http.StatusBadRequest {
  71. var errorNoticed bool
  72. if fields := rw.Fields(); fields != nil {
  73. if v, ok := fields["error"]; ok {
  74. if err, ok := v.(error); ok {
  75. txn.NoticeError(err)
  76. errorNoticed = true
  77. }
  78. }
  79. }
  80. if !errorNoticed {
  81. txn.NoticeError(fmt.Errorf("request failed with status code %d", status))
  82. }
  83. }
  84. })
  85. }
  86. }
  87. func transactionName(r *http.Request) string {
  88. // From https://github.com/gorilla/handlers
  89. uri := r.RequestURI
  90. // Requests using the CONNECT method over HTTP/2.0 must use
  91. // the authority field (aka r.Host) to identify the target.
  92. // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
  93. if r.ProtoMajor == 2 && r.Method == "CONNECT" {
  94. uri = r.Host
  95. }
  96. if uri == "" {
  97. uri = r.URL.RequestURI()
  98. }
  99. return uri
  100. }