From 0688288876deb45cba0a9bb3f87798aaf5a6d676 Mon Sep 17 00:00:00 2001 From: Rodrigo Campos Date: Tue, 1 Aug 2023 16:33:23 +0200 Subject: [PATCH] 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 --- contrib/cmd/fs-idmap/fs-idmap.go | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/contrib/cmd/fs-idmap/fs-idmap.go b/contrib/cmd/fs-idmap/fs-idmap.go index 71971056d..4593490f3 100644 --- a/contrib/cmd/fs-idmap/fs-idmap.go +++ b/contrib/cmd/fs-idmap/fs-idmap.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "log" "os" "os/exec" "syscall" @@ -12,13 +11,20 @@ import ( func main() { if len(os.Args) != 2 { - log.Fatalf("usage: %s path_to_mount_set_attr", os.Args[0]) + fmt.Fprintln(os.Stderr, "usage:", os.Args[0], "path_to_mount_set_attr") + os.Exit(1) } - src := os.Args[1] + if err := supportsIDMap(src); err != nil { + fmt.Fprintln(os.Stderr, "fatal error:", err) + os.Exit(1) + } +} + +func supportsIDMap(src string) error { treeFD, err := unix.OpenTree(unix.AT_FDCWD, src, uint(unix.OPEN_TREE_CLONE|unix.OPEN_TREE_CLOEXEC|unix.AT_EMPTY_PATH)) if err != nil { - log.Fatalf("error calling open_tree %q: %v", src, err) + return fmt.Errorf("error calling open_tree %q: %w", src, err) } defer unix.Close(treeFD) @@ -29,7 +35,7 @@ func main() { GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: 65536, Size: 65536}}, } if err := cmd.Start(); err != nil { - log.Fatalf("failed to run the helper binary: %v", err) + return fmt.Errorf("failed to run the helper binary: %w", err) } defer func() { _ = cmd.Process.Kill() @@ -39,8 +45,7 @@ func main() { path := fmt.Sprintf("/proc/%d/ns/user", cmd.Process.Pid) var userNsFile *os.File if userNsFile, err = os.Open(path); err != nil { - log.Fatalf("unable to get user ns file descriptor: %v", err) - return + return fmt.Errorf("unable to get user ns file descriptor: %w", err) } defer userNsFile.Close() @@ -49,6 +54,8 @@ func main() { Userns_fd: uint64(userNsFile.Fd()), } if err := unix.MountSetattr(treeFD, "", unix.AT_EMPTY_PATH, &attr); err != nil { - log.Fatalf("error calling mount_setattr: %v", err) + return fmt.Errorf("error calling mount_setattr: %w", err) } + + return nil }