trace.go 26 KB

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