-
Notifications
You must be signed in to change notification settings - Fork 20
/
debug.go
93 lines (82 loc) · 2.67 KB
/
debug.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
package handlers
import (
"context"
"encoding/json"
"expvar"
"io/ioutil"
"net/http"
"os"
"runtime"
"runtime/debug"
"github.com/go-masonry/mortar/constructors/partial"
"github.com/go-masonry/mortar/interfaces/log"
"go.uber.org/fx"
)
const (
internalPatternPrefix = "/debug"
)
// StatsInfo some statistics information
type StatsInfo struct {
Memory *runtime.MemStats `json:"memory"`
NumOfCPU int `json:"num_of_cpu"`
NumOfGoRoutines int `json:"num_of_go_routines"`
}
// DebugHandlers different debug handlers
type DebugHandlers interface {
DebugVars() http.Handler
Stats() http.HandlerFunc
DumpFunc() http.HandlerFunc
}
type debugHandlersDeps struct {
fx.In
Logger log.Logger
}
// InternalDebugHandlers defines internal debug handlers
// - dump heap
// - expvar
// - running stats
func InternalDebugHandlers(deps debugHandlersDeps) []partial.HTTPHandlerPatternPair {
return []partial.HTTPHandlerPatternPair{
{Pattern: internalPatternPrefix + "/vars", Handler: deps.DebugVars()},
{Pattern: internalPatternPrefix + "/dump", Handler: deps.DumpFunc()},
{Pattern: internalPatternPrefix + "/stats", Handler: deps.Stats()},
}
}
func (d *debugHandlersDeps) DebugVars() http.Handler {
return expvar.Handler()
}
func (d *debugHandlersDeps) DumpFunc() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
file, err := ioutil.TempFile("", "heapdump")
if err != nil {
d.Logger.WithError(err).Warn(context.TODO(), "failed to create temp file to dump heap into")
http.Error(w, "internal error, failed to serve heap dump", http.StatusInternalServerError)
return
}
defer func(logger log.Logger, tempFile *os.File) {
if err := os.Remove(tempFile.Name()); err != nil {
logger.WithError(err).WithField("tempfile", tempFile.Name()).Warn(context.TODO(), "failed to remove temp file")
}
}(d.Logger, file) // remove garbage
debug.WriteHeapDump(file.Fd())
http.ServeFile(w, req, file.Name())
if err = file.Close(); err != nil {
d.Logger.WithError(err).WithField("tempfile", file.Name()).Warn(context.TODO(), "temp file wasn't closed")
}
}
}
func (d *debugHandlersDeps) Stats() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-type", "application/json; charset=utf-8")
output := &StatsInfo{
Memory: new(runtime.MemStats),
NumOfCPU: runtime.NumCPU(),
NumOfGoRoutines: runtime.NumGoroutine(),
}
runtime.ReadMemStats(output.Memory)
if err := json.NewEncoder(w).Encode(output); err != nil {
d.Logger.WithError(err).Debug(context.TODO(), "failed to serve stats")
w.WriteHeader(http.StatusInternalServerError)
}
}
}