debug.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package tsweb
  4. import (
  5. "expvar"
  6. "fmt"
  7. "html"
  8. "io"
  9. "net/http"
  10. "net/http/pprof"
  11. "net/url"
  12. "os"
  13. "runtime"
  14. "tailscale.com/tsweb/promvarz"
  15. "tailscale.com/tsweb/varz"
  16. "tailscale.com/version"
  17. )
  18. // DebugHandler is an http.Handler that serves a debugging "homepage",
  19. // and provides helpers to register more debug endpoints and reports.
  20. //
  21. // The rendered page consists of three sections: informational
  22. // key/value pairs, links to other pages, and additional
  23. // program-specific HTML. Callers can add to these sections using the
  24. // KV, URL and Section helpers respectively.
  25. //
  26. // Additionally, the Handle method offers a shorthand for correctly
  27. // registering debug handlers and cross-linking them from /debug/.
  28. type DebugHandler struct {
  29. mux *http.ServeMux // where this handler is registered
  30. kvs []func(io.Writer) // output one <li>...</li> each, see KV()
  31. urls []string // one <li>...</li> block with link each
  32. sections []func(io.Writer, *http.Request) // invoked in registration order prior to outputting </body>
  33. }
  34. // Debugger returns the DebugHandler registered on mux at /debug/,
  35. // creating it if necessary.
  36. func Debugger(mux *http.ServeMux) *DebugHandler {
  37. h, pat := mux.Handler(&http.Request{URL: &url.URL{Path: "/debug/"}})
  38. if d, ok := h.(*DebugHandler); ok && pat == "/debug/" {
  39. return d
  40. }
  41. ret := &DebugHandler{
  42. mux: mux,
  43. }
  44. mux.Handle("/debug/", ret)
  45. // Register this one directly on mux, rather than using
  46. // ret.URL/etc, as we don't need another line of output on the
  47. // index page. The /pprof/ index already covers it.
  48. mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
  49. ret.KVFunc("Uptime", func() any { return varz.Uptime() })
  50. ret.KV("Version", version.Long())
  51. ret.Handle("vars", "Metrics (Go)", expvar.Handler())
  52. ret.Handle("varz", "Metrics (Prometheus)", http.HandlerFunc(promvarz.Handler))
  53. ret.Handle("pprof/", "pprof", http.HandlerFunc(pprof.Index))
  54. ret.URL("/debug/pprof/goroutine?debug=1", "Goroutines (collapsed)")
  55. ret.URL("/debug/pprof/goroutine?debug=2", "Goroutines (full)")
  56. ret.Handle("gc", "force GC", http.HandlerFunc(gcHandler))
  57. hostname, err := os.Hostname()
  58. if err == nil {
  59. ret.KV("Machine", hostname)
  60. }
  61. return ret
  62. }
  63. // ServeHTTP implements http.Handler.
  64. func (d *DebugHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  65. if !AllowDebugAccess(r) {
  66. http.Error(w, "debug access denied", http.StatusForbidden)
  67. return
  68. }
  69. if r.URL.Path != "/debug/" {
  70. // Sub-handlers are handled by the parent mux directly.
  71. http.NotFound(w, r)
  72. return
  73. }
  74. f := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
  75. f("<html><body><h1>%s debug</h1><ul>", version.CmdName())
  76. for _, kv := range d.kvs {
  77. kv(w)
  78. }
  79. for _, url := range d.urls {
  80. io.WriteString(w, url)
  81. }
  82. for _, section := range d.sections {
  83. section(w, r)
  84. }
  85. }
  86. // Handle registers handler at /debug/<slug> and creates a descriptive
  87. // entry in /debug/ for it.
  88. func (d *DebugHandler) Handle(slug, desc string, handler http.Handler) {
  89. href := "/debug/" + slug
  90. d.mux.Handle(href, Protected(handler))
  91. d.URL(href, desc)
  92. }
  93. // KV adds a key/value list item to /debug/.
  94. func (d *DebugHandler) KV(k string, v any) {
  95. val := html.EscapeString(fmt.Sprintf("%v", v))
  96. d.kvs = append(d.kvs, func(w io.Writer) {
  97. fmt.Fprintf(w, "<li><b>%s:</b> %s</li>", k, val)
  98. })
  99. }
  100. // KVFunc adds a key/value list item to /debug/. v is called on every
  101. // render of /debug/.
  102. func (d *DebugHandler) KVFunc(k string, v func() any) {
  103. d.kvs = append(d.kvs, func(w io.Writer) {
  104. val := html.EscapeString(fmt.Sprintf("%v", v()))
  105. fmt.Fprintf(w, "<li><b>%s:</b> %s</li>", k, val)
  106. })
  107. }
  108. // URL adds a URL and description list item to /debug/.
  109. func (d *DebugHandler) URL(url, desc string) {
  110. if desc != "" {
  111. desc = " (" + desc + ")"
  112. }
  113. d.urls = append(d.urls, fmt.Sprintf(`<li><a href="%s">%s</a>%s</li>`, url, url, html.EscapeString(desc)))
  114. }
  115. // Section invokes f on every render of /debug/ to add supplemental
  116. // HTML to the page body.
  117. func (d *DebugHandler) Section(f func(w io.Writer, r *http.Request)) {
  118. d.sections = append(d.sections, f)
  119. }
  120. func gcHandler(w http.ResponseWriter, r *http.Request) {
  121. w.Write([]byte("running GC...\n"))
  122. if f, ok := w.(http.Flusher); ok {
  123. f.Flush()
  124. }
  125. runtime.GC()
  126. w.Write([]byte("Done.\n"))
  127. }