Skip to content

Commit

Permalink
ReadEnv() minor improvement
Browse files Browse the repository at this point in the history
 - Improved peformance parsing the environment variables of a process.
 - Added ReadEnv() test.

For a 4kb environ file:

Benchmark-Old    58070 ns/op   19264 B/op   68 allocs/op
Benchmark-New    49174 ns/op   17488 B/op   12 allocs/op
  • Loading branch information
gustavo-iniguez-goya committed Oct 17, 2024
1 parent f63a48d commit ebac200
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 11 deletions.
22 changes: 13 additions & 9 deletions daemon/procmon/details.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,19 +168,23 @@ func (p *Process) ReadCwd() error {

// ReadEnv reads and parses the environment variables of a process.
func (p *Process) ReadEnv() {
data, err := ioutil.ReadFile(p.pathEnviron)
raw, err := ioutil.ReadFile(p.pathEnviron)
if err != nil {
return
}
for _, s := range strings.Split(string(data), "\x00") {
parts := strings.SplitN(core.Trim(s), "=", 2)
if parts != nil && len(parts) == 2 {
key := core.Trim(parts[0])
val := core.Trim(parts[1])
p.mu.Lock()
p.Env[key] = val
p.mu.Unlock()
raw = bytes.Trim(raw, "\r\n\t")
vars := strings.Split(string(raw), "\x00")
for _, s := range vars {
idx := strings.Index(s, "=")
if idx == -1 {
continue
}

key := s[:idx]
val := s[idx+1 : len(s)]
p.mu.Lock()
p.Env[key] = val
p.mu.Unlock()
}
}

Expand Down
30 changes: 28 additions & 2 deletions daemon/procmon/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,31 @@ func TestProcDescriptors(t *testing.T) {
}

func TestProcEnv(t *testing.T) {
proc.pathEnviron = "testdata/proc-environ"
proc.ReadEnv()

if len(proc.Env) == 0 {
t.Error("Proc Env should not be empty:", proc.Env)
expected := map[string]string{
"EMPTY": "",
"TEST1": "xxx=123",
"TEST2": "xxx=123==456",
"SSH_AGENT_PID": "4873",
"XDG_CURRENT_DESKTOP": "i3",
"USER": "opensnitch",
"HOME": "/tmp",
"XDG_DATA_DIRS": "/usr/share/gnome:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share",
"DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus",
// Test latest var
"LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;",

//"LAST": "",
}

for k, v := range expected {
if env, found := proc.Env[k]; !found || env != v {
t.Error("Proc Env error, expected", ":", v, "got:", env, "(", k, ")")
}
}

}

func TestProcIOStats(t *testing.T) {
Expand Down Expand Up @@ -113,3 +133,9 @@ func TestProcCleanPath(t *testing.T) {
t.Error("Proc cleanPath() not cleaned:", proc.Path)
}
}

func BenchmarkProcReadEnv(b *testing.B) {
for i := 0; i < b.N; i++ {
proc.ReadEnv()
}
}
Binary file added daemon/procmon/testdata/proc-environ
Binary file not shown.

0 comments on commit ebac200

Please sign in to comment.