trace.go 28 KB

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