Cache shim v2 exec.LookPath results

Signed-off-by: Justin Terry (VM) <juterry@microsoft.com>
This commit is contained in:
Justin Terry (VM)
2018-11-27 15:11:04 -08:00
parent 3eae8b9c3f
commit 09bf314bfd
3 changed files with 53 additions and 13 deletions

View File

@@ -24,6 +24,7 @@ import (
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/containerd/containerd/namespaces"
@@ -32,6 +33,8 @@ import (
const shimBinaryFormat = "containerd-shim-%s-%s"
var runtimePaths sync.Map
// Command returns the shim command with the provided args and configuration
func Command(ctx context.Context, runtime, containerdAddress, path string, cmdArgs ...string) (*exec.Cmd, error) {
ns, err := namespaces.NamespaceRequired(ctx)
@@ -52,19 +55,30 @@ func Command(ctx context.Context, runtime, containerdAddress, path string, cmdAr
if name == "" {
return nil, fmt.Errorf("invalid runtime name %s, correct runtime name should format like io.containerd.runc.v1", runtime)
}
var cmdPath string
var lerr error
if cmdPath, lerr = exec.LookPath(name); lerr != nil {
if eerr, ok := lerr.(*exec.Error); ok {
if eerr.Err == exec.ErrNotFound {
return nil, errors.Wrapf(os.ErrNotExist, "runtime %q binary not installed %q", runtime, name)
cmdPathI, cmdPathFound := runtimePaths.Load(name)
if cmdPathFound {
cmdPath = cmdPathI.(string)
} else {
var lerr error
if cmdPath, lerr = exec.LookPath(name); lerr != nil {
if eerr, ok := lerr.(*exec.Error); ok {
if eerr.Err == exec.ErrNotFound {
return nil, errors.Wrapf(os.ErrNotExist, "runtime %q binary not installed %q", runtime, name)
}
}
}
cmdPath, err = filepath.Abs(cmdPath)
if err != nil {
return nil, err
}
if cmdPathI, cmdPathFound = runtimePaths.LoadOrStore(name, cmdPath); cmdPathFound {
// We didn't store cmdPath we loaded an already cached value. Use it.
cmdPath = cmdPathI.(string)
}
}
cmdPath, err = filepath.Abs(cmdPath)
if err != nil {
return nil, err
}
cmd := exec.Command(cmdPath, args...)
cmd.Dir = path
cmd.Env = append(os.Environ(), "GOMAXPROCS=2")