id_generator.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package trace // import "go.opentelemetry.io/otel/sdk/trace"
  15. import (
  16. "context"
  17. crand "crypto/rand"
  18. "encoding/binary"
  19. "math/rand"
  20. "sync"
  21. "go.opentelemetry.io/otel/trace"
  22. )
  23. // IDGenerator allows custom generators for TraceID and SpanID.
  24. type IDGenerator interface {
  25. // DO NOT CHANGE: any modification will not be backwards compatible and
  26. // must never be done outside of a new major release.
  27. // NewIDs returns a new trace and span ID.
  28. NewIDs(ctx context.Context) (trace.TraceID, trace.SpanID)
  29. // DO NOT CHANGE: any modification will not be backwards compatible and
  30. // must never be done outside of a new major release.
  31. // NewSpanID returns a ID for a new span in the trace with traceID.
  32. NewSpanID(ctx context.Context, traceID trace.TraceID) trace.SpanID
  33. // DO NOT CHANGE: any modification will not be backwards compatible and
  34. // must never be done outside of a new major release.
  35. }
  36. type randomIDGenerator struct {
  37. sync.Mutex
  38. randSource *rand.Rand
  39. }
  40. var _ IDGenerator = &randomIDGenerator{}
  41. // NewSpanID returns a non-zero span ID from a randomly-chosen sequence.
  42. func (gen *randomIDGenerator) NewSpanID(ctx context.Context, traceID trace.TraceID) trace.SpanID {
  43. gen.Lock()
  44. defer gen.Unlock()
  45. sid := trace.SpanID{}
  46. _, _ = gen.randSource.Read(sid[:])
  47. return sid
  48. }
  49. // NewIDs returns a non-zero trace ID and a non-zero span ID from a
  50. // randomly-chosen sequence.
  51. func (gen *randomIDGenerator) NewIDs(ctx context.Context) (trace.TraceID, trace.SpanID) {
  52. gen.Lock()
  53. defer gen.Unlock()
  54. tid := trace.TraceID{}
  55. _, _ = gen.randSource.Read(tid[:])
  56. sid := trace.SpanID{}
  57. _, _ = gen.randSource.Read(sid[:])
  58. return tid, sid
  59. }
  60. func defaultIDGenerator() IDGenerator {
  61. gen := &randomIDGenerator{}
  62. var rngSeed int64
  63. _ = binary.Read(crand.Reader, binary.LittleEndian, &rngSeed)
  64. gen.randSource = rand.New(rand.NewSource(rngSeed))
  65. return gen
  66. }