debug.go 4.3 KB

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