Skip to content

Commit cbf8c67

Browse files
authored
Merge pull request #3954 from kinvolk/rata/idmap-tests
contrib/fs-idmap: Minor cleanups
2 parents 534fa8e + 0688288 commit cbf8c67

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

contrib/cmd/fs-idmap/fs-idmap.go

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"fmt"
5-
"log"
65
"os"
76
"os/exec"
87
"syscall"
@@ -11,40 +10,52 @@ import (
1110
)
1211

1312
func main() {
14-
if len(os.Args) < 2 {
15-
log.Fatalf("usage: %s path_to_mount_set_attr", os.Args[0])
13+
if len(os.Args) != 2 {
14+
fmt.Fprintln(os.Stderr, "usage:", os.Args[0], "path_to_mount_set_attr")
15+
os.Exit(1)
1616
}
17-
1817
src := os.Args[1]
19-
treeFD, err := unix.OpenTree(-1, src, uint(unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC|unix.AT_EMPTY_PATH|unix.AT_RECURSIVE))
18+
if err := supportsIDMap(src); err != nil {
19+
fmt.Fprintln(os.Stderr, "fatal error:", err)
20+
os.Exit(1)
21+
}
22+
}
23+
24+
func supportsIDMap(src string) error {
25+
treeFD, err := unix.OpenTree(unix.AT_FDCWD, src, uint(unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC|unix.AT_EMPTY_PATH))
2026
if err != nil {
21-
log.Fatalf("error calling open_tree %q: %v", src, err)
27+
return fmt.Errorf("error calling open_tree %q: %w", src, err)
2228
}
2329
defer unix.Close(treeFD)
2430

25-
cmd := exec.Command("/usr/bin/sleep", "5")
31+
cmd := exec.Command("sleep", "5")
2632
cmd.SysProcAttr = &syscall.SysProcAttr{
2733
Cloneflags: syscall.CLONE_NEWUSER,
2834
UidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: 65536, Size: 65536}},
2935
GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: 65536, Size: 65536}},
3036
}
3137
if err := cmd.Start(); err != nil {
32-
log.Fatalf("failed to run the helper binary: %v", err)
38+
return fmt.Errorf("failed to run the helper binary: %w", err)
3339
}
40+
defer func() {
41+
_ = cmd.Process.Kill()
42+
_ = cmd.Wait()
43+
}()
3444

3545
path := fmt.Sprintf("/proc/%d/ns/user", cmd.Process.Pid)
3646
var userNsFile *os.File
3747
if userNsFile, err = os.Open(path); err != nil {
38-
log.Fatalf("unable to get user ns file descriptor: %v", err)
39-
return
48+
return fmt.Errorf("unable to get user ns file descriptor: %w", err)
4049
}
4150
defer userNsFile.Close()
4251

4352
attr := unix.MountAttr{
4453
Attr_set: unix.MOUNT_ATTR_IDMAP,
4554
Userns_fd: uint64(userNsFile.Fd()),
4655
}
47-
if err := unix.MountSetattr(treeFD, "", unix.AT_EMPTY_PATH|unix.AT_RECURSIVE, &attr); err != nil {
48-
log.Fatalf("error calling mount_setattr: %v", err)
56+
if err := unix.MountSetattr(treeFD, "", unix.AT_EMPTY_PATH, &attr); err != nil {
57+
return fmt.Errorf("error calling mount_setattr: %w", err)
4958
}
59+
60+
return nil
5061
}

0 commit comments

Comments
 (0)