You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1080 lines
27 KiB

  1. // Copyright 2015 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 trace implements tracing of requests and long-lived objects.
  6. It exports HTTP interfaces on /debug/requests and /debug/events.
  7. A trace.Trace provides tracing for short-lived objects, usually requests.
  8. A request handler might be implemented like this:
  9. func fooHandler(w http.ResponseWriter, req *http.Request) {
  10. tr := trace.New("mypkg.Foo", req.URL.Path)
  11. defer tr.Finish()
  12. ...
  13. tr.LazyPrintf("some event %q happened", str)
  14. ...
  15. if err := somethingImportant(); err != nil {
  16. tr.LazyPrintf("somethingImportant failed: %v", err)
  17. tr.SetError()
  18. }
  19. }
  20. The /debug/requests HTTP endpoint organizes the traces by family,
  21. errors, and duration. It also provides histogram of request duration
  22. for each family.
  23. A trace.EventLog provides tracing for long-lived objects, such as RPC
  24. connections.
  25. // A Fetcher fetches URL paths for a single domain.
  26. type Fetcher struct {
  27. domain string
  28. events trace.EventLog
  29. }
  30. func NewFetcher(domain string) *Fetcher {
  31. return &Fetcher{
  32. domain,
  33. trace.NewEventLog("mypkg.Fetcher", domain),
  34. }
  35. }
  36. func (f *Fetcher) Fetch(path string) (string, error) {
  37. resp, err := http.Get("http://" + f.domain + "/" + path)
  38. if err != nil {
  39. f.events.Errorf("Get(%q) = %v", path, err)
  40. return "", err
  41. }
  42. f.events.Printf("Get(%q) = %s", path, resp.Status)
  43. ...
  44. }
  45. func (f *Fetcher) Close() error {
  46. f.events.Finish()
  47. return nil
  48. }
  49. The /debug/events HTTP endpoint organizes the event logs by family and
  50. by time since the last error. The expanded view displays recent log
  51. entries and the log's call stack.
  52. */
  53. package trace // import "golang.org/x/net/trace"
  54. import (
  55. "bytes"
  56. "fmt"
  57. "html/template"
  58. "io"
  59. "log"
  60. "net"
  61. "net/http"
  62. "runtime"
  63. "sort"
  64. "strconv"
  65. "sync"
  66. "sync/atomic"
  67. "time"
  68. "golang.org/x/net/context"
  69. "golang.org/x/net/internal/timeseries"
  70. )
  71. // DebugUseAfterFinish controls whether to debug uses of Trace values after finishing.
  72. // FOR DEBUGGING ONLY. This will slow down the program.
  73. var DebugUseAfterFinish = false
  74. // AuthRequest determines whether a specific request is permitted to load the
  75. // /debug/requests or /debug/events pages.
  76. //
  77. // It returns two bools; the first indicates whether the page may be viewed at all,
  78. // and the second indicates whether sensitive events will be shown.
  79. //
  80. // AuthRequest may be replaced by a program to customize its authorization requirements.
  81. //
  82. // The default AuthRequest function returns (true, true) if and only if the request
  83. // comes from localhost/127.0.0.1/[::1].
  84. var AuthRequest = func(req *http.Request) (any, sensitive bool) {
  85. // RemoteAddr is commonly in the form "IP" or "IP:port".
  86. // If it is in the form "IP:port", split off the port.
  87. host, _, err := net.SplitHostPort(req.RemoteAddr)
  88. if err != nil {
  89. host = req.RemoteAddr
  90. }
  91. switch host {
  92. case "localhost", "127.0.0.1", "::1":
  93. return true, true
  94. default:
  95. return false, false
  96. }
  97. }
  98. func init() {
  99. http.HandleFunc("/debug/requests", func(w http.ResponseWriter, req *http.Request) {
  100. any, sensitive := AuthRequest(req)
  101. if !any {
  102. http.Error(w, "not allowed", http.StatusUnauthorized)
  103. return
  104. }
  105. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  106. Render(w, req, sensitive)
  107. })
  108. http.HandleFunc("/debug/events", func(w http.ResponseWriter, req *http.Request) {
  109. any, sensitive := AuthRequest(req)
  110. if !any {
  111. http.Error(w, "not allowed", http.StatusUnauthorized)
  112. return
  113. }
  114. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  115. RenderEvents(w, req, sensitive)
  116. })
  117. }
  118. // Render renders the HTML page typically served at /debug/requests.
  119. // It does not do any auth checking; see AuthRequest for the default auth check
  120. // used by the handler registered on http.DefaultServeMux.
  121. // req may be nil.
  122. func Render(w io.Writer, req *http.Request, sensitive bool) {
  123. data := &struct {
  124. Families []string
  125. ActiveTraceCount map[string]int
  126. CompletedTraces map[string]*family
  127. // Set when a bucket has been selected.
  128. Traces traceList
  129. Family string
  130. Bucket int
  131. Expanded bool
  132. Traced bool
  133. Active bool
  134. ShowSensitive bool // whether to show sensitive events
  135. Histogram template.HTML
  136. HistogramWindow string // e.g. "last minute", "last hour", "all time"
  137. // If non-zero, the set of traces is a partial set,
  138. // and this is the total number.
  139. Total int
  140. }{
  141. CompletedTraces: completedTraces,
  142. }
  143. data.ShowSensitive = sensitive
  144. if req != nil {
  145. // Allow show_sensitive=0 to force hiding of sensitive data for testing.
  146. // This only goes one way; you can't use show_sensitive=1 to see things.
  147. if req.FormValue("show_sensitive") == "0" {
  148. data.ShowSensitive = false
  149. }
  150. if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil {
  151. data.Expanded = exp
  152. }
  153. if exp, err := strconv.ParseBool(req.FormValue("rtraced")); err == nil {
  154. data.Traced = exp
  155. }
  156. }
  157. completedMu.RLock()
  158. data.Families = make([]string, 0, len(completedTraces))
  159. for fam := range completedTraces {
  160. data.Families = append(data.Families, fam)
  161. }
  162. completedMu.RUnlock()
  163. sort.Strings(data.Families)
  164. // We are careful here to minimize the time spent locking activeMu,
  165. // since that lock is required every time an RPC starts and finishes.
  166. data.ActiveTraceCount = make(map[string]int, len(data.Families))
  167. activeMu.RLock()
  168. for fam, s := range activeTraces {
  169. data.ActiveTraceCount[fam] = s.Len()
  170. }
  171. activeMu.RUnlock()
  172. var ok bool
  173. data.Family, data.Bucket, ok = parseArgs(req)
  174. switch {
  175. case !ok:
  176. // No-op
  177. case data.Bucket == -1:
  178. data.Active = true
  179. n := data.ActiveTraceCount[data.Family]
  180. data.Traces = getActiveTraces(data.Family)
  181. if len(data.Traces) < n {
  182. data.Total = n
  183. }
  184. case data.Bucket < bucketsPerFamily:
  185. if b := lookupBucket(data.Family, data.Bucket); b != nil {
  186. data.Traces = b.Copy(data.Traced)
  187. }
  188. default:
  189. if f := getFamily(data.Family, false); f != nil {
  190. var obs timeseries.Observable
  191. f.LatencyMu.RLock()
  192. switch o := data.Bucket - bucketsPerFamily; o {
  193. case 0:
  194. obs = f.Latency.Minute()
  195. data.HistogramWindow = "last minute"
  196. case 1:
  197. obs = f.Latency.Hour()
  198. data.HistogramWindow = "last hour"
  199. case 2:
  200. obs = f.Latency.Total()
  201. data.HistogramWindow = "all time"
  202. }
  203. f.LatencyMu.RUnlock()
  204. if obs != nil {
  205. data.Histogram = obs.(*histogram).html()
  206. }
  207. }
  208. }
  209. if data.Traces != nil {
  210. defer data.Traces.Free()
  211. sort.Sort(data.Traces)
  212. }
  213. completedMu.RLock()
  214. defer completedMu.RUnlock()
  215. if err := pageTmpl().ExecuteTemplate(w, "Page", data); err != nil {
  216. log.Printf("net/trace: Failed executing template: %v", err)
  217. }
  218. }
  219. func parseArgs(req *http.Request) (fam string, b int, ok bool) {
  220. if req == nil {
  221. return "", 0, false
  222. }
  223. fam, bStr := req.FormValue("fam"), req.FormValue("b")
  224. if fam == "" || bStr == "" {
  225. return "", 0, false
  226. }
  227. b, err := strconv.Atoi(bStr)
  228. if err != nil || b < -1 {
  229. return "", 0, false
  230. }
  231. return fam, b, true
  232. }
  233. func lookupBucket(fam string, b int) *traceBucket {
  234. f := getFamily(fam, false)
  235. if f == nil || b < 0 || b >= len(f.Buckets) {
  236. return nil
  237. }
  238. return f.Buckets[b]
  239. }
  240. type contextKeyT string
  241. var contextKey = contextKeyT("golang.org/x/net/trace.Trace")
  242. // NewContext returns a copy of the parent context
  243. // and associates it with a Trace.
  244. func NewContext(ctx context.Context, tr Trace) context.Context {
  245. return context.WithValue(ctx, contextKey, tr)
  246. }
  247. // FromContext returns the Trace bound to the context, if any.
  248. func FromContext(ctx context.Context) (tr Trace, ok bool) {
  249. tr, ok = ctx.Value(contextKey).(Trace)
  250. return
  251. }
  252. // Trace represents an active request.
  253. type Trace interface {
  254. // LazyLog adds x to the event log. It will be evaluated each time the
  255. // /debug/requests page is rendered. Any memory referenced by x will be
  256. // pinned until the trace is finished and later discarded.
  257. LazyLog(x fmt.Stringer, sensitive bool)
  258. // LazyPrintf evaluates its arguments with fmt.Sprintf each time the
  259. // /debug/requests page is rendered. Any memory referenced by a will be
  260. // pinned until the trace is finished and later discarded.
  261. LazyPrintf(format string, a ...interface{})
  262. // SetError declares that this trace resulted in an error.
  263. SetError()
  264. // SetRecycler sets a recycler for the trace.
  265. // f will be called for each event passed to LazyLog at a time when
  266. // it is no longer required, whether while the trace is still active
  267. // and the event is discarded, or when a completed trace is discarded.
  268. SetRecycler(f func(interface{}))
  269. // SetTraceInfo sets the trace info for the trace.
  270. // This is currently unused.
  271. SetTraceInfo(traceID, spanID uint64)
  272. // SetMaxEvents sets the maximum number of events that will be stored
  273. // in the trace. This has no effect if any events have already been
  274. // added to the trace.
  275. SetMaxEvents(m int)
  276. // Finish declares that this trace is complete.
  277. // The trace should not be used after calling this method.
  278. Finish()
  279. }
  280. type lazySprintf struct {
  281. format string
  282. a []interface{}
  283. }
  284. func (l *lazySprintf) String() string {
  285. return fmt.Sprintf(l.format, l.a...)
  286. }
  287. // New returns a new Trace with the specified family and title.
  288. func New(family, title string) Trace {
  289. tr := newTrace()
  290. tr.ref()
  291. tr.Family, tr.Title = family, title
  292. tr.Start = time.Now()
  293. tr.maxEvents = maxEventsPerTrace
  294. tr.events = tr.eventsBuf[:0]
  295. activeMu.RLock()
  296. s := activeTraces[tr.Family]
  297. activeMu.RUnlock()
  298. if s == nil {
  299. activeMu.Lock()
  300. s = activeTraces[tr.Family] // check again
  301. if s == nil {
  302. s = new(traceSet)
  303. activeTraces[tr.Family] = s
  304. }
  305. activeMu.Unlock()
  306. }
  307. s.Add(tr)
  308. // Trigger allocation of the completed trace structure for this family.
  309. // This will cause the family to be present in the request page during
  310. // the first trace of this family. We don't care about the return value,
  311. // nor is there any need for this to run inline, so we execute it in its
  312. // own goroutine, but only if the family isn't allocated yet.
  313. completedMu.RLock()
  314. if _, ok := completedTraces[tr.Family]; !ok {
  315. go allocFamily(tr.Family)
  316. }
  317. completedMu.RUnlock()
  318. return tr
  319. }
  320. func (tr *trace) Finish() {
  321. tr.Elapsed = time.Now().Sub(tr.Start)
  322. if DebugUseAfterFinish {
  323. buf := make([]byte, 4<<10) // 4 KB should be enough
  324. n := runtime.Stack(buf, false)
  325. tr.finishStack = buf[:n]
  326. }
  327. activeMu.RLock()
  328. m := activeTraces[tr.Family]
  329. activeMu.RUnlock()
  330. m.Remove(tr)
  331. f := getFamily(tr.Family, true)
  332. for _, b := range f.Buckets {
  333. if b.Cond.match(tr) {
  334. b.Add(tr)
  335. }
  336. }
  337. // Add a sample of elapsed time as microseconds to the family's timeseries
  338. h := new(histogram)
  339. h.addMeasurement(tr.Elapsed.Nanoseconds() / 1e3)
  340. f.LatencyMu.Lock()
  341. f.Latency.Add(h)
  342. f.LatencyMu.Unlock()
  343. tr.unref() // matches ref in New
  344. }
  345. const (
  346. bucketsPerFamily = 9
  347. tracesPerBucket = 10
  348. maxActiveTraces = 20 // Maximum number of active traces to show.
  349. maxEventsPerTrace = 10
  350. numHistogramBuckets = 38
  351. )
  352. var (
  353. // The active traces.
  354. activeMu sync.RWMutex
  355. activeTraces = make(map[string]*traceSet) // family -> traces
  356. // Families of completed traces.
  357. completedMu sync.RWMutex
  358. completedTraces = make(map[string]*family) // family -> traces
  359. )
  360. type traceSet struct {
  361. mu sync.RWMutex
  362. m map[*trace]bool
  363. // We could avoid the entire map scan in FirstN by having a slice of all the traces
  364. // ordered by start time, and an index into that from the trace struct, with a periodic
  365. // repack of the slice after enough traces finish; we could also use a skip list or similar.
  366. // However, that would shift some of the expense from /debug/requests time to RPC time,
  367. // which is probably the wrong trade-off.
  368. }
  369. func (ts *traceSet) Len() int {
  370. ts.mu.RLock()
  371. defer ts.mu.RUnlock()
  372. return len(ts.m)
  373. }
  374. func (ts *traceSet) Add(tr *trace) {
  375. ts.mu.Lock()
  376. if ts.m == nil {
  377. ts.m = make(map[*trace]bool)
  378. }
  379. ts.m[tr] = true
  380. ts.mu.Unlock()
  381. }
  382. func (ts *traceSet) Remove(tr *trace) {
  383. ts.mu.Lock()
  384. delete(ts.m, tr)
  385. ts.mu.Unlock()
  386. }
  387. // FirstN returns the first n traces ordered by time.
  388. func (ts *traceSet) FirstN(n int) traceList {
  389. ts.mu.RLock()
  390. defer ts.mu.RUnlock()
  391. if n > len(ts.m) {
  392. n = len(ts.m)
  393. }
  394. trl := make(traceList, 0, n)
  395. // Fast path for when no selectivity is needed.
  396. if n == len(ts.m) {
  397. for tr := range ts.m {
  398. tr.ref()
  399. trl = append(trl, tr)
  400. }
  401. sort.Sort(trl)
  402. return trl
  403. }
  404. // Pick the oldest n traces.
  405. // This is inefficient. See the comment in the traceSet struct.
  406. for tr := range ts.m {
  407. // Put the first n traces into trl in the order they occur.
  408. // When we have n, sort trl, and thereafter maintain its order.
  409. if len(trl) < n {
  410. tr.ref()
  411. trl = append(trl, tr)
  412. if len(trl) == n {
  413. // This is guaranteed to happen exactly once during this loop.
  414. sort.Sort(trl)
  415. }
  416. continue
  417. }
  418. if tr.Start.After(trl[n-1].Start) {
  419. continue
  420. }
  421. // Find where to insert this one.
  422. tr.ref()
  423. i := sort.Search(n, func(i int) bool { return trl[i].Start.After(tr.Start) })
  424. trl[n-1].unref()
  425. copy(trl[i+1:], trl[i:])
  426. trl[i] = tr
  427. }
  428. return trl
  429. }
  430. func getActiveTraces(fam string) traceList {
  431. activeMu.RLock()
  432. s := activeTraces[fam]
  433. activeMu.RUnlock()
  434. if s == nil {
  435. return nil
  436. }
  437. return s.FirstN(maxActiveTraces)
  438. }
  439. func getFamily(fam string, allocNew bool) *family {
  440. completedMu.RLock()
  441. f := completedTraces[fam]
  442. completedMu.RUnlock()
  443. if f == nil && allocNew {
  444. f = allocFamily(fam)
  445. }
  446. return f
  447. }
  448. func allocFamily(fam string) *family {
  449. completedMu.Lock()
  450. defer completedMu.Unlock()
  451. f := completedTraces[fam]
  452. if f == nil {
  453. f = newFamily()
  454. completedTraces[fam] = f
  455. }
  456. return f
  457. }
  458. // family represents a set of trace buckets and associated latency information.
  459. type family struct {
  460. // traces may occur in multiple buckets.
  461. Buckets [bucketsPerFamily]*traceBucket
  462. // latency time series
  463. LatencyMu sync.RWMutex
  464. Latency *timeseries.MinuteHourSeries
  465. }
  466. func newFamily() *family {
  467. return &family{
  468. Buckets: [bucketsPerFamily]*traceBucket{
  469. {Cond: minCond(0)},
  470. {Cond: minCond(50 * time.Millisecond)},
  471. {Cond: minCond(100 * time.Millisecond)},
  472. {Cond: minCond(200 * time.Millisecond)},
  473. {Cond: minCond(500 * time.Millisecond)},
  474. {Cond: minCond(1 * time.Second)},
  475. {Cond: minCond(10 * time.Second)},
  476. {Cond: minCond(100 * time.Second)},
  477. {Cond: errorCond{}},
  478. },
  479. Latency: timeseries.NewMinuteHourSeries(func() timeseries.Observable { return new(histogram) }),
  480. }
  481. }
  482. // traceBucket represents a size-capped bucket of historic traces,
  483. // along with a condition for a trace to belong to the bucket.
  484. type traceBucket struct {
  485. Cond cond
  486. // Ring buffer implementation of a fixed-size FIFO queue.
  487. mu sync.RWMutex
  488. buf [tracesPerBucket]*trace
  489. start int // < tracesPerBucket
  490. length int // <= tracesPerBucket
  491. }
  492. func (b *traceBucket) Add(tr *trace) {
  493. b.mu.Lock()
  494. defer b.mu.Unlock()
  495. i := b.start + b.length
  496. if i >= tracesPerBucket {
  497. i -= tracesPerBucket
  498. }
  499. if b.length == tracesPerBucket {
  500. // "Remove" an element from the bucket.
  501. b.buf[i].unref()
  502. b.start++
  503. if b.start == tracesPerBucket {
  504. b.start = 0
  505. }
  506. }
  507. b.buf[i] = tr
  508. if b.length < tracesPerBucket {
  509. b.length++
  510. }
  511. tr.ref()
  512. }
  513. // Copy returns a copy of the traces in the bucket.
  514. // If tracedOnly is true, only the traces with trace information will be returned.
  515. // The logs will be ref'd before returning; the caller should call
  516. // the Free method when it is done with them.
  517. // TODO(dsymonds): keep track of traced requests in separate buckets.
  518. func (b *traceBucket) Copy(tracedOnly bool) traceList {
  519. b.mu.RLock()
  520. defer b.mu.RUnlock()
  521. trl := make(traceList, 0, b.length)
  522. for i, x := 0, b.start; i < b.length; i++ {
  523. tr := b.buf[x]
  524. if !tracedOnly || tr.spanID != 0 {
  525. tr.ref()
  526. trl = append(trl, tr)
  527. }
  528. x++
  529. if x == b.length {
  530. x = 0
  531. }
  532. }
  533. return trl
  534. }
  535. func (b *traceBucket) Empty() bool {
  536. b.mu.RLock()
  537. defer b.mu.RUnlock()
  538. return b.length == 0
  539. }
  540. // cond represents a condition on a trace.
  541. type cond interface {
  542. match(t *trace) bool
  543. String() string
  544. }
  545. type minCond time.Duration
  546. func (m minCond) match(t *trace) bool { return t.Elapsed >= time.Duration(m) }
  547. func (m minCond) String() string { return fmt.Sprintf("≥%gs", time.Duration(m).Seconds()) }
  548. type errorCond struct{}
  549. func (e errorCond) match(t *trace) bool { return t.IsError }
  550. func (e errorCond) String() string { return "errors" }
  551. type traceList []*trace
  552. // Free calls unref on each element of the list.
  553. func (trl traceList) Free() {
  554. for _, t := range trl {
  555. t.unref()
  556. }
  557. }
  558. // traceList may be sorted in reverse chronological order.
  559. func (trl traceList) Len() int { return len(trl) }
  560. func (trl traceList) Less(i, j int) bool { return trl[i].Start.After(trl[j].Start) }
  561. func (trl traceList) Swap(i, j int) { trl[i], trl[j] = trl[j], trl[i] }
  562. // An event is a timestamped log entry in a trace.
  563. type event struct {
  564. When time.Time
  565. Elapsed time.Duration // since previous event in trace
  566. NewDay bool // whether this event is on a different day to the previous event
  567. Recyclable bool // whether this event was passed via LazyLog
  568. Sensitive bool // whether this event contains sensitive information
  569. What interface{} // string or fmt.Stringer
  570. }
  571. // WhenString returns a string representation of the elapsed time of the event.
  572. // It will include the date if midnight was crossed.
  573. func (e event) WhenString() string {
  574. if e.NewDay {
  575. return e.When.Format("2006/01/02 15:04:05.000000")
  576. }
  577. return e.When.Format("15:04:05.000000")
  578. }
  579. // discarded represents a number of discarded events.
  580. // It is stored as *discarded to make it easier to update in-place.
  581. type discarded int
  582. func (d *discarded) String() string {
  583. return fmt.Sprintf("(%d events discarded)", int(*d))
  584. }
  585. // trace represents an active or complete request,
  586. // either sent or received by this program.
  587. type trace struct {
  588. // Family is the top-level grouping of traces to which this belongs.
  589. Family string
  590. // Title is the title of this trace.
  591. Title string
  592. // Timing information.
  593. Start time.Time
  594. Elapsed time.Duration // zero while active
  595. // Trace information if non-zero.
  596. traceID uint64
  597. spanID uint64
  598. // Whether this trace resulted in an error.
  599. IsError bool
  600. // Append-only sequence of events (modulo discards).
  601. mu sync.RWMutex
  602. events []event
  603. maxEvents int
  604. refs int32 // how many buckets this is in
  605. recycler func(interface{})
  606. disc discarded // scratch space to avoid allocation
  607. finishStack []byte // where finish was called, if DebugUseAfterFinish is set
  608. eventsBuf [4]event // preallocated buffer in case we only log a few events
  609. }
  610. func (tr *trace) reset() {
  611. // Clear all but the mutex. Mutexes may not be copied, even when unlocked.
  612. tr.Family = ""
  613. tr.Title = ""
  614. tr.Start = time.Time{}
  615. tr.Elapsed = 0
  616. tr.traceID = 0
  617. tr.spanID = 0
  618. tr.IsError = false
  619. tr.maxEvents = 0
  620. tr.events = nil
  621. tr.refs = 0
  622. tr.recycler = nil
  623. tr.disc = 0
  624. tr.finishStack = nil
  625. for i := range tr.eventsBuf {
  626. tr.eventsBuf[i] = event{}
  627. }
  628. }
  629. // delta returns the elapsed time since the last event or the trace start,
  630. // and whether it spans midnight.
  631. // L >= tr.mu
  632. func (tr *trace) delta(t time.Time) (time.Duration, bool) {
  633. if len(tr.events) == 0 {
  634. return t.Sub(tr.Start), false
  635. }
  636. prev := tr.events[len(tr.events)-1].When
  637. return t.Sub(prev), prev.Day() != t.Day()
  638. }
  639. func (tr *trace) addEvent(x interface{}, recyclable, sensitive bool) {
  640. if DebugUseAfterFinish && tr.finishStack != nil {
  641. buf := make([]byte, 4<<10) // 4 KB should be enough
  642. n := runtime.Stack(buf, false)
  643. log.Printf("net/trace: trace used after finish:\nFinished at:\n%s\nUsed at:\n%s", tr.finishStack, buf[:n])
  644. }
  645. /*
  646. NOTE TO DEBUGGERS
  647. If you are here because your program panicked in this code,
  648. it is almost definitely the fault of code using this package,
  649. and very unlikely to be the fault of this code.
  650. The most likely scenario is that some code elsewhere is using
  651. a trace.Trace after its Finish method is called.
  652. You can temporarily set the DebugUseAfterFinish var
  653. to help discover where that is; do not leave that var set,
  654. since it makes this package much less efficient.
  655. */
  656. e := event{When: time.Now(), What: x, Recyclable: recyclable, Sensitive: sensitive}
  657. tr.mu.Lock()
  658. e.Elapsed, e.NewDay = tr.delta(e.When)
  659. if len(tr.events) < tr.maxEvents {
  660. tr.events = append(tr.events, e)
  661. } else {
  662. // Discard the middle events.
  663. di := int((tr.maxEvents - 1) / 2)
  664. if d, ok := tr.events[di].What.(*discarded); ok {
  665. (*d)++
  666. } else {
  667. // disc starts at two to count for the event it is replacing,
  668. // plus the next one that we are about to drop.
  669. tr.disc = 2
  670. if tr.recycler != nil && tr.events[di].Recyclable {
  671. go tr.recycler(tr.events[di].What)
  672. }
  673. tr.events[di].What = &tr.disc
  674. }
  675. // The timestamp of the discarded meta-event should be
  676. // the time of the last event it is representing.
  677. tr.events[di].When = tr.events[di+1].When
  678. if tr.recycler != nil && tr.events[di+1].Recyclable {
  679. go tr.recycler(tr.events[di+1].What)
  680. }
  681. copy(tr.events[di+1:], tr.events[di+2:])
  682. tr.events[tr.maxEvents-1] = e
  683. }
  684. tr.mu.Unlock()
  685. }
  686. func (tr *trace) LazyLog(x fmt.Stringer, sensitive bool) {
  687. tr.addEvent(x, true, sensitive)
  688. }
  689. func (tr *trace) LazyPrintf(format string, a ...interface{}) {
  690. tr.addEvent(&lazySprintf{format, a}, false, false)
  691. }
  692. func (tr *trace) SetError() { tr.IsError = true }
  693. func (tr *trace) SetRecycler(f func(interface{})) {
  694. tr.recycler = f
  695. }
  696. func (tr *trace) SetTraceInfo(traceID, spanID uint64) {
  697. tr.traceID, tr.spanID = traceID, spanID
  698. }
  699. func (tr *trace) SetMaxEvents(m int) {
  700. // Always keep at least three events: first, discarded count, last.
  701. if len(tr.events) == 0 && m > 3 {
  702. tr.maxEvents = m
  703. }
  704. }
  705. func (tr *trace) ref() {
  706. atomic.AddInt32(&tr.refs, 1)
  707. }
  708. func (tr *trace) unref() {
  709. if atomic.AddInt32(&tr.refs, -1) == 0 {
  710. if tr.recycler != nil {
  711. // freeTrace clears tr, so we hold tr.recycler and tr.events here.
  712. go func(f func(interface{}), es []event) {
  713. for _, e := range es {
  714. if e.Recyclable {
  715. f(e.What)
  716. }
  717. }
  718. }(tr.recycler, tr.events)
  719. }
  720. freeTrace(tr)
  721. }
  722. }
  723. func (tr *trace) When() string {
  724. return tr.Start.Format("2006/01/02 15:04:05.000000")
  725. }
  726. func (tr *trace) ElapsedTime() string {
  727. t := tr.Elapsed
  728. if t == 0 {
  729. // Active trace.
  730. t = time.Since(tr.Start)
  731. }
  732. return fmt.Sprintf("%.6f", t.Seconds())
  733. }
  734. func (tr *trace) Events() []event {
  735. tr.mu.RLock()
  736. defer tr.mu.RUnlock()
  737. return tr.events
  738. }
  739. var traceFreeList = make(chan *trace, 1000) // TODO(dsymonds): Use sync.Pool?
  740. // newTrace returns a trace ready to use.
  741. func newTrace() *trace {
  742. select {
  743. case tr := <-traceFreeList:
  744. return tr
  745. default:
  746. return new(trace)
  747. }
  748. }
  749. // freeTrace adds tr to traceFreeList if there's room.
  750. // This is non-blocking.
  751. func freeTrace(tr *trace) {
  752. if DebugUseAfterFinish {
  753. return // never reuse
  754. }
  755. tr.reset()
  756. select {
  757. case traceFreeList <- tr:
  758. default:
  759. }
  760. }
  761. func elapsed(d time.Duration) string {
  762. b := []byte(fmt.Sprintf("%.6f", d.Seconds()))
  763. // For subsecond durations, blank all zeros before decimal point,
  764. // and all zeros between the decimal point and the first non-zero digit.
  765. if d < time.Second {
  766. dot := bytes.IndexByte(b, '.')
  767. for i := 0; i < dot; i++ {
  768. b[i] = ' '
  769. }
  770. for i := dot + 1; i < len(b); i++ {
  771. if b[i] == '0' {
  772. b[i] = ' '
  773. } else {
  774. break
  775. }
  776. }
  777. }
  778. return string(b)
  779. }
  780. var pageTmplCache *template.Template
  781. var pageTmplOnce sync.Once
  782. func pageTmpl() *template.Template {
  783. pageTmplOnce.Do(func() {
  784. pageTmplCache = template.Must(template.New("Page").Funcs(template.FuncMap{
  785. "elapsed": elapsed,
  786. "add": func(a, b int) int { return a + b },
  787. }).Parse(pageHTML))
  788. })
  789. return pageTmplCache
  790. }
  791. const pageHTML = `
  792. {{template "Prolog" .}}
  793. {{template "StatusTable" .}}
  794. {{template "Epilog" .}}
  795. {{define "Prolog"}}
  796. <html>
  797. <head>
  798. <title>/debug/requests</title>
  799. <style type="text/css">
  800. body {
  801. font-family: sans-serif;
  802. }
  803. table#tr-status td.family {
  804. padding-right: 2em;
  805. }
  806. table#tr-status td.active {
  807. padding-right: 1em;
  808. }
  809. table#tr-status td.latency-first {
  810. padding-left: 1em;
  811. }
  812. table#tr-status td.empty {
  813. color: #aaa;
  814. }
  815. table#reqs {
  816. margin-top: 1em;
  817. }
  818. table#reqs tr.first {
  819. {{if $.Expanded}}font-weight: bold;{{end}}
  820. }
  821. table#reqs td {
  822. font-family: monospace;
  823. }
  824. table#reqs td.when {
  825. text-align: right;
  826. white-space: nowrap;
  827. }
  828. table#reqs td.elapsed {
  829. padding: 0 0.5em;
  830. text-align: right;
  831. white-space: pre;
  832. width: 10em;
  833. }
  834. address {
  835. font-size: smaller;
  836. margin-top: 5em;
  837. }
  838. </style>
  839. </head>
  840. <body>
  841. <h1>/debug/requests</h1>
  842. {{end}} {{/* end of Prolog */}}
  843. {{define "StatusTable"}}
  844. <table id="tr-status">
  845. {{range $fam := .Families}}
  846. <tr>
  847. <td class="family">{{$fam}}</td>
  848. {{$n := index $.ActiveTraceCount $fam}}
  849. <td class="active {{if not $n}}empty{{end}}">
  850. {{if $n}}<a href="?fam={{$fam}}&b=-1{{if $.Expanded}}&exp=1{{end}}">{{end}}
  851. [{{$n}} active]
  852. {{if $n}}</a>{{end}}
  853. </td>
  854. {{$f := index $.CompletedTraces $fam}}
  855. {{range $i, $b := $f.Buckets}}
  856. {{$empty := $b.Empty}}
  857. <td {{if $empty}}class="empty"{{end}}>
  858. {{if not $empty}}<a href="?fam={{$fam}}&b={{$i}}{{if $.Expanded}}&exp=1{{end}}">{{end}}
  859. [{{.Cond}}]
  860. {{if not $empty}}</a>{{end}}
  861. </td>
  862. {{end}}
  863. {{$nb := len $f.Buckets}}
  864. <td class="latency-first">
  865. <a href="?fam={{$fam}}&b={{$nb}}">[minute]</a>
  866. </td>
  867. <td>
  868. <a href="?fam={{$fam}}&b={{add $nb 1}}">[hour]</a>
  869. </td>
  870. <td>
  871. <a href="?fam={{$fam}}&b={{add $nb 2}}">[total]</a>
  872. </td>
  873. </tr>
  874. {{end}}
  875. </table>
  876. {{end}} {{/* end of StatusTable */}}
  877. {{define "Epilog"}}
  878. {{if $.Traces}}
  879. <hr />
  880. <h3>Family: {{$.Family}}</h3>
  881. {{if or $.Expanded $.Traced}}
  882. <a href="?fam={{$.Family}}&b={{$.Bucket}}">[Normal/Summary]</a>
  883. {{else}}
  884. [Normal/Summary]
  885. {{end}}
  886. {{if or (not $.Expanded) $.Traced}}
  887. <a href="?fam={{$.Family}}&b={{$.Bucket}}&exp=1">[Normal/Expanded]</a>
  888. {{else}}
  889. [Normal/Expanded]
  890. {{end}}
  891. {{if not $.Active}}
  892. {{if or $.Expanded (not $.Traced)}}
  893. <a href="?fam={{$.Family}}&b={{$.Bucket}}&rtraced=1">[Traced/Summary]</a>
  894. {{else}}
  895. [Traced/Summary]
  896. {{end}}
  897. {{if or (not $.Expanded) (not $.Traced)}}
  898. <a href="?fam={{$.Family}}&b={{$.Bucket}}&exp=1&rtraced=1">[Traced/Expanded]</a>
  899. {{else}}
  900. [Traced/Expanded]
  901. {{end}}
  902. {{end}}
  903. {{if $.Total}}
  904. <p><em>Showing <b>{{len $.Traces}}</b> of <b>{{$.Total}}</b> traces.</em></p>
  905. {{end}}
  906. <table id="reqs">
  907. <caption>
  908. {{if $.Active}}Active{{else}}Completed{{end}} Requests
  909. </caption>
  910. <tr><th>When</th><th>Elapsed&nbsp;(s)</th></tr>
  911. {{range $tr := $.Traces}}
  912. <tr class="first">
  913. <td class="when">{{$tr.When}}</td>
  914. <td class="elapsed">{{$tr.ElapsedTime}}</td>
  915. <td>{{$tr.Title}}</td>
  916. {{/* TODO: include traceID/spanID */}}
  917. </tr>
  918. {{if $.Expanded}}
  919. {{range $tr.Events}}
  920. <tr>
  921. <td class="when">{{.WhenString}}</td>
  922. <td class="elapsed">{{elapsed .Elapsed}}</td>
  923. <td>{{if or $.ShowSensitive (not .Sensitive)}}... {{.What}}{{else}}<em>[redacted]</em>{{end}}</td>
  924. </tr>
  925. {{end}}
  926. {{end}}
  927. {{end}}
  928. </table>
  929. {{end}} {{/* if $.Traces */}}
  930. {{if $.Histogram}}
  931. <h4>Latency (&micro;s) of {{$.Family}} over {{$.HistogramWindow}}</h4>
  932. {{$.Histogram}}
  933. {{end}} {{/* if $.Histogram */}}
  934. </body>
  935. </html>
  936. {{end}} {{/* end of Epilog */}}
  937. `