cli, gateway: magpie cpu records the running magpie's CPU profile for 30s, for a report of high CPU (@LeiCheng42 on X)

@LeiCheng42 on X reports magpie using the most CPU while Codex runs. As
with magpie heap (e085d6e92), Activity Monitor and `sample` show Go's
frames as ???, so `magpie cpu [<file>] [--seconds N]` asks the magpie
serving the gateway for GET /v1/magpie/cpu?seconds=N: runtime/pprof's CPU
profile over 30s (5..120; else 400), gzipped protobuf, with the pid,
version, uptime, CPU time used over the window (getrusage / GetProcessTimes)
and since start, cores, GOMAXPROCS and goroutines in X-Magpie-CPU-Stats. It
tells the user to use magpie as when busy (run Codex) while it records,
writes <file> else magpie-cpu-<date>-<time>.pb.gz (0600), refuses a file
that is there before recording, and says "is magpie running?" at once when
nothing answers. --help writes nothing; an unknown flag, "-", a second file
or --seconds out of range are refused before anything is asked.

Only the profiling request waits: the gateway serves everything else
meanwhile. pprof keeps one CPU profile at a time, so a second ask gets 409
(cpuRecording), and a caller that hangs up stops the recording. The route
takes heap's guard: heapRefused's checks move into profileRefused, shared
by cpuRefused, so only a loopback, unproxied, browserless call to a
loopback Host gets it, with or without a gateway key or lanGuard.

Run at bad4508c4 + this: gofmt -l (nothing); go vet ./..., GOOS=linux go
vet -tags nogui ./..., GOOS=windows go vet ./... (clean); go test -tags
nogui -timeout 45m ./... under a sandbox HOME: every package ok except
internal/agent (45m timeout, #2544; again alone, in TestPortMovesEveryAgent)
and internal/gateway (TestTranslatedStreamKeepsClientAlive/chat_to_responses,
sibling of #2169/#2711, filed as #2737; alone with -timeout 45m only
/chat_to_anthropic, #2169; the test passes 5/5 alone). TestCPU* -race
-count=3 ok. Broken by hand: cpuRefused returning "" (19 failures in
TestCPUProfileOnlyToThisComputer); no one-at-a-time guard and no hang-up
stop (TestCPUProfileOneAtATime red each); no seconds bounds, no pre-check
of the file, no is-it-running check, no help case (each CLI test red).
Rebased on 2042123f4: go build ./..., gofmt -l, GOOS=windows and
GOOS=linux vet of internal/gateway and internal/cli clean; go test -run
'CPU|Cpu|Heap|Help' ./internal/cli ./internal/gateway ok.

Real use: the built binary's `magpie serve` under a sandbox HOME on
127.0.0.1:3493; `magpie cpu --seconds 5` saved a 0600 profile that go tool
pprof -top reads and printed the numbers; a concurrent second one got the
409 while GET / answered in ms; Origin: null and a rebound Host got 403;
--help wrote nothing; an existing file was refused. Not tried: the GUI
app's process, or the Windows box.
This commit is contained in:
yetone
2026-10-17 20:52:13 +08:00
parent 2042123f43
commit 89521b03d6
14 changed files with 811 additions and 5 deletions
+17
View File
@@ -1812,6 +1812,23 @@ any other `Host` are refused 403, with a gateway key too. With
`MAGPIE_ADDR` on an address that isn't loopback, the call isn't from
loopback, so it is refused as well.
`magpie cpu [<file>] [--seconds N]` is for a report of magpie using too
much CPU (@LeiCheng42 on X, while Codex ran). It asks the same running
magpie for `GET /v1/magpie/cpu?seconds=N`, a Go CPU profile recorded for
30 seconds, or N from 5 to 120 (`runtime/pprof`'s CPU profile, gzipped
protobuf, which `go tool pprof` reads). While it records, use magpie as
you do when it is busy, such as running Codex: the gateway goes on serving
every other call, and the profile is of that. It writes the profile to
`<file>`, else `magpie-cpu-<date>-<time>.pb.gz` in the working folder,
and refuses a file that is there before it records, not after. It prints
the file and the numbers the gateway sends in `X-Magpie-CPU-Stats`: the
process, the CPU time it used over the seconds recorded (user and system,
as the system counts it, with the share of one core) and since it started,
its cores and `GOMAXPROCS`, and the goroutine count. Go records one CPU
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.
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
+201
View File
@@ -0,0 +1,201 @@
package cli
// magpie cpu: a Go CPU profile of the running magpie, recorded for some
// seconds while the user goes on using it, for a report of magpie using
// too much CPU (@LeiCheng42 on X, while Codex runs). Activity Monitor and
// a macOS `sample` show Go's frames as ???, so the profile is asked of the
// process itself, through the gateway it serves on this computer
// (gateway.CPUPath, loopback only, as magpie heap's).
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/gateway"
)
const cpuUsage = `usage: magpie cpu [<file>] [--seconds N]
records a Go CPU profile of the magpie serving the gateway on this computer (the app,
the menu bar, magpie serve or magpie web) for 30 seconds, or N from 5 to 120, for a
report of magpie using too much CPU. While it records, use magpie as you do when it is
busy: run Codex or whichever agent it was. The profile is written to <file>, else to
magpie-cpu-<date>-<time>.pb.gz in this folder, and never over a file that is there.
magpie then prints the file, the CPU time the process used while recording and its
goroutines: send both. The profile holds where the time went (function names, source
lines) and the path of the magpie program, not keys or messages; go tool pprof <file>
reads it. It asks the gateway at Settings' Gateway port (or MAGPIE_ADDR) over loopback.`
// cpuArgs reads magpie cpu's arguments: the file, "" for the default, and
// the seconds to record.
func cpuArgs(args []string) (file string, secs int, err error) {
const form = "(magpie cpu [<file>] [--seconds N])"
secs = gateway.CPUSeconds
seen := false
setSecs := func(v string) error {
n, err := strconv.Atoi(v)
if err != nil || n < gateway.CPUMinSeconds || n > gateway.CPUMaxSeconds {
return fmt.Errorf("--seconds is a whole number from %d to %d, not %q: nothing was recorded %s", gateway.CPUMinSeconds, gateway.CPUMaxSeconds, v, form)
}
if seen {
return fmt.Errorf("--seconds is given twice: nothing was recorded %s", form)
}
seen, secs = true, n
return nil
}
for i := 0; i < len(args); i++ {
a := args[i]
switch {
case a == "--seconds":
if i+1 >= len(args) {
return "", 0, fmt.Errorf("--seconds needs a number: nothing was recorded %s", form)
}
i++
if err := setSecs(args[i]); err != nil {
return "", 0, err
}
case strings.HasPrefix(a, "--seconds="):
if err := setSecs(strings.TrimPrefix(a, "--seconds=")); err != nil {
return "", 0, err
}
case strings.HasPrefix(a, "-") && a != "-":
return "", 0, fmt.Errorf("unknown flag %s: nothing was recorded %s", a, form)
case a == "-" || strings.TrimSpace(a) == "":
return "", 0, fmt.Errorf("%q is not a file name: nothing was recorded %s", a, form)
case file != "":
return "", 0, fmt.Errorf("magpie cpu takes one file: nothing was recorded %s", form)
default:
file = a
}
}
return file, secs, nil
}
// cpuCmd: magpie cpu [<file>] [--seconds N]
func cpuCmd(args []string) error {
file, secs, err := cpuArgs(args)
if err != nil {
return err
}
if file == "" {
file = "magpie-cpu-" + time.Now().Format("20060102-150405") + ".pb.gz"
}
// before the seconds of recording, not after them: the file is
// opened without writing over one again once the profile is here
if _, err := os.Lstat(file); err == nil {
return fmt.Errorf("%s is there already: name another file (magpie cpu <file>)", file)
}
base := gateway.URL()
if err := pingMagpie(base); err != nil {
return err
}
fmt.Printf("%s magpie's CPU for %ds, until %s. Use magpie as you do when it is busy (run Codex) until then.\n",
green.Render("Recording"), secs, time.Now().Add(time.Duration(secs)*time.Second).Format("15:04:05"))
prof, stats, err := fetchCPU(base, secs)
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 cpu <file>)", file)
}
return err
}
if _, err := f.Write(prof); 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(prof))))
fmt.Print(cpuSummary(stats))
fmt.Println(muted.Render("Send the file and these lines with the report."))
return nil
}
// pingMagpie checks that a magpie answers at base before the seconds of
// recording are waited out.
func pingMagpie(base string) error {
c := &http.Client{Timeout: 5 * time.Second}
res, err := c.Get(base + "/")
if err != nil {
return fmt.Errorf("no magpie answers at %s, so there is nothing to profile: is magpie running? (%v)", base, err)
}
defer res.Body.Close()
io.Copy(io.Discard, io.LimitReader(res.Body, 4096))
return nil
}
// fetchCPU asks the gateway at base for a profile of secs seconds: its
// bytes, checked to be gzip, and the process's numbers beside it.
func fetchCPU(base string, secs int) ([]byte, gateway.CPUStats, error) {
var st gateway.CPUStats
// the seconds recorded, and room for a busy machine to send it
c := &http.Client{Timeout: time.Duration(secs)*time.Second + 2*time.Minute}
res, err := c.Get(base + gateway.CPUPath + "?seconds=" + url.QueryEscape(strconv.Itoa(secs)))
if err != nil {
return nil, st, fmt.Errorf("no magpie answers at %s, so there is nothing to profile: 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 profile 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 CPU profile: update it, then run magpie cpu 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{0x1f, 0x8b}) {
return nil, st, fmt.Errorf("what %s answered is not a CPU profile (%d bytes): is it magpie?", base, len(body))
}
if err := json.Unmarshal([]byte(res.Header.Get(gateway.CPUStatsHeader)), &st); err != nil {
return nil, st, fmt.Errorf("the magpie at %s sent no CPU numbers with its profile: %v", base, err)
}
return body, st, nil
}
// cpuSummary is the lines magpie cpu prints of st.
func cpuSummary(st gateway.CPUStats) 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)
if st.CPUKnown && st.Seconds > 0 {
fmt.Fprintf(&b, " CPU %.2fs in the %.1fs recorded (%.0f%% of one core)\n", st.CPU, st.Seconds, 100*st.CPU/st.Seconds)
fmt.Fprintf(&b, " CPU total %.1fs since it started\n", st.CPUTotal)
} else {
fmt.Fprintf(&b, " CPU the system didn't say (%.1fs recorded)\n", st.Seconds)
}
fmt.Fprintf(&b, " cores %d (GOMAXPROCS %d)\n", st.NumCPU, st.GOMAXPROCS)
fmt.Fprintf(&b, " goroutines %d\n", st.Goroutines)
return b.String()
}
+166
View File
@@ -0,0 +1,166 @@
package cli
import (
"bytes"
"compress/gzip"
"io"
"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 cpu's usage, ask nothing and
// write nothing, here or under the home; a flag it doesn't take, "-", a
// second file, or --seconds out of 5..120 are refused the same way,
// before the gateway is asked.
func TestCPUHelpAndBadArgsWriteNothing(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{{"cpu", "--help"}, {"cpu", "-h"}, {"cpu", "help"}, {"cpu", "out.pb.gz", "--help"}, {"cpu", "--seconds", "10", "-h"}} {
out, err := runOut(t, args...)
if err != nil || !strings.Contains(out, "usage: magpie cpu [<file>] [--seconds N]") {
t.Errorf("magpie %s: %v %q", strings.Join(args, " "), err, out)
}
}
for _, args := range [][]string{
{"cpu", "--out", "x"}, {"cpu", "-o"}, {"cpu", "-s", "10"}, {"cpu", "-"}, {"cpu", "a.pb.gz", "b.pb.gz"}, {"cpu", " "},
{"cpu", "--seconds"}, {"cpu", "--seconds", "4"}, {"cpu", "--seconds", "121"}, {"cpu", "--seconds=0"}, {"cpu", "--seconds", "x"},
{"cpu", "--seconds", "30s"}, {"cpu", "--seconds=-5"}, {"cpu", "--seconds", "10", "--seconds", "20"}, {"cpu", "x.pb.gz", "--seconds"},
} {
if _, err := runOut(t, args...); err == nil || !strings.Contains(err.Error(), "nothing was recorded") {
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)
}
}
// --seconds N and --seconds=N are read, in any place among the file.
func TestCPUArgs(t *testing.T) {
for _, c := range []struct {
args []string
file string
secs int
}{
{nil, "", gateway.CPUSeconds},
{[]string{"a.pb.gz"}, "a.pb.gz", 30},
{[]string{"--seconds", "5"}, "", 5},
{[]string{"--seconds=120", "a.pb.gz"}, "a.pb.gz", 120},
{[]string{"a.pb.gz", "--seconds", "60"}, "a.pb.gz", 60},
} {
file, secs, err := cpuArgs(c.args)
if err != nil || file != c.file || secs != c.secs {
t.Errorf("%q: %q %d %v", c.args, file, secs, err)
}
}
}
// A file that is there already is refused before anything is recorded,
// and is kept as it was.
func TestCPUKeepsAFileThere(t *testing.T) {
_, dir := 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://"))
file := filepath.Join(dir, "mine.pb.gz")
if err := os.WriteFile(file, []byte("mine"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := runOut(t, "cpu", "mine.pb.gz"); err == nil || !strings.Contains(err.Error(), "there already") {
t.Fatalf("written over: %v", err)
}
if b, _ := os.ReadFile(file); string(b) != "mine" {
t.Fatalf("the file changed: %q", b)
}
if asked {
t.Error("the gateway was asked")
}
}
// Against a running gateway (its Handler, on loopback), magpie cpu says
// it records and for how long, then writes the gzipped profile into the
// working folder and prints its path, the CPU used and the goroutines.
// It records the 5 seconds asked for.
func TestCPUWritesTheRunningGatewaysProfile(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, "cpu", "--seconds", "5")
if err != nil {
t.Fatal(err)
}
m, _ := filepath.Glob(filepath.Join(dir, "magpie-cpu-*.pb.gz"))
if len(m) != 1 {
t.Fatalf("no default file: %v", m)
}
b, err := os.ReadFile(m[0])
if err != nil {
t.Fatal(err)
}
zr, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
if raw, err := io.ReadAll(zr); err != nil || !bytes.Contains(raw, []byte("samples")) || !bytes.Contains(raw, []byte("nanoseconds")) {
t.Fatalf("not a CPU profile: %v", err)
}
if info, _ := os.Stat(m[0]); info.Mode().Perm() != 0o600 && os.PathSeparator == '/' {
t.Errorf("mode %v", info.Mode())
}
for _, want := range []string{"Recording", "for 5s", "run Codex", filepath.Base(m[0]), "process", "CPU ", "of one core", "goroutines"} {
if !strings.Contains(out, want) {
t.Errorf("printed no %s: %q", want, out)
}
}
}
// With no magpie answering, magpie cpu says so at once and writes
// nothing.
func TestCPUWithNoGateway(t *testing.T) {
_, dir := heapDir(t)
// 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())
out, err := runOut(t, "cpu", "x.pb.gz")
if err == nil || !strings.Contains(err.Error(), "is magpie running") {
t.Fatalf("%v", err)
}
if strings.Contains(out, "Recording") {
t.Errorf("said it records: %q", out)
}
if ents, _ := os.ReadDir(dir); len(ents) != 0 {
t.Fatalf("written: %v", ents)
}
}
+2
View File
@@ -53,6 +53,8 @@ func helpFor(args []string) string {
return statuslineUsage
case "heap":
return heapUsage
case "cpu":
return cpuUsage
case "sessions":
return sessionsUsage
case "search":
+1 -1
View File
@@ -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")
return append(cmds, "healthcheck", "heap", "cpu")
}
func types(ix *ast.IndexExpr) string {
+5
View File
@@ -114,6 +114,7 @@ const usage = `magpie — one place to pick every agent's model
the service's page: its link, or turn it on or off
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 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
@@ -226,6 +227,10 @@ func run(args []string) error {
// the running magpie's heap profile: asks it, and moves nothing here
return heapCmd(args[1:])
}
if len(args) > 0 && args[0] == "cpu" {
// the running magpie's CPU profile: asks it, and moves nothing here
return cpuCmd(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
+143
View File
@@ -0,0 +1,143 @@
package gateway
// GET /v1/magpie/cpu: a Go CPU profile of the process serving the gateway,
// recorded for some seconds while the user goes on using magpie, for a
// report of magpie using too much CPU (@LeiCheng42 on X: the most CPU of
// anything while Codex runs). A macOS `sample` or Activity Monitor names
// none of Go's frames, so this is the one way to see where the Go side
// spends it; `magpie cpu` asks for it and writes the file the user sends.
import (
"bytes"
"encoding/json"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/provider"
)
// CPUPath is where the gateway answers a CPU profile.
const CPUPath = "/v1/magpie/cpu"
// CPUStatsHeader carries CPUStats, as JSON, beside the profile.
const CPUStatsHeader = "X-Magpie-CPU-Stats"
// The seconds a CPU profile records: CPUSeconds unless the caller asks
// for others, from CPUMinSeconds to CPUMaxSeconds.
const (
CPUSeconds = 30
CPUMinSeconds = 5
CPUMaxSeconds = 120
)
// CPUStats is what the process used while the profile recorded. CPU is
// the process's own user and system time over those seconds, as the
// system counts it (all its threads, Go's or not), and CPUTotal since it
// started; both are 0 with CPUKnown false where the system doesn't say.
type CPUStats 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"`
Seconds float64 `json:"seconds"` // how long the profile recorded
CPUKnown bool `json:"cpuKnown"`
CPU float64 `json:"cpu"` // seconds of CPU used while recording
CPUTotal float64 `json:"cpuTotal"` // seconds of CPU used since the process started
Goroutines int `json:"goroutines"`
NumCPU int `json:"numCPU"`
GOMAXPROCS int `json:"gomaxprocs"`
}
// cpuRecording is true while a CPU profile records: runtime/pprof keeps
// one at a time, so a second ask is told so rather than racing the first.
var cpuRecording atomic.Bool
// cpuSecond is one second of recording; tests shorten it.
var cpuSecond = time.Second
// cpuRefused says why r may not have the CPU profile, "" when it may: the
// same callers as the heap profile (heapRefused).
func cpuRefused(r *http.Request) string {
return profileRefused(r, "CPU profile", "magpie cpu")
}
// cpuProfile answers CPUPath: the "cpu" profile (gzipped protobuf, as go
// tool pprof reads it) over ?seconds= (CPUSeconds by default), with
// CPUStats in CPUStatsHeader. It holds only its own request: the gateway
// goes on serving while it records, which is what it records. A caller
// that hangs up ends the recording, and nothing is sent.
func (s *Server) cpuProfile(w http.ResponseWriter, r *http.Request) {
if why := cpuRefused(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
}
secs := CPUSeconds
if v := r.URL.Query().Get("seconds"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < CPUMinSeconds || n > CPUMaxSeconds {
writeError(w, provider.Chat, http.StatusBadRequest, "seconds is a whole number from "+strconv.Itoa(CPUMinSeconds)+" to "+strconv.Itoa(CPUMaxSeconds)+", not "+strconv.Quote(v))
return
}
secs = n
}
if !cpuRecording.CompareAndSwap(false, true) {
writeError(w, provider.Chat, http.StatusConflict, "magpie is recording a CPU profile already: wait for that one to finish, then run magpie cpu again")
return
}
defer cpuRecording.Store(false)
var buf bytes.Buffer
before, known := processCPU()
start := time.Now()
if err := pprof.StartCPUProfile(&buf); err != nil {
// another profiler of this process (a test's -cpuprofile)
writeError(w, provider.Chat, http.StatusConflict, "magpie couldn't start a CPU profile: "+err.Error())
return
}
t := time.NewTimer(time.Duration(secs) * cpuSecond)
defer t.Stop()
select {
case <-t.C:
case <-r.Context().Done():
pprof.StopCPUProfile()
log.Printf("CPU profile for %s ended early: the caller went away", r.RemoteAddr)
return
}
goroutines := runtime.NumGoroutine()
pprof.StopCPUProfile()
took := time.Since(start)
after, known2 := processCPU()
st := CPUStats{
PID: os.Getpid(),
Version: Version,
Window: Window,
Uptime: time.Since(processStarted).Round(time.Second).String(),
Seconds: took.Round(time.Millisecond).Seconds(),
CPUKnown: known && known2,
Goroutines: goroutines,
NumCPU: runtime.NumCPU(),
GOMAXPROCS: runtime.GOMAXPROCS(0),
}
if exe, err := os.Executable(); err == nil {
st.Program = filepath.Base(exe)
}
if st.CPUKnown {
st.CPU = (after - before).Seconds()
st.CPUTotal = after.Seconds()
}
stats, _ := json.Marshal(st)
h := w.Header()
h.Set("Content-Type", "application/octet-stream")
h.Set("Content-Disposition", `attachment; filename="magpie-cpu.pb.gz"`)
h.Set("Cache-Control", "no-store")
h.Set(CPUStatsHeader, string(stats))
w.Write(buf.Bytes())
}
+8
View File
@@ -0,0 +1,8 @@
//go:build !unix && !windows
package gateway
import "time"
// processCPU: this system doesn't say what the process used.
func processCPU() (time.Duration, bool) { return 0, false }
+215
View File
@@ -0,0 +1,215 @@
package gateway
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// The CPU profile goes to the same callers as the heap profile and no
// others: a foreign page, Origin null, a page on localhost, a listed page
// with its key, a rebound Host, another machine with or without a key and
// a proxy's client are refused with lanGuard and without it, before a
// second is recorded.
func TestCPUProfileOnlyToThisComputer(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]
old := cpuSecond
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)
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
}
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}},
}
for _, c := range refused {
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(CPUStatsHeader) != "" || bytes.HasPrefix(w.Body.Bytes(), []byte{0x1f, 0x8b}) {
t.Errorf("%s (lanGuard %v): %d %q", c.name, guarded, w.Code, w.Body.String())
}
}
}
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 cpu at %s: %d %q", host, w.Code, w.Body.String())
}
zr, err := gzip.NewReader(bytes.NewReader(w.Body.Bytes()))
if err != nil {
t.Fatalf("at %s: not gzip: %v", host, err)
}
raw, err := io.ReadAll(zr)
if err != nil || len(raw) == 0 {
t.Fatalf("at %s: %v, %d bytes", host, err, len(raw))
}
// a pprof CPU profile's string table names its sample types
for _, want := range []string{"samples", "cpu", "nanoseconds"} {
if !bytes.Contains(raw, []byte(want)) {
t.Errorf("at %s: the profile names no %s", host, want)
}
}
var st CPUStats
if err := json.Unmarshal([]byte(w.Header().Get(CPUStatsHeader)), &st); err != nil {
t.Fatalf("at %s: stats %q: %v", host, w.Header().Get(CPUStatsHeader), err)
}
if st.PID != os.Getpid() || st.Seconds <= 0 || st.Goroutines < 1 || st.NumCPU < 1 || st.GOMAXPROCS < 1 || !st.CPUKnown || st.CPUTotal <= 0 || st.CPU < 0 || st.CPUTotal < st.CPU {
t.Errorf("at %s: stats %+v", host, st)
}
if !strings.Contains(w.Header().Get("Cache-Control"), "no-store") {
t.Errorf("at %s: cacheable: %v", host, w.Header())
}
}
}
// seconds out of 5..120, or not a number, is refused before anything is
// recorded.
func TestCPUProfileSecondsBounded(t *testing.T) {
srv := New()
for _, v := range []string{"4", "121", "0", "-5", "x", "30s", "1e2"} {
r := httptest.NewRequest("GET", CPUPath+"?seconds="+v, nil)
r.RemoteAddr = "127.0.0.1:50123"
r.Host = "127.0.0.1:3425"
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, r)
if w.Code != http.StatusBadRequest || w.Header().Get(CPUStatsHeader) != "" {
t.Errorf("seconds=%s: %d %q", v, w.Code, w.Body.String())
}
}
}
// While one CPU profile records, the gateway goes on answering other
// calls, and a second profile is told one is recording (409), not left to
// runtime/pprof, which keeps one at a time. A caller that hangs up ends
// its recording, and the next profile can start.
func TestCPUProfileOneAtATime(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
srv := New()
ts := httptest.NewServer(srv.Handler())
defer ts.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
first := make(chan error, 1)
go func() {
// 120 real seconds: it ends when the test hangs up
req, _ := http.NewRequestWithContext(ctx, "GET", ts.URL+CPUPath+"?seconds=120", nil)
res, err := http.DefaultClient.Do(req)
if err == nil {
res.Body.Close()
}
first <- err
}()
// wait for the first to hold the recording, not for a duration
deadline := time.Now().Add(30 * time.Second)
for !cpuRecording.Load() {
if time.Now().After(deadline) {
t.Fatal("the first profile never started")
}
time.Sleep(5 * time.Millisecond)
}
// the gateway answers meanwhile
// a minute: far less than the 120 seconds recorded, and room for a busy
// machine
c := &http.Client{Timeout: time.Minute}
res, err := c.Get(ts.URL + "/")
if err != nil {
t.Fatalf("the gateway didn't answer while a profile recorded: %v", err)
}
res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Fatalf("GET / while recording: %s", res.Status)
}
// a second profile is refused, at once
res, err = c.Get(ts.URL + CPUPath + "?seconds=5")
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != http.StatusConflict || !strings.Contains(string(body), "recording a CPU profile already") || res.Header.Get(CPUStatsHeader) != "" {
t.Fatalf("second profile: %s %q", res.Status, body)
}
// hanging up ends the first, and frees the recording
cancel()
select {
case <-first:
case <-time.After(30 * time.Second):
t.Fatal("the first call didn't end")
}
deadline = time.Now().Add(30 * time.Second)
for cpuRecording.Load() {
if time.Now().After(deadline) {
t.Fatal("a hung-up profile kept recording")
}
time.Sleep(5 * time.Millisecond)
}
old := cpuSecond
cpuSecond = time.Millisecond
t.Cleanup(func() { cpuSecond = old })
res, err = c.Get(ts.URL + CPUPath + "?seconds=5")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Fatalf("the next profile: %s", res.Status)
}
}
+18
View File
@@ -0,0 +1,18 @@
//go:build unix
package gateway
import (
"syscall"
"time"
)
// processCPU is the user and system time this process used since it
// started, and whether the system said.
func processCPU() (time.Duration, bool) {
var ru syscall.Rusage
if err := syscall.Getrusage(syscall.RUSAGE_SELF, &ru); err != nil {
return 0, false
}
return time.Duration(ru.Utime.Nano() + ru.Stime.Nano()), true
}
+22
View File
@@ -0,0 +1,22 @@
package gateway
import (
"syscall"
"time"
)
// processCPU is the user and kernel time this process used since it
// started, and whether Windows said. GetProcessTimes counts both in
// 100-nanosecond ticks.
func processCPU() (time.Duration, bool) {
h, err := syscall.GetCurrentProcess()
if err != nil {
return 0, false
}
var created, exited, kernel, user syscall.Filetime
if err := syscall.GetProcessTimes(h, &created, &exited, &kernel, &user); err != nil {
return 0, false
}
ticks := func(f syscall.Filetime) int64 { return int64(f.HighDateTime)<<32 | int64(f.LowDateTime) }
return time.Duration((ticks(kernel) + ticks(user)) * 100), true
}
+3
View File
@@ -638,6 +638,9 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
// a heap profile of this process, for magpie heap (loopback only)
mux.HandleFunc("GET "+HeapPath, s.heapProfile)
// a CPU profile of this process over some seconds, for magpie cpu
// (loopback only)
mux.HandleFunc("GET "+CPUPath, s.cpuProfile)
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))
+9 -3
View File
@@ -109,13 +109,19 @@ func (s *Server) heapProfile(w http.ResponseWriter, r *http.Request) {
// and corsGuard turn most of these away first; this holds where Handler
// is served without them too.
func heapRefused(r *http.Request) string {
return profileRefused(r, "heap profile", "magpie heap")
}
// profileRefused is heapRefused for any profile of this process (cpuRefused
// too): what names the profile, cmd the command that asks for it.
func profileRefused(r *http.Request, what, cmd string) string {
switch {
case !local(r):
return "magpie hands its heap profile only to a program on this computer, over loopback: run magpie heap there"
return "magpie hands its " + what + " only to a program on this computer, over loopback: run " + cmd + " there"
case fromBrowser(r):
return "magpie doesn't hand its heap profile to a web page: run magpie heap in a terminal"
return "magpie doesn't hand its " + what + " to a web page: run " + cmd + " in a terminal"
case !loopbackHost(r.Host):
return "magpie hands its heap profile only to a call to localhost or a loopback address, not " + r.Host + ": run magpie heap"
return "magpie hands its " + what + " only to a call to localhost or a loopback address, not " + r.Host + ": run " + cmd
}
return ""
}