process

package
v0.11.4 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2024 License: Apache-2.0 Imports: 27 Imported by: 9

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrProcNotExist = errors.New("process does not exist")

ErrProcNotExist indicates that a process was not found.

View Source
var PidStates = map[byte]PidState{
	'S': Sleeping,
	'R': Running,
	'D': DiskSleep,
	'I': Idle,
	'T': Stopped,
	'Z': Zombie,
	'X': Dead,
	'x': Dead,
	'K': WakeKill,
	'W': Waking,
	'P': Parked,
}

PidStates is a Map of all pid states, mostly applicable to linux

Functions

func GetProcMemPercentage

func GetProcMemPercentage(proc ProcState, totalPhyMem uint64) opt.Float

GetProcMemPercentage returns process memory usage as a percent of total memory usage

func GetSelfPid added in v0.10.0

func GetSelfPid(hostfs resolve.Resolver) (int, error)

GetSelfPid returns the process we're running as. for cases of self-monitoring this requires some actual thought; if we use os.Getpid() and we're running inside a container, that PID will only be valid inside the container, and an attempt to fetch metrics from `/hostfs/proc/` for that pid will fail. If we're using a hostfs, revert to _that_ for fetching the pid metrics.

Types

type CPUTicks

type CPUTicks struct {
	Ticks opt.Uint `struct:"ticks,omitempty"`
}

CPUTicks is a formatting wrapper for `tick` metric values

func (CPUTicks) IsZero

func (t CPUTicks) IsZero() bool

IsZero returns true if the underlying value nil

type CPUTotal

type CPUTotal struct {
	Value opt.Float  `struct:"value,omitempty"`
	Ticks opt.Uint   `struct:"ticks,omitempty"`
	Pct   opt.Float  `struct:"pct,omitempty"`
	Norm  opt.PctOpt `struct:"norm,omitempty"`
}

CPUTotal is the struct for cpu.total metrics

func (CPUTotal) IsZero added in v0.4.3

func (t CPUTotal) IsZero() bool

type CgroupPctStats

type CgroupPctStats struct {
	CPUTotalPct      float64
	CPUTotalPctNorm  float64
	CPUUserPct       float64
	CPUUserPctNorm   float64
	CPUSystemPct     float64
	CPUSystemPctNorm float64
}

CgroupPctStats stores rendered percent values from cgroup CPU data

type IncludeTopConfig

type IncludeTopConfig struct {
	Enabled  bool `config:"enabled"`
	ByCPU    int  `config:"by_cpu"`
	ByMemory int  `config:"by_memory"`
}

IncludeTopConfig is the configuration for the "top N processes filtering" feature

type MemBytePct

type MemBytePct struct {
	Bytes opt.Uint  `struct:"bytes,omitempty"`
	Pct   opt.Float `struct:"pct,omitempty"`
}

MemBytePct is the formatting struct for wrapping pct/byte metrics

type Name

type Name struct {
	Name string `struct:"name,omitempty"`
}

type NonFatalErr added in v0.8.0

type NonFatalErr struct {
	Err error
}

NonFatalErr indicates an error occurred during metrics collection, however the metrics already gathered and returned are still valid. This error can be safely ignored, this will result in having partial metrics for a process rather than no metrics at all.

It was introduced to allow for partial metrics collection on privileged process on Windows.

func (NonFatalErr) Error added in v0.8.0

func (c NonFatalErr) Error() string

func (NonFatalErr) Is added in v0.8.0

func (c NonFatalErr) Is(other error) bool

func (NonFatalErr) Unwrap added in v0.10.5

func (c NonFatalErr) Unwrap() error

type Parent

type Parent struct {
	Pid opt.Int `struct:"pid,omitempty"`
}

type PidState

type PidState string

PidState are the constants for various PID states

var (
	// Dead state, on linux this is both "x" and "X"
	Dead PidState = "dead"
	// Running state
	Running PidState = "running"
	// Sleeping state
	Sleeping PidState = "sleeping"
	// Idle state.
	Idle PidState = "idle"
	// DiskSleep is uninterruptible disk sleep
	DiskSleep PidState = "disk_sleep"
	// Stopped state.
	Stopped PidState = "stopped"
	// Zombie state.
	Zombie PidState = "zombie"
	// WakeKill is a linux state only found on kernels 2.6.33-3.13
	WakeKill PidState = "wakekill"
	// Waking  is a linux state only found on kernels 2.6.33-3.13
	Waking PidState = "waking"
	// Parked is a linux state. On the proc man page, it says it's available on 3.9-3.13, but it appears to still be in the code.
	Parked PidState = "parked"
	// Unknown state
	Unknown PidState = "unknown"
)

func GetPIDState added in v0.4.5

func GetPIDState(hostfs resolve.Resolver, pid int) (PidState, error)

GetPIDState returns the state of a given PID It will return ErrProcNotExist if the process was not found.

type ProcCPUInfo

type ProcCPUInfo struct {
	StartTime string   `struct:"start_time,omitempty"`
	Total     CPUTotal `struct:"total,omitempty"`
	// Optional Tick values
	User   CPUTicks `struct:"user,omitempty"`
	System CPUTicks `struct:"system,omitempty"`
}

ProcCPUInfo is the main struct for CPU metrics

type ProcCallback

type ProcCallback func(in ProcState) (ProcState, error)

ProcCallback is a function that FetchPid* methods can call at various points to do OS-agnostic processing

type ProcFDInfo

type ProcFDInfo struct {
	Open  opt.Uint   `struct:"open,omitempty"`
	Limit ProcLimits `struct:"limit,omitempty"`
}

ProcFDInfo is the struct for process.fd metrics

func (ProcFDInfo) IsZero

func (t ProcFDInfo) IsZero() bool

IsZero returns true if the underlying value nil

type ProcIOInfo added in v0.9.0

type ProcIOInfo struct {
	// ReadChar is bytes read from the system, as passed from read() and similar syscalls
	ReadChar opt.Uint `struct:"read_char,omitempty"`
	// WriteChar is bytes written to the system, as passed to various syscalls
	WriteChar opt.Uint `struct:"write_char,omitempty"`
	//ReadSyscalls counts the number of read operations
	ReadSyscalls opt.Uint `struct:"read_ops,omitempty"`
	//WriteSyscalls counts the number of write operations
	WriteSyscalls opt.Uint `struct:"write_ops,omitempty"`
	// ReadBytes is the count of bytes that were actually fetched from the storage layer
	ReadBytes opt.Uint `struct:"read_bytes,omitempty"`
	// WriteBytes is the count of bytes that were actually written to the storage layer
	WriteBytes opt.Uint `struct:"write_bytes,omitempty"`
	// the number of bytes which this process caused to not happen, by truncating pagecache
	CancelledWriteBytes opt.Uint `struct:"cancelled_write_bytes,omitempty"`
}

ProcIOInfo is the struct for I/O counters from /proc/[pid]/io

type ProcLimits

type ProcLimits struct {
	Soft opt.Uint `struct:"soft,omitempty"`
	Hard opt.Uint `struct:"hard,omitempty"`
}

ProcLimits wraps the fd.limit metrics

type ProcMemInfo

type ProcMemInfo struct {
	Size  opt.Uint   `struct:"size,omitempty"`
	Share opt.Uint   `struct:"share,omitempty"`
	Rss   MemBytePct `struct:"rss,omitempty"`
}

ProcMemInfo is the struct for cpu.memory metrics

type ProcState

type ProcState struct {
	// Basic Process data
	Name       string   `struct:"name,omitempty"`
	State      PidState `struct:"state,omitempty"`
	Username   string   `struct:"username,omitempty"`
	Pid        opt.Int  `struct:"pid,omitempty"`
	Ppid       opt.Int  `struct:"ppid,omitempty"`
	Pgid       opt.Int  `struct:"pgid,omitempty"`
	NumThreads opt.Int  `struct:"num_threads,omitempty"`

	// Extended Process Data
	Args    []string `struct:"args,omitempty"`
	Cmdline string   `struct:"cmdline,omitempty"`
	Cwd     string   `struct:"cwd,omitempty"`
	Exe     string   `struct:"exe,omitempty"`
	Env     mapstr.M `struct:"env,omitempty"`

	// Resource Metrics
	Memory  ProcMemInfo                       `struct:"memory,omitempty"`
	CPU     ProcCPUInfo                       `struct:"cpu,omitempty"`
	FD      ProcFDInfo                        `struct:"fd,omitempty"`
	Network *sysinfotypes.NetworkCountersInfo `struct:"-,omitempty"`
	IO      ProcIOInfo                        `struct:"io,omitempty"`

	// cgroups
	Cgroup cgroup.CGStats `struct:"cgroup,omitempty"`

	// meta
	SampleTime time.Time `struct:"-,omitempty"`
}

ProcState is the main struct for process information and metrics.

func FillMetricsRequiringMoreAccess added in v0.8.0

func FillMetricsRequiringMoreAccess(_ int, state ProcState) (ProcState, error)

func FillPidMetrics

func FillPidMetrics(hostfs resolve.Resolver, pid int, state ProcState, filter func(string) bool) (ProcState, error)

func GetInfoForPid

func GetInfoForPid(hostFS resolve.Resolver, pid int) (ProcState, error)

GetInfoForPid fetches and parses the process information of the process identified by pid from /proc/[PID]/stat

func GetProcCPUPercentage

func GetProcCPUPercentage(s0, s1 ProcState) ProcState

GetProcCPUPercentage returns the percentage of total CPU time consumed by the process during the period between the given samples. Two percentages are returned (these must be multiplied by 100). The first is a normalized based on the number of cores such that the value ranges on [0, 1]. The second is not normalized and the value ranges on [0, number_of_cores].

Implementation note: The total system CPU time (including idle) is not provided so this method will resort to using the difference in wall-clock time multiplied by the number of cores as the total amount of CPU time available between samples. This could result in incorrect percentages if the wall-clock is adjusted (prior to Go 1.9) or the machine is suspended.

func ListStates

func ListStates(hostfs resolve.Resolver) ([]ProcState, error)

ListStates is a wrapper that returns a list of processess with only the basic PID info filled out.

func (*ProcState) FormatForRoot

func (p *ProcState) FormatForRoot() ProcStateRootEvent

FormatForRoot takes the ProcState event and turns the fields into a ProcStateRootEvent struct. These are the root fields expected for events sent from the system/process metricset.

type ProcStateRootEvent

type ProcStateRootEvent struct {
	Process ProcessRoot `struct:"process,omitempty"`
	User    Name        `struct:"user,omitempty"`
}

ProcStateRootEvent represents the "root" beat/agent ECS event fields that are copied from the integration-level event.

type ProcessRoot

type ProcessRoot struct {
	Cmdline string        `struct:"command_line,omitempty"`
	State   PidState      `struct:"state,omitempty"`
	CPU     RootCPUFields `struct:"cpu,omitempty"`
	Memory  opt.PctOpt    `struct:"memory,omitempty"`
	Cwd     string        `struct:"working_directory,omitempty"`
	Exe     string        `struct:"executable,omitempty"`
	Args    []string      `struct:"args,omitempty"`
	Name    string        `struct:"name,omitempty"`
	Pid     opt.Int       `struct:"pid,omitempty"`
	Parent  Parent        `struct:"parent,omitempty"`
	Pgid    opt.Int       `struct:"pgid,omitempty"`
}

ProcessRoot wraps the process metrics for the root ECS fields

type ProcsMap

type ProcsMap map[int]ProcState

ProcsMap is a convenience wrapper for the oft-used idiom of map[int]ProcState

type ProcsTrack added in v0.4.4

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

ProcsTrack is a thread-safe wrapper for a process Stat object's internal map of processes.

func NewProcsTrack added in v0.4.4

func NewProcsTrack() *ProcsTrack

func (*ProcsTrack) GetPid added in v0.4.4

func (pm *ProcsTrack) GetPid(pid int) (ProcState, bool)

func (*ProcsTrack) SetMap added in v0.4.4

func (pm *ProcsTrack) SetMap(pids map[int]ProcState)

func (*ProcsTrack) SetPid added in v0.4.4

func (pm *ProcsTrack) SetPid(pid int, ps ProcState)

type RootCPUFields

type RootCPUFields struct {
	StartTime string    `struct:"start_time,omitempty"`
	Pct       opt.Float `struct:"pct,omitempty"`
}

type Stats

type Stats struct {
	Hostfs        resolve.Resolver
	Procs         []string
	ProcsMap      *ProcsTrack
	CPUTicks      bool
	EnvWhitelist  []string
	CacheCmdLine  bool
	IncludeTop    IncludeTopConfig
	CgroupOpts    cgroup.ReaderOptions
	EnableCgroups bool
	EnableNetwork bool
	// NetworkMetrics is an allowlist of network metrics,
	// the names of which can be found in /proc/PID/net/snmp and /proc/PID/net/netstat
	NetworkMetrics []string
	// contains filtered or unexported fields
}

Stats stores the stats of processes on the host.

func (*Stats) FetchPids

func (procStats *Stats) FetchPids() (ProcsMap, []ProcState, error)

FetchPids is the linux implementation of FetchPids

func (*Stats) Get

func (procStats *Stats) Get() ([]mapstr.M, []mapstr.M, error)

Get fetches the configured processes and returns a list of formatted events and root ECS fields

func (*Stats) GetOne

func (procStats *Stats) GetOne(pid int) (mapstr.M, error)

GetOne fetches process data for a given PID if its name matches the regexes provided from the host.

func (*Stats) GetOneRootEvent added in v0.10.0

func (procStats *Stats) GetOneRootEvent(pid int) (mapstr.M, mapstr.M, error)

GetOneRootEvent is the same as `GetOne()` but it returns an event formatted as expected by ECS

func (*Stats) GetSelf

func (procStats *Stats) GetSelf() (ProcState, error)

GetSelf gets process info for the beat itself Be advised that if you call this method on a Stats object that was created with an alternate `Hostfs` setting, this method will return data for that pid as it exists on that hostfs. For example, if called from inside a container with a `hostfs` path for the container host, the PID in the ProcState object will be the PID as the host sees it.

func (*Stats) Init

func (procStats *Stats) Init() error

Init initializes a Stats instance. It returns errors if the provided process regexes cannot be compiled.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL