trace.go 26 KB

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