perfagent

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package perfagent provides a library interface for the performance monitoring agent.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent is the main performance monitoring agent.

func New

func New(opts ...Option) (*Agent, error)

New creates a new Agent with the given options.

func (*Agent) Close

func (a *Agent) Close() error

Close releases all resources associated with the agent.

func (*Agent) Config

func (a *Agent) Config() Config

Config returns a copy of the agent's configuration.

func (*Agent) GetMetrics

func (a *Agent) GetMetrics() (*metrics.MetricsSnapshot, error)

GetMetrics returns the current PMU metrics snapshot.

func (*Agent) PythonInjectStats

func (a *Agent) PythonInjectStats() *python.Stats

PythonInjectStats returns counters for the Python injector. Returns a zero-value Stats if --inject-python was not enabled.

func (*Agent) Start

func (a *Agent) Start(ctx context.Context) error

Start initializes and starts all enabled profilers.

func (*Agent) Stop

func (a *Agent) Stop(ctx context.Context) error

Stop stops data collection and writes profiles.

type Config

type Config struct {
	// PID is the target process ID to monitor (0 for system-wide).
	PID int

	// SystemWide enables system-wide profiling of all processes.
	SystemWide bool

	// EnableCPUProfile enables CPU profiling with stack traces.
	EnableCPUProfile bool

	// CPUProfilePath is the output path for CPU profiles.
	CPUProfilePath string

	// CPUProfileWriter is an optional writer for CPU profile output.
	// If set, profile data is written here instead of to CPUProfilePath.
	CPUProfileWriter io.Writer

	// EnableOffCPUProfile enables off-CPU profiling with stack traces.
	EnableOffCPUProfile bool

	// OffCPUProfilePath is the output path for off-CPU profiles.
	OffCPUProfilePath string

	// OffCPUProfileWriter is an optional writer for off-CPU profile output.
	// If set, profile data is written here instead of to OffCPUProfilePath.
	OffCPUProfileWriter io.Writer

	// PerfDataOutput is the path for a kernel-format perf.data file. Empty
	// disables emission. Set via WithPerfDataOutput. Only on-CPU samples
	// are written; off-CPU and PMU modes ignore this option.
	PerfDataOutput string

	// EnablePMU enables PMU hardware counter monitoring.
	EnablePMU bool

	// PerPID shows per-PID breakdown in system-wide mode.
	PerPID bool

	// SampleRate is the CPU profiling sample rate in Hz.
	SampleRate int

	// Tags are key=value pairs to add to profiles.
	Tags []string

	// MetricsExporters are the exporters to use for metrics output.
	MetricsExporters []metrics.Exporter

	// Unwind selects the stack unwinding strategy for --profile and
	// --offcpu modes. Valid values: "fp" (frame pointer),
	// "dwarf" (DWARF CFI), "auto" (default; aliases to "dwarf",
	// and the DWARF walker already takes the FP path for FP-safe
	// frames). After options parsing, an empty string is treated
	// as "auto".
	Unwind string

	// CPUs is the list of CPUs to monitor. If nil, all online CPUs are used.
	CPUs []uint

	// InjectPython enables Python perf-trampoline injection during profiling.
	// Only valid with EnableCPUProfile. Requires CAP_SYS_PTRACE.
	InjectPython bool

	// Labels are static per-sample pprof labels. Merged on top of the enricher
	// output (Labels wins on key collision). Set via WithLabels.
	Labels map[string]string

	// LabelEnricher computes additional per-sample labels at agent startup
	// from the resolved host PID. Default is internal/k8slabels.FromPID.
	// Override via WithLabelEnricher; pass nil to disable defaults entirely.
	// LabelEnricherSet records whether the user explicitly called
	// WithLabelEnricher (so passing nil to disable is distinguishable from
	// not calling it at all).
	LabelEnricher    func(hostPID int) map[string]string
	LabelEnricherSet bool

	// DebuginfodURLs is the ordered list of debuginfod servers to consult for
	// off-box DWARF/executable fetching. If empty (and DEBUGINFOD_URLS env is
	// also empty), the agent uses the local symbolizer.
	DebuginfodURLs []string

	// SymbolCacheDir overrides the debuginfod cache directory.
	// Default: /tmp/perf-agent-debuginfod.
	SymbolCacheDir string

	// SymbolCacheMaxBytes overrides the debuginfod cache size cap. Default: 2 GiB.
	SymbolCacheMaxBytes int64

	// SymbolFetchTimeout overrides per-artifact fetch timeout. Default: 30s.
	SymbolFetchTimeout time.Duration

	// SymbolFailClosed makes the agent refuse to symbolize a mapping whose
	// debuginfod fetch failed (vs. fall back to local). Default: false.
	// Note: M1 ships the option but FailClosed semantics are M2.
	SymbolFailClosed bool

	// KernelStacks enables kernel-mode stack capture and symbolization.
	// Default: false. Opt in via --kernel-stacks (CLI) or
	// WithKernelStacks() (library).
	//
	// When set:
	//   - BPF programs enable the kernel-stack capture path (a volatile
	//     bool global flipped at load time; no per-sample cost when off).
	//   - The Agent constructs a LocalKernelSymbolizer; on
	//     ErrKernelSymbolsUnavailable, falls back to NoopKernelSymbolizer
	//     + a one-time warning.
	//   - --perf-data-output emits a kernel MMAP2 record at writer init,
	//     and SampleRecord callchains carry PERF_CONTEXT_{KERNEL,USER}
	//     markers around the merged kernel+user IPs.
	KernelStacks bool
}

Config holds the configuration for the performance agent.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults.

type Option

type Option func(*Config)

Option is a functional option for configuring the Agent.

func WithCPUProfile

func WithCPUProfile(outputPath string) Option

WithCPUProfile enables CPU profiling and sets the output path.

func WithCPUProfileWriter

func WithCPUProfileWriter(w io.Writer) Option

WithCPUProfileWriter enables CPU profiling and sets a writer for output. The writer receives gzip-compressed pprof data. This takes precedence over CPUProfilePath if both are set.

func WithCPUs

func WithCPUs(cpus []uint) Option

WithCPUs sets the list of CPUs to monitor.

func WithDebuginfodURL

func WithDebuginfodURL(url string) Option

WithDebuginfodURL appends a debuginfod server URL. Repeatable.

func WithInjectPython

func WithInjectPython(enabled bool) Option

WithInjectPython enables Python perf-trampoline injection during profiling. Caller must hold CAP_SYS_PTRACE. With --pid N, any per-target failure exits non-zero (strict). With -a, failures are logged and the profile continues (lenient). Only valid when CPU profiling is enabled.

func WithKernelStacks added in v1.2.0

func WithKernelStacks() Option

WithKernelStacks enables kernel-mode stack capture + symbolization. Default: off.

func WithLabelEnricher

func WithLabelEnricher(fn func(hostPID int) map[string]string) Option

WithLabelEnricher overrides the default label enricher (which derives k8s identity labels from /proc/<hostPID>/cgroup and downward-API env vars). Pass nil to disable all enricher-sourced labels — only labels from WithLabels will be attached.

func WithLabels

func WithLabels(labels map[string]string) Option

WithLabels attaches static per-sample labels to every emitted pprof sample. Merged with WithLabelEnricher output; static labels win on key collision.

func WithMetricsExporter

func WithMetricsExporter(exp metrics.Exporter) Option

WithMetricsExporter adds a metrics exporter.

func WithOffCPUProfile

func WithOffCPUProfile(outputPath string) Option

WithOffCPUProfile enables off-CPU profiling and sets the output path.

func WithOffCPUProfileWriter

func WithOffCPUProfileWriter(w io.Writer) Option

WithOffCPUProfileWriter enables off-CPU profiling and sets a writer for output. The writer receives gzip-compressed pprof data. This takes precedence over OffCPUProfilePath if both are set.

func WithPID

func WithPID(pid int) Option

WithPID sets the target process ID to monitor.

func WithPMU

func WithPMU() Option

WithPMU enables PMU hardware counter monitoring.

func WithPerPID

func WithPerPID() Option

WithPerPID enables per-PID breakdown in system-wide mode.

func WithPerfDataOutput

func WithPerfDataOutput(path string) Option

WithPerfDataOutput enables writing a Linux perf.data file alongside the pprof output. Only on-CPU samples are emitted (off-CPU and PMU modes ignore this). The output is consumable by perf script, perf report, create_llvm_prof (AutoFDO PGO), FlameGraph, hotspot, etc.

func WithSampleRate

func WithSampleRate(hz int) Option

WithSampleRate sets the CPU profiling sample rate in Hz.

func WithSymbolCacheDir

func WithSymbolCacheDir(dir string) Option

WithSymbolCacheDir overrides the debuginfod cache directory.

func WithSymbolCacheMaxBytes

func WithSymbolCacheMaxBytes(n int64) Option

WithSymbolCacheMaxBytes overrides the debuginfod cache cap.

func WithSymbolFailClosed

func WithSymbolFailClosed() Option

WithSymbolFailClosed enables fail-closed behavior on debuginfod errors.

func WithSymbolFetchTimeout

func WithSymbolFetchTimeout(d time.Duration) Option

WithSymbolFetchTimeout overrides per-artifact fetch timeout.

func WithSystemWide

func WithSystemWide() Option

WithSystemWide enables system-wide profiling.

func WithTags

func WithTags(tags ...string) Option

WithTags adds tags to profiles.

func WithUnwind

func WithUnwind(mode string) Option

WithUnwind selects the stack-unwinding strategy. See Config.Unwind.