Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 90 additions & 22 deletions discover/discovery_fd.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,71 @@ import (
// sufficies to only iterate the process fd entries, leaving out the copies in
// the task fd entries.
func discoverFromFd(t species.NamespaceType, procfs string, result *Result) {
if !result.Options.ScanFds && !result.Options.DiscoverSocketProcesses {
if !result.Options.ScanFds && !result.Options.DiscoverSocketProcesses &&
len(result.Options.fdCallbacks) == 0 {
slog.Info("skipping discovery of fd-referenced namespaces and socket processes")
return
}
switch {
case result.Options.ScanFds:
slog.Debug("discovering fd-referenced namespaces and socket processes")
default:
case result.Options.DiscoverSocketProcesses:
slog.Debug("discovering socket processes")
default:
slog.Debug("scanning fds for callbacks")
}
scanFd(t, procfs, false, result)
// don't keep callbacks (and whatever they reference) alive with the result.
result.Options.fdCallbacks = nil
}

// FdEntry describes an open file descriptor of a process, as passed to an
// [FdCallback] during discovery. An FdEntry is only valid for the duration of
// the callback.
type FdEntry struct {
Process *model.Process // process owning the file descriptor.
Fd int // file descriptor number in the owning process.
Target string // link target, such as "socket:[123]" or "/dev/net/tun".
scan *fdScanProcess
}

// PidFd returns a PID file descriptor for the owning process, suitable for
// [unix.PidfdGetfd]. The PID fd is shared with the discovery and opened only on
// demand; the caller must neither close nor retain it beyond the callback.
func (e FdEntry) PidFd() (int, error) {
if e.scan == nil {
return -1, unix.EBADF
}
return e.scan.pidFd()
}

// FdCallback gets called during discovery for each open file descriptor of
// each discovered process, see [WithFdCallback].
type FdCallback func(FdEntry)

// fdScanProcess is the per-process state of an fd scan, sharing an on-demand
// PID fd between the FdEntries of a process and the socket inspection.
type fdScanProcess struct {
pid model.PIDType
pidfd int // -1 if not opened (yet).
}

func (p *fdScanProcess) pidFd() (int, error) {
if p.pidfd < 0 {
fd, err := unix.PidfdOpen(int(p.pid), 0)
if err != nil {
return -1, err
}
p.pidfd = fd
}
return p.pidfd, nil
}

func (p *fdScanProcess) close() {
if p.pidfd >= 0 {
_ = unix.Close(p.pidfd)
p.pidfd = -1
}
}

const socketPrefix = "socket:["
Expand All @@ -73,20 +127,26 @@ const socketPrefixLen = len(socketPrefix)
func scanFd(_ species.NamespaceType, procfs string, fakeprocfs bool, result *Result) {
debugEnabled := slog.Default().Enabled(context.Background(), slog.LevelDebug)

result.SocketProcessMap = SocketProcesses{}
/* shorthand */ scanFds := result.Options.ScanFds
/* shorthand */
scanFds := result.Options.ScanFds
/* shorthand */ fdCallbacks := result.Options.fdCallbacks
wantSockets := scanFds || result.Options.DiscoverSocketProcesses
if wantSockets {
result.SocketProcessMap = SocketProcesses{}
}
// Iterate over all known processes, and then over all of their open file
// descriptors. The /proc filesystem will give us the required
// information.
total := 0
pidfd := 0 // grudingly accepting zero albeit being a valid fd, sigh.
var scanproc *fdScanProcess
defer func() {
// ensure to not leak a process fd in any case.
if pidfd > 0 {
_ = unix.Close(pidfd)
if scanproc != nil {
scanproc.close()
}
}()
for pid := range result.Processes {
for pid, proc := range result.Processes {
scanproc = &fdScanProcess{pid: pid, pidfd: -1}
// concatenating strings in combination with strconv.Itoa is roughly
// 2.3× faster than to fmt.Sprintf, so its worth any minor inconvenience
// anyway. (Intel Core i5 with amd64 architecture)
Expand Down Expand Up @@ -120,6 +180,17 @@ func scanFd(_ species.NamespaceType, procfs string, fakeprocfs bool, result *Res
if err != nil {
continue
}
if len(fdCallbacks) > 0 {
if fdno, err := strconv.Atoi(fdEntry.Name()); err == nil {
entry := FdEntry{Process: proc, Fd: fdno, Target: fdDestination, scan: scanproc}
for _, fdCallback := range fdCallbacks {
fdCallback(entry)
}
}
}
if !wantSockets {
continue
}
var nsid species.NamespaceID
var nstype species.NamespaceType
var nsr relations.Relation
Expand All @@ -141,16 +212,14 @@ func scanFd(_ species.NamespaceType, procfs string, fakeprocfs bool, result *Res
continue
}
// So the calling explorer really wants to discover network
// namespaces from sockets. If we haven't done yet for this
// process, get a PID fd so we can later duplicate the
// processes's fd into our process for further inspection.
if pidfd <= 0 {
pidfd, err = unix.PidfdOpen(int(pid), 0)
if err != nil {
continue
}
// namespaces from sockets. Get the (shared) PID fd so we can
// duplicate the processes's fd into our process for further
// inspection.
procPidfd, err := scanproc.pidFd()
if err != nil {
continue
}
nsid, nstype = namespaceOfSocket(pidfd, fdEntry.Name())
nsid, nstype = namespaceOfSocket(procPidfd, fdEntry.Name())
if nstype == species.NaNS {
continue
}
Expand Down Expand Up @@ -191,16 +260,15 @@ func scanFd(_ species.NamespaceType, procfs string, fakeprocfs bool, result *Res
}
// Release the process fd as we don't need it anymore because we're
// progressing to the next process in our list.
if pidfd > 0 {
_ = unix.Close(pidfd)
pidfd = 0
}
scanproc.close()
}
if scanFds {
slog.Info("found namespaces",
slog.String("src", "fd"), slog.Int("count", total))
}
slog.Info("found sockets", slog.Int("count", len(result.SocketProcessMap)))
if wantSockets {
slog.Info("found sockets", slog.Int("count", len(result.SocketProcessMap)))
}
}

// namespaceOfSocket returns the network namespace a particular socket fd (of
Expand Down
46 changes: 46 additions & 0 deletions discover/discovery_fd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,50 @@ read # wait for test to proceed()
sockstat.Ino, ConsistOf(model.PIDType(os.Getpid()))))
})

It("calls back for open fds of processes", func() {
f := Successful(os.CreateTemp("", "lxkns-test-"))
DeferCleanup(os.Remove, f.Name())
DeferCleanup(f.Close)
var fstat unix.Stat_t
Expect(unix.Fstat(int(f.Fd()), &fstat)).To(Succeed())

ourpid := model.PIDType(os.Getpid())
var targets, others []string
var dupstat unix.Stat_t
_ = Namespaces(
WithFdCallback(func(e FdEntry) {
if e.Process.PID != ourpid || e.Fd != int(f.Fd()) {
return
}
targets = append(targets, e.Target)
dupfd := Successful(unix.PidfdGetfd(Successful(e.PidFd()), e.Fd, 0))
defer func() { _ = unix.Close(dupfd) }()
Expect(unix.Fstat(dupfd, &dupstat)).To(Succeed())
}),
WithFdCallback(nil),
WithFdCallback(func(e FdEntry) {
if e.Process.PID == ourpid && e.Fd == int(f.Fd()) {
others = append(others, e.Target)
}
}))
Expect(targets).To(ConsistOf(f.Name()))
Expect(others).To(Equal(targets))
Expect(dupstat.Ino).To(Equal(fstat.Ino))
})

It("doesn't change the result when only calling back for fds", func() {
called := false
allns := Namespaces(WithFdCallback(func(FdEntry) { called = true }))
Expect(called).To(BeTrue())
Expect(allns.SocketProcessMap).To(BeNil())
Expect(allns.Options.fdCallbacks).To(BeNil())
for _, nsmap := range allns.Namespaces {
Expect(nsmap).To(BeEmpty())
}

pidfd, err := FdEntry{}.PidFd()
Expect(err).To(MatchError(unix.EBADF))
Expect(pidfd).To(Equal(-1))
})

})
18 changes: 18 additions & 0 deletions discover/discovery_opt.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type DiscoverOpts struct {
Labels map[string]string `json:"labels"` // Pass options (in form of labels) to decorators

Containerizer containerizer.Containerizer `json:"-"` // Discover containers using containerizer.
fdCallbacks []FdCallback // called for each open fd of each process.

withPIDmap bool `json:"-"` // create a PID translator.
}
Expand Down Expand Up @@ -223,6 +224,23 @@ func WithoutSocketProcesses() DiscoveryOption {
return func(o *DiscoverOpts) { o.DiscoverSocketProcesses = false }
}

// WithFdCallback registers fn to be called for each open file descriptor of
// each discovered process, implicitly enabling scanning the file descriptors
// of processes. It can be specified multiple times to register multiple
// callbacks.
//
// The callbacks get called synchronously and in sequence from the discovering
// goroutine, before containers are discovered, so they must not block. As the
// file descriptors are only a snapshot, they might already be closed or even
// reused when the callback acts upon them.
func WithFdCallback(fn FdCallback) DiscoveryOption {
return func(o *DiscoverOpts) {
if fn != nil {
o.fdCallbacks = append(o.fdCallbacks, fn)
}
}
}

// WithLabel adds a key-value pair to the discovery options.
func WithLabel(key, value string) DiscoveryOption {
return func(o *DiscoverOpts) {
Expand Down
Loading