forked from mattrobenolt/go-memcached
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
114 lines (94 loc) · 2.24 KB
/
stats.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package memcached
import (
"fmt"
"os"
"runtime"
"strconv"
"syscall"
"time"
)
type Stats map[string]fmt.Stringer
type StaticStat struct {
Value string
}
func (s *StaticStat) String() string {
return s.Value
}
type TimerStat struct {
Start int64
}
func (t *TimerStat) String() string {
return strconv.Itoa(int(time.Now().Unix() - t.Start))
}
func NewTimerStat() *TimerStat {
return &TimerStat{time.Now().Unix()}
}
type FuncStat struct {
Callable func() string
}
func (f *FuncStat) String() string {
return f.Callable()
}
type CounterStat struct {
Count int
calculations chan int
}
func (c *CounterStat) Increment(num int) {
c.calculations <- num
}
func (c *CounterStat) SetCount(num int) {
c.Count = num
}
func (c *CounterStat) Decrement(num int) {
c.calculations <- -num
}
func (c *CounterStat) String() string {
return strconv.Itoa(c.Count)
}
func (c *CounterStat) work() {
for num := range c.calculations {
c.Count = c.Count + num
}
}
func NewCounterStat() *CounterStat {
c := &CounterStat{}
c.calculations = make(chan int, 100)
go c.work()
return c
}
type usageType int
const (
USER_TIME usageType = iota
SYSTEM_TIME
)
func getRusage(usage usageType) float64 {
rusage := &syscall.Rusage{}
syscall.Getrusage(0, rusage)
var time *syscall.Timeval
if usage == USER_TIME {
time = &rusage.Utime
} else {
time = &rusage.Stime
}
nsec := time.Nano()
return float64(nsec) / 1000000000
}
func NewStats() Stats {
s := make(Stats)
s["pid"] = &StaticStat{strconv.Itoa(os.Getpid())}
s["uptime"] = NewTimerStat()
s["time"] = &FuncStat{func() string { return strconv.Itoa(int(time.Now().Unix())) }}
s["version"] = &StaticStat{VERSION}
s["golang"] = &StaticStat{runtime.Version()}
s["goroutines"] = &FuncStat{func() string { return strconv.Itoa(runtime.NumGoroutine()) }}
s["rusage_user"] = &FuncStat{func() string { return fmt.Sprintf("%f", getRusage(USER_TIME)) }}
s["rusage_system"] = &FuncStat{func() string { return fmt.Sprintf("%f", getRusage(SYSTEM_TIME)) }}
s["cmd_get"] = NewCounterStat()
s["cmd_set"] = NewCounterStat()
s["get_hits"] = NewCounterStat()
s["get_misses"] = NewCounterStat()
s["curr_connections"] = NewCounterStat()
s["total_connections"] = NewCounterStat()
s["evictions"] = NewCounterStat()
return s
}