trace.go 24 KB

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