debug.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. ret.KVFunc("Uptime", func() any { return varz.Uptime() })
  46. ret.KV("Version", version.Long())
  47. ret.Handle("vars", "Metrics (Go)", expvar.Handler())
  48. ret.Handle("varz", "Metrics (Prometheus)", http.HandlerFunc(promvarz.Handler))
  49. ret.Handle("pprof/", "pprof (index)", http.HandlerFunc(pprof.Index))
  50. // the CPU profile handler is special because it responds
  51. // streamily, unlike every other pprof handler. This means it's
  52. // not made available through pprof.Index the way all the other
  53. // pprof types are, you have to register the CPU profile handler
  54. // separately. Use HandleSilent for that to not pollute the human
  55. // debug list with a link that produces streaming line noise if
  56. // you click it.
  57. ret.HandleSilent("pprof/profile", http.HandlerFunc(pprof.Profile))
  58. ret.URL("/debug/pprof/goroutine?debug=1", "Goroutines (collapsed)")
  59. ret.URL("/debug/pprof/goroutine?debug=2", "Goroutines (full)")
  60. ret.Handle("gc", "force GC", http.HandlerFunc(gcHandler))
  61. hostname, err := os.Hostname()
  62. if err == nil {
  63. ret.KV("Machine", hostname)
  64. }
  65. return ret
  66. }
  67. // ServeHTTP implements http.Handler.
  68. func (d *DebugHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  69. if !AllowDebugAccess(r) {
  70. http.Error(w, "debug access denied", http.StatusForbidden)
  71. return
  72. }
  73. if r.URL.Path != "/debug/" {
  74. // Sub-handlers are handled by the parent mux directly.
  75. http.NotFound(w, r)
  76. return
  77. }
  78. AddBrowserHeaders(w)
  79. f := func(format string, args ...any) { fmt.Fprintf(w, format, args...) }
  80. f("<html><body><h1>%s debug</h1><ul>", version.CmdName())
  81. for _, kv := range d.kvs {
  82. kv(w)
  83. }
  84. for _, url := range d.urls {
  85. io.WriteString(w, url)
  86. }
  87. for _, section := range d.sections {
  88. section(w, r)
  89. }
  90. }
  91. func (d *DebugHandler) handle(slug string, handler http.Handler) string {
  92. href := "/debug/" + slug
  93. d.mux.Handle(href, Protected(debugBrowserHeaderHandler(handler)))
  94. return href
  95. }
  96. // Handle registers handler at /debug/<slug> and creates a descriptive
  97. // entry in /debug/ for it.
  98. func (d *DebugHandler) Handle(slug, desc string, handler http.Handler) {
  99. href := d.handle(slug, handler)
  100. d.URL(href, desc)
  101. }
  102. // HandleSilent registers handler at /debug/<slug>. It does not create
  103. // a descriptive entry in /debug/ for it. This should be used
  104. // sparingly, for things that need to be registered but would pollute
  105. // the list of debug links.
  106. func (d *DebugHandler) HandleSilent(slug string, handler http.Handler) {
  107. d.handle(slug, handler)
  108. }
  109. // KV adds a key/value list item to /debug/.
  110. func (d *DebugHandler) KV(k string, v any) {
  111. val := html.EscapeString(fmt.Sprintf("%v", v))
  112. d.kvs = append(d.kvs, func(w io.Writer) {
  113. fmt.Fprintf(w, "<li><b>%s:</b> %s</li>", k, val)
  114. })
  115. }
  116. // KVFunc adds a key/value list item to /debug/. v is called on every
  117. // render of /debug/.
  118. func (d *DebugHandler) KVFunc(k string, v func() any) {
  119. d.kvs = append(d.kvs, func(w io.Writer) {
  120. val := html.EscapeString(fmt.Sprintf("%v", v()))
  121. fmt.Fprintf(w, "<li><b>%s:</b> %s</li>", k, val)
  122. })
  123. }
  124. // URL adds a URL and description list item to /debug/.
  125. func (d *DebugHandler) URL(url, desc string) {
  126. if desc != "" {
  127. desc = " (" + desc + ")"
  128. }
  129. d.urls = append(d.urls, fmt.Sprintf(`<li><a href="%s">%s</a>%s</li>`, url, url, html.EscapeString(desc)))
  130. }
  131. // Section invokes f on every render of /debug/ to add supplemental
  132. // HTML to the page body.
  133. func (d *DebugHandler) Section(f func(w io.Writer, r *http.Request)) {
  134. d.sections = append(d.sections, f)
  135. }
  136. func gcHandler(w http.ResponseWriter, r *http.Request) {
  137. w.Write([]byte("running GC...\n"))
  138. if f, ok := w.(http.Flusher); ok {
  139. f.Flush()
  140. }
  141. runtime.GC()
  142. w.Write([]byte("Done.\n"))
  143. }
  144. // debugBrowserHeaderHandler is a wrapper around BrowserHeaderHandler with a
  145. // more relaxed Content-Security-Policy that's acceptable for internal debug
  146. // pages. It should not be used on any public-facing handlers!
  147. func debugBrowserHeaderHandler(h http.Handler) http.Handler {
  148. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  149. AddBrowserHeaders(w)
  150. // The only difference from AddBrowserHeaders is that this policy
  151. // allows inline CSS styles. They make debug pages much easier to
  152. // prototype, while the risk of user-injected CSS is relatively low.
  153. w.Header().Set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; block-all-mixed-content; object-src 'none'; style-src 'self' 'unsafe-inline'")
  154. h.ServeHTTP(w, r)
  155. })
  156. }