Skip to content

Commit

Permalink
Add --profile-{cpu,mem} flags
Browse files Browse the repository at this point in the history
The flags allow debugging `crictl` with respect to CPU and memory
consumption.

Signed-off-by: Sascha Grunert <[email protected]>
  • Loading branch information
saschagrunert committed Nov 14, 2024
1 parent 4dc7922 commit 6e76f2f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ linters-settings:
disabled: true
nestif:
min-complexity: 17
maintidx:
under: 18
godox:
keywords:
- BUG
Expand All @@ -132,7 +134,7 @@ linters-settings:
cyclop:
max-complexity: 37
gocognit:
min-complexity: 53
min-complexity: 63
gci:
sections:
- standard
Expand Down
49 changes: 49 additions & 0 deletions cmd/crictl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"fmt"
"os"
"runtime"
"runtime/pprof"
"slices"
"sort"
"strings"
Expand Down Expand Up @@ -270,12 +271,34 @@ func main() {
Usage: "Address to which the gRPC tracing collector will send spans to.",
Value: "127.0.0.1:4317",
},
&cli.StringFlag{
Name: "profile-cpu",
Usage: "Write a pprof CPU profile to the provided path.",
},
&cli.StringFlag{
Name: "profile-mem",
Usage: "Write a pprof memory profile to the provided path.",
},
}

app.Before = func(context *cli.Context) (err error) {
var config *common.ServerConfiguration
var exePath string

cpuProfilePath := context.String("profile-cpu")
if cpuProfilePath != "" {
logrus.Infof("Creating CPU profile in: %s", cpuProfilePath)

file, err := os.Create(cpuProfilePath)
if err != nil {
return fmt.Errorf("could not create CPU profile: %w", err)
}

if err := pprof.StartCPUProfile(file); err != nil {
return fmt.Errorf("could not start CPU profiling: %w", err)
}
}

if exePath, err = os.Executable(); err != nil {
logrus.Fatal(err)
}
Expand Down Expand Up @@ -355,6 +378,29 @@ func main() {

return nil
}

app.After = func(ctx *cli.Context) error {
memProfilePath := ctx.String("profile-mem")
if memProfilePath != "" {
logrus.Infof("Creating memory profile in: %s", memProfilePath)

file, err := os.Create(memProfilePath)
if err != nil {
return fmt.Errorf("could not create memory profile: %w", err)
}
defer file.Close()

// Ensure up to date data
runtime.GC()

if err := pprof.WriteHeapProfile(file); err != nil {
return fmt.Errorf("could not write memory profile: %w", err)
}
}

return nil
}

// sort all flags
for _, cmd := range app.Commands {
sort.Sort(cli.FlagsByName(cmd.Flags))
Expand All @@ -373,4 +419,7 @@ func main() {
logrus.Errorf("Unable to shutdown tracer provider: %v", err)
}
}

// noop when profiling is not enabled
pprof.StopCPUProfile()
}

0 comments on commit 6e76f2f

Please sign in to comment.