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 onb437e4ad, 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 onb437e4adwithout 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).
This commit is contained in:
@@ -1936,6 +1936,21 @@ profile at a time, so a second `magpie cpu` while one records is refused
|
||||
409; one whose caller hangs up stops recording. The route answers the same
|
||||
callers as `/v1/magpie/heap`, and refuses the same ones 403.
|
||||
|
||||
`magpie goroutines [<file>]` is for a report of magpie stuck at something
|
||||
while it goes on running, such as an app that kept an old partner list for
|
||||
days (#3362): killing it to look would end what was stuck. It asks the same
|
||||
running magpie for `GET /v1/magpie/goroutines`, every goroutine's stack as
|
||||
text (`runtime/pprof`'s `goroutine` profile at debug 2, the form a crash
|
||||
prints): each goroutine's state and how long it has waited
|
||||
(`[select, 4320 minutes]`), its frames with source lines, and who started
|
||||
it. Arguments are printed as numbers, never what they point at, so it holds
|
||||
no keys or messages. Nothing is stopped. It writes the dump to `<file>`,
|
||||
else `magpie-goroutines-<date>-<time>.txt` in the working folder, never
|
||||
over a file there, and prints the file and the process the gateway names in
|
||||
`X-Magpie-Goroutine-Stats` (its id, program, version, uptime and goroutine
|
||||
count). The route answers the same callers as `/v1/magpie/heap`, and
|
||||
refuses the same ones 403.
|
||||
|
||||
A gateway key held to a budget, to some models or to some accounts is told
|
||||
none of this magpie's accounts (#1981): `/v1/magpie/quotas`,
|
||||
`/v1/magpie/quotas/history`, `/v1/magpie/quotas/cards`,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,135 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,8 @@ func helpFor(args []string) string {
|
||||
return heapUsage
|
||||
case "cpu":
|
||||
return cpuUsage
|
||||
case "goroutines":
|
||||
return goroutinesUsage
|
||||
case "sessions":
|
||||
return sessionsUsage
|
||||
case "search":
|
||||
|
||||
@@ -129,7 +129,7 @@ func runCommands(t *testing.T) []string {
|
||||
if len(cmds) < 40 {
|
||||
t.Fatalf("read %d commands from run's switch: %v", len(cmds), cmds)
|
||||
}
|
||||
return append(cmds, "healthcheck", "heap", "cpu")
|
||||
return append(cmds, "healthcheck", "heap", "cpu", "goroutines")
|
||||
}
|
||||
|
||||
func types(ix *ast.IndexExpr) string {
|
||||
|
||||
@@ -115,6 +115,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK)
|
||||
magpie heap [<file>] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory
|
||||
magpie cpu [<file>] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU
|
||||
magpie goroutines [<file>] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something
|
||||
magpie gateway-key list|add <name>|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
|
||||
magpie gateway-key limit <id> [list|off|reset [n]|remove <n>|[add] day|week|month|<N>d|<N>h --tokens N --cost USD --cache-reads] a key's own limits, and what it used
|
||||
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
|
||||
@@ -231,6 +232,10 @@ func run(args []string) error {
|
||||
// the running magpie's CPU profile: asks it, and moves nothing here
|
||||
return cpuCmd(args[1:])
|
||||
}
|
||||
if len(args) > 0 && args[0] == "goroutines" {
|
||||
// the running magpie's goroutines: asks it, and moves nothing here
|
||||
return goroutinesCmd(args[1:])
|
||||
}
|
||||
if len(args) == 2 && args[0] == agent.DryRunArg {
|
||||
// an agent disconnected on a copy of its files under a temporary
|
||||
// home, for the Agents page to show what disconnecting changes
|
||||
|
||||
@@ -36,7 +36,6 @@ func TestCPUProfileOnlyToThisComputer(t *testing.T) {
|
||||
cpuSecond = time.Millisecond
|
||||
t.Cleanup(func() { cpuSecond = old })
|
||||
srv := New()
|
||||
chrome := []string{"User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Version/27.2 Safari/605.1.15", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"}
|
||||
call := func(guarded bool, remote, host string, hdr ...string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest("GET", CPUPath+"?seconds=5", nil)
|
||||
@@ -53,26 +52,7 @@ func TestCPUProfileOnlyToThisComputer(t *testing.T) {
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
refused := []struct {
|
||||
name string
|
||||
remote, host string
|
||||
hdr []string
|
||||
}{
|
||||
{"a foreign page", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://evil.example"}, chrome...)},
|
||||
{"Origin null", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null"}, chrome...)},
|
||||
{"Origin null with a key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null", "Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a page on localhost", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://localhost:5173"}, chrome...)},
|
||||
{"a localhost subdomain", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://evil.localhost"}, chrome...)},
|
||||
{"a listed page with its key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://listed.example", "Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a rebound page's GET", "127.0.0.1:50123", "rebind.attacker.example:3425", chrome},
|
||||
{"a rebound page with a key", "127.0.0.1:50123", "rebind.attacker.example:3425", append([]string{"Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a call to another name", "127.0.0.1:50123", "rebind.attacker.example:3425", []string{"User-Agent", "curl/8"}},
|
||||
{"a localhost subdomain as Host", "127.0.0.1:50123", "wails.localhost:3425", []string{"User-Agent", "curl/8"}},
|
||||
{"another machine", "192.168.1.20:50123", "192.168.1.10:3425", nil},
|
||||
{"another machine with a key", "192.168.1.20:50123", "192.168.1.10:3425", []string{"Authorization", "Bearer " + key}},
|
||||
{"a proxy's client", "127.0.0.1:50123", "127.0.0.1:3425", []string{"X-Forwarded-For", "203.0.113.9"}},
|
||||
{"a proxy's client with a key", "127.0.0.1:50123", "127.0.0.1:3425", []string{"Cf-Connecting-IP", "203.0.113.9", "Authorization", "Bearer " + key}},
|
||||
}
|
||||
refused := profileCallersRefused(key)
|
||||
for _, c := range refused {
|
||||
for _, guarded := range []bool{true, false} {
|
||||
w := call(guarded, c.remote, c.host, c.hdr...)
|
||||
|
||||
@@ -699,6 +699,9 @@ func (s *Server) Handler() http.Handler {
|
||||
// a CPU profile of this process over some seconds, for magpie cpu
|
||||
// (loopback only)
|
||||
mux.HandleFunc("GET "+CPUPath, s.cpuProfile)
|
||||
// every goroutine's stack and wait, for magpie goroutines (loopback
|
||||
// only)
|
||||
mux.HandleFunc("GET "+GoroutinesPath, s.goroutineDump)
|
||||
mux.HandleFunc("GET /v1/magpie/omarchy", s.omarchyTheme)
|
||||
mux.HandleFunc("OPTIONS /v1/magpie/omarchy", s.omarchyTheme)
|
||||
mux.HandleFunc("POST /v1/chat/completions", s.handle(provider.Chat))
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package gateway
|
||||
|
||||
// GET /v1/magpie/goroutines: every goroutine of the process serving the
|
||||
// gateway, with its stack and how long it has waited, for a report of
|
||||
// magpie stuck at something while it goes on running. An app that kept
|
||||
// the partner list it had for three days could only be read by killing
|
||||
// it, which ends what was stuck (#3362); `magpie goroutines` asks the
|
||||
// running process instead and writes the file the user sends.
|
||||
//
|
||||
// The dump is runtime/pprof's "goroutine" profile at debug=2, the form a
|
||||
// crash prints: each goroutine's state, its wait ("[select, 4320
|
||||
// minutes]"), its frames with source lines, and who started it. A frame's
|
||||
// arguments are words in hex, never what they point at, so it holds no
|
||||
// keys, prompts or messages; it names the source files magpie was built
|
||||
// from and the program's path.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"runtime/pprof"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// GoroutinesPath is where the gateway answers a goroutine dump.
|
||||
const GoroutinesPath = "/v1/magpie/goroutines"
|
||||
|
||||
// GoroutineStatsHeader carries GoroutineStats, as JSON, beside the dump.
|
||||
const GoroutineStatsHeader = "X-Magpie-Goroutine-Stats"
|
||||
|
||||
// GoroutineStats says which process the dump is of.
|
||||
type GoroutineStats struct {
|
||||
PID int `json:"pid"`
|
||||
Program string `json:"program"`
|
||||
Version string `json:"version"`
|
||||
Window bool `json:"window"` // the app's window or magpie web serves the gateway
|
||||
Uptime string `json:"uptime"`
|
||||
Goroutines int `json:"goroutines"`
|
||||
}
|
||||
|
||||
// goroutinesRefused says why r may not have the goroutine dump, "" when it
|
||||
// may: the same callers as the heap profile (heapRefused).
|
||||
func goroutinesRefused(r *http.Request) string {
|
||||
return profileRefused(r, "goroutine dump", "magpie goroutines")
|
||||
}
|
||||
|
||||
// goroutineDump answers GoroutinesPath: the dump as text, with
|
||||
// GoroutineStats in GoroutineStatsHeader.
|
||||
func (s *Server) goroutineDump(w http.ResponseWriter, r *http.Request) {
|
||||
if why := goroutinesRefused(r); why != "" {
|
||||
log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, why)
|
||||
writeError(w, provider.Chat, http.StatusForbidden, why)
|
||||
return
|
||||
}
|
||||
goroutines := runtime.NumGoroutine()
|
||||
var buf bytes.Buffer
|
||||
if err := pprof.Lookup("goroutine").WriteTo(&buf, 2); err != nil {
|
||||
writeError(w, provider.Chat, http.StatusInternalServerError, "the goroutine dump couldn't be written: "+err.Error())
|
||||
return
|
||||
}
|
||||
exe, _ := os.Executable()
|
||||
stats, _ := json.Marshal(GoroutineStats{
|
||||
PID: os.Getpid(),
|
||||
Program: filepath.Base(exe),
|
||||
Version: Version,
|
||||
Window: Window,
|
||||
Uptime: time.Since(processStarted).Round(time.Second).String(),
|
||||
Goroutines: goroutines,
|
||||
})
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/plain; charset=utf-8")
|
||||
h.Set("Content-Disposition", `attachment; filename="magpie-goroutines.txt"`)
|
||||
h.Set("Cache-Control", "no-store")
|
||||
h.Set(GoroutineStatsHeader, string(stats))
|
||||
w.Write(buf.Bytes())
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// parkedForTheDump waits on ch, as a goroutine stuck in magpie would: the
|
||||
// dump must name it and what it waits on.
|
||||
func parkedForTheDump(ch <-chan struct{}, parked chan<- struct{}) {
|
||||
close(parked)
|
||||
<-ch
|
||||
}
|
||||
|
||||
// The goroutine dump goes to the same callers as the heap profile (a
|
||||
// program on this computer over loopback, nothing a browser sends, no
|
||||
// other Host) and is refused to the rest. What it answers is every
|
||||
// goroutine's stack, a goroutine parked in magpie's code among them,
|
||||
// named with what it waits on, and which process it is of (#3362: an app
|
||||
// stuck for days could only be read by killing it).
|
||||
func TestGoroutineDumpOnlyToThisComputer(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
_, secrets := newCaller(t, "Page")
|
||||
s := settings.Load()
|
||||
s.CORSOrigins = []string{"https://listed.example"}
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := secrets[0]
|
||||
srv := New()
|
||||
call := func(guarded bool, remote, host string, hdr ...string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest("GET", GoroutinesPath, nil)
|
||||
r.RemoteAddr = remote
|
||||
r.Host = host
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
r.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h := srv.Handler()
|
||||
if guarded {
|
||||
h = lanGuard(h)
|
||||
}
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, c := range profileCallersRefused(key) {
|
||||
for _, guarded := range []bool{true, false} {
|
||||
w := call(guarded, c.remote, c.host, c.hdr...)
|
||||
// lanGuard asks another machine without a key for one (401)
|
||||
if w.Code != http.StatusForbidden && w.Code != http.StatusUnauthorized || w.Header().Get(GoroutineStatsHeader) != "" || bytes.HasPrefix(w.Body.Bytes(), []byte("goroutine ")) {
|
||||
t.Errorf("%s (lanGuard %v): %d %q", c.name, guarded, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
release, parked := make(chan struct{}), make(chan struct{})
|
||||
defer close(release)
|
||||
go parkedForTheDump(release, parked)
|
||||
<-parked
|
||||
for _, host := range []string{"127.0.0.1:3425", "localhost:3425", "[::1]:3425"} {
|
||||
w := call(true, "127.0.0.1:50123", host, "User-Agent", "Go-http-client/1.1")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("magpie goroutines at %s: %d %q", host, w.Code, w.Body.String())
|
||||
}
|
||||
body := w.Body.String()
|
||||
if !strings.HasPrefix(body, "goroutine ") {
|
||||
t.Fatalf("at %s: not a goroutine dump: %.200q", host, body)
|
||||
}
|
||||
// the parked one, with its state and its frame in this file
|
||||
i := strings.Index(body, "gateway.parkedForTheDump(")
|
||||
if i < 0 {
|
||||
t.Fatalf("at %s: the parked goroutine isn't in the dump", host)
|
||||
}
|
||||
head := body[strings.LastIndex(body[:i], "goroutine "):i]
|
||||
if !strings.Contains(head, "[chan receive") {
|
||||
t.Errorf("at %s: the parked goroutine's state isn't its wait: %q", host, head)
|
||||
}
|
||||
if !strings.Contains(body[i:], "goroutines_test.go:") {
|
||||
t.Errorf("at %s: no source line for the parked goroutine", host)
|
||||
}
|
||||
var st GoroutineStats
|
||||
if err := json.Unmarshal([]byte(w.Header().Get(GoroutineStatsHeader)), &st); err != nil {
|
||||
t.Fatalf("at %s: stats %q: %v", host, w.Header().Get(GoroutineStatsHeader), err)
|
||||
}
|
||||
if st.PID != os.Getpid() || st.Goroutines < 2 || st.Uptime == "" {
|
||||
t.Errorf("at %s: stats %+v", host, st)
|
||||
}
|
||||
if !strings.Contains(w.Header().Get("Cache-Control"), "no-store") || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/plain") {
|
||||
t.Errorf("at %s: headers %v", host, w.Header())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,6 @@ func TestHeapProfileOnlyToThisComputer(t *testing.T) {
|
||||
}
|
||||
key := secrets[0]
|
||||
srv := New()
|
||||
chrome := []string{"User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Version/27.2 Safari/605.1.15", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"}
|
||||
call := func(guarded bool, remote, host string, hdr ...string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest("GET", HeapPath, nil)
|
||||
@@ -50,26 +49,7 @@ func TestHeapProfileOnlyToThisComputer(t *testing.T) {
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
refused := []struct {
|
||||
name string
|
||||
remote, host string
|
||||
hdr []string
|
||||
}{
|
||||
{"a foreign page", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://evil.example"}, chrome...)},
|
||||
{"Origin null", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null"}, chrome...)},
|
||||
{"Origin null with a key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null", "Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a page on localhost", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://localhost:5173"}, chrome...)},
|
||||
{"a localhost subdomain", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://evil.localhost"}, chrome...)},
|
||||
{"a listed page with its key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://listed.example", "Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a rebound page's GET", "127.0.0.1:50123", "rebind.attacker.example:3425", chrome},
|
||||
{"a rebound page with a key", "127.0.0.1:50123", "rebind.attacker.example:3425", append([]string{"Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a call to another name", "127.0.0.1:50123", "rebind.attacker.example:3425", []string{"User-Agent", "curl/8"}},
|
||||
{"a localhost subdomain as Host", "127.0.0.1:50123", "wails.localhost:3425", []string{"User-Agent", "curl/8"}},
|
||||
{"another machine", "192.168.1.20:50123", "192.168.1.10:3425", nil},
|
||||
{"another machine with a key", "192.168.1.20:50123", "192.168.1.10:3425", []string{"Authorization", "Bearer " + key}},
|
||||
{"a proxy's client", "127.0.0.1:50123", "127.0.0.1:3425", []string{"X-Forwarded-For", "203.0.113.9"}},
|
||||
{"a proxy's client with a key", "127.0.0.1:50123", "127.0.0.1:3425", []string{"Cf-Connecting-IP", "203.0.113.9", "Authorization", "Bearer " + key}},
|
||||
}
|
||||
refused := profileCallersRefused(key)
|
||||
for _, c := range refused {
|
||||
for _, guarded := range []bool{true, false} {
|
||||
w := call(guarded, c.remote, c.host, c.hdr...)
|
||||
@@ -111,3 +91,32 @@ func TestHeapProfileOnlyToThisComputer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// profileRefusal is a caller a profile of this process is refused to.
|
||||
type profileRefusal struct {
|
||||
name string
|
||||
remote, host string
|
||||
hdr []string
|
||||
}
|
||||
|
||||
// profileCallersRefused are the callers every profile of this process
|
||||
// (heap, CPU, goroutines) is refused to, key a gateway key they may carry.
|
||||
func profileCallersRefused(key string) []profileRefusal {
|
||||
chrome := []string{"User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Version/27.2 Safari/605.1.15", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"}
|
||||
return []profileRefusal{
|
||||
{"a foreign page", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://evil.example"}, chrome...)},
|
||||
{"Origin null", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null"}, chrome...)},
|
||||
{"Origin null with a key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null", "Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a page on localhost", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://localhost:5173"}, chrome...)},
|
||||
{"a localhost subdomain", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://evil.localhost"}, chrome...)},
|
||||
{"a listed page with its key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://listed.example", "Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a rebound page's GET", "127.0.0.1:50123", "rebind.attacker.example:3425", chrome},
|
||||
{"a rebound page with a key", "127.0.0.1:50123", "rebind.attacker.example:3425", append([]string{"Authorization", "Bearer " + key}, chrome...)},
|
||||
{"a call to another name", "127.0.0.1:50123", "rebind.attacker.example:3425", []string{"User-Agent", "curl/8"}},
|
||||
{"a localhost subdomain as Host", "127.0.0.1:50123", "wails.localhost:3425", []string{"User-Agent", "curl/8"}},
|
||||
{"another machine", "192.168.1.20:50123", "192.168.1.10:3425", nil},
|
||||
{"another machine with a key", "192.168.1.20:50123", "192.168.1.10:3425", []string{"Authorization", "Bearer " + key}},
|
||||
{"a proxy's client", "127.0.0.1:50123", "127.0.0.1:3425", []string{"X-Forwarded-For", "203.0.113.9"}},
|
||||
{"a proxy's client with a key", "127.0.0.1:50123", "127.0.0.1:3425", []string{"Cf-Connecting-IP", "203.0.113.9", "Authorization", "Bearer " + key}},
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user