OSDN Git Service

add timerange to txbuilder (#461)
[bytom/bytom.git] / blockchain / metrics.go
1 package blockchain
2
3 import (
4         "expvar"
5         "net/http"
6         "sync"
7         "time"
8
9         "github.com/bytom/metrics"
10         "github.com/bytom/net/http/reqid"
11 )
12
13 var (
14         latencyMu sync.Mutex
15         latencies = map[string]*metrics.RotatingLatency{}
16
17         latencyRange = map[string]time.Duration{
18                 crosscoreRPCPrefix + "get-block":         20 * time.Second,
19                 crosscoreRPCPrefix + "signer/sign-block": 5 * time.Second,
20                 crosscoreRPCPrefix + "get-snapshot":      30 * time.Second,
21                 // the rest have a default range
22         }
23 )
24
25 // latency returns a rotating latency histogram for the given request.
26 func latency(tab *http.ServeMux, req *http.Request) *metrics.RotatingLatency {
27         latencyMu.Lock()
28         defer latencyMu.Unlock()
29         if l := latencies[req.URL.Path]; l != nil {
30                 return l
31         }
32         // Create a histogram only if the path is legit.
33         if _, pat := tab.Handler(req); pat == req.URL.Path {
34                 d, ok := latencyRange[req.URL.Path]
35                 if !ok {
36                         d = 100 * time.Millisecond
37                 }
38                 l := metrics.NewRotatingLatency(5, d)
39                 latencies[req.URL.Path] = l
40                 metrics.PublishLatency(req.URL.Path, l)
41                 return l
42         }
43         return nil
44 }
45
46 var (
47         ncoreMu   sync.Mutex
48         ncore     = expvar.NewInt("ncore")
49         ncoreTime time.Time
50         coresSeen map[string]bool
51 )
52
53 func coreCounter(h http.Handler) http.Handler {
54         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
55                 countCore(reqid.CoreIDFromContext(req.Context()))
56                 h.ServeHTTP(w, req)
57         })
58 }
59
60 func countCore(id string) {
61         t := time.Now()
62         ncoreMu.Lock()
63         defer ncoreMu.Unlock()
64         if t.Sub(ncoreTime) > time.Minute {
65                 ncore.Set(int64(len(coresSeen)))
66                 ncoreTime = t
67                 coresSeen = make(map[string]bool)
68         }
69         coresSeen[id] = true
70 }