-
Notifications
You must be signed in to change notification settings - Fork 290
/
profiler.go
72 lines (59 loc) · 1.44 KB
/
profiler.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
package engine
import (
"context"
"os"
"runtime/pprof"
"github.com/pkg/errors"
"github.com/windmilleng/tilt/internal/store"
"github.com/windmilleng/tilt/pkg/logger"
)
const profileFileName = "tilt.profile"
func (p *ProfilerManager) Start(ctx context.Context, filename string) error {
f, err := os.Create(filename)
if err != nil {
return errors.Wrapf(err, "error creating profile file %s", filename)
}
p.f = f
err = pprof.StartCPUProfile(f)
if err != nil {
return errors.Wrap(err, "error starting cpu profile")
}
logger.Get(ctx).Infof("starting pprof profile to %s", profileFileName)
return nil
}
func (p *ProfilerManager) Stop(ctx context.Context) error {
pprof.StopCPUProfile()
err := p.f.Close()
if err != nil {
return errors.Wrap(err, "error closing profile file")
}
logger.Get(ctx).Infof("stopped pprof profile to %s", profileFileName)
p.f = nil
return nil
}
type ProfilerManager struct {
isProfiling bool
f *os.File
}
func (p *ProfilerManager) OnChange(ctx context.Context, st store.RStore) {
state := st.RLockState()
defer st.RUnlockState()
if p.isProfiling == state.IsProfiling {
return
}
p.isProfiling = state.IsProfiling
if p.isProfiling {
err := p.Start(ctx, profileFileName)
if err != nil {
st.Dispatch(NewErrorAction(err))
}
} else {
err := p.Stop(ctx)
if err != nil {
st.Dispatch(NewErrorAction(err))
}
}
}
func NewProfilerManager() *ProfilerManager {
return &ProfilerManager{}
}