|
21 | 21 | package process |
22 | 22 |
|
23 | 23 | import ( |
| 24 | + "context" |
24 | 25 | "fmt" |
25 | 26 | "os" |
26 | 27 | "sort" |
27 | 28 | "strings" |
28 | 29 | "time" |
29 | 30 |
|
| 31 | + psutil "github.com/shirou/gopsutil/process" |
| 32 | + |
30 | 33 | "github.com/elastic/elastic-agent-libs/mapstr" |
31 | 34 | "github.com/elastic/elastic-agent-libs/opt" |
32 | 35 | "github.com/elastic/elastic-agent-libs/transform/typeconv" |
33 | 36 | "github.com/elastic/elastic-agent-system-metrics/metric" |
| 37 | + "github.com/elastic/elastic-agent-system-metrics/metric/system/resolve" |
34 | 38 | ) |
35 | 39 |
|
| 40 | +// ListStates is a wrapper that returns a list of processess with only the basic PID info filled out. |
| 41 | +func ListStates(hostfs resolve.Resolver) ([]ProcState, error) { |
| 42 | + init := Stats{ |
| 43 | + Hostfs: hostfs, |
| 44 | + Procs: []string{".*"}, |
| 45 | + EnableCgroups: false, |
| 46 | + skipExtended: true, |
| 47 | + } |
| 48 | + err := init.Init() |
| 49 | + if err != nil { |
| 50 | + return nil, fmt.Errorf("error initializing process collectors: %w", err) |
| 51 | + } |
| 52 | + |
| 53 | + // actually fetch the PIDs from the OS-specific code |
| 54 | + _, plist, err := init.FetchPids() |
| 55 | + if err != nil { |
| 56 | + return nil, fmt.Errorf("error gathering PIDs: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + return plist, nil |
| 60 | +} |
| 61 | + |
| 62 | +// GetPIDState returns the state of a given PID |
| 63 | +// It will return ProcNotExist if the process was not found. |
| 64 | +func GetPIDState(hostfs resolve.Resolver, pid int) (PidState, error) { |
| 65 | + // This library still doesn't have a good cross-platform way to distinguish between "does not eixst" and other process errors. |
| 66 | + // This is a fairly difficult problem to solve in a cross-platform way |
| 67 | + exists, err := psutil.PidExistsWithContext(context.Background(), int32(pid)) |
| 68 | + if err != nil { |
| 69 | + return "", fmt.Errorf("Error trying to find process: %d: %w", pid, err) |
| 70 | + } |
| 71 | + if !exists { |
| 72 | + return "", ProcNotExist |
| 73 | + } |
| 74 | + //GetInfoForPid will return the smallest possible dataset for a PID |
| 75 | + procState, err := GetInfoForPid(hostfs, pid) |
| 76 | + if err != nil { |
| 77 | + return "", fmt.Errorf("error getting state info for pid %d: %w", pid, err) |
| 78 | + } |
| 79 | + |
| 80 | + return procState.State, nil |
| 81 | +} |
| 82 | + |
36 | 83 | // Get fetches the configured processes and returns a list of formatted events and root ECS fields |
37 | 84 | func (procStats *Stats) Get() ([]mapstr.M, []mapstr.M, error) { |
38 | 85 | //If the user hasn't configured any kind of process glob, return |
|
0 commit comments