trace.go 26 KB

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