| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package xray // import "go.opentelemetry.io/contrib/propagators/aws/xray" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
crand "crypto/rand" |
| 9 |
"encoding/binary" |
| 10 |
"encoding/hex" |
| 11 |
"math/rand" |
| 12 |
"strconv" |
| 13 |
"sync" |
| 14 |
"time" |
| 15 |
|
| 16 |
sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 17 |
"go.opentelemetry.io/otel/trace" |
| 18 |
) |
| 19 |
|
| 20 |
// IDGenerator is used for generating a new traceID and spanID. |
| 21 |
type IDGenerator struct { |
| 22 |
sync.Mutex |
| 23 |
randSource *rand.Rand |
| 24 |
} |
| 25 |
|
| 26 |
var _ sdktrace.IDGenerator = &IDGenerator{} |
| 27 |
|
| 28 |
// NewSpanID returns a non-zero span ID from a randomly-chosen sequence. |
| 29 |
func (gen *IDGenerator) NewSpanID(context.Context, trace.TraceID) trace.SpanID { |
| 30 |
gen.Lock() |
| 31 |
defer gen.Unlock() |
| 32 |
sid := trace.SpanID{} |
| 33 |
_, _ = gen.randSource.Read(sid[:]) |
| 34 |
return sid |
| 35 |
} |
| 36 |
|
| 37 |
// NewIDs returns a non-zero trace ID and a non-zero span ID. |
| 38 |
// trace ID returned is based on AWS X-Ray TraceID format. |
| 39 |
// - https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-traceids |
| 40 |
// |
| 41 |
// span ID is from a randomly-chosen sequence. |
| 42 |
func (gen *IDGenerator) NewIDs(context.Context) (trace.TraceID, trace.SpanID) { |
| 43 |
gen.Lock() |
| 44 |
defer gen.Unlock() |
| 45 |
|
| 46 |
tid := trace.TraceID{} |
| 47 |
currentTime := getCurrentTimeHex() |
| 48 |
copy(tid[:4], currentTime) |
| 49 |
_, _ = gen.randSource.Read(tid[4:]) |
| 50 |
|
| 51 |
sid := trace.SpanID{} |
| 52 |
_, _ = gen.randSource.Read(sid[:]) |
| 53 |
return tid, sid |
| 54 |
} |
| 55 |
|
| 56 |
// NewIDGenerator returns an IDGenerator reference used for sending traces to AWS X-Ray. |
| 57 |
func NewIDGenerator() *IDGenerator { |
| 58 |
gen := &IDGenerator{} |
| 59 |
var rngSeed int64 |
| 60 |
_ = binary.Read(crand.Reader, binary.LittleEndian, &rngSeed) |
| 61 |
gen.randSource = rand.New(rand.NewSource(rngSeed)) //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand) is ignored as this is not security-sensitive. |
| 62 |
return gen |
| 63 |
} |
| 64 |
|
| 65 |
func getCurrentTimeHex() []uint8 { |
| 66 |
currentTime := time.Now().Unix() |
| 67 |
// Ignore error since no expected error should result from this operation |
| 68 |
// Odd-length strings and non-hex digits are the only 2 error conditions for hex.DecodeString() |
| 69 |
// strconv.FromatInt() do not produce odd-length strings or non-hex digits |
| 70 |
currentTimeHex, _ := hex.DecodeString(strconv.FormatInt(currentTime, 16)) |
| 71 |
return currentTimeHex |
| 72 |
} |