trace.go 26 KB

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