-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathbucketreqcounter.go
50 lines (43 loc) · 1.48 KB
/
bucketreqcounter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Deprecated: this package is no longer supported.
package web
import (
"net/http"
"sync/atomic"
"github.com/signalfx/golib/v3/datapoint"
"github.com/signalfx/golib/v3/sfxclient"
)
// BucketRequestCounter is a negroni handler that tracks connection stats including p99/etc. It's, ideally, an
// improvment over reqcounter.go
type BucketRequestCounter struct {
ActiveConnections int64
Bucket *sfxclient.RollingBucket
}
var (
_ HTTPConstructor = (&BucketRequestCounter{}).Wrap
_ NextHTTP = (&BucketRequestCounter{}).ServeHTTP
)
// Wrap returns a handler that forwards calls to next and counts the calls forwarded
func (m *BucketRequestCounter) Wrap(next http.Handler) http.Handler {
f := func(w http.ResponseWriter, r *http.Request) {
m.ServeHTTP(w, r, next)
}
return http.HandlerFunc(f)
}
func (m *BucketRequestCounter) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.Handler) {
atomic.AddInt64(&m.ActiveConnections, 1)
start := m.Bucket.Timer.Now()
defer func() {
atomic.AddInt64(&m.ActiveConnections, -1)
end := m.Bucket.Timer.Now()
reqDuration := end.Sub(start)
m.Bucket.AddAt(reqDuration.Seconds(), end)
}()
next.ServeHTTP(rw, r)
}
// Datapoints returns active connections plus wrapped bucket stats
func (m *BucketRequestCounter) Datapoints() []*datapoint.Datapoint {
dps := m.Bucket.Datapoints()
return append(dps,
sfxclient.Gauge(m.Bucket.MetricName+".active_connections", m.Bucket.Dimensions, atomic.LoadInt64(&m.ActiveConnections)),
)
}