Revise CPU Profiling implementation

cgr-engine.go:
- use filepath.Join instead of path.Join
- handle *CoreService.StopCPUProfiling error inside deferred function
- same with the error from *os.File.Close()

cores/core.go:
- StartCPUProfile now returns an io.Closer (as opposed to an io.WriteCloser)
- handle pprof.StartCPUProfile error and ensure file is closed before returning
- log file close error as a warning if it occurs
- return missing mandatory error with correct path field name ('DirPath')
- no need to check if fileCPU is nil for profiling status
  - pprof.StartCPUProfiling will return an error if profiling is already started
  - os.File.Close() will return ErrClosed if profiling is already stopped
- differentiate between calling StopCPUProfiling when profiling hasn't started
and when it was already stopped by returning appropriate errors

- improved comments and error messages
This commit is contained in:
ionutboangiu
2024-07-21 02:56:08 +03:00
committed by Dan Christian Bogos
parent 6f4d2144a6
commit 9d4561f79c
2 changed files with 51 additions and 36 deletions

View File

@@ -26,6 +26,7 @@ import (
"os"
"os/signal"
"path"
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
@@ -368,21 +369,24 @@ func main() {
}()
}
var cpuProfileFile io.Closer
var cpuProf io.Closer
if *cpuProfDir != utils.EmptyString {
cpuPath := path.Join(*cpuProfDir, utils.CpuPathCgr)
cpuProfileFile, err = cores.StartCPUProfiling(cpuPath)
cpuPath := filepath.Join(*cpuProfDir, utils.CpuPathCgr)
cpuProf, err = cores.StartCPUProfiling(cpuPath)
if err != nil {
log.Fatalf("<%s> error received: <%s>, exiting!", utils.InitS, err.Error())
log.Fatal(err)
}
defer func() {
if cS != nil {
cS.StopCPUProfiling()
// Use CoreService's StopCPUProfiling method if it has been initialized.
if err := cS.StopCPUProfiling(); err != nil {
log.Print(err)
}
return
}
if cpuProfileFile != nil {
pprof.StopCPUProfile()
cpuProfileFile.Close()
pprof.StopCPUProfile()
if err := cpuProf.Close(); err != nil {
log.Printf("could not close file %q: %v", cpuProf.(*os.File).Name(), err)
}
}()
}
@@ -576,7 +580,7 @@ func main() {
// init CoreSv1
coreS := services.NewCoreService(cfg, caps, server, internalCoreSv1Chan, anz, cpuProfileFile, memPrfDirForCores, shdWg, stopMemProf, shdChan, srvDep)
coreS := services.NewCoreService(cfg, caps, server, internalCoreSv1Chan, anz, cpuProf, *memProfDir, shdWg, stopMemProf, shdChan, srvDep)
shdWg.Add(1)
if err := coreS.Start(); err != nil {
log.Fatalf("<%s> error received: <%s>, exiting!", utils.InitS, err.Error())