Improve getting process group leader

This commit is contained in:
Daniel
2023-12-21 13:17:05 +01:00
parent 30fee07a89
commit 425a0bed4c
12 changed files with 217 additions and 156 deletions

View File

@@ -30,21 +30,26 @@ type Process struct {
// Process attributes.
// Don't change; safe for concurrent access.
Name string
UserID int
UserName string
UserHome string
Pid int
Pgid int // linux only
CreatedAt int64
Name string
UserID int
UserName string
UserHome string
Pid int
CreatedAt int64
ParentPid int
ParentCreatedAt int64
Path string
ExecName string
Cwd string
CmdLine string
FirstArg string
Env map[string]string
LeaderPid int
leader *Process
Path string
ExecName string
Cwd string
CmdLine string
FirstArg string
Env map[string]string
// unique process identifier ("Pid-CreatedAt")
processKey string
@@ -92,6 +97,16 @@ func (p *Process) Profile() *profile.LayeredProfile {
return p.profile
}
// Leader returns the process group leader that is attached to the process.
// This will not trigger a new search for the process group leader, it only
// returns existing data.
func (p *Process) Leader() *Process {
p.Lock()
defer p.Unlock()
return p.leader
}
// IsIdentified returns whether the process has been identified or if it
// represents some kind of unidentified process.
func (p *Process) IsIdentified() bool {
@@ -213,12 +228,9 @@ func loadProcess(ctx context.Context, key string, pInfo *processInfo.Process) (*
return process, nil
}
pgid, _ := GetProcessGroupID(ctx, int(pInfo.Pid))
// Create new a process object.
process = &Process{
Pid: int(pInfo.Pid),
Pgid: pgid,
FirstSeen: time.Now().Unix(),
processKey: key,
}
@@ -250,7 +262,7 @@ func loadProcess(ctx context.Context, key string, pInfo *processInfo.Process) (*
// TODO: User Home
// new.UserHome, err =
// Parent process id
// Parent process ID
ppid, err := pInfo.PpidWithContext(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get PPID for p%d: %w", pInfo.Pid, err)
@@ -267,6 +279,19 @@ func loadProcess(ctx context.Context, key string, pInfo *processInfo.Process) (*
process.ParentCreatedAt = parentCreatedAt
}
// Leader process ID
// Get process group ID to find group leader, which is the process "nearest"
// to the user and will have more/better information for finding names and
// icons, for example.
leaderPid, err := GetProcessGroupID(ctx, process.Pid)
if err != nil {
// Fail gracefully.
log.Warningf("process: failed to get process group ID for p%d: %s", process.Pid, err)
process.LeaderPid = UndefinedProcessID
} else {
process.LeaderPid = leaderPid
}
// Path
process.Path, err = pInfo.ExeWithContext(ctx)
if err != nil {