client_stats.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. // Copyright 2018, OpenCensus Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ochttp
  15. import (
  16. "context"
  17. "io"
  18. "net/http"
  19. "strconv"
  20. "sync"
  21. "time"
  22. "go.opencensus.io/stats"
  23. "go.opencensus.io/tag"
  24. )
  25. // statsTransport is an http.RoundTripper that collects stats for the outgoing requests.
  26. type statsTransport struct {
  27. base http.RoundTripper
  28. }
  29. // RoundTrip implements http.RoundTripper, delegating to Base and recording stats for the request.
  30. func (t statsTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  31. ctx, _ := tag.New(req.Context(),
  32. tag.Upsert(KeyClientHost, req.Host),
  33. tag.Upsert(Host, req.Host),
  34. tag.Upsert(KeyClientPath, req.URL.Path),
  35. tag.Upsert(Path, req.URL.Path),
  36. tag.Upsert(KeyClientMethod, req.Method),
  37. tag.Upsert(Method, req.Method))
  38. req = req.WithContext(ctx)
  39. track := &tracker{
  40. start: time.Now(),
  41. ctx: ctx,
  42. }
  43. if req.Body == nil {
  44. // TODO: Handle cases where ContentLength is not set.
  45. track.reqSize = -1
  46. } else if req.ContentLength > 0 {
  47. track.reqSize = req.ContentLength
  48. }
  49. stats.Record(ctx, ClientRequestCount.M(1))
  50. // Perform request.
  51. resp, err := t.base.RoundTrip(req)
  52. if err != nil {
  53. track.statusCode = http.StatusInternalServerError
  54. track.end()
  55. } else {
  56. track.statusCode = resp.StatusCode
  57. if req.Method != "HEAD" {
  58. track.respContentLength = resp.ContentLength
  59. }
  60. if resp.Body == nil {
  61. track.end()
  62. } else {
  63. track.body = resp.Body
  64. resp.Body = wrappedBody(track, resp.Body)
  65. }
  66. }
  67. return resp, err
  68. }
  69. // CancelRequest cancels an in-flight request by closing its connection.
  70. func (t statsTransport) CancelRequest(req *http.Request) {
  71. type canceler interface {
  72. CancelRequest(*http.Request)
  73. }
  74. if cr, ok := t.base.(canceler); ok {
  75. cr.CancelRequest(req)
  76. }
  77. }
  78. type tracker struct {
  79. ctx context.Context
  80. respSize int64
  81. respContentLength int64
  82. reqSize int64
  83. start time.Time
  84. body io.ReadCloser
  85. statusCode int
  86. endOnce sync.Once
  87. }
  88. var _ io.ReadCloser = (*tracker)(nil)
  89. func (t *tracker) end() {
  90. t.endOnce.Do(func() {
  91. latencyMs := float64(time.Since(t.start)) / float64(time.Millisecond)
  92. respSize := t.respSize
  93. if t.respSize == 0 && t.respContentLength > 0 {
  94. respSize = t.respContentLength
  95. }
  96. m := []stats.Measurement{
  97. ClientSentBytes.M(t.reqSize),
  98. ClientReceivedBytes.M(respSize),
  99. ClientRoundtripLatency.M(latencyMs),
  100. ClientLatency.M(latencyMs),
  101. ClientResponseBytes.M(t.respSize),
  102. }
  103. if t.reqSize >= 0 {
  104. m = append(m, ClientRequestBytes.M(t.reqSize))
  105. }
  106. stats.RecordWithTags(t.ctx, []tag.Mutator{
  107. tag.Upsert(StatusCode, strconv.Itoa(t.statusCode)),
  108. tag.Upsert(KeyClientStatus, strconv.Itoa(t.statusCode)),
  109. }, m...)
  110. })
  111. }
  112. func (t *tracker) Read(b []byte) (int, error) {
  113. n, err := t.body.Read(b)
  114. t.respSize += int64(n)
  115. switch err {
  116. case nil:
  117. return n, nil
  118. case io.EOF:
  119. t.end()
  120. }
  121. return n, err
  122. }
  123. func (t *tracker) Close() error {
  124. // Invoking endSpan on Close will help catch the cases
  125. // in which a read returned a non-nil error, we set the
  126. // span status but didn't end the span.
  127. t.end()
  128. return t.body.Close()
  129. }