Debian Codegraph @

memmetrics/roundtrip.go

raw
1 package memmetrics
2
3 import (
4 "errors"
5 "net/http"
6 "sync"
7 "time"
8
9 "github.com/vulcand/oxy/v2/internal/holsterv4/clock"
10 )
11
12 // NewRTMetricsFn builder function type.
13 type NewRTMetricsFn func() (*RTMetrics, error)
14
15 // NewCounterFn builder function type.
16 type NewCounterFn func() (*RollingCounter, error)
17
18 // NewRollingHistogramFn builder function type.
19 type NewRollingHistogramFn func() (*RollingHDRHistogram, error)
20
21 // RTMetrics provides aggregated performance metrics for HTTP requests processing
22 // such as round trip latency, response codes counters network error and total requests.
23 // all counters are collected as rolling window counters with defined precision, histograms
24 // are a rolling window histograms with defined precision as well.
25 // See RTOptions for more detail on parameters.
26 type RTMetrics struct {
27 total *RollingCounter
28 netErrors *RollingCounter
29 statusCodes map[int]*RollingCounter
30 statusCodesLock sync.RWMutex
31 histogram *RollingHDRHistogram
32 histogramLock sync.RWMutex
33
34 newCounter NewCounterFn
35 newHist NewRollingHistogramFn
36 }
37
38 // NewRTMetrics returns new instance of metrics collector.
39 func NewRTMetrics(settings ...RTOption) (*RTMetrics, error) {
40 m := &RTMetrics{
41 statusCodes: make(map[int]*RollingCounter),
42 statusCodesLock: sync.RWMutex{},
43 }
44 for _, s := range settings {
45 if err := s(m); err != nil {
46 return nil, err
47 }
48 }
49
50 if m.newCounter == nil {
51 m.newCounter = func() (*RollingCounter, error) {
52 return NewCounter(counterBuckets, counterResolution)
53 }
54 }
55
56 if m.newHist == nil {
57 m.newHist = func() (*RollingHDRHistogram, error) {
58 return NewRollingHDRHistogram(histMin, histMax, histSignificantFigures, histPeriod, histBuckets)
59 }
60 }
61
62 h, err := m.newHist()
63 if err != nil {
64 return nil, err
65 }
66
67 netErrors, err := m.newCounter()
68 if err != nil {
69 return nil, err
70 }
71
72 total, err := m.newCounter()
73 if err != nil {
74 return nil, err
75 }
76
77 m.histogram = h
78 m.netErrors = netErrors
79 m.total = total
80 return m, nil
81 }
82
83 // Export Returns a new RTMetrics which is a copy of the current one.
84 func (m *RTMetrics) Export() *RTMetrics {
85 m.statusCodesLock.RLock()
86 defer m.statusCodesLock.RUnlock()
87 m.histogramLock.RLock()
88 defer m.histogramLock.RUnlock()
89
90 export := &RTMetrics{}
91 export.statusCodesLock = sync.RWMutex{}
92 export.histogramLock = sync.RWMutex{}
93 export.total = m.total.Clone()
94 export.netErrors = m.netErrors.Clone()
95 exportStatusCodes := map[int]*RollingCounter{}
96 for code, rollingCounter := range m.statusCodes {
97 exportStatusCodes[code] = rollingCounter.Clone()
98 }
99 export.statusCodes = exportStatusCodes
100 if m.histogram != nil {
101 export.histogram = m.histogram.Export()
102 }
103 export.newCounter = m.newCounter
104 export.newHist = m.newHist
105
106 return export
107 }
108
109 // CounterWindowSize gets total windows size.
110 func (m *RTMetrics) CounterWindowSize() time.Duration {
111 return m.total.WindowSize()
112 }
113
114 // NetworkErrorRatio calculates the amont of network errors such as time outs and dropped connection
115 // that occurred in the given time window compared to the total requests count.
116 func (m *RTMetrics) NetworkErrorRatio() float64 {
117 if m.total.Count() == 0 {
118 return 0
119 }
120 return float64(m.netErrors.Count()) / float64(m.total.Count())
121 }
122
123 // ResponseCodeRatio calculates ratio of count(startA to endA) / count(startB to endB).
124 func (m *RTMetrics) ResponseCodeRatio(startA, endA, startB, endB int) float64 {
125 a := int64(0)
126 b := int64(0)
127 m.statusCodesLock.RLock()
128 defer m.statusCodesLock.RUnlock()
129 for code, v := range m.statusCodes {
130 if code < endA && code >= startA {
131 a += v.Count()
132 }
133 if code < endB && code >= startB {
134 b += v.Count()
135 }
136 }
137 if b != 0 {
138 return float64(a) / float64(b)
139 }
140 return 0
141 }
142
143 // Append append a metric.
144 func (m *RTMetrics) Append(other *RTMetrics) error {
145 if m == other {
146 return errors.New("RTMetrics cannot append to self")
147 }
148
149 if err := m.total.Append(other.total); err != nil {
150 return err
151 }
152
153 if err := m.netErrors.Append(other.netErrors); err != nil {
154 return err
155 }
156
157 copied := other.Export()
158
159 m.statusCodesLock.Lock()
160 defer m.statusCodesLock.Unlock()
161 m.histogramLock.Lock()
162 defer m.histogramLock.Unlock()
163 for code, c := range copied.statusCodes {
164 o, ok := m.statusCodes[code]
165 if ok {
166 if err := o.Append(c); err != nil {
167 return err
168 }
169 } else {
170 m.statusCodes[code] = c.Clone()
171 }
172 }
173
174 return m.histogram.Append(copied.histogram)
175 }
176
177 // Record records a metric.
178 func (m *RTMetrics) Record(code int, duration time.Duration) {
179 m.total.Inc(1)
180 if code == http.StatusGatewayTimeout || code == http.StatusBadGateway {
181 m.netErrors.Inc(1)
182 }
183 _ = m.recordStatusCode(code)
184 _ = m.recordLatency(duration)
185 }
186
187 // TotalCount returns total count of processed requests collected.
188 func (m *RTMetrics) TotalCount() int64 {
189 return m.total.Count()
190 }
191
192 // NetworkErrorCount returns total count of processed requests observed.
193 func (m *RTMetrics) NetworkErrorCount() int64 {
194 return m.netErrors.Count()
195 }
196
197 // StatusCodesCounts returns map with counts of the response codes.
198 func (m *RTMetrics) StatusCodesCounts() map[int]int64 {
199 sc := make(map[int]int64)
200 m.statusCodesLock.RLock()
201 defer m.statusCodesLock.RUnlock()
202 for k, v := range m.statusCodes {
203 if v.Count() != 0 {
204 sc[k] = v.Count()
205 }
206 }
207 return sc
208 }
209
210 // LatencyHistogram computes and returns resulting histogram with latencies observed.
211 func (m *RTMetrics) LatencyHistogram() (*HDRHistogram, error) {
212 m.histogramLock.Lock()
213 defer m.histogramLock.Unlock()
214 return m.histogram.Merged()
215 }
216
217 // Reset reset metrics.
218 func (m *RTMetrics) Reset() {
219 m.statusCodesLock.Lock()
220 defer m.statusCodesLock.Unlock()
221 m.histogramLock.Lock()
222 defer m.histogramLock.Unlock()
223 m.histogram.Reset()
224 m.total.Reset()
225 m.netErrors.Reset()
226 m.statusCodes = make(map[int]*RollingCounter)
227 }
228
229 func (m *RTMetrics) recordLatency(d time.Duration) error {
230 m.histogramLock.Lock()
231 defer m.histogramLock.Unlock()
232 return m.histogram.RecordLatencies(d, 1)
233 }
234
235 func (m *RTMetrics) recordStatusCode(statusCode int) error {
236 m.statusCodesLock.Lock()
237 if c, ok := m.statusCodes[statusCode]; ok {
238 c.Inc(1)
239 m.statusCodesLock.Unlock()
240 return nil
241 }
242 m.statusCodesLock.Unlock()
243
244 m.statusCodesLock.Lock()
245 defer m.statusCodesLock.Unlock()
246
247 // Check if another goroutine has written our counter already
248 if c, ok := m.statusCodes[statusCode]; ok {
249 c.Inc(1)
250 return nil
251 }
252
253 c, err := m.newCounter()
254 if err != nil {
255 return err
256 }
257 c.Inc(1)
258 m.statusCodes[statusCode] = c
259 return nil
260 }
261
262 const (
263 counterBuckets = 10
264 counterResolution = clock.Second
265 histMin = 1
266 histMax = 3600000000 // 1 hour in microseconds
267 histSignificantFigures = 2 // significant figures (1% precision)
268 histBuckets = 6 // number of sub-histograms in a rolling histogram
269 histPeriod = 10 * clock.Second // roll time
270 )