Files
magpie/internal/cli/goroutines_cli.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

136 lines
4.8 KiB
Go

package cli
// magpie goroutines: every goroutine of the running magpie, with its stack
// and how long it has waited, for a report of magpie stuck at something
// while it goes on running (#3362). Killing the app to see would end what
// was stuck, so the dump is asked of the process itself, through the
// gateway it serves on this computer (gateway.GoroutinesPath, loopback
// only, as magpie heap's).
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/gateway"
)
const goroutinesUsage = `usage: magpie goroutines [<file>]
every goroutine of the magpie serving the gateway on this computer (the app, the menu
bar, magpie serve or magpie web), with its stack and how long it has waited, for a
report of magpie stuck at something while it runs. magpie keeps running; nothing is
stopped. It is written to <file>, else to magpie-goroutines-<date>-<time>.txt in this
folder, and never over a file that is there. magpie then prints the file and which
process it is of: send both. The dump holds function names, source lines and the path of
the magpie program, with arguments as numbers only, not keys or messages.
It asks the gateway at the port in Settings' Gateway address (or MAGPIE_ADDR) over loopback.`
// goroutinesWait bounds the ask: a dump of thousands of goroutines is
// written in well under a second, so a magpie that doesn't answer in this
// is stuck where its gateway answers too.
const goroutinesWait = 30 * time.Second
// goroutinesCmd: magpie goroutines [<file>]
func goroutinesCmd(args []string) error {
file := ""
for _, a := range args {
switch {
case strings.HasPrefix(a, "-") && a != "-":
return fmt.Errorf("unknown flag %s: nothing was written (magpie goroutines [<file>])", a)
case a == "-" || strings.TrimSpace(a) == "":
return fmt.Errorf("%q is not a file name: nothing was written (magpie goroutines [<file>])", a)
case file != "":
return errors.New("magpie goroutines takes one file: nothing was written (magpie goroutines [<file>])")
default:
file = a
}
}
if file == "" {
file = "magpie-goroutines-" + time.Now().Format("20060102-150405") + ".txt"
}
dump, stats, err := fetchGoroutines(gateway.URL())
if err != nil {
return err
}
f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
if errors.Is(err, os.ErrExist) {
return fmt.Errorf("%s is there already: name another file (magpie goroutines <file>)", file)
}
return err
}
if _, err := f.Write(dump); err != nil {
f.Close()
os.Remove(file)
return err
}
if err := f.Close(); err != nil {
os.Remove(file)
return err
}
if abs, err := filepath.Abs(file); err == nil {
file = abs
}
fmt.Printf("%s %s (%s)\n", green.Render("saved"), file, bytesSize(uint64(len(dump))))
fmt.Print(goroutinesSummary(stats))
fmt.Println(muted.Render("Send the file and these lines with the report."))
return nil
}
// fetchGoroutines asks the gateway at base for the dump: its text, checked
// to be one, and which process it is of.
func fetchGoroutines(base string) ([]byte, gateway.GoroutineStats, error) {
var st gateway.GoroutineStats
c := &http.Client{Timeout: goroutinesWait}
res, err := c.Get(base + gateway.GoroutinesPath)
if err != nil {
return nil, st, fmt.Errorf("no magpie answers at %s, so there is nothing to dump: is magpie running? (%v)", base, err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, st, fmt.Errorf("the dump from %s was cut off: %w", base, err)
}
if res.StatusCode == http.StatusNotFound {
return nil, st, fmt.Errorf("the magpie at %s is older than this one and has no goroutine dump: update it, then run magpie goroutines again", base)
}
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
msg := strings.TrimSpace(string(body))
if json.Unmarshal(body, &e) == nil && e.Error.Message != "" {
msg = e.Error.Message
}
return nil, st, fmt.Errorf("the magpie at %s answered %s: %s", base, res.Status, msg)
}
if !bytes.HasPrefix(body, []byte("goroutine ")) {
return nil, st, fmt.Errorf("what %s answered is not a goroutine dump (%d bytes): is it magpie?", base, len(body))
}
if err := json.Unmarshal([]byte(res.Header.Get(gateway.GoroutineStatsHeader)), &st); err != nil {
return nil, st, fmt.Errorf("the magpie at %s sent no process numbers with its dump: %v", base, err)
}
return body, st, nil
}
// goroutinesSummary is the lines magpie goroutines prints of st.
func goroutinesSummary(st gateway.GoroutineStats) string {
var b strings.Builder
who := st.Program
if st.Window {
who += ", with a window"
}
fmt.Fprintf(&b, " process %d (%s) magpie %s, up %s\n", st.PID, who, st.Version, st.Uptime)
fmt.Fprintf(&b, " goroutines %d\n", st.Goroutines)
return b.String()
}