trace.go 28 KB

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