/
plugin.go
91 lines (74 loc) · 1.76 KB
/
plugin.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package usage
import (
"math/rand"
"net/http"
"os"
"sync/atomic"
"time"
"github.com/micro/cli"
"github.com/micro/go-micro/registry"
"github.com/micro/micro/plugin"
)
func init() {
plugin.Register(Plugin())
}
func Plugin() plugin.Plugin {
var requests uint64
// create rand
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
return plugin.NewPlugin(
plugin.WithName("usage"),
plugin.WithInit(func(c *cli.Context) error {
// only do if enabled
if !c.GlobalBool("report_usage") {
os.Setenv("MICRO_REPORT_USAGE", "false")
return nil
}
var service string
// set service name
if len(c.Args()) > 0 && len(c.Args()[0]) > 0 {
service = c.Args()[0]
}
// kick off the tracker
go func() {
// new report
u := New(service)
// initial publish in 30-60 seconds
d := 30 + r.Intn(30)
time.Sleep(time.Second * time.Duration(d))
for {
// get service list
s, _ := registry.ListServices()
// get requests
reqs := atomic.LoadUint64(&requests)
srvs := uint64(len(s))
// reset requests
atomic.StoreUint64(&requests, 0)
// set metrics
u.Metrics.Count["instances"] = uint64(1)
u.Metrics.Count["requests"] = reqs
u.Metrics.Count["services"] = srvs
// send report
Report(u)
// now sleep 24 hours
time.Sleep(time.Hour * 24)
}
}()
return nil
}),
plugin.WithHandler(func(h http.Handler) http.Handler {
// only enable if set
if v := os.Getenv("MICRO_REPORT_USAGE"); v == "false" {
return h
}
// return usage recorder
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// count requests
atomic.AddUint64(&requests, 1)
// serve the request
h.ServeHTTP(w, r)
})
}),
)
}