High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(e2e-runner): bound the docker stats probe with a timeout and scope memory sampling to the stack's own container ids (PIN-382)
Luigi Agosti9e6c4d69196e
diff --git a/tests/tools/runner/internal/e2e/runner.go b/tests/tools/runner/internal/e2e/runner.goindex 12e60564..2b4a912c 100644--- a/tests/tools/runner/internal/e2e/runner.go+++ b/tests/tools/runner/internal/e2e/runner.go@@ -3,6 +3,7 @@ package e2eimport ("bufio""bytes"+ "context""errors""fmt""io"@@ -535,7 +536,7 @@ func (r *Runner) runSinglePlanWithCompose(plan suitePlan, composeFile string) invar probe *memoryProbeif !r.args.DryRun {- probe = r.startMemorySampler()+ probe = r.startMemorySampler(composeFile)}code := r.runLoggedCommand("running "+def.Name+" suite", def.Output, command)if probe != nil {@@ -1047,23 +1048,40 @@ type memoryProbe struct {result chan memoryResult}-func (r *Runner) startMemorySampler() *memoryProbe {+const (+ dockerProbeTimeout = 10 * time.Second+ memorySamplerDeadline = 15 * time.Second+)++func (r *Runner) startMemorySampler(composeFile string) *memoryProbe {probe := &memoryProbe{stop: make(chan struct{}), result: make(chan memoryResult, 1)}go func() {acc := newMemoryAccumulator()firstErr := ""+ note := func(err error) {+ if err != nil && firstErr == "" {+ firstErr = err.Error()+ }+ }++ stackIDs, err := r.stackContainerIDs(composeFile)+ note(err)+ ids := make([]string, 0, len(stackIDs))+ for id := range stackIDs {+ ids = append(ids, id)+ }+sampleOnce := func() {- out, err := r.dockerStatsSnapshot()+ if len(ids) == 0 {+ return+ }+ out, err := r.dockerStatsSnapshot(ids)if err != nil {- if firstErr == "" {- firstErr = err.Error()- }+ note(err)return}- for _, line := range strings.Split(strings.TrimSpace(out), "\n") {- if s, ok := parseDockerStatsLine(line); ok && isPinchtabBrowserContainer(s.Name) {- acc.add(s)- }+ for _, s := range selectStackSamples(out, stackIDs) {+ acc.add(s)}}@@ -1075,14 +1093,14 @@ func (r *Runner) startMemorySampler() *memoryProbe {case <-probe.stop:sampleOnce()containers := acc.reduce()- note := ""+ reason := ""if len(containers) == 0 {- note = "no pinchtab container memory sampled"+ reason = "no pinchtab container memory sampled"if firstErr != "" {- note += " (" + firstErr + ")"+ reason += " (" + firstErr + ")"}}- probe.result <- memoryResult{containers: containers, note: note}+ probe.result <- memoryResult{containers: containers, note: reason}returncase <-ticker.C:sampleOnce()@@ -1094,7 +1112,12 @@ func (r *Runner) startMemorySampler() *memoryProbe {func (p *memoryProbe) finish() memoryResult {close(p.stop)- return <-p.result+ select {+ case result := <-p.result:+ return result+ case <-time.After(memorySamplerDeadline):+ return memoryResult{note: "memory sampler did not finish within " + memorySamplerDeadline.String()}+ }}func (r *Runner) applyMemoryResult(result memoryResult) {@@ -1108,15 +1131,44 @@ func (r *Runner) applyMemoryResult(result memoryResult) {r.mem = &suiteMemory{Provider: r.provider(), Containers: result.containers}}-func (r *Runner) dockerStatsSnapshot() (string, error) {- cmd := exec.Command("docker", "stats", "--no-stream", "--format", "{{.Name}},{{.MemUsage}},{{.PIDs}}") // #nosec G204 -- fixed docker stats invocation+func (r *Runner) stackContainerIDs(composeFile string) (map[string]bool, error) {+ out, err := r.captureWithTimeout(r.composeArgs(composeFile, "ps", "-q"))+ if err != nil {+ return nil, fmt.Errorf("docker compose ps: %w", err)+ }+ ids := map[string]bool{}+ for _, line := range strings.Split(strings.TrimSpace(out), "\n") {+ if id := strings.TrimSpace(line); id != "" {+ ids[id] = true+ }+ }+ return ids, nil+}++func (r *Runner) dockerStatsSnapshot(ids []string) (string, error) {+ command := append([]string{"docker", "stats", "--no-stream", "--format", "{{.ID}},{{.Name}},{{.MemUsage}},{{.PIDs}}"}, ids...)+ out, err := r.captureWithTimeout(command)+ if err != nil {+ return "", fmt.Errorf("docker stats unavailable: %w", err)+ }+ return out, nil+}++func (r *Runner) captureWithTimeout(command []string) (string, error) {+ ctx, cancel := context.WithTimeout(context.Background(), dockerProbeTimeout)+ defer cancel()+ cmd := exec.CommandContext(ctx, command[0], command[1:]...) // #nosec G204 -- commands are fixed docker/compose invocationscmd.Dir = r.repoRootcmd.Env = os.Environ()var buf bytes.Buffercmd.Stdout = &bufcmd.Stderr = &buf- if err := cmd.Run(); err != nil {- return "", fmt.Errorf("docker stats unavailable: %v: %s", err, strings.TrimSpace(buf.String()))+ err := cmd.Run()+ if ctx.Err() == context.DeadlineExceeded {+ return "", fmt.Errorf("timed out after %s", dockerProbeTimeout)+ }+ if err != nil {+ return "", fmt.Errorf("%v: %s", err, strings.TrimSpace(buf.String()))}return buf.String(), nil}diff --git a/tests/tools/runner/internal/e2e/timings.go b/tests/tools/runner/internal/e2e/timings.goindex c9b39682..3cc0d33e 100644--- a/tests/tools/runner/internal/e2e/timings.go+++ b/tests/tools/runner/internal/e2e/timings.go@@ -60,6 +60,7 @@ type containerMemory struct {}type memorySample struct {+ ID stringName stringMiB float64Pids int@@ -115,19 +116,44 @@ func round1(v float64) float64 {func parseDockerStatsLine(line string) (memorySample, bool) {fields := strings.Split(strings.TrimSpace(line), ",")- if len(fields) != 3 {+ if len(fields) != 4 {return memorySample{}, false}- name := strings.TrimSpace(fields[0])- mib, ok := parseMemUsageMiB(fields[1])- if name == "" || !ok {+ id := strings.TrimSpace(fields[0])+ name := strings.TrimSpace(fields[1])+ mib, ok := parseMemUsageMiB(fields[2])+ if id == "" || name == "" || !ok {return memorySample{}, false}- pids, err := strconv.Atoi(strings.TrimSpace(fields[2]))+ pids, err := strconv.Atoi(strings.TrimSpace(fields[3]))if err != nil {pids = 0}- return memorySample{Name: name, MiB: mib, Pids: pids}, true+ return memorySample{ID: id, Name: name, MiB: mib, Pids: pids}, true+}++func selectStackSamples(statsOutput string, stackIDs map[string]bool) []memorySample {+ var out []memorySample+ for _, line := range strings.Split(strings.TrimSpace(statsOutput), "\n") {+ s, ok := parseDockerStatsLine(line)+ if !ok || !containerIDMatches(s.ID, stackIDs) || !isPinchtabBrowserContainer(s.Name) {+ continue+ }+ out = append(out, s)+ }+ return out+}++func containerIDMatches(statsID string, stackIDs map[string]bool) bool {+ if stackIDs[statsID] {+ return true+ }+ for id := range stackIDs {+ if strings.HasPrefix(id, statsID) || strings.HasPrefix(statsID, id) {+ return true+ }+ }+ return false}func parseMemUsageMiB(field string) (float64, bool) {diff --git a/tests/tools/runner/internal/e2e/timings_test.go b/tests/tools/runner/internal/e2e/timings_test.goindex cc5ac053..13be52d6 100644--- a/tests/tools/runner/internal/e2e/timings_test.go+++ b/tests/tools/runner/internal/e2e/timings_test.go@@ -207,16 +207,17 @@ func TestParseDockerStatsLine(t *testing.T) {name stringline stringwantOK bool+ wantID stringwantName stringwantMiB float64wantPids int}{- {"chrome pinchtab", "pinchtab-pinchtab-1,484MiB / 7.667GiB,12", true, "pinchtab-pinchtab-1", 484, 12},- {"gib used", "pinchtab-pinchtab-secure-1,1.5GiB / 7.667GiB,30", true, "pinchtab-pinchtab-secure-1", 1536, 30},- {"non-numeric pids keeps the memory sample", "pinchtab-pinchtab-1,200MiB / 8GiB,--", true, "pinchtab-pinchtab-1", 200, 0},- {"too few fields", "only-two,200MiB", false, "", 0, 0},- {"unparseable memory", "pinchtab-pinchtab-1,notmem,3", false, "", 0, 0},- {"blank", "", false, "", 0, 0},+ {"chrome pinchtab", "a1b2c3,e2e-pinchtab-1,484MiB / 7.667GiB,12", true, "a1b2c3", "e2e-pinchtab-1", 484, 12},+ {"gib used", "d4e5f6,e2e-pinchtab-secure-1,1.5GiB / 7.667GiB,30", true, "d4e5f6", "e2e-pinchtab-secure-1", 1536, 30},+ {"non-numeric pids keeps the memory sample", "a1b2c3,e2e-pinchtab-1,200MiB / 8GiB,--", true, "a1b2c3", "e2e-pinchtab-1", 200, 0},+ {"too few fields", "e2e-pinchtab-1,200MiB / 8GiB,3", false, "", "", 0, 0},+ {"unparseable memory", "a1b2c3,e2e-pinchtab-1,notmem,3", false, "", "", 0, 0},+ {"blank", "", false, "", "", 0, 0},} {t.Run(tc.name, func(t *testing.T) {got, ok := parseDockerStatsLine(tc.line)@@ -226,13 +227,37 @@ func TestParseDockerStatsLine(t *testing.T) {if !ok {return}- if got.Name != tc.wantName || got.MiB != tc.wantMiB || got.Pids != tc.wantPids {- t.Errorf("parseDockerStatsLine(%q) = %+v, want name %q mib %v pids %d", tc.line, got, tc.wantName, tc.wantMiB, tc.wantPids)+ if got.ID != tc.wantID || got.Name != tc.wantName || got.MiB != tc.wantMiB || got.Pids != tc.wantPids {+ t.Errorf("parseDockerStatsLine(%q) = %+v, want id %q name %q mib %v pids %d", tc.line, got, tc.wantID, tc.wantName, tc.wantMiB, tc.wantPids)}})}}+func TestSelectStackSamplesRecordsOnlyThisStacksContainers(t *testing.T) {+ stackIDs := map[string]bool{"a1b2c3d4e5f6": true}+ statsOutput := strings.Join([]string{+ "a1b2c3d4e5f6,e2e-pinchtab-1,484MiB / 8GiB,12",+ "9988776655ff,pinchtab-stealth-chrome,900MiB / 8GiB,40",+ "1122334455aa,e2e-fixtures-1,10MiB / 8GiB,3",+ }, "\n")++ got := selectStackSamples(statsOutput, stackIDs)+ if len(got) != 1 || got[0].Name != "e2e-pinchtab-1" {+ t.Fatalf("selectStackSamples = %+v; a foreign pinchtab container or the stack's fixtures must not be recorded", got)+ }+}++func TestContainerIDMatchesToleratesShortAndFullIDs(t *testing.T) {+ stackIDs := map[string]bool{"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2": true}+ if !containerIDMatches("a1b2c3d4e5f6", stackIDs) {+ t.Error("a short docker stats id must match the full compose ps id it prefixes")+ }+ if containerIDMatches("ffffffffffff", stackIDs) {+ t.Error("an unrelated id must not match")+ }+}+func TestParseMemUsageMiB(t *testing.T) {for _, tc := range []struct {field string