Skip to content

[bug] CPU profile not stopped if StartCPUProfile fails #1814

@docker-agent

Description

@docker-agent

🟠 high - bug

File: cmd/root/run.go (line 161)

Code

if f.cpuProfile != "" {
	pf, err := os.Create(f.cpuProfile)
	if err != nil {
		return fmt.Errorf("failed to create CPU profile: %w", err)
	}
	if err := pprof.StartCPUProfile(pf); err != nil {
		pf.Close()
		return fmt.Errorf("failed to start CPU profile: %w", err)
	}
	defer pprof.StopCPUProfile()
	defer pf.Close()
	slog.Info("CPU profiling enabled", "file", f.cpuProfile)
}

Problem

If pprof.StartCPUProfile(pf) returns an error, pf.Close() is called, but pprof.StopCPUProfile() is not called. This could lead to a partially started CPU profile or other resource issues if StartCPUProfile allocates resources that need to be cleaned up by StopCPUProfile. The deferred call to pprof.StopCPUProfile() will only be executed if pprof.StartCPUProfile is successful.

Suggested Fix

Only defer pprof.StopCPUProfile() if pprof.StartCPUProfile returns no error. One approach is to use a flag to track whether profiling was successfully started:

if f.cpuProfile != "" {
	pf, err := os.Create(f.cpuProfile)
	if err != nil {
		return fmt.Errorf("failed to create CPU profile: %w", err)
	}
	
	// Ensure pf is closed even if StartCPUProfile fails.
	// If StartCPUProfile succeeds, pf will be closed by the later defer.
	closed := false 
	defer func() {
		if !closed {
			pf.Close()
		}
	}()

	if err := pprof.StartCPUProfile(pf); err != nil {
		return fmt.Errorf("failed to start CPU profile: %w", err)
	}
	defer pprof.StopCPUProfile()
	
	// Mark as closed by defer
	closed = true
	defer pf.Close() 

	slog.Info("CPU profiling enabled", "file", f.cpuProfile)
}

Found by nightly codebase scan

Metadata

Metadata

Assignees

No one assigned

    Labels

    automatedIssues created by cagentkind/bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions