From 349dd6fed7212e08aab5ac00f4310443b66416ca Mon Sep 17 00:00:00 2001 From: matteo Date: Tue, 21 Apr 2026 00:48:36 +0800 Subject: [PATCH 1/4] doc --- go.mod | 7 +- go.sum | 11 ++ internal/biz/analyze.go | 232 ++++++++++++++++++++++++++++++++++++ internal/biz/batch.go | 16 ++- internal/biz/repo.go | 5 +- internal/biz/usecase.go | 14 +++ internal/data/file.go | 22 ++-- internal/data/repo.go | 31 +++-- internal/data/storage.go | 30 +++-- internal/server/router.go | 2 + internal/service/handler.go | 61 ++++++++++ web/template/list.html | 61 ++++------ 12 files changed, 417 insertions(+), 75 deletions(-) create mode 100644 internal/biz/analyze.go diff --git a/go.mod b/go.mod index 6375006..53dd994 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/matteo-gz/prof -go 1.22 +go 1.24.0 require ( github.com/gabriel-vasile/mimetype v1.4.1 @@ -15,11 +15,14 @@ require ( ) require ( + github.com/chzyer/readline v1.5.1 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.13.0 // indirect github.com/go-playground/universal-translator v0.17.0 // indirect github.com/go-playground/validator/v10 v10.4.1 // indirect github.com/golang/protobuf v1.5.2 // indirect + github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 // indirect + github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kr/pretty v0.2.0 // indirect github.com/leodido/go-urn v1.2.0 // indirect @@ -31,7 +34,7 @@ require ( go.uber.org/multierr v1.6.0 // indirect golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa // indirect golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e // indirect - golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect + golang.org/x/sys v0.32.0 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect diff --git a/go.sum b/go.sum index 007637b..8ac2463 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,10 @@ github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLj github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= +github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= +github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= +github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -79,6 +83,8 @@ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 h1:EwtI+Al+DeppwYX2oXJCETMO23COyaKGP6fHVpkpWpg= +github.com/google/pprof v0.0.0-20260402051712-545e8a4df936/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -86,6 +92,8 @@ github.com/google/wire v0.5.0 h1:I7ELFeVBr3yfPIcc8+MWvrjk+3VjbcSzoXm3JVa+jD8= github.com/google/wire v0.5.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1EoU= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b h1:ogbOPx86mIhFy764gGkqnkFC8m5PJA7sPzlk9ppLVQA= +github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= @@ -188,9 +196,12 @@ golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= diff --git a/internal/biz/analyze.go b/internal/biz/analyze.go new file mode 100644 index 0000000..69dbd1f --- /dev/null +++ b/internal/biz/analyze.go @@ -0,0 +1,232 @@ +package biz + +import ( + "fmt" + "math" + "os" + "sort" + "strings" + + "github.com/google/pprof/profile" +) + +type SampleTypeInfo struct { + Type string `json:"type"` + Unit string `json:"unit"` +} + +type TopItem struct { + Rank int `json:"rank"` + Name string `json:"name"` + Flat int64 `json:"flat"` + FlatPct float64 `json:"flat_pct"` + SumPct float64 `json:"sum_pct"` + Cum int64 `json:"cum"` + CumPct float64 `json:"cum_pct"` +} + +type TopResult struct { + Path string `json:"path"` + Type string `json:"type"` + SampleType SampleTypeInfo `json:"sample_type"` + SampleTypes []SampleTypeInfo `json:"sample_types"` + Total int64 `json:"total"` + Unit string `json:"unit"` + Top []TopItem `json:"top"` +} + +type funcStat struct { + FuncID uint64 + Name string + Flat int64 + Cum int64 +} + +func AnalyzeTop(absPath string, n int, sampleIdx int, cumSort bool) (*TopResult, error) { + f, err := os.Open(absPath) + if err != nil { + return nil, fmt.Errorf("open profile: %w", err) + } + defer f.Close() + + p, err := profile.Parse(f) + if err != nil { + return nil, fmt.Errorf("parse profile: %w", err) + } + + if len(p.SampleType) == 0 { + return nil, fmt.Errorf("profile has no sample types") + } + + idx := resolveSampleIndex(p, sampleIdx) + if idx < 0 || idx >= len(p.SampleType) { + return nil, fmt.Errorf("sample index %d out of range [0, %d)", sampleIdx, len(p.SampleType)) + } + + stats, total := aggregateFlatCum(p, idx) + + if cumSort { + sort.Slice(stats, func(i, j int) bool { + if stats[i].Cum != stats[j].Cum { + return stats[i].Cum > stats[j].Cum + } + return stats[i].Name < stats[j].Name + }) + } else { + sort.Slice(stats, func(i, j int) bool { + if stats[i].Flat != stats[j].Flat { + return stats[i].Flat > stats[j].Flat + } + return stats[i].Name < stats[j].Name + }) + } + + if n <= 0 { + n = 20 + } + if n > len(stats) { + n = len(stats) + } + + items := make([]TopItem, n) + var sumPct float64 + for i := 0; i < n; i++ { + s := stats[i] + flatPct := pct(s.Flat, total) + sumPct += flatPct + items[i] = TopItem{ + Rank: i + 1, + Name: s.Name, + Flat: s.Flat, + FlatPct: roundPct(flatPct), + SumPct: roundPct(sumPct), + Cum: s.Cum, + CumPct: roundPct(pct(s.Cum, total)), + } + } + + sampleTypes := make([]SampleTypeInfo, len(p.SampleType)) + for i, st := range p.SampleType { + sampleTypes[i] = SampleTypeInfo{Type: st.Type, Unit: st.Unit} + } + + return &TopResult{ + Path: absPath, + Type: inferType(absPath), + SampleType: SampleTypeInfo{Type: p.SampleType[idx].Type, Unit: p.SampleType[idx].Unit}, + SampleTypes: sampleTypes, + Total: total, + Unit: p.SampleType[idx].Unit, + Top: items, + }, nil +} + +func resolveSampleIndex(p *profile.Profile, si int) int { + if si >= 0 && si < len(p.SampleType) { + return si + } + return len(p.SampleType) - 1 +} + +func aggregateFlatCum(p *profile.Profile, idx int) ([]funcStat, int64) { + flatMap := make(map[uint64]int64) + cumMap := make(map[uint64]int64) + nameMap := make(map[uint64]string) + var total int64 + + for _, s := range p.Sample { + if idx >= len(s.Value) { + continue + } + v := s.Value[idx] + total += v + + // flat: leaf function only (Location[0], innermost Line) + if len(s.Location) > 0 { + if fn := leafFunction(s.Location[0]); fn != nil { + flatMap[fn.ID] += v + nameMap[fn.ID] = fn.Name + } + } + + // cum: every unique function on the stack + seen := make(map[uint64]bool) + for _, loc := range s.Location { + for _, line := range loc.Line { + if line.Function == nil { + continue + } + fid := line.Function.ID + if seen[fid] { + continue + } + seen[fid] = true + cumMap[fid] += v + nameMap[fid] = line.Function.Name + } + } + } + + allIDs := make(map[uint64]bool) + for id := range flatMap { + allIDs[id] = true + } + for id := range cumMap { + allIDs[id] = true + } + + stats := make([]funcStat, 0, len(allIDs)) + for id := range allIDs { + flat, cum := flatMap[id], cumMap[id] + if flat == 0 && cum == 0 { + continue + } + stats = append(stats, funcStat{ + FuncID: id, + Name: nameMap[id], + Flat: flat, + Cum: cum, + }) + } + return stats, total +} + +func leafFunction(loc *profile.Location) *profile.Function { + if len(loc.Line) == 0 { + return nil + } + return loc.Line[0].Function +} + +func pct(value, total int64) float64 { + if total == 0 { + return 0 + } + return float64(value) / float64(total) * 100 +} + +func roundPct(v float64) float64 { + return math.Round(v*100) / 100 +} + +func inferType(path string) string { + lower := strings.ToLower(path) + switch { + case strings.Contains(lower, "cpu"): + return "cpu" + case strings.Contains(lower, "heap"): + return "heap" + case strings.Contains(lower, "alloc"): + return "allocs" + case strings.Contains(lower, "goroutine"): + return "goroutine" + case strings.Contains(lower, "block"): + return "block" + case strings.Contains(lower, "mutex"): + return "mutex" + case strings.Contains(lower, "threadcreate"): + return "threadcreate" + default: + return "unknown" + } +} diff --git a/internal/biz/batch.go b/internal/biz/batch.go index eb79e9f..c0b62e3 100644 --- a/internal/biz/batch.go +++ b/internal/biz/batch.go @@ -163,13 +163,25 @@ func (b *batch) run(ctx context.Context, task urlTask, ch chan Cse, wg *sync.Wai func (uc *Usecase) DealRun(ctx context.Context, p BatchParams) (res []Cse, err error) { b := newBatchFromParams(p, uc.log, uc.denyPrivateIP, uc.samplingSeconds, uc.deltaSeconds, uc.traceSeconds) - return b.Start(ctx, uc.repo.CreateFile) + dir, err := uc.repo.PreAllocDir() + if err != nil { + return + } + return b.Start(ctx, func(uri, contentType string, data []byte) (string, error) { + return uc.repo.CreateFileInDir(dir, uri, contentType, data) + }) } // DealRunLegacy handles the old URL-based batch request for backward compatibility. func (uc *Usecase) DealRunLegacy(ctx context.Context, uri string) (res []Cse, err error) { b := newBatchLegacy(uri, uc.log, uc.denyPrivateIP, uc.samplingSeconds, uc.deltaSeconds, uc.traceSeconds) - return b.Start(ctx, uc.repo.CreateFile) + dir, err := uc.repo.PreAllocDir() + if err != nil { + return + } + return b.Start(ctx, func(u, contentType string, data []byte) (string, error) { + return uc.repo.CreateFileInDir(dir, u, contentType, data) + }) } func (b *batch) setUrl() (err error) { diff --git a/internal/biz/repo.go b/internal/biz/repo.go index da5cf8a..6339574 100644 --- a/internal/biz/repo.go +++ b/internal/biz/repo.go @@ -2,10 +2,11 @@ package biz import "github.com/go-kratos/kratos/v2/log" -// FileInfo holds name and size for a file in the storage directory. +// FileInfo holds name, size and detected type for a file in the storage directory. type FileInfo struct { Name string Size int64 + Type string // "pprof" | "trace" | "txt" | "unknown" } // BatchGroup holds files from one collection batch under a date directory. @@ -22,7 +23,9 @@ type Repo interface { GetFileList(date string) (list []string, files []FileInfo, err error) GetBatchGroups(date string) ([]BatchGroup, error) GetFileType(dir string) string + PreAllocDir() (absDir string, err error) CreateFile(url string, contentType string, data []byte) (relativePath string, err error) + CreateFileInDir(absDir, url, contentType string, data []byte) (relativePath string, err error) CreateFileByUpload(fileName string, data []byte) (relativePath string, err error) } diff --git a/internal/biz/usecase.go b/internal/biz/usecase.go index bf52fa0..ccba794 100644 --- a/internal/biz/usecase.go +++ b/internal/biz/usecase.go @@ -34,3 +34,17 @@ func (uc *Usecase) GetBatchGroups(date string) ([]BatchGroup, error) { func (uc *Usecase) GetFileType(dir string) string { return uc.repo.GetFileType(dir) } + +func (uc *Usecase) AnalyzeTop(enBase64Dir string, n int, sampleIdx int, cumSort bool) (*TopResult, error) { + dir, err := base64.StdEncoding.DecodeString(enBase64Dir) + if err != nil { + return nil, err + } + absPath := uc.repo.GetAbsDir(string(dir)) + result, err := AnalyzeTop(absPath, n, sampleIdx, cumSort) + if err != nil { + return nil, err + } + result.Path = string(dir) + return result, nil +} diff --git a/internal/data/file.go b/internal/data/file.go index 7662763..44bc397 100644 --- a/internal/data/file.go +++ b/internal/data/file.go @@ -3,7 +3,6 @@ package data import ( "fmt" "os" - "path" "sort" "strings" @@ -38,19 +37,11 @@ func (f *file) getAbsDir(relPath string) string { return f.dir + relPath } func getFileType(dir string) (fileType string) { - ext := path.Ext(dir) - if ext != "" { - ext = ext[1:] - } - if pproftype.ExtTrace == ext { - return pproftype.ExtTrace - } else if pproftype.ExtTxt == ext { - return pproftype.ExtTxt - } else if pproftype.ExtPprof == ext { - return pproftype.ExtPprof - } else { + sniffed, err := checkMimeByDir(dir) + if err != nil { return pproftype.ExtUnknown } + return sniffed } func (f *file) getFileList(date string) (list []string, files []biz.FileInfo, err error) { final := f.getAbsDir(date) @@ -67,7 +58,12 @@ func (f *file) getFileList(date string) (list []string, files []biz.FileInfo, er if fi.IsDir() { list = append(list, fi.Name()) } else { - files = append(files, biz.FileInfo{Name: fi.Name(), Size: fi.Size()}) + absFile := final + string(os.PathSeparator) + fi.Name() + files = append(files, biz.FileInfo{ + Name: fi.Name(), + Size: fi.Size(), + Type: getFileType(absFile), + }) } } sort.Sort(sort.Reverse(sort.StringSlice(list))) diff --git a/internal/data/repo.go b/internal/data/repo.go index e59db79..5d975fd 100644 --- a/internal/data/repo.go +++ b/internal/data/repo.go @@ -66,15 +66,29 @@ func (rp *repo) GetFileList(date string) (list []string, files []biz.FileInfo, e return rp.data.file.getFileList(date) } func (rp *repo) GetFileType(dir string) string { - return getFileType(dir) + return getFileType(rp.data.file.getAbsDir(dir)) +} + +func (rp *repo) PreAllocDir() (string, error) { + return rp.data.file.createDir() +} + +func (rp *repo) CreateFileInDir(absDir, uri, contentType string, data []byte) (RelativePath string, err error) { + if _, err = checkMimeByData(data, contentType); err != nil { + return + } + filename, err := rp.data.file.getFileName(uri) + if err != nil { + return + } + return rp.data.file.createFile(filename, absDir, data) } func (rp *repo) CreateFile(uri, contentType string, data []byte) (RelativePath string, err error) { - var ext string - if ext, err = checkMimeByData(data, contentType); err != nil { + if _, err = checkMimeByData(data, contentType); err != nil { return } - filename, err := rp.data.file.getFileName(uri, ext) + filename, err := rp.data.file.getFileName(uri) if err != nil { return } @@ -85,17 +99,12 @@ func (rp *repo) CreateFile(uri, contentType string, data []byte) (RelativePath s return rp.data.file.createFile(filename, dir, data) } func (rp *repo) CreateFileByUpload(fileName string, data []byte) (relativePath string, err error) { - var ext string - if ext, err = checkMimeByData(data, ""); err != nil { - return - } - filename, err := rp.data.file.getFileName2(fileName, ext) - if err != nil { + if _, err = checkMimeByData(data, ""); err != nil { return } dir, err := rp.data.file.createDir() if err != nil { return } - return rp.data.file.createFile(filename, dir, data) + return rp.data.file.createFile(fileName, dir, data) } diff --git a/internal/data/storage.go b/internal/data/storage.go index 1bc08e9..b45605f 100644 --- a/internal/data/storage.go +++ b/internal/data/storage.go @@ -3,15 +3,17 @@ package data import ( "errors" "fmt" - "github.com/gabriel-vasile/mimetype" - "github.com/matteo-gz/prof/pkg/filex" - "github.com/matteo-gz/prof/pkg/pproftype" "net/url" "os" "path" "path/filepath" + "sort" "strings" "time" + + "github.com/gabriel-vasile/mimetype" + "github.com/matteo-gz/prof/pkg/filex" + "github.com/matteo-gz/prof/pkg/pproftype" ) const ( @@ -20,17 +22,25 @@ const ( mimeTxt = "text/plain" ) -func (f *file) getFileName(uri, ext string) (filename string, err error) { +func (f *file) getFileName(uri string) (filename string, err error) { u2, err := url.Parse(uri) if err != nil { return } filename = strings.ReplaceAll(path.Base(u2.Path), "/", "_") - filename += "." + ext - return -} -func (f *file) getFileName2(name, ext string) (filename string, err error) { - filename = name + "." + ext + q := u2.Query() + keys := make([]string, 0, len(q)) + for k := range q { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + v := q.Get(k) + if v == "" || v == "0" { + continue + } + filename += "_" + k + "_" + v + } return } @@ -89,7 +99,7 @@ func checkMimeByDir(dir string) (string, error) { func (f *file) dirName() string { t := time.Now() dateStr := t.Format("20060102") - id := fmt.Sprintf("%d_%d_%d", t.Hour(), t.Minute(), t.Second()) + id := fmt.Sprintf("%02d_%02d_%02d", t.Hour(), t.Minute(), t.Second()) dir := f.getAbsDir(fmt.Sprintf("/%s/%s", dateStr, id)) dir = filepath.Join(filepath.Split(dir)) return dir diff --git a/internal/server/router.go b/internal/server/router.go index f7a6906..c5c53e5 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -57,7 +57,9 @@ func (h *HTTPServerX) router() (r *gin.Engine, err error) { r.POST("/opt/run1", h.srv.Run1) api := r.Group("/api") { + api.GET("/", h.srv.APIIndex) api.GET("/plugins", h.srv.APIPlugins) + api.GET("/pprof/:dir/top", h.srv.APIPprofTop) } return } diff --git a/internal/service/handler.go b/internal/service/handler.go index d79bc09..c97424e 100644 --- a/internal/service/handler.go +++ b/internal/service/handler.go @@ -7,6 +7,7 @@ import ( "net/http" "os" "path/filepath" + "strconv" "strings" "time" @@ -331,6 +332,66 @@ func (s *Service) APIPlugins(c *gin.Context) { }) } +type apiEndpoint struct { + Method string `json:"method"` + Path string `json:"path"` + Desc string `json:"description"` + Params []apiParam `json:"params,omitempty"` +} + +type apiParam struct { + Name string `json:"name"` + In string `json:"in"` + Required bool `json:"required"` + Default string `json:"default,omitempty"` + Desc string `json:"description"` +} + +func (s *Service) APIIndex(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{ + "name": "Prof API", + "version": "1.0", + "docs": "https://github.com/matteo-gz/prof", + "endpoints": []apiEndpoint{ + { + Method: "GET", + Path: "/api/", + Desc: "API 索引,返回所有可用接口列表", + }, + { + Method: "GET", + Path: "/api/plugins", + Desc: "获取已注册的 JS 插件列表及启用状态", + }, + { + Method: "GET", + Path: "/api/pprof/:dir/top", + Desc: "解析 .pprof 文件,返回 Top N 热点函数(flat/cum)", + Params: []apiParam{ + {Name: "dir", In: "path", Required: true, Desc: "profile 相对路径的 base64 编码(与 /pprof/:dir/ 相同)"}, + {Name: "n", In: "query", Default: "20", Desc: "返回前 N 个函数"}, + {Name: "si", In: "query", Default: "-1", Desc: "SampleType 索引,-1 = 最后一个(与 go tool pprof 一致)"}, + {Name: "cum", In: "query", Default: "false", Desc: "true 时按 cum 排序,否则按 flat 排序"}, + }, + }, + }, + }) +} + +func (s *Service) APIPprofTop(c *gin.Context) { + dir := c.Param("dir") + n, _ := strconv.Atoi(c.DefaultQuery("n", "20")) + si, _ := strconv.Atoi(c.DefaultQuery("si", "-1")) + cumSort := c.Query("cum") == "true" + + result, err := s.uc.AnalyzeTop(dir, n, si, cumSort) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, result) +} + func (s *Service) Run1(c *gin.Context) { uri := c.PostForm("url") relativePath, size, err := s.uc.DealRun1(c.Request.Context(), uri) diff --git a/web/template/list.html b/web/template/list.html index 18e0188..1066010 100644 --- a/web/template/list.html +++ b/web/template/list.html @@ -60,7 +60,7 @@