OSDN Git Service

Merge pull request #686 from Bytom/dev-gas
[bytom/bytom.git] / api / metrics.go
1 package api
2
3 import (
4         "net/http"
5         "sync"
6         "time"
7
8         "github.com/bytom/metrics"
9 )
10
11 var (
12         latencyMu sync.Mutex
13         latencies = map[string]*metrics.RotatingLatency{}
14
15         latencyRange = map[string]time.Duration{
16                 crosscoreRPCPrefix + "get-block":         20 * time.Second,
17                 crosscoreRPCPrefix + "signer/sign-block": 5 * time.Second,
18                 crosscoreRPCPrefix + "get-snapshot":      30 * time.Second,
19                 // the rest have a default range
20         }
21 )
22
23 // latency returns a rotating latency histogram for the given request.
24 func latency(tab *http.ServeMux, req *http.Request) *metrics.RotatingLatency {
25         latencyMu.Lock()
26         defer latencyMu.Unlock()
27         if l := latencies[req.URL.Path]; l != nil {
28                 return l
29         }
30         // Create a histogram only if the path is legit.
31         if _, pat := tab.Handler(req); pat == req.URL.Path {
32                 d, ok := latencyRange[req.URL.Path]
33                 if !ok {
34                         d = 100 * time.Millisecond
35                 }
36                 l := metrics.NewRotatingLatency(5, d)
37                 latencies[req.URL.Path] = l
38                 metrics.PublishLatency(req.URL.Path, l)
39                 return l
40         }
41         return nil
42 }