Skip to content

Commit

Permalink
Add cpu profiling capability to base module
Browse files Browse the repository at this point in the history
  • Loading branch information
dhaavi committed Jun 3, 2020
1 parent 328884c commit 381b94a
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
12 changes: 11 additions & 1 deletion core/base/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ import (
_ "github.com/safing/portbase/rng"
)

var (
module *modules.Module
)

func init() {
modules.Register("base", nil, registerDatabases, nil, "database", "config", "rng")
module = modules.Register("base", nil, start, nil, "database", "config", "rng")

// For prettier subsystem graph, printed with --print-subsystem-graph
/*
Expand All @@ -23,3 +27,9 @@ func init() {
)
*/
}

func start() error {
startProfiling()

return registerDatabases()
}
43 changes: 43 additions & 0 deletions core/base/profiling.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package base

import (
"context"
"flag"
"fmt"
"os"
"runtime/pprof"
)

var (
cpuProfile string
)

func init() {
flag.StringVar(&cpuProfile, "cpuprofile", "", "write cpu profile to `file`")
}

func startProfiling() {
if cpuProfile != "" {
module.StartWorker("cpu profiler", cpuProfiler)
}
}

func cpuProfiler(ctx context.Context) error {
f, err := os.Create(cpuProfile)
if err != nil {
return fmt.Errorf("could not create CPU profile: %s", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
return fmt.Errorf("could not start CPU profile: %s", err)
}

// wait for shutdown
<-ctx.Done()

pprof.StopCPUProfile()
err = f.Close()
if err != nil {
return fmt.Errorf("failed to close CPU profile file: %s", err)
}
return nil
}

0 comments on commit 381b94a

Please sign in to comment.