trace.go 27 KB

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