Skip to content

Commit

Permalink
Introduce ability to get profile data
Browse files Browse the repository at this point in the history
This exposes two environment variables, PFLT_MEMPROFILE and
PFLT_CPUPROFILE, that should be set to the path and name of a file to
write the profile data to. These can then be processed with `go tool
pprof` for further analysis.

Signed-off-by: Brad P. Crochet <[email protected]>
  • Loading branch information
bcrochet committed Nov 20, 2024
1 parent ed06ae7 commit 2e93cf9
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions cmd/preflight/cmd/check_container.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os"
"path/filepath"
rt "runtime"
"runtime/pprof"
"slices"
"strings"

Expand Down Expand Up @@ -89,6 +90,9 @@ func checkContainerCmd(runpreflight runPreflight) *cobra.Command {
flags.String("platform", rt.GOARCH, "Architecture of image to pull. Defaults to runtime platform.")
_ = viper.BindPFlag("platform", flags.Lookup("platform"))

_ = viper.BindEnv("cpuprofile")
_ = viper.BindEnv("memprofile")

return checkContainerCmd
}

Expand All @@ -101,6 +105,20 @@ func checkContainerRunE(cmd *cobra.Command, args []string, runpreflight runPrefl
}
logger.Info("certification library version", "version", version.Version.String())

if viper.Instance().IsSet("cpuprofile") {
f, err := os.Create(viper.Instance().GetString("cpuprofile"))
if err != nil {
logger.Error(err, "could not create CPU profile")
return err
}
defer f.Close()

if err := pprof.StartCPUProfile(f); err != nil {
logger.Error(err, "could not start CPU profile")
}
defer pprof.StopCPUProfile()
}

containerImage := args[0]

// Render the Viper configuration as a runtime.Config
Expand Down Expand Up @@ -194,6 +212,18 @@ func checkContainerRunE(cmd *cobra.Command, args []string, runpreflight runPrefl
}
}

if viper.Instance().IsSet("memprofile") {
f, err := os.Create(viper.Instance().GetString("memprofile"))
if err != nil {
logger.Error(err, "could not create memory profile")
}
defer f.Close()

rt.GC() // get up-to-date statistics
if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil {
logger.Error(err, "could not start memory profile")
}
}
return nil
}

Expand Down

0 comments on commit 2e93cf9

Please sign in to comment.