Files
magpie/internal/cli/goroutines_cli_test.go
T
JoeyWu-tech b18a6a080b gateway, cli: magpie goroutines writes the running magpie's goroutine stacks to a file (#3362)
#3362's second ask: an app stuck at something could only be read by
killing it, which ends what was stuck. magpie heap and magpie cpu
already ask the running gateway for a profile over loopback; magpie
goroutines asks it for every goroutine's stack. That works on Windows
too, where there is no SIGUSR1.

GET /v1/magpie/goroutines (goroutines.go) answers the callers
/v1/magpie/heap answers (profileRefused: a program on this computer
over loopback, no browser mark, a loopback Host; a gateway key lets
nothing else in) with runtime/pprof's goroutine profile at debug=2,
the form a crash prints: each goroutine's state and wait ("[select,
4320 minutes]"), its frames with source lines, and who started it. It
is text/plain and no-store, and X-Magpie-Goroutine-Stats names the
process (pid, program, version, window, uptime, goroutine count).
Arguments are words in hex, never what they point at, so the dump
holds no keys, prompts or messages; it does name magpie's source files
and the program's path, which the usage says.

magpie goroutines [<file>] writes it to <file>, else
magpie-goroutines-<date>-<time>.txt in this folder, 0600 and never over
a file there, then prints the file and the process. --help, -h and help
print the usage and ask nothing; a flag it doesn't take, "-", a blank
name or a second file are refused before the gateway is asked. A
magpie older than this one answers 404 and is told to update; with
none answering, it says so.

The refused callers TestHeapProfileOnlyToThisComputer listed move into
profileCallersRefused, which the CPU test and the new one share.

Run on b437e4ad, go1.26.8. internal/gateway and internal/cli are the
same here and at the branch's head (tree 613df3a9), where the checks of
them ran:
- gofmt -l and go vet as in the commit before: clean.
- go test ./internal/gateway -run 'Goroutine|Heap|CPU|Profile': ok;
  ./internal/cli -run 'Goroutines|Heap|CPU|Help': ok.
- Broken by hand: goroutinesRefused letting every caller in makes
  TestGoroutineDumpOnlyToThisComputer red ("Origin null with a key":
  200); debug=1 for 2 makes it red (the parked goroutine isn't in the
  dump); without the route it is red (404), and so is
  TestGoroutinesWritesTheRunningGatewaysDump ("older than this one").
  Restored, green.
- Full suite at this commit, go test -tags nogui -count=1 -timeout 45m
  ./... (tree e5cf04af, 498s): 62 packages ok. 14 reds in 7 packages,
  none in a file this commit touches, each red on b437e4ad without it:
    internal/agent TestInstalledVersion, TestOmpDetectedWithPiDir,
    TestCursorFolderFromTheEditorIsNotTheCLI and TestZedAppPath:
    proc.Look keeps "not found" for a tool written in the tick of its
    folder's last change (#3141).
    internal/agent TestCodexDriftReached: Drift answers from the read of
    Codex's log taken before the test's last insert (#3398).
    internal/agent TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under
    /tmp meets a /tmp/.git that isn't a repository of this user's
    ("error obtaining VCS status: exit status 128").
    internal/claudebridge TestCallbackGoesPastTheAgentsProxy,
    internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress,
    internal/gui TestGatewayHeldByAContainer and
    TestGatewayFixQuitsOnlyAMagpie: the processes this run started had
    their outgoing connections sent through a proxy (graftcp).
    internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv
    TestProgram: umask 077 here; the fixtures' own modes go through it
    (0444 is written as 0400).
    internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun
    1.3.11 on PATH names port 80 in the request line (#3397).
Not tried: a real stuck app; magpie goroutines against the app on macOS
or Windows (the tests serve gateway.New().Handler() on loopback).
2026-10-24 21:33:06 +08:00

129 lines
4.2 KiB
Go

package cli
import (
"bytes"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/yetone/magpie/internal/gateway"
)
// --help and its other forms print magpie goroutines' usage, ask nothing
// and write nothing; a flag it doesn't take, "-", or a second file are
// refused the same way, before the gateway is asked.
func TestGoroutinesHelpAndBadArgsWriteNothing(t *testing.T) {
root, _ := heapDir(t)
asked := false
gw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { asked = true }))
defer gw.Close()
t.Setenv("MAGPIE_ADDR", strings.TrimPrefix(gw.URL, "http://"))
before := tree(t, root)
for _, args := range [][]string{{"goroutines", "--help"}, {"goroutines", "-h"}, {"goroutines", "help"}, {"goroutines", "out.txt", "--help"}} {
out, err := runOut(t, args...)
if err != nil || !strings.Contains(out, "usage: magpie goroutines [<file>]") {
t.Errorf("magpie %s: %v %q", strings.Join(args, " "), err, out)
}
}
for _, args := range [][]string{{"goroutines", "--out", "x"}, {"goroutines", "-o"}, {"goroutines", "-"}, {"goroutines", "a.txt", "b.txt"}, {"goroutines", " "}} {
if _, err := runOut(t, args...); err == nil || !strings.Contains(err.Error(), "nothing was written") {
t.Errorf("magpie %s: %v", strings.Join(args, " "), err)
}
}
if asked {
t.Error("the gateway was asked")
}
if got := tree(t, root); !reflect.DeepEqual(got, before) {
t.Fatalf("written:\nbefore %v\nafter %v", before, got)
}
}
// Against a running gateway (its Handler, on loopback), magpie goroutines
// writes the dump into the working folder, prints its path and which
// process it is of, and never writes over a file there.
func TestGoroutinesWritesTheRunningGatewaysDump(t *testing.T) {
_, dir := heapDir(t)
gw := httptest.NewServer(gateway.New().Handler())
defer gw.Close()
t.Setenv("MAGPIE_ADDR", strings.TrimPrefix(gw.URL, "http://"))
out, err := runOut(t, "goroutines", "stuck.txt")
if err != nil {
t.Fatal(err)
}
file := filepath.Join(dir, "stuck.txt")
b, err := os.ReadFile(file)
if err != nil {
t.Fatal(err)
}
// this test's own goroutine is in it, waiting on the command
if !bytes.HasPrefix(b, []byte("goroutine ")) || !bytes.Contains(b, []byte("TestGoroutinesWritesTheRunningGatewaysDump")) {
t.Fatalf("not this process's goroutine dump: %.300q", b)
}
if info, _ := os.Stat(file); info.Mode().Perm() != 0o600 && os.PathSeparator == '/' {
t.Errorf("mode %v", info.Mode())
}
for _, want := range []string{"stuck.txt", "process", "goroutines"} {
if !strings.Contains(out, want) {
t.Errorf("printed no %s: %q", want, out)
}
}
// the same name again: refused, the first file kept
if _, err := runOut(t, "goroutines", "stuck.txt"); err == nil || !strings.Contains(err.Error(), "there already") {
t.Fatalf("written over: %v", err)
}
if again, _ := os.ReadFile(file); !bytes.Equal(again, b) {
t.Fatal("the first dump changed")
}
// no name: magpie-goroutines-<date>-<time>.txt here
if _, err := runOut(t, "goroutines"); err != nil {
t.Fatal(err)
}
if m, _ := filepath.Glob(filepath.Join(dir, "magpie-goroutines-*.txt")); len(m) != 1 {
t.Fatalf("no default file: %v", m)
}
}
// A magpie older than this one answers 404: magpie goroutines says to
// update it and writes nothing. With no magpie answering, it says so.
func TestGoroutinesWithAnOlderOrNoGateway(t *testing.T) {
_, dir := heapDir(t)
old := httptest.NewServer(http.NotFoundHandler())
defer old.Close()
t.Setenv("MAGPIE_ADDR", strings.TrimPrefix(old.URL, "http://"))
if _, err := runOut(t, "goroutines", "x.txt"); err == nil || !strings.Contains(err.Error(), "older than this one") {
t.Fatalf("an older magpie: %v", err)
}
// a port kept by the test that hangs up on every call: one freed
// could be handed to anything next
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
c.Close()
}
}()
t.Setenv("MAGPIE_ADDR", ln.Addr().String())
if _, err := runOut(t, "goroutines", "x.txt"); err == nil || !strings.Contains(err.Error(), "is magpie running") {
t.Fatalf("no magpie: %v", err)
}
if ents, _ := os.ReadDir(dir); len(ents) != 0 {
t.Fatalf("written: %v", ents)
}
}