1
0

client_stats.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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.URL.Host),
  33. tag.Upsert(Host, req.URL.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 resp.Body == nil {
  58. track.end()
  59. } else {
  60. track.body = resp.Body
  61. resp.Body = track
  62. }
  63. }
  64. return resp, err
  65. }
  66. // CancelRequest cancels an in-flight request by closing its connection.
  67. func (t statsTransport) CancelRequest(req *http.Request) {
  68. type canceler interface {
  69. CancelRequest(*http.Request)
  70. }
  71. if cr, ok := t.base.(canceler); ok {
  72. cr.CancelRequest(req)
  73. }
  74. }
  75. type tracker struct {
  76. ctx context.Context
  77. respSize int64
  78. reqSize int64
  79. start time.Time
  80. body io.ReadCloser
  81. statusCode int
  82. endOnce sync.Once
  83. }
  84. var _ io.ReadCloser = (*tracker)(nil)
  85. func (t *tracker) end() {
  86. t.endOnce.Do(func() {
  87. latencyMs := float64(time.Since(t.start)) / float64(time.Millisecond)
  88. m := []stats.Measurement{
  89. ClientSentBytes.M(t.reqSize),
  90. ClientReceivedBytes.M(t.respSize),
  91. ClientRoundtripLatency.M(latencyMs),
  92. ClientLatency.M(latencyMs),
  93. ClientResponseBytes.M(t.respSize),
  94. }
  95. if t.reqSize >= 0 {
  96. m = append(m, ClientRequestBytes.M(t.reqSize))
  97. }
  98. stats.RecordWithTags(t.ctx, []tag.Mutator{
  99. tag.Upsert(StatusCode, strconv.Itoa(t.statusCode)),
  100. tag.Upsert(KeyClientStatus, strconv.Itoa(t.statusCode)),
  101. }, m...)
  102. })
  103. }
  104. func (t *tracker) Read(b []byte) (int, error) {
  105. n, err := t.body.Read(b)
  106. switch err {
  107. case nil:
  108. t.respSize += int64(n)
  109. return n, nil
  110. case io.EOF:
  111. t.end()
  112. }
  113. return n, err
  114. }
  115. func (t *tracker) Close() error {
  116. // Invoking endSpan on Close will help catch the cases
  117. // in which a read returned a non-nil error, we set the
  118. // span status but didn't end the span.
  119. t.end()
  120. return t.body.Close()
  121. }