Skip to content

Commit

Permalink
libct/userns: implement RunningInUserNS with sync.OnceValue
Browse files Browse the repository at this point in the history
Now that we dropped support for go < 1.21, we can use this; moving
the sync.once out of the runningInUserNS() implementation would also
allow for it to be more easily tested if we'd decide to.

Signed-off-by: Sebastiaan van Stijn <[email protected]>
  • Loading branch information
thaJeztah committed Jul 24, 2024
1 parent bc0de32 commit bc3a8a5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 27 deletions.
2 changes: 1 addition & 1 deletion user/userns/userns.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ package userns
// user namespace and memoizes the result. It returns false on non-Linux
// platforms.
func RunningInUserNS() bool {
return runningInUserNS()
return inUserNS()
}
36 changes: 15 additions & 21 deletions user/userns/userns_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,26 @@ import (
"sync"
)

var (
inUserNS bool
nsOnce sync.Once
)
var inUserNS = sync.OnceValue(runningInUserNS)

// runningInUserNS detects whether we are currently running in a user namespace.
//
// Originally copied from https://github.com/lxc/incus/blob/e45085dd42f826b3c8c3228e9733c0b6f998eafe/shared/util.go#L678-L700.
func runningInUserNS() bool {
nsOnce.Do(func() {
file, err := os.Open("/proc/self/uid_map")
if err != nil {
// This kernel-provided file only exists if user namespaces are supported.
return
}
defer file.Close()

buf := bufio.NewReader(file)
l, _, err := buf.ReadLine()
if err != nil {
return
}

inUserNS = uidMapInUserNS(string(l))
})
return inUserNS
file, err := os.Open("/proc/self/uid_map")
if err != nil {
// This kernel-provided file only exists if user namespaces are supported.
return false
}
defer file.Close()

buf := bufio.NewReader(file)
l, _, err := buf.ReadLine()
if err != nil {
return false
}

return uidMapInUserNS(string(l))
}

func uidMapInUserNS(uidMap string) bool {
Expand Down
7 changes: 2 additions & 5 deletions user/userns/userns_unsupported.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,5 @@

package userns

// runningInUserNS is a stub for non-Linux systems
// Always returns false
func runningInUserNS() bool {
return false
}
// inUserNS is a stub for non-Linux systems. Always returns false.
func inUserNS() bool { return false }

0 comments on commit bc3a8a5

Please sign in to comment.