Skip to content

Commit

Permalink
perf(proctree): remove stat call
Browse files Browse the repository at this point in the history
Calling stat on /proc/<pid> would only increase the window for
process termination between the stat call and the read of the file.

This also replaces fmt.Sprintf with string concatenation and
strconv.FormatInt for better performance.
  • Loading branch information
geyslan committed Feb 4, 2025
1 parent 31937e6 commit 9a53e02
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions pkg/proctree/proctree_procfs.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package proctree

import (
"fmt"
"math"
"os"
"strconv"
"sync"
"time"

Expand Down Expand Up @@ -128,12 +128,12 @@ func dealWithProc(pt *ProcessTree, givenPid int32) error {
},
)
if err != nil {
return errfmt.Errorf("%v", err)
return errfmt.WrapError(err)
}

status, err := proc.NewProcStatus(givenPid)
if err != nil {
return errfmt.Errorf("%v", err)
return errfmt.WrapError(err)
}
if status.GetPid() != status.GetTgid() {
return errfmt.Errorf("invalid process") // sanity check (process, not thread)
Expand Down Expand Up @@ -226,12 +226,12 @@ func dealWithThread(pt *ProcessTree, givenPid, givenTid int32) error {
},
)
if err != nil {
return errfmt.Errorf("%v", err)
return errfmt.WrapError(err)
}

status, err := proc.NewThreadProcStatus(givenPid, givenTid)
if err != nil {
return errfmt.Errorf("%v", err)
return errfmt.WrapError(err)
}

name := status.GetName()
Expand Down Expand Up @@ -308,38 +308,43 @@ func dealWithThread(pt *ProcessTree, givenPid, givenTid int32) error {

// dealWithProcFsEntry deals with a process from procfs.
func dealWithProcFsEntry(pt *ProcessTree, givenPid int32) error {
_, err := os.Stat(fmt.Sprintf("/proc/%v", givenPid))
if os.IsNotExist(err) {
return errfmt.Errorf("could not find process %v", givenPid)
}

err = dealWithProc(pt, givenPid) // run for the given process
err := dealWithProc(pt, givenPid) // run for the given process
if err != nil {
if os.IsNotExist(err) {
err = nil // ignore non-existent processes
}
if debugMsgs {
logger.Debugw("dealWithProc", "pid", givenPid, "err", err)
}

return err
}

taskPath := fmt.Sprintf("/proc/%v/task", givenPid)
taskPath := "/proc/" + strconv.FormatInt(int64(givenPid), 10) + "/task"
taskDirs, err := os.ReadDir(taskPath)
if err != nil {
return err
}

for _, taskDir := range taskDirs {
if !taskDir.IsDir() {
continue
}

tid, err := proc.ParseInt32(taskDir.Name())
if err != nil {
continue
}

err = dealWithThread(pt, givenPid, tid) // run for all threads of the given process
if err != nil {
if os.IsNotExist(err) {
err = nil // ignore non-existent threads
}
if debugMsgs {
logger.Debugw("dealWithThread", "pid", givenPid, "tid", tid, "err", err)
}

continue
}
}
Expand Down

0 comments on commit 9a53e02

Please sign in to comment.