Skip to content

Commit 0688288

Browse files
committed
contrib/fs-idmap: Move logic to a new function
We can't call log.Fatalf() and defer functions, as the former doesn't call any defers. Let's just move the code to a new function and call os.Exit() only in main, when all defer executed. Now that all the code is one function, we only print twice to stderr. It is simpler to just print to stderr instead of logging and having also the timestamp we don't really want. Signed-off-by: Rodrigo Campos <[email protected]>
1 parent 855c5a0 commit 0688288

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

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

Lines changed: 15 additions & 8 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"
@@ -12,13 +11,20 @@ import (
1211

1312
func main() {
1413
if len(os.Args) != 2 {
15-
log.Fatalf("usage: %s path_to_mount_set_attr", os.Args[0])
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]
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 {
1925
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

@@ -29,7 +35,7 @@ func main() {
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
}
3440
defer func() {
3541
_ = cmd.Process.Kill()
@@ -39,8 +45,7 @@ func main() {
3945
path := fmt.Sprintf("/proc/%d/ns/user", cmd.Process.Pid)
4046
var userNsFile *os.File
4147
if userNsFile, err = os.Open(path); err != nil {
42-
log.Fatalf("unable to get user ns file descriptor: %v", err)
43-
return
48+
return fmt.Errorf("unable to get user ns file descriptor: %w", err)
4449
}
4550
defer userNsFile.Close()
4651

@@ -49,6 +54,8 @@ func main() {
4954
Userns_fd: uint64(userNsFile.Fd()),
5055
}
5156
if err := unix.MountSetattr(treeFD, "", unix.AT_EMPTY_PATH, &attr); err != nil {
52-
log.Fatalf("error calling mount_setattr: %v", err)
57+
return fmt.Errorf("error calling mount_setattr: %w", err)
5358
}
59+
60+
return nil
5461
}

0 commit comments

Comments
 (0)