storj/cmd/tools/metabase-verify/profile.go
Egon Elbre 381c1e1257 cmd/tools: move tooling to a separate folder
This helps to cleanup the cmd folder a bit.

Change-Id: I24025c3dbfd35966325d7d5aaa95cd9a1176a8b7
2022-09-02 18:25:36 +03:00

70 lines
1.4 KiB
Go

// 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()
}