utils: call GetRootlessRuntimeDir once

use a sync.Once to potentially avoid multiple system calls everytime
the function is called.

Signed-off-by: Giuseppe Scrivano <gscrivan@redhat.com>
This commit is contained in:
Giuseppe Scrivano 2019-03-29 11:32:02 +01:00
parent 2fa9861d78
commit ca38ca49b8
No known key found for this signature in database
GPG Key ID: E4730F97F60286ED
1 changed files with 45 additions and 28 deletions

View File

@ -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