utils: call GetRootlessRuntimeDir once
use a sync.Once to potentially avoid multiple system calls everytime
the function is called.
@@ -5,6 +5,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"syscall"
"time"
@@ -181,8 +182,16 @@ func ParseIDMapping(UIDMapSlice, GIDMapSlice []string, subUIDMap, subGIDMap stri
return &options, nil
}
+var (
+ rootlessRuntimeDirOnce sync.Once
+ rootlessRuntimeDir string
+)
+
// GetRootlessRuntimeDir returns the runtime directory when running as non root
func GetRootlessRuntimeDir() (string, error) {
+ var rootlessRuntimeDirError error
+
+ rootlessRuntimeDirOnce.Do(func() {
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
uid := fmt.Sprintf("%d", rootless.GetRootlessUID())
if runtimeDir == "" {
@@ -204,15 +213,23 @@ func GetRootlessRuntimeDir() (string, error) {
if runtimeDir == "" {
home := os.Getenv("HOME")
if home == "" {
- return "", fmt.Errorf("neither XDG_RUNTIME_DIR nor HOME was set non-empty")
+ rootlessRuntimeDirError = fmt.Errorf("neither XDG_RUNTIME_DIR nor HOME was set non-empty")
+ return
}
resolvedHome, err := filepath.EvalSymlinks(home)
if err != nil {
- return "", errors.Wrapf(err, "cannot resolve %s", home)
+ rootlessRuntimeDirError = errors.Wrapf(err, "cannot resolve %s", home)
+ return
}
runtimeDir = filepath.Join(resolvedHome, "rundir")
}
- return runtimeDir, nil
+ rootlessRuntimeDir = runtimeDir
+ })
+
+ if rootlessRuntimeDirError != nil {
+ return "", rootlessRuntimeDirError
+ }
+ return rootlessRuntimeDir, nil
}
// GetRootlessDirInfo returns the parent path of where the storage for containers and
