diff --git a/internal/proc/listing.go b/internal/proc/listing.go index 224f19c91..3ed15c8a7 100644 --- a/internal/proc/listing.go +++ b/internal/proc/listing.go @@ -6,6 +6,7 @@ import ( "os/exec" "path/filepath" "runtime" + "slices" "strings" "sync" "time" @@ -155,10 +156,20 @@ func pathDirs() []string { // lookPath is exec.LookPath, with a command no folder of PATH has a name // for answered as not found without looking. +// A folder of PATH that doesn't answer (reach.go) is left out: the +// command is looked for in the others, each as a path. func lookPath(name string) (string, error) { - if !mayBeIn(name, pathDirs()) { + dirs := pathDirs() + hung := hungDirs(dirs) + if hung != nil { + dirs = slices.DeleteFunc(slices.Clone(dirs), func(d string) bool { return hung[d] }) + } + if !mayBeIn(name, dirs) { return "", &exec.Error{Name: name, Err: exec.ErrNotFound} } + if hung != nil && !strings.ContainsAny(name, `/\`) { + return lookIn(name, dirs) + } return execLookPath(name) } diff --git a/internal/proc/look.go b/internal/proc/look.go index bebc59a9d..63340862e 100644 --- a/internal/proc/look.go +++ b/internal/proc/look.go @@ -148,12 +148,18 @@ func lookStamp() (string, bool) { b.WriteString(os.Getenv("PATHEXT")) dirs := filepath.SplitList(os.Getenv("PATH")) dirs = append(dirs, findDirs()...) + hung := hungDirs(dirs) for _, d := range dirs { if d == "" { continue } b.WriteByte(0) b.WriteString(d) + if hung[d] { + // not asked (reach.go); the stamp changes once it answers + b.WriteString("!") + continue + } if st, err := os.Stat(d); err == nil { b.WriteByte('@') b.WriteString(strconv.FormatInt(st.ModTime().UnixNano(), 36)) diff --git a/internal/proc/path_other.go b/internal/proc/path_other.go index 428da751a..4902f5385 100644 --- a/internal/proc/path_other.go +++ b/internal/proc/path_other.go @@ -5,7 +5,6 @@ package proc import ( "context" "os" - "os/exec" "path/filepath" "slices" "strings" @@ -315,7 +314,7 @@ func FindShell(name string) string { } } } - p, _ := exec.LookPath(name) + p, _ := Look(name) return p } diff --git a/internal/proc/reach.go b/internal/proc/reach.go new file mode 100644 index 000000000..a697f4934 --- /dev/null +++ b/internal/proc/reach.go @@ -0,0 +1,176 @@ +package proc + +import ( + "os" + "os/exec" + "path/filepath" + "sync" + "time" +) + +// A folder on PATH on a mount that no longer answers (a network share +// gone away, an autofs path whose server is down) holds every stat and +// open in it until the mount comes back, which can be never. Looking a +// command up walks PATH in order, so a command not found before such a +// folder blocked whoever asked: magpie's start-up asks for every agent's +// command (agent.RenameLegacy → vscodePortableData → code-insiders), and +// `open -a` took over a minute to start while the same binary run from a +// shell, with another PATH, took one second (ifccod7391564 on X). A PATH +// folder is now asked in a goroutine of its own first, and one that +// hasn't answered in reachWait is left out of every look until it does. + +// reachWait is how long a PATH folder has to answer; reachKeep how long +// its answer is trusted before it is asked again. +var ( + reachWait = time.Second + reachKeep = time.Minute +) + +// probeDir is the asking: a stat and an open of the folder, as a lookup +// does. Whatever either answers, the folder answered. A var for the tests. +var probeDir = func(dir string) { + if st, err := os.Stat(dir); err == nil && st.IsDir() { + if f, err := os.Open(dir); err == nil { + f.Close() + } + } +} + +var reach struct { + sync.Mutex + m map[string]*reachProbe +} + +type reachProbe struct { + done chan struct{} + deadline time.Time // when a probe not done counts as hung + at time.Time // when it answered, set before done closes +} + +// answers reports whether dir answers within reachWait. A probe still out +// past its deadline isn't started again: every look leaves the folder out +// at once until that probe returns. +func answers(dir string) bool { + if dir == "" { + return true + } + now := time.Now() + reach.Lock() + p := reach.m[dir] + if p != nil { + select { + case <-p.done: + if now.Sub(p.at) < reachKeep { + reach.Unlock() + return true + } + p = nil // stale: asked again below + default: + } + } + if p == nil { + p = &reachProbe{done: make(chan struct{}), deadline: now.Add(reachWait)} + if reach.m == nil { + reach.m = map[string]*reachProbe{} + } + reach.m[dir] = p + go func(p *reachProbe) { + probeDir(dir) + p.at = time.Now() + close(p.done) + }(p) + } + reach.Unlock() + wait := time.Until(p.deadline) + if wait <= 0 { + select { + case <-p.done: + return true + default: + return false + } + } + t := time.NewTimer(wait) + defer t.Stop() + select { + case <-p.done: + return true + case <-t.C: + return false + } +} + +// hungDirs are the folders of dirs that don't answer; nil when every one +// does. The folders are asked at once, so several gone mounts cost one +// reachWait, not one each. +func hungDirs(dirs []string) map[string]bool { + if allAnswered(dirs) { + return nil + } + var ( + mu sync.Mutex + hung map[string]bool + wg sync.WaitGroup + ) + for _, d := range dirs { + if d == "" { + continue + } + wg.Add(1) + go func(d string) { + defer wg.Done() + if !answers(d) { + mu.Lock() + if hung == nil { + hung = map[string]bool{} + } + hung[d] = true + mu.Unlock() + } + }(d) + } + wg.Wait() + return hung +} + +// allAnswered reports whether every folder of dirs answered within +// reachKeep, so a look asks none of them (no goroutine each). +func allAnswered(dirs []string) bool { + now := time.Now() + reach.Lock() + defer reach.Unlock() + for _, d := range dirs { + if d == "" { + continue + } + p := reach.m[d] + if p == nil { + return false + } + select { + case <-p.done: + if now.Sub(p.at) >= reachKeep { + return false + } + default: + return false + } + } + return true +} + +// lookIn is exec.LookPath over dirs alone, in their order: the command's +// name in each folder asked as a path, as exec.LookPath does along PATH. +// The current folder is left out, as exec.LookPath refuses a command +// found there (exec.ErrDot). +func lookIn(name string, dirs []string) (string, error) { + for _, d := range dirs { + if d == "" || d == "." { + continue + } + if p, err := execLookPath(filepath.Join(d, name)); err == nil { + return p, nil + } + } + return "", &exec.Error{Name: name, Err: exec.ErrNotFound} +} diff --git a/internal/proc/reach_test.go b/internal/proc/reach_test.go new file mode 100644 index 000000000..7f99debfa --- /dev/null +++ b/internal/proc/reach_test.go @@ -0,0 +1,108 @@ +package proc + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// A PATH folder on a mount that doesn't answer is left out of a look, and +// the command is found in the folders after it: a look walking PATH past +// such a folder blocked magpie's start-up for over a minute, after `open +// -a` (ifccod7391564 on X). The gone mount is a probe that doesn't return +// and a walk of PATH that reports itself; the old lookup walked it. +func TestHungPathFolderIsLeftOut(t *testing.T) { + hung, good := t.TempDir(), t.TempDir() + tool := "magpie-reach-tool" + file := tool + if runtime.GOOS == "windows" { + file += ".exe" + } + if err := os.WriteFile(filepath.Join(good, file), []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", joinList([]string{hung, good})) + t.Setenv("NoDefaultCurrentDirectoryInExePath", "1") + + release := make(chan struct{}) + var probes atomic.Int32 + oldProbe, oldWait := probeDir, reachWait + probeDir = func(d string) { + if d == hung { + probes.Add(1) + <-release + } + oldProbe(d) + } + reachWait = 200 * time.Millisecond + var once sync.Once + free := func() { once.Do(func() { close(release) }) } + resetReach := func() { + reach.Lock() + reach.m = nil + reach.Unlock() + } + resetReach() + t.Cleanup(func() { + free() + probeDir, reachWait = oldProbe, oldWait + resetReach() + }) + var walked atomic.Int32 + oldLook := execLookPath + execLookPath = func(name string) (string, error) { + if !strings.ContainsAny(name, `/\`) { + walked.Add(1) // exec.LookPath along all of PATH, the gone mount too + } + return oldLook(name) + } + t.Cleanup(func() { execLookPath = oldLook }) + + for i := 0; i < 3; i++ { + Forget() + done := make(chan struct{}) + var p string + var err error + go func() { + p, err = Look(tool) + close(done) + }() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Fatal("the look waited on the folder that doesn't answer") + } + if err != nil || filepath.Dir(p) != good { + t.Fatalf("look %d: %q, %v; want it in %s", i, p, err, good) + } + } + if n := walked.Load(); n != 0 { + t.Fatalf("PATH was walked %d times with a folder on it that doesn't answer", n) + } + // the folder is asked once while its first probe is out, not per look + if n := probes.Load(); n != 1 { + t.Fatalf("the folder was probed %d times, want 1", n) + } + + // the mount answers again: PATH is walked as it was + free() + deadline := time.Now().Add(30 * time.Second) + for !answers(hung) { + if time.Now().After(deadline) { + t.Fatal("the folder never counted as answering again") + } + time.Sleep(10 * time.Millisecond) + } + Forget() + if p, err := Look(tool); err != nil || filepath.Dir(p) != good { + t.Fatalf("after: %q, %v", p, err) + } + if walked.Load() == 0 { + t.Fatal("a PATH whose folders all answer wasn't walked as exec.LookPath does") + } +} diff --git a/internal/proc/wrapper.go b/internal/proc/wrapper.go index e58d2daf3..589c33187 100644 --- a/internal/proc/wrapper.go +++ b/internal/proc/wrapper.go @@ -13,7 +13,6 @@ import ( "bytes" "context" "os" - "os/exec" "path/filepath" "runtime" "strings" @@ -239,7 +238,7 @@ func findMise(named string) string { } } for _, n := range []string{filepath.Base(named), "mise"} { - if p, err := exec.LookPath(n); err == nil { + if p, err := Look(n); err == nil { return p } if p := toolIn(n, runtime.GOOS, UserBinDirs()); p != "" {