Debian Codegraph @

gopls/internal/debug/trace.go

raw symbols SCIP
1 // Copyright 2019 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 debug
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "html/template"
12 "net/http"
13 "runtime/trace"
14 "slices"
15 "sort"
16 "strings"
17 "sync"
18 "time"
19
20 "golang.org/x/tools/internal/event"
21 "golang.org/x/tools/internal/event/core"
22 "golang.org/x/tools/internal/event/export"
23 "golang.org/x/tools/internal/event/label"
24 )
25
26 // TraceTmpl extends BaseTemplate and renders a TraceResults, e.g. from getData().
27 var TraceTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
28 {{define "title"}}Trace Information{{end}}
29 {{define "body"}}
30 {{range .Traces}}<a href="/trace/{{.Name}}">{{.Name}}</a> last: {{.Last.Duration}}, longest: {{.Longest.Duration}}<br>{{end}}
31 {{if .Selected}}
32 <H2>{{.Selected.Name}}</H2>
33 {{if .Selected.Last}}<H3>Last</H3><ul class='spans'>{{template "completeSpan" .Selected.Last}}</ul>{{end}}
34 {{if .Selected.Longest}}<H3>Longest</H3><ul class='spans'>{{template "completeSpan" .Selected.Longest}}</ul>{{end}}
35 {{end}}
36
37 <H2>Recent spans (oldest first)</H2>
38 <p>
39 A finite number of recent span start/end times are shown below.
40 The nesting represents the children of a parent span (and the log events within a span).
41 A span may appear twice: chronologically at toplevel, and nested within its parent.
42 </p>
43 <ul class='spans'>{{range .Recent}}{{template "spanStartEnd" .}}{{end}}</ul>
44 {{end}}
45 {{define "spanStartEnd"}}
46 {{if .Start}}
47 <li>{{.Span.Header .Start}}</li>
48 {{else}}
49 {{template "completeSpan" .Span}}
50 {{end}}
51 {{end}}
52 {{define "completeSpan"}}
53 <li>{{.Header false}}</li>
54 {{if .Events}}<ul>{{range .Events}}<li>{{.Header}}</li>{{end}}</ul>{{end}}
55 {{if .ChildStartEnd}}<ul>{{range .ChildStartEnd}}{{template "spanStartEnd" .}}{{end}}</ul>{{end}}
56 {{end}}
57 `))
58
59 type traces struct {
60 mu sync.Mutex
61 sets map[string]*traceSet
62 unfinished map[export.SpanContext]*traceSpan
63 recent []spanStartEnd
64 recentEvictions int
65 }
66
67 // A spanStartEnd records the start or end of a span.
68 // If Start, the span may be unfinished, so some fields (e.g. Finish)
69 // may be unset and others (e.g. Events) may be being actively populated.
70 type spanStartEnd struct {
71 Start bool
72 Span *traceSpan
73 }
74
75 func (ev spanStartEnd) Time() time.Time {
76 if ev.Start {
77 return ev.Span.Start
78 } else {
79 return ev.Span.Finish
80 }
81 }
82
83 // A TraceResults is the subject for the /trace HTML template.
84 type TraceResults struct { // exported for testing
85 Traces []*traceSet
86 Selected *traceSet
87 Recent []spanStartEnd
88 }
89
90 // A traceSet holds two representative spans of a given span name.
91 type traceSet struct {
92 Name string
93 Last *traceSpan
94 Longest *traceSpan
95 }
96
97 // A traceSpan holds information about a single span.
98 type traceSpan struct {
99 TraceID export.TraceID
100 SpanID export.SpanID
101 ParentID export.SpanID
102 Name string
103 Start time.Time
104 Finish time.Time // set at end
105 Duration time.Duration // set at end
106 Tags string
107 Events []traceEvent // set at end
108 ChildStartEnd []spanStartEnd // populated while active
109
110 parent *traceSpan
111 }
112
113 const timeFormat = "15:04:05.000"
114
115 // Header renders the time, name, tags, and (if !start),
116 // duration of a span start or end event.
117 func (span *traceSpan) Header(start bool) string {
118 if start {
119 return fmt.Sprintf("%s start %s %s",
120 span.Start.Format(timeFormat), span.Name, span.Tags)
121 } else {
122 return fmt.Sprintf("%s end %s (+%s) %s",
123 span.Finish.Format(timeFormat), span.Name, span.Duration, span.Tags)
124 }
125 }
126
127 type traceEvent struct {
128 Time time.Time
129 Offset time.Duration // relative to start of span
130 Tags string
131 }
132
133 func (ev traceEvent) Header() string {
134 return fmt.Sprintf("%s event (+%s) %s", ev.Time.Format(timeFormat), ev.Offset, ev.Tags)
135 }
136
137 func StdTrace(exporter event.Exporter) event.Exporter {
138 return func(ctx context.Context, ev core.Event, lm label.Map) context.Context {
139 span := export.GetSpan(ctx)
140 if span == nil {
141 return exporter(ctx, ev, lm)
142 }
143 switch {
144 case event.IsStart(ev):
145 if span.ParentID.IsValid() {
146 region := trace.StartRegion(ctx, span.Name)
147 ctx = context.WithValue(ctx, traceKey, region)
148 } else {
149 var task *trace.Task
150 ctx, task = trace.NewTask(ctx, span.Name)
151 ctx = context.WithValue(ctx, traceKey, task)
152 }
153 // Log the start event as it may contain useful labels.
154 msg := formatEvent(ev, lm)
155 trace.Log(ctx, "start", msg)
156 case event.IsLog(ev):
157 category := ""
158 if event.IsError(ev) {
159 category = "error"
160 }
161 msg := formatEvent(ev, lm)
162 trace.Log(ctx, category, msg)
163 case event.IsEnd(ev):
164 if v := ctx.Value(traceKey); v != nil {
165 v.(interface{ End() }).End()
166 }
167 }
168 return exporter(ctx, ev, lm)
169 }
170 }
171
172 func formatEvent(ev core.Event, lm label.Map) string {
173 buf := &bytes.Buffer{}
174 p := export.Printer{}
175 p.WriteEvent(buf, ev, lm)
176 return buf.String()
177 }
178
179 func (t *traces) ProcessEvent(ctx context.Context, ev core.Event, lm label.Map) context.Context {
180 span := export.GetSpan(ctx)
181 if span == nil {
182 return ctx
183 }
184
185 switch {
186 case event.IsStart(ev):
187 // Just starting: add it to the unfinished map.
188 // Allocate before the critical section.
189 td := &traceSpan{
190 TraceID: span.ID.TraceID,
191 SpanID: span.ID.SpanID,
192 ParentID: span.ParentID,
193 Name: span.Name,
194 Start: span.Start().At(),
195 Tags: renderLabels(span.Start()),
196 }
197
198 t.mu.Lock()
199 defer t.mu.Unlock()
200
201 t.addRecentLocked(td, true) // add start event
202
203 if t.sets == nil {
204 t.sets = make(map[string]*traceSet)
205 t.unfinished = make(map[export.SpanContext]*traceSpan)
206 }
207 t.unfinished[span.ID] = td
208
209 // Wire up parents if we have them.
210 if span.ParentID.IsValid() {
211 parentID := export.SpanContext{TraceID: span.ID.TraceID, SpanID: span.ParentID}
212 if parent, ok := t.unfinished[parentID]; ok {
213 td.parent = parent
214 parent.ChildStartEnd = append(parent.ChildStartEnd, spanStartEnd{true, td})
215 }
216 }
217
218 case event.IsEnd(ev):
219 // Finishing: must be already in the map.
220 // Allocate events before the critical section.
221 events := span.Events()
222 tdEvents := make([]traceEvent, len(events))
223 for i, event := range events {
224 tdEvents[i] = traceEvent{
225 Time: event.At(),
226 Tags: renderLabels(event),
227 }
228 }
229
230 t.mu.Lock()
231 defer t.mu.Unlock()
232 td, found := t.unfinished[span.ID]
233 if !found {
234 return ctx // if this happens we are in a bad place
235 }
236 delete(t.unfinished, span.ID)
237 td.Finish = span.Finish().At()
238 td.Duration = span.Finish().At().Sub(span.Start().At())
239 td.Events = tdEvents
240 t.addRecentLocked(td, false) // add end event
241
242 set, ok := t.sets[span.Name]
243 if !ok {
244 set = &traceSet{Name: span.Name}
245 t.sets[span.Name] = set
246 }
247 set.Last = td
248 if set.Longest == nil || set.Last.Duration > set.Longest.Duration {
249 set.Longest = set.Last
250 }
251 if td.parent != nil {
252 td.parent.ChildStartEnd = append(td.parent.ChildStartEnd, spanStartEnd{false, td})
253 } else {
254 fillOffsets(td, td.Start)
255 }
256 }
257 return ctx
258 }
259
260 // addRecentLocked appends a start or end event to the "recent" log,
261 // evicting an old entry if necessary.
262 func (t *traces) addRecentLocked(span *traceSpan, start bool) {
263 t.recent = append(t.recent, spanStartEnd{Start: start, Span: span})
264
265 const maxRecent = 100 // number of log entries before eviction
266 for len(t.recent) > maxRecent {
267 t.recent[0] = spanStartEnd{} // aid GC
268 t.recent = t.recent[1:]
269 t.recentEvictions++
270
271 // Using a slice as a FIFO queue leads to unbounded growth
272 // as Go's GC cannot collect the ever-growing unused prefix.
273 // So, compact it periodically.
274 if t.recentEvictions%maxRecent == 0 {
275 t.recent = slices.Clone(t.recent)
276 }
277 }
278 }
279
280 // getData returns the TraceResults rendered by TraceTmpl for the /trace[/name] endpoint.
281 func (t *traces) getData(req *http.Request) any {
282 // TODO(adonovan): the HTTP request doesn't acquire the mutex
283 // for t or for each span! Audit and fix.
284
285 // Sort last/longest sets by name.
286 traces := make([]*traceSet, 0, len(t.sets))
287 for _, set := range t.sets {
288 traces = append(traces, set)
289 }
290 sort.Slice(traces, func(i, j int) bool {
291 return traces[i].Name < traces[j].Name
292 })
293
294 return TraceResults{
295 Traces: traces,
296 Selected: t.sets[strings.TrimPrefix(req.URL.Path, "/trace/")], // may be nil
297 Recent: t.recent,
298 }
299 }
300
301 func fillOffsets(td *traceSpan, start time.Time) {
302 for i := range td.Events {
303 td.Events[i].Offset = td.Events[i].Time.Sub(start)
304 }
305 for _, child := range td.ChildStartEnd {
306 if !child.Start {
307 fillOffsets(child.Span, start)
308 }
309 }
310 }
311
312 func renderLabels(labels label.List) string {
313 buf := &bytes.Buffer{}
314 for index := 0; labels.Valid(index); index++ {
315 // The 'start' label duplicates the span name, so discard it.
316 if l := labels.Label(index); l.Valid() && l.Key().Name() != "start" {
317 fmt.Fprintf(buf, "%v ", l)
318 }
319 }
320 return buf.String()
321 }