forked from mkevac/debugcharts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
debugcharts.go
254 lines (206 loc) · 4.9 KB
/
debugcharts.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Simple live charts for memory consumption and GC pauses.
//
// To use debugcharts, link this package into your program:
// import _ "github.com/mkevac/debugcharts"
//
// If your application is not already running an http server, you
// need to start one. Add "net/http" and "log" to your imports and
// the following code to your main function:
//
// go func() {
// log.Println(http.ListenAndServe("localhost:6060", nil))
// }()
//
// Then go look at charts:
//
// http://localhost:6060/debug/charts
//
package debugcharts
import (
"encoding/json"
"log"
"net/http"
"runtime"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/mkevac/debugcharts/bindata"
)
type update struct {
Ts int64
BytesAllocated uint64
GcPause uint64
}
type consumer struct {
id uint
c chan update
}
type server struct {
consumers []consumer
consumersMutex sync.RWMutex
}
type timestampedDatum struct {
Count uint64 `json:"C"`
Ts int64 `json:"T"`
}
type exportedData struct {
BytesAllocated []timestampedDatum
GcPauses []timestampedDatum
}
const (
maxCount int = 86400
)
var (
data exportedData
lastPause uint32
mutex sync.RWMutex
lastConsumerId uint
s server
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
func (s *server) gatherData() {
timer := time.Tick(time.Second)
for {
select {
case now := <-timer:
nowUnix := now.Unix()
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
u := update{
Ts: nowUnix,
}
mutex.Lock()
bytesAllocated := ms.Alloc
u.BytesAllocated = bytesAllocated
data.BytesAllocated = append(data.BytesAllocated, timestampedDatum{Count: bytesAllocated, Ts: nowUnix})
if lastPause == 0 || lastPause != ms.NumGC {
gcPause := ms.PauseNs[(ms.NumGC+255)%256]
u.GcPause = gcPause
data.GcPauses = append(data.GcPauses, timestampedDatum{Count: gcPause, Ts: nowUnix})
lastPause = ms.NumGC
}
if len(data.BytesAllocated) > maxCount {
data.BytesAllocated = data.BytesAllocated[len(data.BytesAllocated)-maxCount:]
}
if len(data.GcPauses) > maxCount {
data.GcPauses = data.GcPauses[len(data.GcPauses)-maxCount:]
}
mutex.Unlock()
s.sendToConsumers(u)
}
}
}
func init() {
http.HandleFunc("/debug/charts/data-feed", s.dataFeedHandler)
http.HandleFunc("/debug/charts/data", dataHandler)
http.HandleFunc("/debug/charts/", handleAsset("static/index.html"))
http.HandleFunc("/debug/charts/main.js", handleAsset("static/main.js"))
// preallocate arrays in data, helps save on reallocations caused by append()
// when maxCount is large
data.BytesAllocated = make([]timestampedDatum, 0, maxCount)
data.GcPauses = make([]timestampedDatum, 0, maxCount)
go s.gatherData()
}
func (s *server) sendToConsumers(u update) {
s.consumersMutex.RLock()
defer s.consumersMutex.RUnlock()
for _, c := range s.consumers {
c.c <- u
}
}
func (s *server) removeConsumer(id uint) {
s.consumersMutex.Lock()
defer s.consumersMutex.Unlock()
var consumerId uint
var consumerFound bool
for i, c := range s.consumers {
if c.id == id {
consumerFound = true
consumerId = uint(i)
break
}
}
if consumerFound {
s.consumers = append(s.consumers[:consumerId], s.consumers[consumerId+1:]...)
}
}
func (s *server) addConsumer() consumer {
s.consumersMutex.Lock()
defer s.consumersMutex.Unlock()
lastConsumerId += 1
c := consumer{
id: lastConsumerId,
c: make(chan update),
}
s.consumers = append(s.consumers, c)
return c
}
func (s *server) dataFeedHandler(w http.ResponseWriter, r *http.Request) {
var (
lastPing time.Time
lastPong time.Time
)
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
conn.SetPongHandler(func(s string) error {
lastPong = time.Now()
return nil
})
// read and discard all messages
go func(c *websocket.Conn) {
for {
if _, _, err := c.NextReader(); err != nil {
c.Close()
break
}
}
}(conn)
c := s.addConsumer()
defer func() {
s.removeConsumer(c.id)
conn.Close()
}()
var i uint
for u := range c.c {
websocket.WriteJSON(conn, u)
i += 1
if i%10 == 0 {
if diff := lastPing.Sub(lastPong); diff > time.Second*60 {
return
}
now := time.Now()
if err := conn.WriteControl(websocket.PingMessage, nil, now.Add(time.Second)); err != nil {
return
}
lastPing = now
}
}
}
func dataHandler(w http.ResponseWriter, r *http.Request) {
mutex.RLock()
defer mutex.RUnlock()
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encoder.Encode(data)
}
func handleAsset(path string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
data, err := bindata.Asset(path)
if err != nil {
log.Fatal(err)
}
n, err := w.Write(data)
if err != nil {
log.Fatal(err)
}
if n != len(data) {
log.Fatal("wrote less than supposed to")
}
}
}