debug.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2021 Tailscale Inc & 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. package controlclient
  5. import (
  6. "bytes"
  7. "compress/gzip"
  8. "context"
  9. "fmt"
  10. "log"
  11. "net/http"
  12. "regexp"
  13. "runtime"
  14. "strconv"
  15. "time"
  16. )
  17. func dumpGoroutinesToURL(c *http.Client, targetURL string) {
  18. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  19. defer cancel()
  20. zbuf := new(bytes.Buffer)
  21. zw := gzip.NewWriter(zbuf)
  22. zw.Write(scrubbedGoroutineDump())
  23. zw.Close()
  24. req, err := http.NewRequestWithContext(ctx, "PUT", targetURL, zbuf)
  25. if err != nil {
  26. log.Printf("dumpGoroutinesToURL: %v", err)
  27. return
  28. }
  29. req.Header.Set("Content-Encoding", "gzip")
  30. t0 := time.Now()
  31. _, err = c.Do(req)
  32. d := time.Since(t0).Round(time.Millisecond)
  33. if err != nil {
  34. log.Printf("dumpGoroutinesToURL error: %v to %v (after %v)", err, targetURL, d)
  35. } else {
  36. log.Printf("dumpGoroutinesToURL complete to %v (after %v)", targetURL, d)
  37. }
  38. }
  39. var reHexArgs = regexp.MustCompile(`\b0x[0-9a-f]+\b`)
  40. // scrubbedGoroutineDump returns the list of all current goroutines, but with the actual
  41. // values of arguments scrubbed out, lest it contain some private key material.
  42. func scrubbedGoroutineDump() []byte {
  43. buf := make([]byte, 1<<20)
  44. buf = buf[:runtime.Stack(buf, true)]
  45. saw := map[string][]byte{} // "0x123" => "v1%3" (unique value 1 and its value mod 8)
  46. return reHexArgs.ReplaceAllFunc(buf, func(in []byte) []byte {
  47. if string(in) == "0x0" {
  48. return in
  49. }
  50. if v, ok := saw[string(in)]; ok {
  51. return v
  52. }
  53. u64, err := strconv.ParseUint(string(in[2:]), 16, 64)
  54. if err != nil {
  55. return []byte("??")
  56. }
  57. v := []byte(fmt.Sprintf("v%d%%%d", len(saw)+1, u64%8))
  58. saw[string(in)] = v
  59. return v
  60. })
  61. }