| 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 | //go:build go1.22 |
| 6 | |
| 7 | /* |
| 8 | Package trace provides a mechanism to collect and retrieve |
| 9 | the most recent execution data without keeping the complete |
| 10 | execution tracing history. |
| 11 | |
| 12 | The flight recorder was integrated into Go 1.25. The |
| 13 | integrated flight recorder should be used when possible. |
| 14 | */ |
| 15 | package trace |
| 16 | |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "encoding/binary" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "io" |
| 23 | "math/bits" |
| 24 | "runtime/trace" |
| 25 | "slices" |
| 26 | stdsync "sync" |
| 27 | "time" |
| 28 | _ "unsafe" // for go:linkname |
| 29 | |
| 30 | "golang.org/x/exp/trace/internal/tracev2" |
| 31 | "golang.org/x/exp/trace/internal/version" |
| 32 | ) |
| 33 | |
| 34 | // FlightRecorder represents a flight recording configuration. |
| 35 | // |
| 36 | // Flight recording holds execution trace data in a circular buffer representing |
| 37 | // the most recent execution data. |
| 38 | // |
| 39 | // Only one flight recording may be active at any given time. |
| 40 | type FlightRecorder struct { |
| 41 | err error |
| 42 | |
| 43 | // State specific to the recorder. |
| 44 | header [16]byte |
| 45 | active rawGeneration |
| 46 | ringMu stdsync.Mutex |
| 47 | ring []rawGeneration |
| 48 | freq frequency // timestamp conversion factor, from the runtime |
| 49 | version version.Version |
| 50 | |
| 51 | // Externally-set options. |
| 52 | targetSize int |
| 53 | targetPeriod time.Duration |
| 54 | |
| 55 | enabled bool // whether the flight recorder is enabled. |
| 56 | writing stdsync.Mutex // protects concurrent calls to WriteTo |
| 57 | |
| 58 | // The values of targetSize and targetPeriod we've committed to since the last Start. |
| 59 | wantSize int |
| 60 | wantDur time.Duration |
| 61 | } |
| 62 | |
| 63 | // NewFlightRecorder creates a new flight recording configuration. |
| 64 | func NewFlightRecorder() *FlightRecorder { |
| 65 | return &FlightRecorder{ |
| 66 | // These are just some optimistic, reasonable defaults. |
| 67 | // |
| 68 | // In reality we're also bound by whatever the runtime defaults are, because |
| 69 | // we currently have no way to change them. |
| 70 | // |
| 71 | // TODO(mknyszek): Consider adding a function that allows mutating one or |
| 72 | // both of these values' equivalents in the runtime. |
| 73 | targetSize: 10 << 20, // 10 MiB. |
| 74 | targetPeriod: 10 * time.Second, |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | // SetPeriod sets the approximate time duration that the flight recorder's circular buffer |
| 79 | // represents. |
| 80 | // |
| 81 | // Note that SetPeriod does not make any guarantees on the amount of time the trace |
| 82 | // produced by WriteTo will represent. |
| 83 | // This is just a hint to the runtime to enable some control the resulting trace. |
| 84 | // |
| 85 | // The initial period is implementation defined, but can be assumed to be on the order |
| 86 | // of seconds. |
| 87 | // |
| 88 | // Adjustments to this value will not apply to an active flight recorder, and will not apply |
| 89 | // if tracing is already enabled via trace.Start. All tracing must be stopped and started |
| 90 | // again to change this value. |
| 91 | func (r *FlightRecorder) SetPeriod(d time.Duration) { |
| 92 | r.targetPeriod = d |
| 93 | } |
| 94 | |
| 95 | // SetSize sets the approximate size of the flight recorder's circular buffer. |
| 96 | // |
| 97 | // This generally takes precedence over the duration passed to SetPeriod. |
| 98 | // However, it does not make any guarantees on the size of the data WriteTo will write. |
| 99 | // This is just a hint to the runtime to enable some control over the memory overheads |
| 100 | // of tracing. |
| 101 | // |
| 102 | // The initial size is implementation defined. |
| 103 | // |
| 104 | // Adjustments to this value will not apply to an active flight recorder, and will not apply |
| 105 | // if tracing is already enabled via trace.Start. All tracing must be stopped and started |
| 106 | // again to change this value. |
| 107 | func (r *FlightRecorder) SetSize(bytes int) { |
| 108 | r.targetSize = bytes |
| 109 | } |
| 110 | |
| 111 | // A recorder receives bytes from the runtime tracer, processes it. |
| 112 | type recorder struct { |
| 113 | r *FlightRecorder |
| 114 | |
| 115 | headerReceived bool |
| 116 | } |
| 117 | |
| 118 | func (w *recorder) Write(p []byte) (n int, err error) { |
| 119 | r := w.r |
| 120 | |
| 121 | defer func() { |
| 122 | if err != nil { |
| 123 | // Propagate errors to the flightrecorder. |
| 124 | if r.err == nil { |
| 125 | r.err = err |
| 126 | } |
| 127 | trace.Stop() // Stop the tracer, preventing further writes. |
| 128 | } |
| 129 | }() |
| 130 | |
| 131 | rd := bytes.NewReader(p) |
| 132 | |
| 133 | if !w.headerReceived { |
| 134 | if len(p) < len(r.header) { |
| 135 | return 0, fmt.Errorf("expected at least %d bytes in the first write", len(r.header)) |
| 136 | } |
| 137 | rd.Read(r.header[:]) |
| 138 | if r.version, err = version.ReadHeader(bytes.NewReader(r.header[:])); err != nil { |
| 139 | return len(p) - rd.Len(), fmt.Errorf("failed to parse version from header: %s", err) |
| 140 | } |
| 141 | w.headerReceived = true |
| 142 | } |
| 143 | |
| 144 | b, gen, err := readBatch(rd) // Every write from the runtime is guaranteed to be a complete batch. |
| 145 | if err == io.EOF { |
| 146 | if rd.Len() > 0 { |
| 147 | return len(p) - rd.Len(), errors.New("short read") |
| 148 | } |
| 149 | return len(p), nil |
| 150 | } |
| 151 | if err != nil { |
| 152 | return len(p) - rd.Len(), err |
| 153 | } |
| 154 | if b.isEndOfGeneration() { |
| 155 | gen = r.active.gen |
| 156 | } |
| 157 | |
| 158 | // Check if we're entering a new generation. |
| 159 | if r.active.gen != 0 && r.active.gen+1 == gen { |
| 160 | r.ringMu.Lock() |
| 161 | |
| 162 | // Validate r.active.freq before we use it. It's required for a generation |
| 163 | // to not be considered broken, and without it, we can't correctly handle |
| 164 | // SetPeriod. |
| 165 | if r.active.freq == 0 { |
| 166 | return len(p) - rd.Len(), fmt.Errorf("broken trace: failed to find frequency event in generation %d", r.active.gen) |
| 167 | } |
| 168 | |
| 169 | // Get the current trace clock time. |
| 170 | now := traceTimeNow(r.active.freq) |
| 171 | |
| 172 | // Add the current generation to the ring. Make sure we always have at least one |
| 173 | // complete generation by putting the active generation onto the new list, regardless |
| 174 | // of whatever our settings are. |
| 175 | // |
| 176 | // N.B. Let's completely replace the ring here, so that WriteTo can just make a copy |
| 177 | // and not worry about aliasing. This creates allocations, but at a very low rate. |
| 178 | newRing := []rawGeneration{r.active} |
| 179 | size := r.active.size |
| 180 | for i := len(r.ring) - 1; i >= 0; i-- { |
| 181 | // Stop adding older generations if the new ring already exceeds the thresholds. |
| 182 | // This ensures we keep generations that cross a threshold, but not any that lie |
| 183 | // entirely outside it. |
| 184 | if size > r.wantSize || now.Sub(newRing[len(newRing)-1].minTraceTime()) > r.wantDur { |
| 185 | break |
| 186 | } |
| 187 | size += r.ring[i].size |
| 188 | newRing = append(newRing, r.ring[i]) |
| 189 | } |
| 190 | slices.Reverse(newRing) |
| 191 | r.ring = newRing |
| 192 | r.ringMu.Unlock() |
| 193 | |
| 194 | // Start a new active generation. |
| 195 | r.active = rawGeneration{} |
| 196 | } |
| 197 | |
| 198 | // Obtain the frequency if this is a frequency batch. |
| 199 | if b.isSyncBatch(r.version) { |
| 200 | var s sync |
| 201 | setSyncBatch(&s, b, r.version) |
| 202 | r.active.freq = s.freq |
| 203 | } |
| 204 | |
| 205 | // Append the batch to the current generation. |
| 206 | if !b.isEndOfGeneration() { |
| 207 | if r.active.gen == 0 { |
| 208 | r.active.gen = gen |
| 209 | } |
| 210 | if r.active.minTime == 0 || r.active.minTime > b.time { |
| 211 | r.active.minTime = b.time |
| 212 | } |
| 213 | r.active.size += 1 |
| 214 | r.active.size += uvarintSize(gen) |
| 215 | r.active.size += uvarintSize(uint64(b.m)) |
| 216 | r.active.size += uvarintSize(uint64(b.time)) |
| 217 | r.active.size += uvarintSize(uint64(len(b.data))) |
| 218 | r.active.size += len(b.data) |
| 219 | } |
| 220 | r.active.batches = append(r.active.batches, b) |
| 221 | |
| 222 | return len(p) - rd.Len(), nil |
| 223 | } |
| 224 | |
| 225 | // Start begins flight recording. Only one flight recorder or one call to [runtime/trace.Start] |
| 226 | // may be active at any given time. Returns an error if starting the flight recorder would |
| 227 | // violate this rule. |
| 228 | func (r *FlightRecorder) Start() error { |
| 229 | if r.enabled { |
| 230 | return fmt.Errorf("cannot enable a enabled flight recorder") |
| 231 | } |
| 232 | |
| 233 | r.wantSize = r.targetSize |
| 234 | r.wantDur = r.targetPeriod |
| 235 | r.err = nil |
| 236 | |
| 237 | // Start tracing, data is sent to a recorder which forwards it to our own |
| 238 | // storage. |
| 239 | if err := trace.Start(&recorder{r: r}); err != nil { |
| 240 | return err |
| 241 | } |
| 242 | |
| 243 | r.enabled = true |
| 244 | return nil |
| 245 | } |
| 246 | |
| 247 | // Stop ends flight recording. It waits until any concurrent [FlightRecorder.WriteTo] calls exit. |
| 248 | // Returns an error if the flight recorder is inactive. |
| 249 | func (r *FlightRecorder) Stop() error { |
| 250 | if !r.enabled { |
| 251 | return fmt.Errorf("cannot disable a disabled flight recorder") |
| 252 | } |
| 253 | r.enabled = false |
| 254 | trace.Stop() |
| 255 | |
| 256 | // Reset all state. No need to lock because the reader has already exited. |
| 257 | r.active = rawGeneration{} |
| 258 | r.ring = nil |
| 259 | return r.err |
| 260 | } |
| 261 | |
| 262 | // Enabled returns true if the flight recorder is active. Specifically, it will return true if |
| 263 | // Start did not return an error, and Stop has not yet been called. |
| 264 | // It is safe to call from multiple goroutines simultaneously. |
| 265 | func (r *FlightRecorder) Enabled() bool { |
| 266 | return r.enabled |
| 267 | } |
| 268 | |
| 269 | // ErrSnapshotActive indicates that a call to WriteTo was made while one was already in progress. |
| 270 | // If the caller of WriteTo sees this error, they should use the result from the other call to WriteTo. |
| 271 | var ErrSnapshotActive = fmt.Errorf("call to WriteTo for trace.FlightRecorder already in progress") |
| 272 | |
| 273 | // WriteTo takes a snapshots of the circular buffer's contents and writes the execution data to w. |
| 274 | // Returns the number of bytes written and an error. |
| 275 | // An error is returned upon failure to write to w or if the flight recorder is inactive. |
| 276 | // Only one goroutine may execute WriteTo at a time, but it is safe to call from multiple goroutines. |
| 277 | // If a goroutine calls WriteTo while another goroutine is currently executing it, WriteTo will return |
| 278 | // ErrSnapshotActive to that goroutine. |
| 279 | func (r *FlightRecorder) WriteTo(w io.Writer) (total int, err error) { |
| 280 | if !r.enabled { |
| 281 | return 0, fmt.Errorf("cannot snapshot a disabled flight recorder") |
| 282 | } |
| 283 | if !r.writing.TryLock() { |
| 284 | return 0, ErrSnapshotActive |
| 285 | } |
| 286 | defer r.writing.Unlock() |
| 287 | |
| 288 | // Force a global buffer flush twice. |
| 289 | // |
| 290 | // This is pretty unfortunate, but because the signal that a generation is done is that a new |
| 291 | // generation appears in the trace *or* the trace stream ends, the recorder goroutine will |
| 292 | // have no idea when to add a generation to the ring if we just flush once. If we flush twice, |
| 293 | // at least the first one will end up on the ring, which is the one we wanted anyway. |
| 294 | // |
| 295 | // In a runtime-internal implementation this is a non-issue. The runtime is fully aware |
| 296 | // of what generations are complete, so only one flush is necessary. |
| 297 | // |
| 298 | // As of Go 1.25, it's not required to call runtime_traceAdvance twice. |
| 299 | runtime_traceAdvance(false) |
| 300 | runtime_traceAdvance(false) |
| 301 | |
| 302 | // Now that everything has been flushed and written, grab whatever we have. |
| 303 | // |
| 304 | // N.B. traceAdvance blocks until the tracer goroutine has actually written everything |
| 305 | // out, which means the generation we just flushed must have been already been observed |
| 306 | // by the recorder goroutine. Because we flushed twice, the first flush is guaranteed to |
| 307 | // have been both completed *and* processed by the recorder goroutine. |
| 308 | r.ringMu.Lock() |
| 309 | gens := r.ring |
| 310 | r.ringMu.Unlock() |
| 311 | |
| 312 | // Write the header. |
| 313 | total, err = w.Write(r.header[:]) |
| 314 | if err != nil { |
| 315 | return total, err |
| 316 | } |
| 317 | |
| 318 | // Helper for writing varints. |
| 319 | var varintBuf [binary.MaxVarintLen64]byte |
| 320 | writeUvarint := func(u uint64) error { |
| 321 | v := binary.PutUvarint(varintBuf[:], u) |
| 322 | n, err := w.Write(varintBuf[:v]) |
| 323 | total += n |
| 324 | return err |
| 325 | } |
| 326 | |
| 327 | // Write all the data. |
| 328 | for _, gen := range gens { |
| 329 | for _, batch := range gen.batches { |
| 330 | var n int |
| 331 | if !batch.isEndOfGeneration() { |
| 332 | // Rewrite the batch header event with four arguments: gen, M ID, timestamp, and data length. |
| 333 | n, err := w.Write([]byte{byte(tracev2.EvEventBatch)}) |
| 334 | total += n |
| 335 | if err != nil { |
| 336 | return total, err |
| 337 | } |
| 338 | if err := writeUvarint(gen.gen); err != nil { |
| 339 | return total, err |
| 340 | } |
| 341 | if err := writeUvarint(uint64(batch.m)); err != nil { |
| 342 | return total, err |
| 343 | } |
| 344 | if err := writeUvarint(uint64(batch.time)); err != nil { |
| 345 | return total, err |
| 346 | } |
| 347 | if err := writeUvarint(uint64(len(batch.data))); err != nil { |
| 348 | return total, err |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | // Write batch data. |
| 353 | n, err = w.Write(batch.data) |
| 354 | total += n |
| 355 | if err != nil { |
| 356 | return total, err |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | return total, nil |
| 361 | } |
| 362 | |
| 363 | type rawGeneration struct { |
| 364 | gen uint64 |
| 365 | size int |
| 366 | minTime timestamp |
| 367 | freq frequency |
| 368 | batches []batch |
| 369 | } |
| 370 | |
| 371 | func (r *rawGeneration) minTraceTime() Time { |
| 372 | return r.freq.mul(r.minTime) |
| 373 | } |
| 374 | |
| 375 | func traceTimeNow(freq frequency) Time { |
| 376 | // TODO(mknyszek): It's unfortunate that we have to rely on runtime-internal details |
| 377 | // like this. This would be better off in the runtime. |
| 378 | return freq.mul(timestamp(runtime_traceClockNow())) |
| 379 | } |
| 380 | |
| 381 | func uvarintSize(x uint64) int { |
| 382 | return 1 + bits.Len64(x)/7 |
| 383 | } |
| 384 | |
| 385 | //go:linkname runtime_traceAdvance runtime.traceAdvance |
| 386 | func runtime_traceAdvance(stopTrace bool) |
| 387 | |
| 388 | //go:linkname runtime_traceClockNow runtime.traceClockNow |
| 389 | func runtime_traceClockNow() int64 |