trace.go 27 KB

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