forked from mkevac/debugcharts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
debugcharts.go
334 lines (276 loc) · 6.82 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// 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"
"fmt"
"log"
"net/http"
"os"
"runtime"
"runtime/pprof"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/Monibuca/debugcharts/bindata"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/process"
)
type update struct {
Ts int64
BytesAllocated uint64
GcPause uint64
CPUUser float64
CPUSys float64
Block int
Goroutine int
Heap int
Mutex int
Threadcreate int
}
type consumer struct {
id uint
c chan update
}
type server struct {
consumers []consumer
consumersMutex sync.RWMutex
}
type SimplePair struct {
Ts uint64
Value uint64
}
type CPUPair struct {
Ts uint64
User float64
Sys float64
}
type PprofPair struct {
Ts uint64
Block int
Goroutine int
Heap int
Mutex int
Threadcreate int
}
type DataStorage struct {
BytesAllocated []SimplePair
GcPauses []SimplePair
CPUUsage []CPUPair
Pprof []PprofPair
}
const (
maxCount int = 86400
)
var (
data DataStorage
lastPause uint32
mutex sync.RWMutex
lastConsumerID uint
s server
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
prevSysTime float64
prevUserTime float64
myProcess *process.Process
)
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 * 1000,
Block: pprof.Lookup("block").Count(),
Goroutine: pprof.Lookup("goroutine").Count(),
Heap: pprof.Lookup("heap").Count(),
Mutex: pprof.Lookup("mutex").Count(),
Threadcreate: pprof.Lookup("threadcreate").Count(),
}
data.Pprof = append(data.Pprof, PprofPair{
uint64(nowUnix) * 1000,
u.Block,
u.Goroutine,
u.Heap,
u.Mutex,
u.Threadcreate,
})
cpuTimes, err := myProcess.Times()
if err != nil {
cpuTimes = &cpu.TimesStat{}
}
if prevUserTime != 0 {
u.CPUUser = cpuTimes.User - prevUserTime
u.CPUSys = cpuTimes.System - prevSysTime
data.CPUUsage = append(data.CPUUsage, CPUPair{uint64(nowUnix) * 1000, u.CPUUser, u.CPUSys})
}
prevUserTime = cpuTimes.User
prevSysTime = cpuTimes.System
mutex.Lock()
bytesAllocated := ms.Alloc
u.BytesAllocated = bytesAllocated
data.BytesAllocated = append(data.BytesAllocated, SimplePair{uint64(nowUnix) * 1000, bytesAllocated})
if lastPause == 0 || lastPause != ms.NumGC {
gcPause := ms.PauseNs[(ms.NumGC+255)%256]
u.GcPause = gcPause
data.GcPauses = append(data.GcPauses, SimplePair{uint64(nowUnix) * 1000, gcPause})
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"))
http.HandleFunc("/debug/charts/jquery-2.1.4.min.js", handleAsset("static/jquery-2.1.4.min.js"))
http.HandleFunc("/debug/charts/plotly-1.51.3.min.js", handleAsset("static/plotly-1.51.3.min.js"))
http.HandleFunc("/debug/charts/moment.min.js", handleAsset("static/moment.min.js"))
myProcess, _ = process.NewProcess(int32(os.Getpid()))
// preallocate arrays in data, helps save on reallocations caused by append()
// when maxCount is large
data.BytesAllocated = make([]SimplePair, 0, maxCount)
data.GcPauses = make([]SimplePair, 0, maxCount)
data.CPUUsage = make([]CPUPair, 0, maxCount)
data.Pprof = make([]PprofPair, 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++
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++
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()
if e := r.ParseForm(); e != nil {
log.Print("error parsing form")
return
}
callback := r.FormValue("callback")
fmt.Fprintf(w, "%v(", callback)
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encoder.Encode(data)
fmt.Fprint(w, ")")
}
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.Print(err)
return
}
n, err := w.Write(data)
if err != nil {
log.Print(err)
return
}
if n != len(data) {
log.Print("wrote less than supposed to")
return
}
}
}