monitoring.go 3.3 KB

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