Debian Codegraph @

cmd/panicweb/main.go

raw
1 // Copyright 2020 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 // panicweb implements a simulation of a web server that panics.
6 //
7 // It starts a web server, a few handlers and a few hanging clients, then
8 // panics.
9 //
10 // It loads both panicparse's http handler and pprof's one for comparison.
11 //
12 // It is separate from the panic tool because importing "net/http" creates a
13 // background thread, which breaks the "asleep" panic case in tool panic.
14 package main
15
16 import (
17 "flag"
18 "fmt"
19 "log"
20 "net"
21 "net/http"
22
23 /* #nosec G108 */
24 _ "net/http/pprof"
25 "os"
26 "runtime"
27 "strings"
28 "sync"
29 "time"
30
31 "github.com/maruel/panicparse/v2/cmd/panicweb/internal"
32 "github.com/maruel/panicparse/v2/stack/webstack"
33 "github.com/mattn/go-colorable"
34 )
35
36 var rootPage = []byte(`<!DOCTYPE html>
37 <ul>
38 <li><a href="/panicparse">/panicparse</a></li>
39 <li><a href="/debug/pprof/goroutine?debug=2">/debug/pprof/goroutine?debug=2</a></li>
40 <li><a href="/url1">/url1</a></li>
41 <li><a href="/url2">/url2</a></li>
42 </ul>
43 `)
44
45 func main() {
46 allowremote := flag.Bool("allowremote", false, "allows access from non-localhost; implies -wait")
47 sleep := flag.Bool("wait", false, "sleep instead of crashing")
48 port := flag.Int("port", 0, "specify a port number, defaults to a ephemeral port; implies -wait")
49 limit := flag.Bool("limit", false, "throttle, port limit")
50 flag.Parse()
51
52 if *port != 0 || *allowremote {
53 *sleep = true
54 }
55 addr := fmt.Sprintf(":%d", *port)
56 if !*allowremote {
57 addr = "localhost" + addr
58 }
59 ln, err := net.Listen("tcp", addr)
60 if err != nil {
61 log.Fatalf("Failed to listen on localhost: %v", err)
62 }
63 http.HandleFunc("/url1", internal.URL1Handler)
64 http.HandleFunc("/url2", internal.URL2Handler)
65 if *limit {
66 // This is similar to ExampleSnapshotHandler_complex in stack/webstack,
67 // albeit form values are not altered.
68 const delay = time.Second
69 mu := sync.Mutex{}
70 var last time.Time
71 http.HandleFunc("/panicparse", func(w http.ResponseWriter, req *http.Request) {
72 // Only allow requests from localhost or in the 100.64.x.x/10 IPv4 range
73 // (e.g. Tailscale).
74 ok := false
75 if i := strings.LastIndexByte(req.RemoteAddr, ':'); i != -1 {
76 switch ip := req.RemoteAddr[:i]; ip {
77 case "localhost", "127.0.0.1", "[::1]", "::1":
78 ok = true
79 default:
80 p := net.ParseIP(ip).To4()
81 ok = p != nil && p[0] == 100 && p[1] >= 64 && p[1] < 128
82 }
83 }
84 log.Printf("- %s: %t", req.RemoteAddr, ok)
85 if !ok {
86 http.Error(w, "forbidden", http.StatusForbidden)
87 return
88 }
89
90 // Serialize the handler.
91 mu.Lock()
92 defer mu.Unlock()
93
94 // Throttle requests.
95 if time.Since(last) < delay {
96 http.Error(w, "retry later", http.StatusTooManyRequests)
97 return
98 }
99
100 webstack.SnapshotHandler(w, req)
101 last = time.Now()
102 })
103 } else {
104 http.HandleFunc("/panicparse", webstack.SnapshotHandler)
105 }
106 http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
107 w.Header().Set("Content-Type", "text/html; charset=utf-8")
108 _, _ = w.Write(rootPage)
109 })
110 srv := &http.Server{
111 Handler: http.DefaultServeMux,
112 ReadHeaderTimeout: 2 * time.Second,
113 }
114 go srv.Serve(ln)
115
116 // Start many clients.
117 a := ln.Addr()
118 url := fmt.Sprintf("http://%s/", a)
119 if *allowremote {
120 if h, err := os.Hostname(); err == nil {
121 if t, ok := a.(*net.TCPAddr); ok {
122 url = fmt.Sprintf("http://%s:%d/", h, t.Port)
123 }
124 }
125 }
126 for i := 0; i < 10; i++ {
127 internal.GetAsync(url + "url1")
128 }
129 for i := 0; i < 3; i++ {
130 internal.GetAsync(url + "url2")
131 }
132
133 // Try to get something hung in package golang.org/x/unix.
134 wait := make(chan struct{})
135 go func() {
136 wait <- struct{}{}
137 sysHang()
138 }()
139 <-wait
140
141 // It's convoluted but colorable is the only go module used by panicparse
142 // that is both versioned and can be hacked to call back user code.
143 w := writeHang{hung: make(chan struct{}), unblock: make(chan struct{})}
144 v := colorable.NewNonColorable(&w)
145 go v.Write([]byte("foo bar"))
146 <-w.hung
147
148 if *sleep {
149 fmt.Printf("Compare:\n- %spanicparse\n- %sdebug/pprof/goroutine?debug=2\n", url, url)
150 <-make(chan struct{})
151 } else {
152 panic("Here's a snapshot of a normal web server.")
153 }
154 }
155
156 type writeHang struct {
157 hung chan struct{}
158 unblock chan struct{}
159 }
160
161 func (w *writeHang) Write(b []byte) (int, error) {
162 runtime.LockOSThread()
163 w.hung <- struct{}{}
164 <-w.unblock
165 return 0, nil
166 }