@@ -20,34 +20,43 @@ import (
2020 "bufio"
2121 "fmt"
2222 "os"
23+ "sync"
24+ )
25+
26+ var (
27+ inUserNS bool
28+ nsOnce sync.Once
2329)
2430
2531// RunningInUserNS detects whether we are currently running in a user namespace.
2632// Originally copied from github.com/lxc/lxd/shared/util.go
2733func RunningInUserNS () bool {
28- file , err := os .Open ("/proc/self/uid_map" )
29- if err != nil {
30- // This kernel-provided file only exists if user namespaces are supported
31- return false
32- }
33- defer file .Close ()
34-
35- buf := bufio .NewReader (file )
36- l , _ , err := buf .ReadLine ()
37- if err != nil {
38- return false
39- }
40-
41- line := string (l )
42- var a , b , c int64
43- fmt .Sscanf (line , "%d %d %d" , & a , & b , & c )
44-
45- /*
46- * We assume we are in the initial user namespace if we have a full
47- * range - 4294967295 uids starting at uid 0.
48- */
49- if a == 0 && b == 0 && c == 4294967295 {
50- return false
51- }
52- return true
34+ nsOnce .Do (func () {
35+ file , err := os .Open ("/proc/self/uid_map" )
36+ if err != nil {
37+ // This kernel-provided file only exists if user namespaces are supported
38+ return
39+ }
40+ defer file .Close ()
41+
42+ buf := bufio .NewReader (file )
43+ l , _ , err := buf .ReadLine ()
44+ if err != nil {
45+ return
46+ }
47+
48+ line := string (l )
49+ var a , b , c int64
50+ fmt .Sscanf (line , "%d %d %d" , & a , & b , & c )
51+
52+ /*
53+ * We assume we are in the initial user namespace if we have a full
54+ * range - 4294967295 uids starting at uid 0.
55+ */
56+ if a == 0 && b == 0 && c == 4294967295 {
57+ return
58+ }
59+ inUserNS = true
60+ })
61+ return inUserNS
5362}
0 commit comments