X Tutup
Skip to content

Commit 0088c2d

Browse files
committed
sys: RunningInUserNS(): use sync.Once
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent 76c62f2 commit 0088c2d

File tree

2 files changed

+35
-37
lines changed

2 files changed

+35
-37
lines changed

archive/tar_unix.go

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import (
2222
"archive/tar"
2323
"os"
2424
"strings"
25-
"sync"
2625
"syscall"
2726

2827
"github.com/containerd/containerd/sys"
@@ -84,21 +83,11 @@ func mkdir(path string, perm os.FileMode) error {
8483
return os.Chmod(path, perm)
8584
}
8685

87-
var (
88-
inUserNS bool
89-
nsOnce sync.Once
90-
)
91-
92-
func setInUserNS() {
93-
inUserNS = sys.RunningInUserNS()
94-
}
95-
9686
func skipFile(hdr *tar.Header) bool {
9787
switch hdr.Typeflag {
9888
case tar.TypeBlock, tar.TypeChar:
9989
// cannot create a device if running in user namespace
100-
nsOnce.Do(setInUserNS)
101-
return inUserNS
90+
return sys.RunningInUserNS()
10291
default:
10392
return false
10493
}

sys/userns_linux.go

Lines changed: 34 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -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
2733
func 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

Comments
 (0)
X Tutup