Debian Codegraph @

stack/example_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2018 Marc-Antoine Ruel. All rights reserved.
2 // Use of this source code is governed under the Apache License, Version 2.0
3 // that can be found in the LICENSE file.
4
5 // Output is currently different on 32 bits on go1.17 so skip the examples for
6 // now. It's a gross hack.
7
8 //go:build go1.18 || !386
9
10 package stack_test
11
12 import (
13 "bytes"
14 "errors"
15 "fmt"
16 "io"
17 "log"
18 "net"
19 "net/http"
20 "os"
21 "os/exec"
22 "path/filepath"
23 "runtime/debug"
24
25 "github.com/maruel/panicparse/v2/stack"
26 )
27
28 // Runs a crashing program and converts it to a dense text format like pp does.
29 func Example_text() {
30 source := `package main
31
32 import "time"
33
34 func main() {
35 c := crashy{}
36 go func() {
37 c.die(42.)
38 }()
39 select {}
40 }
41
42 type crashy struct{}
43
44 func (c crashy) die(f float32) {
45 time.Sleep(time.Millisecond)
46 panic(int(f))
47 }`
48
49 // Skipped error handling to make the example shorter.
50 root, _ := os.MkdirTemp("", "stack")
51 defer os.RemoveAll(root)
52 p := filepath.Join(root, "main.go")
53 os.WriteFile(p, []byte(source), 0600)
54 // Disable both optimization (-N) and inlining (-l).
55 c := exec.Command("go", "run", "-gcflags", "-N -l", p)
56 // This is important, otherwise only the panicking goroutine will be printed.
57 c.Env = append(os.Environ(), "GOTRACEBACK=1")
58 raw, _ := c.CombinedOutput()
59 stream := bytes.NewReader(raw)
60
61 s, suffix, err := stack.ScanSnapshot(stream, os.Stdout, stack.DefaultOpts())
62 if err != nil && err != io.EOF {
63 log.Fatal(err)
64 }
65
66 // Find out similar goroutine traces and group them into buckets.
67 buckets := s.Aggregate(stack.AnyValue).Buckets
68
69 // Calculate alignment.
70 srcLen := 0
71 pkgLen := 0
72 for _, bucket := range buckets {
73 for _, line := range bucket.Signature.Stack.Calls {
74 if l := len(fmt.Sprintf("%s:%d", line.SrcName, line.Line)); l > srcLen {
75 srcLen = l
76 }
77 if l := len(filepath.Base(line.Func.ImportPath)); l > pkgLen {
78 pkgLen = l
79 }
80 }
81 }
82
83 for _, bucket := range buckets {
84 // Print the goroutine header.
85 extra := ""
86 if s := bucket.SleepString(); s != "" {
87 extra += " [" + s + "]"
88 }
89 if bucket.Locked {
90 extra += " [locked]"
91 }
92
93 if len(bucket.CreatedBy.Calls) != 0 {
94 extra += fmt.Sprintf(" [Created by %s.%s @ %s:%d]", bucket.CreatedBy.Calls[0].Func.DirName, bucket.CreatedBy.Calls[0].Func.Name, bucket.CreatedBy.Calls[0].SrcName, bucket.CreatedBy.Calls[0].Line)
95 }
96 fmt.Printf("%d: %s%s\n", len(bucket.IDs), bucket.State, extra)
97
98 // Print the stack lines.
99 for _, line := range bucket.Stack.Calls {
100 fmt.Printf(
101 " %-*s %-*s %s(%s)\n",
102 pkgLen, line.Func.DirName, srcLen,
103 fmt.Sprintf("%s:%d", line.SrcName, line.Line),
104 line.Func.Name, &line.Args)
105 }
106 if bucket.Stack.Elided {
107 io.WriteString(os.Stdout, " (...)\n")
108 }
109 }
110
111 // If there was any remaining data in the pipe, dump it now.
112 if len(suffix) != 0 {
113 os.Stdout.Write(suffix)
114 }
115 if err == nil {
116 io.Copy(os.Stdout, stream)
117 }
118
119 // Output:
120 // panic: 42
121 //
122 // 1: running [Created by main.main @ main.go:7]
123 // main main.go:17 crashy.die(42)
124 // main main.go:8 main.func1()
125 // 1: select (no cases)
126 // main main.go:10 main()
127 // exit status 2
128 }
129
130 // Process multiple consecutive goroutine snapshots.
131 func Example_stream() {
132 // Stream of stack traces:
133 var r io.Reader
134 var w io.Writer
135 opts := stack.DefaultOpts()
136 for {
137 s, suffix, err := stack.ScanSnapshot(r, w, opts)
138 if s != nil {
139 // Process the snapshot...
140 }
141
142 if err != nil && err != io.EOF {
143 if len(suffix) != 0 {
144 w.Write(suffix)
145 }
146 log.Fatal(err)
147 }
148 // Prepend the suffix that was read to the rest of the input stream to
149 // catch the next snapshot signature:
150 r = io.MultiReader(bytes.NewReader(suffix), r)
151 }
152 }
153
154 // Converts a stack trace from os.Stdin into HTML on os.Stdout, discarding
155 // everything else.
156 func Example_hTML() {
157 s, _, err := stack.ScanSnapshot(os.Stdin, io.Discard, stack.DefaultOpts())
158 if err != nil && err != io.EOF {
159 log.Fatal(err)
160 }
161 if s != nil {
162 s.Aggregate(stack.AnyValue).ToHTML(os.Stdout, "")
163 }
164 }
165
166 // A sample parseStack function expects a stdlib stacktrace from runtime.Stack or debug.Stack and returns
167 // the parsed stack object.
168 func Example_simple() {
169 parseStack := func(rawStack []byte) stack.Stack {
170 s, _, err := stack.ScanSnapshot(bytes.NewReader(rawStack), io.Discard, stack.DefaultOpts())
171 if err != nil && err != io.EOF {
172 panic(err)
173 }
174
175 if len(s.Goroutines) > 1 {
176 panic(errors.New("provided stacktrace had more than one goroutine"))
177 }
178
179 return s.Goroutines[0].Signature.Stack
180 }
181
182 parsedStack := parseStack(debug.Stack())
183 fmt.Printf("parsedStack: %#v", parsedStack)
184 }
185
186 // Registers a middleware to trap exceptions and report them on http.Handler.
187 //
188 // For demonstration purposes, start a web server that panics and call into
189 // it.
190 func Example_httpHandlerMiddleware() {
191 // Start the web server.
192 ln, err := net.Listen("tcp", "localhost:0")
193 if err != nil {
194 log.Fatal(err)
195 }
196 mux := http.ServeMux{}
197 mux.Handle("/", wrapPanic(http.HandlerFunc(panickingHandler)))
198 ch := make(chan error)
199 go func() {
200 ch <- http.Serve(ln, &mux)
201 }()
202
203 // Call the server once to force a stack trace to be printed.
204 resp, err := http.Get("http://" + ln.Addr().String() + "/")
205 if err != nil {
206 log.Fatal(err)
207 }
208 b, err := io.ReadAll(resp.Body)
209 if err != nil {
210 log.Fatal(err)
211 }
212 resp.Body.Close()
213 if v := string(b); v != "Done" {
214 log.Fatal(v)
215 }
216
217 // Close the server.
218 if err := ln.Close(); err != nil {
219 log.Fatal(err)
220 }
221 <-ch
222 // Output:
223 // recovered: "It happens"
224 // Parsed stack:
225 // stack_test example_test.go:239 recoverPanic(<args>)
226 // stack_test example_test.go:233 panickingHandler(<args>)
227 // stack_test example_test.go:295 Example_httpHandlerMiddleware.wrapPanic.func2(<args>)
228 }
229
230 // panickingHandler is an http.HandlerFunc that panics.
231 func panickingHandler(w http.ResponseWriter, r *http.Request) {
232 w.Write([]byte("Done"))
233 panic("It happens")
234 }
235
236 func recoverPanic() {
237 if v := recover(); v != nil {
238 // Collect the stack and process it.
239 rawStack := append(debug.Stack(), '\n', '\n')
240 st, _, err := stack.ScanSnapshot(bytes.NewReader(rawStack), io.Discard, stack.DefaultOpts())
241
242 if err != nil || len(st.Goroutines) != 1 {
243 // Processing failed. Print out the raw stack.
244 fmt.Fprintf(os.Stdout, "recovered: %q\nStack processing failed: %v\nRaw stack:\n%s", v, err, rawStack)
245 return
246 }
247
248 // Calculate alignment.
249 srcLen := 0
250 pkgLen := 0
251 for _, line := range st.Goroutines[0].Stack.Calls {
252 if l := len(fmt.Sprintf("%s:%d", line.SrcName, line.Line)); l > srcLen {
253 srcLen = l
254 }
255 if l := len(filepath.Base(line.Func.ImportPath)); l > pkgLen {
256 pkgLen = l
257 }
258 }
259 buf := bytes.Buffer{}
260 // Reduce memory allocation.
261 buf.Grow(len(st.Goroutines[0].Stack.Calls) * (40 + srcLen + pkgLen))
262 for _, line := range st.Goroutines[0].Stack.Calls {
263
264 // REMOVE: Skip the standard library in this test since it would
265 // make it Go version dependent.
266 if line.Location == stack.Stdlib {
267 continue
268 }
269
270 // REMOVE: Not printing args here to make the test deterministic.
271 args := "<args>"
272 //args := line.Args.String()
273
274 fmt.Fprintf(
275 &buf,
276 " %-*s %-*s %s(%s)\n",
277 pkgLen, line.Func.DirName, srcLen,
278 fmt.Sprintf("%s:%d", line.SrcName, line.Line),
279 line.Func.Name,
280 args)
281 }
282 if st.Goroutines[0].Stack.Elided {
283 io.WriteString(&buf, " (...)\n")
284 }
285 // Print out the formatted stack.
286 fmt.Fprintf(os.Stdout, "recovered: %q\nParsed stack:\n%s", v, buf.String())
287 }
288 }
289
290 // wrapPanic is a http.Handler middleware that traps panics and print it out to
291 // os.Stdout.
292 func wrapPanic(h http.Handler) http.Handler {
293 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
294 defer recoverPanic()
295 h.ServeHTTP(w, r)
296 })
297 }