gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmhttp/pprof/pprof_test.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package pprof 6 7 import ( 8 "bytes" 9 "fmt" 10 "io" 11 "runtime" 12 "runtime/pprof" 13 "strings" 14 "sync" 15 "sync/atomic" 16 "testing" 17 "time" 18 19 "gitee.com/ks-custle/core-gm/internal/profile" 20 21 http "gitee.com/ks-custle/core-gm/gmhttp" 22 "gitee.com/ks-custle/core-gm/gmhttp/httptest" 23 ) 24 25 // TestDescriptions checks that the profile names under runtime/pprof package 26 // have a key in the description map. 27 func TestDescriptions(t *testing.T) { 28 for _, p := range pprof.Profiles() { 29 _, ok := profileDescriptions[p.Name()] 30 if ok != true { 31 t.Errorf("%s does not exist in profileDescriptions map\n", p.Name()) 32 } 33 } 34 } 35 36 func TestHandlers(t *testing.T) { 37 testCases := []struct { 38 path string 39 handler http.HandlerFunc 40 statusCode int 41 contentType string 42 contentDisposition string 43 resp []byte 44 }{ 45 {"/debug/pprof/<script>scripty<script>", Index, http.StatusNotFound, "text/plain; charset=utf-8", "", []byte("Unknown profile\n")}, 46 {"/debug/pprof/heap", Index, http.StatusOK, "application/octet-stream", `attachment; filename="heap"`, nil}, 47 {"/debug/pprof/heap?debug=1", Index, http.StatusOK, "text/plain; charset=utf-8", "", nil}, 48 {"/debug/pprof/cmdline", Cmdline, http.StatusOK, "text/plain; charset=utf-8", "", nil}, 49 {"/debug/pprof/profile?seconds=1", Profile, http.StatusOK, "application/octet-stream", `attachment; filename="profile"`, nil}, 50 {"/debug/pprof/symbol", Symbol, http.StatusOK, "text/plain; charset=utf-8", "", nil}, 51 {"/debug/pprof/trace", Trace, http.StatusOK, "application/octet-stream", `attachment; filename="trace"`, nil}, 52 {"/debug/pprof/mutex", Index, http.StatusOK, "application/octet-stream", `attachment; filename="mutex"`, nil}, 53 {"/debug/pprof/block?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="block-delta"`, nil}, 54 {"/debug/pprof/goroutine?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="goroutine-delta"`, nil}, 55 {"/debug/pprof/", Index, http.StatusOK, "text/html; charset=utf-8", "", []byte("Types of profiles available:")}, 56 } 57 for _, tc := range testCases { 58 t.Run(tc.path, func(t *testing.T) { 59 //goland:noinspection HttpUrlsUsage 60 req := httptest.NewRequest("GET", "http://example.com"+tc.path, nil) 61 w := httptest.NewRecorder() 62 tc.handler(w, req) 63 64 resp := w.Result() 65 if got, want := resp.StatusCode, tc.statusCode; got != want { 66 t.Errorf("status code: got %d; want %d", got, want) 67 } 68 69 body, err := io.ReadAll(resp.Body) 70 if err != nil { 71 t.Errorf("when reading response body, expected non-nil err; got %v", err) 72 } 73 if got, want := resp.Header.Get("X-Content-Type-Options"), "nosniff"; got != want { 74 t.Errorf("X-Content-Type-Options: got %q; want %q", got, want) 75 } 76 if got, want := resp.Header.Get("Content-Type"), tc.contentType; got != want { 77 t.Errorf("Content-Type: got %q; want %q", got, want) 78 } 79 if got, want := resp.Header.Get("Content-Disposition"), tc.contentDisposition; got != want { 80 t.Errorf("Content-Disposition: got %q; want %q", got, want) 81 } 82 83 if resp.StatusCode == http.StatusOK { 84 return 85 } 86 if got, want := resp.Header.Get("X-Go-Pprof"), "1"; got != want { 87 t.Errorf("X-Go-Pprof: got %q; want %q", got, want) 88 } 89 if !bytes.Equal(body, tc.resp) { 90 t.Errorf("response: got %q; want %q", body, tc.resp) 91 } 92 }) 93 } 94 } 95 96 var Sink uint32 97 98 func mutexHog1(mu1, mu2 *sync.Mutex, start time.Time, dt time.Duration) { 99 atomic.AddUint32(&Sink, 1) 100 for time.Since(start) < dt { 101 // When using gccgo the loop of mutex operations is 102 // not preemptible. This can cause the loop to block a GC, 103 // causing the time limits in TestDeltaContentionz to fail. 104 // Since this loop is not very realistic, when using 105 // gccgo add preemption points 100 times a second. 106 t1 := time.Now() 107 for time.Since(start) < dt && time.Since(t1) < 10*time.Millisecond { 108 mu1.Lock() 109 mu2.Lock() 110 mu1.Unlock() 111 mu2.Unlock() 112 } 113 //goland:noinspection GoBoolExpressions 114 if runtime.Compiler == "gccgo" { 115 runtime.Gosched() 116 } 117 } 118 } 119 120 // mutexHog2 is almost identical to mutexHog but we keep them separate 121 // in order to distinguish them with function names in the stack trace. 122 // We make them slightly different, using Sink, because otherwise 123 // gccgo -c opt will merge them. 124 func mutexHog2(mu1, mu2 *sync.Mutex, start time.Time, dt time.Duration) { 125 atomic.AddUint32(&Sink, 2) 126 for time.Since(start) < dt { 127 // See comment in mutexHog. 128 t1 := time.Now() 129 for time.Since(start) < dt && time.Since(t1) < 10*time.Millisecond { 130 mu1.Lock() 131 mu2.Lock() 132 mu1.Unlock() 133 mu2.Unlock() 134 } 135 //goland:noinspection GoBoolExpressions 136 if runtime.Compiler == "gccgo" { 137 runtime.Gosched() 138 } 139 } 140 } 141 142 // mutexHog starts multiple goroutines that runs the given hogger function for the specified duration. 143 // The hogger function will be given two mutexes to lock & unlock. 144 func mutexHog(duration time.Duration, hogger func(mu1, mu2 *sync.Mutex, start time.Time, dt time.Duration)) { 145 start := time.Now() 146 mu1 := new(sync.Mutex) 147 mu2 := new(sync.Mutex) 148 var wg sync.WaitGroup 149 wg.Add(10) 150 for i := 0; i < 10; i++ { 151 go func() { 152 defer wg.Done() 153 hogger(mu1, mu2, start, duration) 154 }() 155 } 156 wg.Wait() 157 } 158 159 func TestDeltaProfile(t *testing.T) { 160 rate := runtime.SetMutexProfileFraction(1) 161 defer func() { 162 runtime.SetMutexProfileFraction(rate) 163 }() 164 165 // mutexHog1 will appear in non-delta mutex profile 166 // if the mutex profile works. 167 mutexHog(20*time.Millisecond, mutexHog1) 168 169 // If mutexHog1 does not appear in the mutex profile, 170 // skip this test. Mutex profile is likely not working, 171 // so is the delta profile. 172 173 p, err := query("/debug/pprof/mutex") 174 if err != nil { 175 t.Skipf("mutex profile is unsupported: %v", err) 176 } 177 178 if !seen(p, "mutexHog1") { 179 t.Skipf("mutex profile is not working: %v", p) 180 } 181 182 // causes mutexHog2 call stacks to appear in the mutex profile. 183 done := make(chan bool) 184 go func() { 185 for { 186 mutexHog(20*time.Millisecond, mutexHog2) 187 select { 188 case <-done: 189 done <- true 190 return 191 default: 192 time.Sleep(10 * time.Millisecond) 193 } 194 } 195 }() 196 defer func() { // cleanup the above goroutine. 197 done <- true 198 <-done // wait for the goroutine to exit. 199 }() 200 201 for _, d := range []int{1, 4, 16, 32} { 202 endpoint := fmt.Sprintf("/debug/pprof/mutex?seconds=%d", d) 203 p, err := query(endpoint) 204 if err != nil { 205 t.Fatalf("failed to query %q: %v", endpoint, err) 206 } 207 if !seen(p, "mutexHog1") && seen(p, "mutexHog2") && p.DurationNanos > 0 { 208 break // pass 209 } 210 if d == 32 { 211 t.Errorf("want mutexHog2 but no mutexHog1 in the profile, and non-zero p.DurationNanos, got %v", p) 212 } 213 } 214 p, err = query("/debug/pprof/mutex") 215 if err != nil { 216 t.Fatalf("failed to query mutex profile: %v", err) 217 } 218 if !seen(p, "mutexHog1") || !seen(p, "mutexHog2") { 219 t.Errorf("want both mutexHog1 and mutexHog2 in the profile, got %v", p) 220 } 221 } 222 223 var srv = httptest.NewServer(nil) 224 225 func query(endpoint string) (*profile.Profile, error) { 226 url := srv.URL + endpoint 227 r, err := http.Get(url) 228 if err != nil { 229 return nil, fmt.Errorf("failed to fetch %q: %v", url, err) 230 } 231 if r.StatusCode != http.StatusOK { 232 return nil, fmt.Errorf("failed to fetch %q: %v", url, r.Status) 233 } 234 235 b, err := io.ReadAll(r.Body) 236 _ = r.Body.Close() 237 if err != nil { 238 return nil, fmt.Errorf("failed to read and parse the result from %q: %v", url, err) 239 } 240 return profile.Parse(bytes.NewBuffer(b)) 241 } 242 243 // seen returns true if the profile includes samples whose stacks include 244 // the specified function name (fname). 245 func seen(p *profile.Profile, fname string) bool { 246 locIDs := map[*profile.Location]bool{} 247 for _, loc := range p.Location { 248 for _, l := range loc.Line { 249 if strings.Contains(l.Function.Name, fname) { 250 locIDs[loc] = true 251 break 252 } 253 } 254 } 255 for _, sample := range p.Sample { 256 for _, loc := range sample.Location { 257 if locIDs[loc] { 258 return true 259 } 260 } 261 } 262 return false 263 }