Created
August 9, 2023 16:23
-
-
Save requilence/ee4a732d0aeef1dd8f3381b4403a3624 to your computer and use it in GitHub Desktop.
Filter goroutines stack by state and group by func
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bufio" | |
| "fmt" | |
| "io" | |
| "os" | |
| "sort" | |
| "strings" | |
| ) | |
| func main() { | |
| if len(os.Args) < 2 { | |
| fmt.Println("Usage: go run main.go <state> [file]") | |
| return | |
| } | |
| state := os.Args[1] | |
| var reader io.Reader | |
| if len(os.Args) > 2 { | |
| file, err := os.Open(os.Args[2]) | |
| if err != nil { | |
| fmt.Printf("Error opening file: %v\n", err) | |
| return | |
| } | |
| defer file.Close() | |
| reader = file | |
| } else { | |
| reader = os.Stdin | |
| } | |
| funcCount := make(map[string]int) | |
| totalCount := 0 | |
| printing := false | |
| scanner := bufio.NewScanner(reader) | |
| for scanner.Scan() { | |
| line := scanner.Text() | |
| if strings.HasPrefix(line, "goroutine ") { | |
| if printing { | |
| fmt.Println() // end of previous goroutine | |
| printing = false | |
| } | |
| // Check if the current goroutine is in the specified state | |
| if strings.Contains(line, state) { | |
| printing = true | |
| totalCount++ | |
| } | |
| } | |
| if printing { | |
| fmt.Println(line) | |
| // Only count the functions in the first stack frame to avoid duplicates | |
| if strings.Contains(line, "(") && !strings.HasPrefix(line, "goroutine ") { | |
| funcName := strings.Fields(line)[0] // function name is the first word in the line | |
| funcCount[funcName]++ | |
| } | |
| } | |
| } | |
| fmt.Println("============================================") | |
| fmt.Printf("Total goroutines in state %s: %d\n", state, totalCount) | |
| fmt.Println("\nCount per function:") | |
| // Sort function names by count in descending order | |
| type FuncStat struct { | |
| Name string | |
| Count int | |
| } | |
| stats := make([]FuncStat, 0, len(funcCount)) | |
| for f, c := range funcCount { | |
| stats = append(stats, FuncStat{f, c}) | |
| } | |
| sort.Slice(stats, func(i, j int) bool { | |
| return stats[i].Count > stats[j].Count | |
| }) | |
| for _, stat := range stats { | |
| fmt.Printf("%s: %d\n", stat.Name, stat.Count) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment