Files
magpie/internal/gateway/cpu.go
T
yetone 89521b03d6 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.
2026-10-17 20:52:13 +08:00

144 lines
5.0 KiB
Go

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())
}