trace.go 26 KB

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