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" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"syscall" "syscall"
"time" "time"
@ -181,8 +182,16 @@ func ParseIDMapping(UIDMapSlice, GIDMapSlice []string, subUIDMap, subGIDMap stri
return &options, nil return &options, nil
} }
var (
rootlessRuntimeDirOnce sync.Once
rootlessRuntimeDir string
)
// GetRootlessRuntimeDir returns the runtime directory when running as non root // GetRootlessRuntimeDir returns the runtime directory when running as non root
func GetRootlessRuntimeDir() (string, error) { func GetRootlessRuntimeDir() (string, error) {
var rootlessRuntimeDirError error
rootlessRuntimeDirOnce.Do(func() {
runtimeDir := os.Getenv("XDG_RUNTIME_DIR") runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
uid := fmt.Sprintf("%d", rootless.GetRootlessUID()) uid := fmt.Sprintf("%d", rootless.GetRootlessUID())
if runtimeDir == "" { if runtimeDir == "" {
@ -204,15 +213,23 @@ func GetRootlessRuntimeDir() (string, error) {
if runtimeDir == "" { if runtimeDir == "" {
home := os.Getenv("HOME") home := os.Getenv("HOME")
if 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) resolvedHome, err := filepath.EvalSymlinks(home)
if err != nil { 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") 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 // GetRootlessDirInfo returns the parent path of where the storage for containers and