Debian Codegraph @

trace/reader.go

raw symbols SCIP
1 // Copyright 2023 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 // Code generated by "gen.bash" from internal/trace; DO NOT EDIT.
6
7 //go:build go1.23
8
9 package trace
10
11 import (
12 "bufio"
13 "errors"
14 "fmt"
15 "io"
16 "slices"
17 "strings"
18
19 "golang.org/x/exp/trace/internal/tracev1"
20 "golang.org/x/exp/trace/internal/tracev2"
21 "golang.org/x/exp/trace/internal/version"
22 )
23
24 // Reader reads a byte stream, validates it, and produces trace events.
25 //
26 // Provided the trace is non-empty the Reader always produces a Sync
27 // event as the first event, and a Sync event as the last event.
28 // (There may also be any number of Sync events in the middle, too.)
29 type Reader struct {
30 version version.Version
31 r *bufio.Reader
32 lastTs Time
33 gen *generation
34 frontier []*batchCursor
35 cpuSamples []cpuSample
36 order ordering
37 syncs int
38 readGenErr error
39 done bool
40
41 // Spill state.
42 //
43 // Traces before Go 1.26 had no explicit end-of-generation signal, and
44 // so the first batch of the next generation needed to be parsed to identify
45 // a new generation. This batch is the "spilled" so we don't lose track
46 // of it when parsing the next generation.
47 //
48 // This is unnecessary after Go 1.26 because of an explicit end-of-generation
49 // signal.
50 spill *spilledBatch
51 spillErr error // error from reading spill
52 spillErrSync bool // whether we emitted a Sync before reporting spillErr
53
54 v1Events *traceV1Converter
55 }
56
57 // NewReader creates a new trace reader.
58 func NewReader(r io.Reader) (*Reader, error) {
59 br := bufio.NewReader(r)
60 v, err := version.ReadHeader(br)
61 if err != nil {
62 return nil, err
63 }
64 switch v {
65 case version.Go111, version.Go119, version.Go121:
66 tr, err := tracev1.Parse(br, v)
67 if err != nil {
68 return nil, err
69 }
70 return &Reader{
71 v1Events: convertV1Trace(tr),
72 }, nil
73 case version.Go122, version.Go123, version.Go125, version.Go126:
74 return &Reader{
75 version: v,
76 r: br,
77 order: ordering{
78 traceVer: v,
79 mStates: make(map[ThreadID]*mState),
80 pStates: make(map[ProcID]*pState),
81 gStates: make(map[GoID]*gState),
82 activeTasks: make(map[TaskID]taskState),
83 },
84 }, nil
85 default:
86 return nil, fmt.Errorf("unknown or unsupported version go 1.%d", v)
87 }
88 }
89
90 // ReadEvent reads a single event from the stream.
91 //
92 // If the stream has been exhausted, it returns an invalid event and io.EOF.
93 func (r *Reader) ReadEvent() (e Event, err error) {
94 // Return only io.EOF if we're done.
95 if r.done {
96 return Event{}, io.EOF
97 }
98
99 // Handle v1 execution traces.
100 if r.v1Events != nil {
101 if r.syncs == 0 {
102 // Always emit a sync event first, if we have any events at all.
103 ev, ok := r.v1Events.events.Peek()
104 if ok {
105 r.syncs++
106 return syncEvent(r.v1Events.evt, Time(ev.Ts-1), r.syncs), nil
107 }
108 }
109 ev, err := r.v1Events.next()
110 if err == io.EOF {
111 // Always emit a sync event at the end.
112 r.done = true
113 r.syncs++
114 return syncEvent(nil, r.v1Events.lastTs+1, r.syncs), nil
115 } else if err != nil {
116 return Event{}, err
117 }
118 return ev, nil
119 }
120
121 // Trace v2 parsing algorithm.
122 //
123 // (1) Read in all the batches for the next generation from the stream.
124 // (a) Use the size field in the header to quickly find all batches.
125 // (2) Parse out the strings, stacks, CPU samples, and timestamp conversion data.
126 // (3) Group each event batch by M, sorted by timestamp. (batchCursor contains the groups.)
127 // (4) Organize batchCursors in a min-heap, ordered by the timestamp of the next event for each M.
128 // (5) Try to advance the next event for the M at the top of the min-heap.
129 // (a) On success, select that M.
130 // (b) On failure, sort the min-heap and try to advance other Ms. Select the first M that advances.
131 // (c) If there's nothing left to advance, goto (1).
132 // (6) Select the latest event for the selected M and get it ready to be returned.
133 // (7) Read the next event for the selected M and update the min-heap.
134 // (8) Return the selected event, goto (5) on the next call.
135
136 // Set us up to track the last timestamp and fix up
137 // the timestamp of any event that comes through.
138 defer func() {
139 if err != nil {
140 return
141 }
142 if err = e.validateTableIDs(); err != nil {
143 return
144 }
145 if e.base.time <= r.lastTs {
146 e.base.time = r.lastTs + 1
147 }
148 r.lastTs = e.base.time
149 }()
150
151 // Consume any events in the ordering first.
152 if ev, ok := r.order.Next(); ok {
153 return ev, nil
154 }
155
156 // Check if we need to refresh the generation.
157 if len(r.frontier) == 0 && len(r.cpuSamples) == 0 {
158 if r.version < version.Go126 {
159 return r.nextGenWithSpill()
160 }
161 if r.readGenErr != nil {
162 return Event{}, r.readGenErr
163 }
164 gen, err := readGeneration(r.r, r.version)
165 if err != nil {
166 // Before returning an error, emit the sync event
167 // for the current generation and queue up the error
168 // for the next call.
169 r.readGenErr = err
170 r.gen = nil
171 r.syncs++
172 return syncEvent(nil, r.lastTs, r.syncs), nil
173 }
174 return r.installGen(gen)
175 }
176 tryAdvance := func(i int) (bool, error) {
177 bc := r.frontier[i]
178
179 if ok, err := r.order.Advance(&bc.ev, r.gen.evTable, bc.m, r.gen.gen); !ok || err != nil {
180 return ok, err
181 }
182
183 // Refresh the cursor's event.
184 ok, err := bc.nextEvent(r.gen.batches[bc.m], r.gen.freq)
185 if err != nil {
186 return false, err
187 }
188 if ok {
189 // If we successfully refreshed, update the heap.
190 heapUpdate(r.frontier, i)
191 } else {
192 // There's nothing else to read. Delete this cursor from the frontier.
193 r.frontier = heapRemove(r.frontier, i)
194 }
195 return true, nil
196 }
197 // Inject a CPU sample if it comes next.
198 if len(r.cpuSamples) != 0 {
199 if len(r.frontier) == 0 || r.cpuSamples[0].time < r.frontier[0].ev.time {
200 e := r.cpuSamples[0].asEvent(r.gen.evTable)
201 r.cpuSamples = r.cpuSamples[1:]
202 return e, nil
203 }
204 }
205 // Try to advance the head of the frontier, which should have the minimum timestamp.
206 // This should be by far the most common case
207 if len(r.frontier) == 0 {
208 return Event{}, fmt.Errorf("broken trace: frontier is empty:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order))
209 }
210 if ok, err := tryAdvance(0); err != nil {
211 return Event{}, err
212 } else if !ok {
213 // Try to advance the rest of the frontier, in timestamp order.
214 //
215 // To do this, sort the min-heap. A sorted min-heap is still a
216 // min-heap, but now we can iterate over the rest and try to
217 // advance in order. This path should be rare.
218 slices.SortFunc(r.frontier, (*batchCursor).compare)
219 success := false
220 for i := 1; i < len(r.frontier); i++ {
221 if ok, err = tryAdvance(i); err != nil {
222 return Event{}, err
223 } else if ok {
224 success = true
225 break
226 }
227 }
228 if !success {
229 return Event{}, fmt.Errorf("broken trace: failed to advance: frontier:\n[gen=%d]\n\n%s\n%s\n", r.gen.gen, dumpFrontier(r.frontier), dumpOrdering(&r.order))
230 }
231 }
232
233 // Pick off the next event on the queue. At this point, one must exist.
234 ev, ok := r.order.Next()
235 if !ok {
236 panic("invariant violation: advance successful, but queue is empty")
237 }
238 return ev, nil
239 }
240
241 // nextGenWithSpill reads the generation and calls nextGen while
242 // also handling any spilled batches.
243 func (r *Reader) nextGenWithSpill() (Event, error) {
244 if r.version >= version.Go126 {
245 return Event{}, errors.New("internal error: nextGenWithSpill called for Go 1.26+ trace")
246 }
247 if r.spillErr != nil {
248 if r.spillErrSync {
249 return Event{}, r.spillErr
250 }
251 r.spillErrSync = true
252 r.syncs++
253 return syncEvent(nil, r.lastTs, r.syncs), nil
254 }
255 if r.gen != nil && r.spill == nil {
256 // If we have a generation from the last read,
257 // and there's nothing left in the frontier, and
258 // there's no spilled batch, indicating that there's
259 // no further generation, it means we're done.
260 // Emit the final sync event.
261 r.done = true
262 r.syncs++
263 return syncEvent(nil, r.lastTs, r.syncs), nil
264 }
265
266 // Read the next generation.
267 var gen *generation
268 gen, r.spill, r.spillErr = readGenerationWithSpill(r.r, r.spill, r.version)
269 if gen == nil {
270 r.gen = nil
271 r.spillErrSync = true
272 r.syncs++
273 return syncEvent(nil, r.lastTs, r.syncs), nil
274 }
275 return r.installGen(gen)
276 }
277
278 // installGen installs the new generation into the Reader and returns
279 // a Sync event for the new generation.
280 func (r *Reader) installGen(gen *generation) (Event, error) {
281 if gen == nil {
282 // Emit the final sync event.
283 r.gen = nil
284 r.done = true
285 r.syncs++
286 return syncEvent(nil, r.lastTs, r.syncs), nil
287 }
288 r.gen = gen
289
290 // Reset CPU samples cursor.
291 r.cpuSamples = r.gen.cpuSamples
292
293 // Reset frontier.
294 for _, m := range r.gen.batchMs {
295 batches := r.gen.batches[m]
296 bc := &batchCursor{m: m}
297 ok, err := bc.nextEvent(batches, r.gen.freq)
298 if err != nil {
299 return Event{}, err
300 }
301 if !ok {
302 // Turns out there aren't actually any events in these batches.
303 continue
304 }
305 r.frontier = heapInsert(r.frontier, bc)
306 }
307 r.syncs++
308
309 // Always emit a sync event at the beginning of the generation.
310 return syncEvent(r.gen.evTable, r.gen.freq.mul(r.gen.minTs), r.syncs), nil
311 }
312
313 func dumpFrontier(frontier []*batchCursor) string {
314 var sb strings.Builder
315 for _, bc := range frontier {
316 spec := tracev2.Specs()[bc.ev.typ]
317 fmt.Fprintf(&sb, "M %d [%s time=%d", bc.m, spec.Name, bc.ev.time)
318 for i, arg := range spec.Args[1:] {
319 fmt.Fprintf(&sb, " %s=%d", arg, bc.ev.args[i])
320 }
321 fmt.Fprintf(&sb, "]\n")
322 }
323 return sb.String()
324 }