Skip to content

Commit 15b2c76

Browse files
authored
Merge pull request #86 from coroot/process_lazy_netns
process: implement lazy retrieval of network namespace
2 parents 97d36da + 4d233eb commit 15b2c76

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

containers/container.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -922,7 +922,7 @@ func (c *Container) gc(now time.Time) {
922922
listens := map[netaddr.IPPort]string{}
923923
seenNamespaces := map[string]bool{}
924924
for _, p := range c.processes {
925-
if seenNamespaces[p.NetNsId] {
925+
if seenNamespaces[p.NetNsId()] {
926926
continue
927927
}
928928
sockets, err := proc.GetSockets(p.Pid)
@@ -937,7 +937,7 @@ func (c *Container) gc(now time.Time) {
937937
establishedDst[s.DAddr] = struct{}{}
938938
}
939939
}
940-
seenNamespaces[p.NetNsId] = true
940+
seenNamespaces[p.NetNsId()] = true
941941
}
942942

943943
for ns := range c.ipsByNs {

containers/process.go

+16-8
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ import (
1515
type Process struct {
1616
Pid uint32
1717
StartedAt time.Time
18-
NetNsId string
18+
19+
netNsId string
1920

2021
ctx context.Context
2122
cancelFunc context.CancelFunc
@@ -28,19 +29,26 @@ type Process struct {
2829
}
2930

3031
func NewProcess(pid uint32, stats *taskstats.Stats) *Process {
31-
ns, err := proc.GetNetNs(pid)
32-
if err != nil {
33-
return nil
34-
}
35-
defer ns.Close()
36-
p := &Process{Pid: pid, StartedAt: stats.BeginTime, NetNsId: ns.UniqueId()}
32+
p := &Process{Pid: pid, StartedAt: stats.BeginTime}
3733
p.ctx, p.cancelFunc = context.WithCancel(context.Background())
3834
go p.instrument()
3935
return p
4036
}
4137

38+
func (p *Process) NetNsId() string {
39+
if p.netNsId == "" {
40+
ns, err := proc.GetNetNs(p.Pid)
41+
if err != nil {
42+
return ""
43+
}
44+
p.netNsId = ns.UniqueId()
45+
_ = ns.Close()
46+
}
47+
return p.netNsId
48+
}
49+
4250
func (p *Process) isHostNs() bool {
43-
return p.NetNsId == hostNetNsId
51+
return p.NetNsId() == hostNetNsId
4452
}
4553

4654
func (p *Process) instrument() {

0 commit comments

Comments
 (0)