-
Notifications
You must be signed in to change notification settings - Fork 402
/
profile.go
69 lines (57 loc) · 1.45 KB
/
profile.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
// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
package main
import (
"os"
"runtime/pprof"
"github.com/spf13/cobra"
"github.com/zeebo/errs"
)
var errProfile = errs.Class("profile")
// IncludeProfiling adds persistent profiling to cmd.
func IncludeProfiling(cmd *cobra.Command) {
var path string
var profile *CPUProfile
flag := cmd.PersistentFlags()
flag.StringVar(&path, "cpuprofile", "", "write cpu profile to file")
preRunE := cmd.PersistentPreRunE
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) (err error) {
profile, err = NewProfile(path)
if err != nil {
return err
}
if preRunE != nil {
return preRunE(cmd, args)
}
return nil
}
postRunE := cmd.PersistentPostRunE
cmd.PersistentPostRunE = func(cmd *cobra.Command, args []string) (err error) {
if postRunE != nil {
return postRunE(cmd, args)
}
profile.Close()
return nil
}
}
// CPUProfile contains active profiling information.
type CPUProfile struct{ file *os.File }
// NewProfile starts a new profile on `path`.
func NewProfile(path string) (*CPUProfile, error) {
if path == "" {
return nil, nil
}
f, err := os.Create(path)
if err != nil {
return nil, errProfile.New("unable to create file: %w", err)
}
err = pprof.StartCPUProfile(f)
return &CPUProfile{file: f}, Error.Wrap(err)
}
// Close finishes the profile.
func (p *CPUProfile) Close() {
if p == nil || p.file == nil {
return
}
pprof.StopCPUProfile()
}