diff --git a/Directory.Build.props b/Directory.Build.props index 3dcd994492e..abd99817026 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,5 +2,6 @@ git https://github.com/open-telemetry/opentelemetry-dotnet + 7.3 \ No newline at end of file diff --git a/src/OpenTelemetry.Abstractions/Context/Propagation/BinaryFormat.cs b/src/OpenTelemetry.Abstractions/Context/Propagation/BinaryFormat.cs index ebcda32141c..f4a661e793b 100644 --- a/src/OpenTelemetry.Abstractions/Context/Propagation/BinaryFormat.cs +++ b/src/OpenTelemetry.Abstractions/Context/Propagation/BinaryFormat.cs @@ -17,12 +17,16 @@ namespace OpenTelemetry.Context.Propagation { using System; + using System.Diagnostics; using OpenTelemetry.Trace; public class BinaryFormat : IBinaryFormat { private const byte VersionId = 0; private const int VersionIdOffset = 0; + private const int TraceIdSize = 16; + private const int SpanIdSize = 8; + private const int TraceOptionsSize = 1; // The version_id/field_id size in bytes. private const byte IdSize = 1; @@ -30,12 +34,12 @@ public class BinaryFormat : IBinaryFormat private const int TraceIdFieldIdOffset = VersionIdOffset + IdSize; private const int TraceIdOffset = TraceIdFieldIdOffset + IdSize; private const byte SpanIdFieldId = 1; - private const int SpaneIdFieldIdOffset = TraceIdOffset + TraceId.Size; + private const int SpaneIdFieldIdOffset = TraceIdOffset + TraceIdSize; private const int SpanIdOffset = SpaneIdFieldIdOffset + IdSize; private const byte TraceOptionsFieldId = 2; - private const int TraceOptionFieldIdOffset = SpanIdOffset + SpanId.Size; + private const int TraceOptionFieldIdOffset = SpanIdOffset + SpanIdSize; private const int TraceOptionOffset = TraceOptionFieldIdOffset + IdSize; - private const int FormatLength = (4 * IdSize) + TraceId.Size + SpanId.Size + TraceOptions.Size; + private const int FormatLength = (4 * IdSize) + TraceIdSize + SpanIdSize + TraceOptionsSize; public SpanContext FromByteArray(byte[] bytes) { @@ -49,28 +53,29 @@ public SpanContext FromByteArray(byte[] bytes) throw new SpanContextParseException("Unsupported version."); } - var traceId = TraceId.Invalid; - var spanId = SpanId.Invalid; - var traceOptions = TraceOptions.Default; + ActivityTraceId traceId = default; + ActivitySpanId spanId = default; + var traceOptions = ActivityTraceFlags.None; + var traceparentBytes = new ReadOnlySpan(bytes); var pos = 1; try { if (bytes.Length > pos && bytes[pos] == TraceIdFieldId) { - traceId = TraceId.FromBytes(bytes, pos + IdSize); - pos += IdSize + TraceId.Size; + traceId = ActivityTraceId.CreateFromBytes(traceparentBytes.Slice(pos + IdSize, 16)); + pos += IdSize + TraceIdSize; } if (bytes.Length > pos && bytes[pos] == SpanIdFieldId) { - spanId = SpanId.FromBytes(bytes, pos + IdSize); - pos += IdSize + SpanId.Size; + spanId = ActivitySpanId.CreateFromBytes(traceparentBytes.Slice(pos + IdSize, 8)); + pos += IdSize + SpanIdSize; } if (bytes.Length > pos && bytes[pos] == TraceOptionsFieldId) { - traceOptions = TraceOptions.FromBytes(bytes, pos + IdSize); + traceOptions = (ActivityTraceFlags)traceparentBytes[pos + IdSize]; } return SpanContext.Create(traceId, spanId, traceOptions, Tracestate.Empty); @@ -88,15 +93,16 @@ public byte[] ToByteArray(SpanContext spanContext) throw new ArgumentNullException(nameof(spanContext)); } - var bytes = new byte[FormatLength]; - bytes[VersionIdOffset] = VersionId; - bytes[TraceIdFieldIdOffset] = TraceIdFieldId; - spanContext.TraceId.CopyBytesTo(bytes, TraceIdOffset); - bytes[SpaneIdFieldIdOffset] = SpanIdFieldId; - spanContext.SpanId.CopyBytesTo(bytes, SpanIdOffset); - bytes[TraceOptionFieldIdOffset] = TraceOptionsFieldId; - spanContext.TraceOptions.CopyBytesTo(bytes, TraceOptionOffset); - return bytes; + Span spanBytes = stackalloc byte[FormatLength]; + spanBytes[VersionIdOffset] = VersionId; + spanBytes[TraceIdFieldIdOffset] = TraceIdFieldId; + spanBytes[SpaneIdFieldIdOffset] = SpanIdFieldId; + spanBytes[TraceOptionFieldIdOffset] = TraceOptionsFieldId; + spanBytes[TraceOptionOffset] = (byte)spanContext.TraceOptions; + spanContext.TraceId.CopyTo(spanBytes.Slice(TraceIdOffset)); + spanContext.SpanId.CopyTo(spanBytes.Slice(SpanIdOffset)); + + return spanBytes.ToArray(); } } } diff --git a/src/OpenTelemetry.Abstractions/Context/Propagation/TraceContextFormat.cs b/src/OpenTelemetry.Abstractions/Context/Propagation/TraceContextFormat.cs index f8042318847..bd56c1a817d 100644 --- a/src/OpenTelemetry.Abstractions/Context/Propagation/TraceContextFormat.cs +++ b/src/OpenTelemetry.Abstractions/Context/Propagation/TraceContextFormat.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Context.Propagation { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using System.Text; using OpenTelemetry.Trace; @@ -35,6 +36,7 @@ public class TraceContextFormat : ITextFormat private static readonly int SpanIdLength = "00f067aa0ba902b7".Length; private static readonly int VersionAndTraceIdAndSpanIdLength = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-".Length; private static readonly int OptionsLength = "00".Length; + private static readonly int TraceparentLengthV0 = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-00".Length; /// public ISet Fields => new HashSet { "tracestate", "traceparent" }; @@ -47,13 +49,13 @@ public SpanContext Extract(T carrier, Func> ge var traceparentCollection = getter(carrier, "traceparent"); var tracestateCollection = getter(carrier, "tracestate"); - if (traceparentCollection.Count() > 1) + if (traceparentCollection != null && traceparentCollection.Count() > 1) { // multiple traceparent are not allowed return SpanContext.Blank; } - var traceparent = traceparentCollection?.FirstOrDefault(); + var traceparent = traceparentCollection.First(); var traceparentParsed = this.TryExtractTraceparent(traceparent, out var traceId, out var spanId, out var traceoptions); if (!traceparentParsed) @@ -165,8 +167,8 @@ public SpanContext Extract(T carrier, Func> ge /// public void Inject(SpanContext spanContext, T carrier, Action setter) { - var traceparent = string.Concat("00-", spanContext.TraceId.ToLowerBase16(), "-", spanContext.SpanId.ToLowerBase16()); - traceparent = string.Concat(traceparent, spanContext.TraceOptions.IsSampled ? "-01" : "-00"); + var traceparent = string.Concat("00-", spanContext.TraceId.ToHexString(), "-", spanContext.SpanId.ToHexString()); + traceparent = string.Concat(traceparent, (spanContext.TraceOptions & ActivityTraceFlags.Recorded) != 0 ? "-01" : "-00"); setter(carrier, "traceparent", traceparent); @@ -193,50 +195,51 @@ public void Inject(SpanContext spanContext, T carrier, Action 0) + if (version0 > 0) { // expected version is 00 // for higher versions - best attempt parsing of trace id, span id, etc. bestAttempt = true; } - if (traceparent.Length < VersionAndTraceIdLength || traceparent[VersionAndTraceIdLength - 1] != '-') + if (traceparent[VersionAndTraceIdLength - 1] != '-') { return false; } try { - traceId = TraceId.FromBytes(Arrays.StringToByteArray(traceparent, VersionPrefixIdLength, TraceIdLength)); + traceId = ActivityTraceId.CreateFromString(traceparent.AsSpan().Slice(VersionPrefixIdLength, TraceIdLength)); } catch (ArgumentOutOfRangeException) { @@ -244,14 +247,14 @@ private bool TryExtractTraceparent(string traceparent, out TraceId traceId, out return false; } - if (traceparent.Length < VersionAndTraceIdAndSpanIdLength || traceparent[VersionAndTraceIdAndSpanIdLength - 1] != '-') + if (traceparent[VersionAndTraceIdAndSpanIdLength - 1] != '-') { return false; } try { - spanId = SpanId.FromBytes(Arrays.StringToByteArray(traceparent, VersionAndTraceIdLength, SpanIdLength)); + spanId = ActivitySpanId.CreateFromString(traceparent.AsSpan().Slice(VersionAndTraceIdLength, SpanIdLength)); } catch (ArgumentOutOfRangeException) { @@ -259,16 +262,13 @@ private bool TryExtractTraceparent(string traceparent, out TraceId traceId, out return false; } - if (traceparent.Length < VersionAndTraceIdAndSpanIdLength + OptionsLength) - { - return false; - } - - byte[] optionsArray; + byte options0; + byte options1; try { - optionsArray = Arrays.StringToByteArray(traceparent, VersionAndTraceIdAndSpanIdLength, OptionsLength); + options0 = this.HexCharToByte(traceparent[VersionAndTraceIdAndSpanIdLength]); + options1 = this.HexCharToByte(traceparent[VersionAndTraceIdAndSpanIdLength]); } catch (ArgumentOutOfRangeException) { @@ -276,9 +276,9 @@ private bool TryExtractTraceparent(string traceparent, out TraceId traceId, out return false; } - if ((optionsArray[0] | 1) == 1) + if ((options0 | 1) == 1) { - traceoptions = TraceOptions.Builder().SetIsSampled(true).Build(); + traceoptions |= ActivityTraceFlags.Recorded; } if ((!bestAttempt) && (traceparent.Length != VersionAndTraceIdAndSpanIdLength + OptionsLength)) @@ -288,8 +288,7 @@ private bool TryExtractTraceparent(string traceparent, out TraceId traceId, out if (bestAttempt) { - if ((traceparent.Length > VersionAndTraceIdAndSpanIdLength + OptionsLength) && - (traceparent[VersionAndTraceIdAndSpanIdLength + OptionsLength] != '-')) + if ((traceparent.Length > TraceparentLengthV0) && (traceparent[TraceparentLengthV0] != '-')) { return false; } @@ -297,5 +296,25 @@ private bool TryExtractTraceparent(string traceparent, out TraceId traceId, out return true; } + + private byte HexCharToByte(char c) + { + if ((c >= '0') && (c <= '9')) + { + return (byte)(c - '0'); + } + + if ((c >= 'a') && (c <= 'f')) + { + return (byte)(c - 'a' + 10); + } + + if ((c >= 'A') && (c <= 'F')) + { + return (byte)(c - 'A' + 10); + } + + throw new ArgumentOutOfRangeException("Invalid character: " + c); + } } } diff --git a/src/OpenTelemetry.Abstractions/OpenTelemetry.Abstractions.csproj b/src/OpenTelemetry.Abstractions/OpenTelemetry.Abstractions.csproj index 5627e7283e8..d8b5a12eacf 100644 --- a/src/OpenTelemetry.Abstractions/OpenTelemetry.Abstractions.csproj +++ b/src/OpenTelemetry.Abstractions/OpenTelemetry.Abstractions.csproj @@ -5,4 +5,8 @@ OpenTelemetry .NET API abstractions OpenTelemetry + + + + \ No newline at end of file diff --git a/src/OpenTelemetry.Abstractions/Properties/AssemblyInfo.cs b/src/OpenTelemetry.Abstractions/Properties/AssemblyInfo.cs index 42f8afafa48..3c66417ce38 100644 --- a/src/OpenTelemetry.Abstractions/Properties/AssemblyInfo.cs +++ b/src/OpenTelemetry.Abstractions/Properties/AssemblyInfo.cs @@ -16,8 +16,6 @@ using System.Runtime.CompilerServices; -[assembly: System.CLSCompliant(true)] - [assembly: InternalsVisibleTo("OpenTelemetry.Tests" + AssemblyInfo.PublicKey)] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2" + AssemblyInfo.MoqPublicKey)] @@ -33,4 +31,4 @@ internal static class AssemblyInfo public const string PublicKey = ""; public const string MoqPublicKey = ""; } -#endif \ No newline at end of file +#endif diff --git a/src/OpenTelemetry.Abstractions/Trace/ISampler.cs b/src/OpenTelemetry.Abstractions/Trace/ISampler.cs index 9b97f960051..bcb0a16e5e4 100644 --- a/src/OpenTelemetry.Abstractions/Trace/ISampler.cs +++ b/src/OpenTelemetry.Abstractions/Trace/ISampler.cs @@ -17,6 +17,7 @@ namespace OpenTelemetry.Trace { using System.Collections.Generic; + using System.Diagnostics; /// /// Sampler to reduce data volume. This sampler executes before Span object was created. @@ -41,6 +42,6 @@ public interface ISampler /// /// Links associated with the span. /// True of span needs to be created. False otherwise. - bool ShouldSample(SpanContext parentContext, TraceId traceId, SpanId spanId, string name, IEnumerable links); + bool ShouldSample(SpanContext parentContext, ActivityTraceId traceId, ActivitySpanId spanId, string name, IEnumerable links); } } diff --git a/src/OpenTelemetry.Abstractions/Trace/Link.cs b/src/OpenTelemetry.Abstractions/Trace/Link.cs index 6fa4a0008c0..dcd6d02e19f 100644 --- a/src/OpenTelemetry.Abstractions/Trace/Link.cs +++ b/src/OpenTelemetry.Abstractions/Trace/Link.cs @@ -56,8 +56,8 @@ public static ILink FromSpanContext(SpanContext context, IDictionary this.ToString(); /// - public bool ShouldSample(SpanContext parentContext, TraceId traceId, SpanId spanId, string name, IEnumerable parentLinks) + public bool ShouldSample(SpanContext parentContext, ActivityTraceId traceId, ActivitySpanId spanId, string name, IEnumerable parentLinks) { return true; } diff --git a/src/OpenTelemetry.Abstractions/Trace/Sampler/Internal/NeverSampleSampler.cs b/src/OpenTelemetry.Abstractions/Trace/Sampler/Internal/NeverSampleSampler.cs index 22b1b856b9e..d34c8a7e785 100644 --- a/src/OpenTelemetry.Abstractions/Trace/Sampler/Internal/NeverSampleSampler.cs +++ b/src/OpenTelemetry.Abstractions/Trace/Sampler/Internal/NeverSampleSampler.cs @@ -17,6 +17,7 @@ namespace OpenTelemetry.Trace.Sampler.Internal { using System.Collections.Generic; + using System.Diagnostics; /// internal sealed class NeverSampleSampler : ISampler @@ -28,7 +29,7 @@ internal NeverSampleSampler() public string Description => this.ToString(); /// - public bool ShouldSample(SpanContext parentContext, TraceId traceId, SpanId spanId, string name, IEnumerable links) + public bool ShouldSample(SpanContext parentContext, ActivityTraceId traceId, ActivitySpanId spanId, string name, IEnumerable links) { return false; } diff --git a/src/OpenTelemetry.Abstractions/Trace/SpanContext.cs b/src/OpenTelemetry.Abstractions/Trace/SpanContext.cs index cc46ab3aceb..fc61f93202a 100644 --- a/src/OpenTelemetry.Abstractions/Trace/SpanContext.cs +++ b/src/OpenTelemetry.Abstractions/Trace/SpanContext.cs @@ -16,19 +16,21 @@ namespace OpenTelemetry.Trace { + using System.Diagnostics; + /// /// A class that represents a span context. A span context contains the state that must propagate to - /// child and across process boundaries. It contains the identifiers - /// and associated with the and a set of . + /// child and across process boundaries. It contains the identifiers + /// and associated with the and a set of . /// public sealed class SpanContext { /// /// A blank that can be used for no-op operations. /// - public static readonly SpanContext Blank = new SpanContext(Trace.TraceId.Invalid, Trace.SpanId.Invalid, TraceOptions.Default, Tracestate.Empty); + public static readonly SpanContext Blank = new SpanContext(default(ActivityTraceId), default(ActivitySpanId), ActivityTraceFlags.None, Tracestate.Empty); - private SpanContext(TraceId traceId, SpanId spanId, TraceOptions traceOptions, Tracestate tracestate) + private SpanContext(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags traceOptions, Tracestate tracestate) { this.TraceId = traceId; this.SpanId = spanId; @@ -37,24 +39,24 @@ private SpanContext(TraceId traceId, SpanId spanId, TraceOptions traceOptions, T } /// - /// Gets the associated with this . + /// Gets the associated with this . /// - public TraceId TraceId { get; } + public ActivityTraceId TraceId { get; } /// - /// Gets the associated with this . + /// Gets the associated with this . /// - public SpanId SpanId { get; } + public ActivitySpanId SpanId { get; } /// /// Gets the associated with this . /// - public TraceOptions TraceOptions { get; } + public ActivityTraceFlags TraceOptions { get; } /// /// Gets a value indicating whether this is valid. /// - public bool IsValid => this.TraceId.IsValid && this.SpanId.IsValid; + public bool IsValid => this.IsTraceIdValid(this.TraceId) && this.IsSpanIdValid(this.SpanId); /// /// Gets the associated with this . @@ -64,12 +66,12 @@ private SpanContext(TraceId traceId, SpanId spanId, TraceOptions traceOptions, T /// /// Creates a new with the given identifiers and options. /// - /// The to associate with the . - /// The to associate with the . + /// The to associate with the . + /// The to associate with the . /// The to associate with the . /// The to associate with the . /// A new with the given identifiers and options. - public static SpanContext Create(TraceId traceId, SpanId spanId, TraceOptions traceOptions, Tracestate tracestate) + public static SpanContext Create(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags traceOptions, Tracestate tracestate) { return new SpanContext(traceId, spanId, traceOptions, tracestate); } @@ -78,9 +80,9 @@ public static SpanContext Create(TraceId traceId, SpanId spanId, TraceOptions tr public override int GetHashCode() { var result = 1; - result = (31 * result) + (this.TraceId == null ? 0 : this.TraceId.GetHashCode()); - result = (31 * result) + (this.SpanId == null ? 0 : this.SpanId.GetHashCode()); - result = (31 * result) + (this.TraceOptions == null ? 0 : this.TraceOptions.GetHashCode()); + result = (31 * result) + this.TraceId.GetHashCode(); + result = (31 * result) + this.SpanId.GetHashCode(); + result = (31 * result) + this.TraceOptions.GetHashCode(); return result; } @@ -112,5 +114,15 @@ public override string ToString() + "traceOptions=" + this.TraceOptions + "}"; } + + private bool IsTraceIdValid(ActivityTraceId traceId) + { + return traceId != default; + } + + private bool IsSpanIdValid(ActivitySpanId spanId) + { + return spanId != default; + } } } diff --git a/src/OpenTelemetry.Abstractions/Trace/SpanData.cs b/src/OpenTelemetry.Abstractions/Trace/SpanData.cs index 65e002d7796..c9f1aa42b28 100644 --- a/src/OpenTelemetry.Abstractions/Trace/SpanData.cs +++ b/src/OpenTelemetry.Abstractions/Trace/SpanData.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Trace { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using OpenTelemetry.Common; using OpenTelemetry.Resources; @@ -30,7 +31,7 @@ public class SpanData { internal SpanData( SpanContext context, - SpanId parentSpanId, + ActivitySpanId parentSpanId, Resource resource, string name, Timestamp startTimestamp, @@ -62,9 +63,9 @@ internal SpanData( public SpanContext Context { get; } /// - /// Gets the parent . + /// Gets the parent . /// - public SpanId ParentSpanId { get; } + public ActivitySpanId ParentSpanId { get; } /// /// Gets the this span was executed on. @@ -120,7 +121,7 @@ internal SpanData( /// Returns a new immutable . /// /// The of the . - /// The parent of the . null if the is a root. + /// The parent of the . null if the is a root. /// The this span was executed on. /// The name of the . /// The start of the . @@ -134,7 +135,7 @@ internal SpanData( /// A new immutable . public static SpanData Create( SpanContext context, - SpanId parentSpanId, + ActivitySpanId parentSpanId, Resource resource, string name, Timestamp startTimestamp, diff --git a/src/OpenTelemetry.Abstractions/Trace/SpanId.cs b/src/OpenTelemetry.Abstractions/Trace/SpanId.cs deleted file mode 100644 index c23b1e56e39..00000000000 --- a/src/OpenTelemetry.Abstractions/Trace/SpanId.cs +++ /dev/null @@ -1,181 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace -{ - using System; - using OpenTelemetry.Utils; - - /// - /// Span identifier. - /// - public sealed class SpanId : IComparable - { - public const int Size = 8; - - private static readonly SpanId InvalidSpanId = new SpanId(new byte[Size]); - - private readonly byte[] bytes; - - private SpanId(byte[] bytes) - { - this.bytes = bytes; - } - - public static SpanId Invalid - { - get - { - return InvalidSpanId; - } - } - - /// - /// Gets the span identifier as bytes. - /// - public byte[] Bytes - { - get - { - var copyOf = new byte[Size]; - Buffer.BlockCopy(this.bytes, 0, copyOf, 0, Size); - return copyOf; - } - } - - /// - /// Gets a value indicating whether span identifier is valid. - /// - public bool IsValid - { - get { return !Arrays.Equals(this.bytes, InvalidSpanId.bytes); } - } - - public static SpanId FromBytes(byte[] buffer) - { - if (buffer == null) - { - throw new ArgumentNullException("buffer"); - } - - if (buffer.Length != Size) - { - throw new ArgumentOutOfRangeException(string.Format("Invalid size: expected {0}, got {1}", Size, buffer.Length)); - } - - var bytesCopied = new byte[Size]; - Buffer.BlockCopy(buffer, 0, bytesCopied, 0, Size); - return new SpanId(bytesCopied); - } - - public static SpanId FromBytes(byte[] src, int srcOffset) - { - var bytes = new byte[Size]; - Buffer.BlockCopy(src, srcOffset, bytes, 0, Size); - return new SpanId(bytes); - } - - public static SpanId FromLowerBase16(string src) - { - if (src.Length != 2 * Size) - { - throw new ArgumentOutOfRangeException(string.Format("Invalid size: expected {0}, got {1}", 2 * Size, src.Length)); - } - - var bytes = Arrays.StringToByteArray(src); - return new SpanId(bytes); - } - - public static SpanId GenerateRandomId(IRandomGenerator random) - { - var bytes = new byte[Size]; - do - { - random.NextBytes(bytes); - } - while (Arrays.Equals(bytes, InvalidSpanId.bytes)); - return new SpanId(bytes); - } - - /// - /// Copy span id as bytes into destination byte array. - /// - /// Destination byte array. - /// Offset to start writing from. - public void CopyBytesTo(byte[] dest, int destOffset) - { - Buffer.BlockCopy(this.bytes, 0, dest, destOffset, Size); - } - - /// - /// Gets the span identifier as a string. - /// - /// String representation of Span identifier. - public string ToLowerBase16() - { - var bytes = this.Bytes; - return Arrays.ByteArrayToString(bytes); - } - - /// - public override bool Equals(object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj is SpanId)) - { - return false; - } - - var that = (SpanId)obj; - return Arrays.Equals(this.bytes, that.bytes); - } - - /// - public override int GetHashCode() - { - return Arrays.GetHashCode(this.bytes); - } - - /// - public override string ToString() - { - return "SpanId{" - + "bytes=" + this.ToLowerBase16() - + "}"; - } - - /// - public int CompareTo(SpanId other) - { - for (var i = 0; i < Size; i++) - { - if (this.bytes[i] != other.bytes[i]) - { - var b1 = (sbyte)this.bytes[i]; - var b2 = (sbyte)other.bytes[i]; - - return b1 < b2 ? -1 : 1; - } - } - - return 0; - } - } -} diff --git a/src/OpenTelemetry.Abstractions/Trace/TraceId.cs b/src/OpenTelemetry.Abstractions/Trace/TraceId.cs deleted file mode 100644 index 3e42b61b8a5..00000000000 --- a/src/OpenTelemetry.Abstractions/Trace/TraceId.cs +++ /dev/null @@ -1,209 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace -{ - using System; - using OpenTelemetry.Utils; - - /// - /// Trace ID. - /// - public sealed class TraceId : IComparable - { - public const int Size = 16; - private static readonly TraceId InvalidTraceId = new TraceId(new byte[Size]); - - private readonly byte[] bytes; - - private TraceId(byte[] bytes) - { - this.bytes = bytes; - } - - public static TraceId Invalid - { - get - { - return InvalidTraceId; - } - } - - /// - /// Gets the bytes representation of a trace id. - /// - public byte[] Bytes - { - get - { - var copyOf = new byte[Size]; - Buffer.BlockCopy(this.bytes, 0, copyOf, 0, Size); - return copyOf; - } - } - - /// - /// Gets a value indicating whether trace if is valid. - /// - public bool IsValid - { - get - { - return !Arrays.Equals(this.bytes, InvalidTraceId.bytes); - } - } - - /// - /// Gets the lower long of the trace ID. - /// - public long LowerLong - { - get - { - long result = 0; - for (var i = 0; i < 8; i++) - { - result <<= 8; -#pragma warning disable CS0675 // Bitwise-or operator used on a sign-extended operand - result |= this.bytes[i] & 0xff; -#pragma warning restore CS0675 // Bitwise-or operator used on a sign-extended operand - } - - if (result < 0) - { - return -result; - } - - return result; - } - } - - public static TraceId FromBytes(byte[] buffer) - { - if (buffer == null) - { - throw new ArgumentNullException("buffer"); - } - - if (buffer.Length != Size) - { - throw new ArgumentOutOfRangeException(string.Format("Invalid size: expected {0}, got {1}", Size, buffer.Length)); - } - - var bytesCopied = new byte[Size]; - Buffer.BlockCopy(buffer, 0, bytesCopied, 0, Size); - return new TraceId(bytesCopied); - } - - public static TraceId FromBytes(byte[] src, int srcOffset) - { - var bytes = new byte[Size]; - Buffer.BlockCopy(src, srcOffset, bytes, 0, Size); - return new TraceId(bytes); - } - - public static TraceId FromLowerBase16(string src) - { - if (src.Length != 2 * Size) - { - throw new ArgumentOutOfRangeException(string.Format("Invalid size: expected {0}, got {1}", 2 * Size, src.Length)); - } - - var bytes = Arrays.StringToByteArray(src); - return new TraceId(bytes); - } - - public static TraceId GenerateRandomId(IRandomGenerator random) - { - var bytes = new byte[Size]; - do - { - random.NextBytes(bytes); - } - while (Arrays.Equals(bytes, InvalidTraceId.bytes)); - return new TraceId(bytes); - } - - /// - /// Copy trace ID as bytes into the destination bytes array at a given offset. - /// - /// Destination bytes array. - /// Desitnation bytes array offset. - public void CopyBytesTo(byte[] dest, int destOffset) - { - Buffer.BlockCopy(this.bytes, 0, dest, destOffset, Size); - } - - /// - /// Gets the lower base 16 representaiton of the trace id. - /// - /// Canonical string representation of a trace id. - public string ToLowerBase16() - { - var bytes = this.Bytes; - var result = Arrays.ByteArrayToString(bytes); - return result; - } - - /// - public override bool Equals(object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj is TraceId)) - { - return false; - } - - var that = (TraceId)obj; - return Arrays.Equals(this.bytes, that.bytes); - } - - /// - public override int GetHashCode() - { - return Arrays.GetHashCode(this.bytes); - } - - /// - public override string ToString() - { - return "TraceId{" - + "bytes=" + this.ToLowerBase16() - + "}"; - } - - public int CompareTo(TraceId other) - { - var that = other as TraceId; - for (var i = 0; i < Size; i++) - { - if (this.bytes[i] != that.bytes[i]) - { - var b1 = (sbyte)this.bytes[i]; - var b2 = (sbyte)that.bytes[i]; - - return b1 < b2 ? -1 : 1; - } - } - - return 0; - } - } -} diff --git a/src/OpenTelemetry.Abstractions/Trace/TraceOptions.cs b/src/OpenTelemetry.Abstractions/Trace/TraceOptions.cs deleted file mode 100644 index e6483b4e4d5..00000000000 --- a/src/OpenTelemetry.Abstractions/Trace/TraceOptions.cs +++ /dev/null @@ -1,200 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace -{ - using System; - - /// - /// Trace options. - /// - public sealed class TraceOptions - { - /// - /// Size of trace options flag. - /// - public const int Size = 1; - - /// - /// Default trace options. Nothing set. - /// - public static readonly TraceOptions Default = new TraceOptions(DefaultOptions); - - /// - /// Sampled trace options. - /// - public static readonly TraceOptions Sampled = new TraceOptions(1); - - internal const byte DefaultOptions = 0; - - internal const byte IsSampledBit = 0x1; - - private byte options; - - internal TraceOptions(byte options) - { - this.options = options; - } - - /// - /// Gets the bytes representation of a trace options. - /// - public byte[] Bytes - { - get - { - var bytes = new byte[Size]; - bytes[0] = this.options; - return bytes; - } - } - - /// - /// Gets a value indicating whether span is sampled or not. - /// - public bool IsSampled - { - get - { - return this.HasOption(IsSampledBit); - } - } - - internal sbyte Options - { - get { return (sbyte)this.options; } - } - - /// - /// Deserializes trace options from bytes. - /// - /// Buffer to deserialize. - /// Trace options deserialized from the bytes array. - public static TraceOptions FromBytes(byte[] buffer) - { - if (buffer == null) - { - throw new ArgumentNullException("buffer"); - } - - if (buffer.Length != Size) - { - throw new ArgumentOutOfRangeException(string.Format("Invalid size: expected {0}, got {1}", Size, buffer.Length)); - } - - var bytesCopied = new byte[Size]; - Buffer.BlockCopy(buffer, 0, bytesCopied, 0, Size); - return new TraceOptions(bytesCopied[0]); - } - - /// - /// Trace options from bytes with the given offset. - /// - /// Buffer to sdeserialize trace optiosn from. - /// Buffer offset. - /// Trace options deserialized from the buffer. - public static TraceOptions FromBytes(byte[] src, int srcOffset) - { - if (srcOffset < 0 || srcOffset >= src.Length) - { - throw new IndexOutOfRangeException("srcOffset"); - } - - return new TraceOptions(src[srcOffset]); - } - - /// - /// Gets the trace options builder. - /// - /// Trace options builder. - public static TraceOptionsBuilder Builder() - { - return new TraceOptionsBuilder(DefaultOptions); - } - - /// - /// Trace options builder pre-initialized from the given trace options instance. - /// - /// Trace options to pre-initialize the builder. - /// Trace options builder. - public static TraceOptionsBuilder Builder(TraceOptions traceOptions) - { - return new TraceOptionsBuilder(traceOptions.options); - } - - /// - /// Serializes trace options into bytes array at a given offset. - /// - /// Destination to serialize value to. - /// Destintion offset. - public void CopyBytesTo(byte[] dest, int destOffset) - { - if (destOffset < 0 || destOffset >= dest.Length) - { - throw new IndexOutOfRangeException("destOffset"); - } - - dest[destOffset] = this.options; - } - - /// - public override bool Equals(object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj is TraceOptions)) - { - return false; - } - - var that = (TraceOptions)obj; - return this.options == that.options; - } - - /// - public override int GetHashCode() - { - var result = (31 * 1) + this.options; - return result; - } - - /// - public override string ToString() - { - return "TraceOptions{" - + "sampled=" + this.IsSampled - + "}"; - } - - private bool HasOption(int mask) - { - return (this.options & mask) != 0; - } - - private void ClearOption(int mask) - { - this.options = (byte)(this.options & ~mask); - } - - private void SetOption(int mask) - { - this.options = (byte)(this.options | mask); - } - } -} diff --git a/src/OpenTelemetry.Abstractions/Trace/TraceOptionsBuilder.cs b/src/OpenTelemetry.Abstractions/Trace/TraceOptionsBuilder.cs deleted file mode 100644 index 09d3e72cbd8..00000000000 --- a/src/OpenTelemetry.Abstractions/Trace/TraceOptionsBuilder.cs +++ /dev/null @@ -1,64 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace -{ - /// - /// Trace options builder. - /// - public class TraceOptionsBuilder - { - private byte options; - - internal TraceOptionsBuilder() - : this(TraceOptions.DefaultOptions) - { - } - - internal TraceOptionsBuilder(byte options) - { - this.options = options; - } - - /// - /// Sets is sampled flag. - /// - /// New value for the isSampled flag. - /// This builder for operations chaining. - public TraceOptionsBuilder SetIsSampled(bool isSampled) - { - if (isSampled) - { - this.options = (byte)(this.options | TraceOptions.IsSampledBit); - } - else - { - this.options = (byte)(this.options & ~TraceOptions.IsSampledBit); - } - - return this; - } - - /// - /// Builds span options from the values provided. - /// - /// Span options built by this builder. - public TraceOptions Build() - { - return new TraceOptions(this.options); - } - } -} diff --git a/src/OpenTelemetry.Abstractions/Utils/Arrays.cs b/src/OpenTelemetry.Abstractions/Utils/Arrays.cs deleted file mode 100644 index 59ed7dfe6db..00000000000 --- a/src/OpenTelemetry.Abstractions/Utils/Arrays.cs +++ /dev/null @@ -1,145 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Utils -{ - using System; - using System.Text; - - internal static class Arrays - { - private static readonly uint[] ByteToHexLookupTable = CreateLookupTable(); - - public static bool Equals(byte[] array1, byte[] array2) - { - if (array1 == array2) - { - return true; - } - - if (array1 == null || array2 == null) - { - return false; - } - - if (array2.Length != array1.Length) - { - return false; - } - - for (var i = 0; i < array1.Length; i++) - { - if (array1[i] != array2[i]) - { - return false; - } - } - - return true; - } - - internal static int GetHashCode(byte[] array) - { - if (array == null) - { - return 0; - } - - var result = 1; - foreach (var b in array) - { - result = (31 * result) + b; - } - - return result; - } - - internal static int HexCharToInt(char c) - { - if ((c >= '0') && (c <= '9')) - { - return c - '0'; - } - - if ((c >= 'a') && (c <= 'f')) - { - return c - 'a' + 10; - } - - if ((c >= 'A') && (c <= 'F')) - { - return c - 'A' + 10; - } - - throw new ArgumentOutOfRangeException("Invalid character: " + c); - } - - // https://stackoverflow.com/a/24343727 - internal static uint[] CreateLookupTable() - { - var table = new uint[256]; - for (var i = 0; i < 256; i++) - { - var s = i.ToString("x2"); - table[i] = (uint)s[0]; - table[i] += (uint)s[1] << 16; - } - - return table; - } - - // https://stackoverflow.com/a/24343727 - internal static char[] ByteToHexCharArray(byte b) - { - var result = new char[2]; - - result[0] = (char)ByteToHexLookupTable[b]; - result[1] = (char)(ByteToHexLookupTable[b] >> 16); - - return result; - } - - internal static byte[] StringToByteArray(string src, int start = 0, int len = -1) - { - if (len == -1) - { - len = src.Length; - } - - var size = len / 2; - var bytes = new byte[size]; - for (int i = 0, j = start; i < size; i++) - { - var high = HexCharToInt(src[j++]); - var low = HexCharToInt(src[j++]); - bytes[i] = (byte)(high << 4 | low); - } - - return bytes; - } - - internal static string ByteArrayToString(byte[] bytes) - { - var sb = new StringBuilder(); - for (var i = 0; i < bytes.Length; i++) - { - sb.Append(ByteToHexCharArray(bytes[i])); - } - - return sb.ToString(); - } - } -} diff --git a/src/OpenTelemetry.Abstractions/Trace/IRandomGenerator.cs b/src/OpenTelemetry.Collector.AspNetCore/AssemblyInfo.cs similarity index 75% rename from src/OpenTelemetry.Abstractions/Trace/IRandomGenerator.cs rename to src/OpenTelemetry.Collector.AspNetCore/AssemblyInfo.cs index a7b79c2b755..23da982fdad 100644 --- a/src/OpenTelemetry.Abstractions/Trace/IRandomGenerator.cs +++ b/src/OpenTelemetry.Collector.AspNetCore/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// +// // Copyright 2018, OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -13,11 +13,3 @@ // See the License for the specific language governing permissions and // limitations under the License. // - -namespace OpenTelemetry.Trace -{ - public interface IRandomGenerator - { - void NextBytes(byte[] bytes); - } -} diff --git a/src/OpenTelemetry.Collector.AspNetCore/OpenTelemetry.Collector.AspNetCore.csproj b/src/OpenTelemetry.Collector.AspNetCore/OpenTelemetry.Collector.AspNetCore.csproj index e086dc0da8c..9fbdadc7244 100644 --- a/src/OpenTelemetry.Collector.AspNetCore/OpenTelemetry.Collector.AspNetCore.csproj +++ b/src/OpenTelemetry.Collector.AspNetCore/OpenTelemetry.Collector.AspNetCore.csproj @@ -8,7 +8,6 @@ - diff --git a/src/OpenTelemetry.Collector.Dependencies/AssemblyInfo.cs b/src/OpenTelemetry.Collector.Dependencies/AssemblyInfo.cs index 69dc126db66..23da982fdad 100644 --- a/src/OpenTelemetry.Collector.Dependencies/AssemblyInfo.cs +++ b/src/OpenTelemetry.Collector.Dependencies/AssemblyInfo.cs @@ -13,5 +13,3 @@ // See the License for the specific language governing permissions and // limitations under the License. // - -[assembly: System.CLSCompliant(true)] diff --git a/src/OpenTelemetry.Collector.Dependencies/OpenTelemetry.Collector.Dependencies.csproj b/src/OpenTelemetry.Collector.Dependencies/OpenTelemetry.Collector.Dependencies.csproj index 8645907dcf3..9ffc850c8b1 100644 --- a/src/OpenTelemetry.Collector.Dependencies/OpenTelemetry.Collector.Dependencies.csproj +++ b/src/OpenTelemetry.Collector.Dependencies/OpenTelemetry.Collector.Dependencies.csproj @@ -12,7 +12,6 @@ - diff --git a/src/OpenTelemetry.Collector.StackExchangeRedis/Implementation/RedisProfilerEntryToSpanConverter.cs b/src/OpenTelemetry.Collector.StackExchangeRedis/Implementation/RedisProfilerEntryToSpanConverter.cs index 862cacbcab4..bf3d8135bab 100644 --- a/src/OpenTelemetry.Collector.StackExchangeRedis/Implementation/RedisProfilerEntryToSpanConverter.cs +++ b/src/OpenTelemetry.Collector.StackExchangeRedis/Implementation/RedisProfilerEntryToSpanConverter.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Collector.StackExchangeRedis.Implementation { using System; using System.Collections.Generic; + using System.Diagnostics; using OpenTelemetry.Common; using OpenTelemetry.Resources; using OpenTelemetry.Trace; @@ -46,12 +47,12 @@ public static void DrainSession(ISpan parentSpan, IEnumerable } } - internal static bool ShouldSample(SpanContext parentContext, string name, ISampler sampler, out SpanContext context, out SpanId parentSpanId) + internal static bool ShouldSample(SpanContext parentContext, string name, ISampler sampler, out SpanContext context, out ActivitySpanId parentSpanId) { - var traceId = TraceId.Invalid; + ActivityTraceId traceId = default; var tracestate = Tracestate.Empty; - parentSpanId = SpanId.Invalid; - var parentOptions = TraceOptions.Default; + parentSpanId = default; + var parentOptions = ActivityTraceFlags.None; if (parentContext.IsValid) { @@ -61,19 +62,21 @@ internal static bool ShouldSample(SpanContext parentContext, string name, ISampl } else { - traceId = TraceId.FromBytes(Guid.NewGuid().ToByteArray()); + traceId = ActivityTraceId.CreateRandom(); } - var result = parentOptions.IsSampled; - var spanId = SpanId.FromBytes(Guid.NewGuid().ToByteArray(), 8); - var traceOptions = TraceOptions.Default; + var result = (parentOptions & ActivityTraceFlags.Recorded) != 0; + var spanId = ActivitySpanId.CreateRandom(); + var traceOptions = ActivityTraceFlags.None; if (sampler != null) { - var builder = TraceOptions.Builder(parentContext.TraceOptions); + traceOptions = parentContext.TraceOptions; result = sampler.ShouldSample(parentContext, traceId, spanId, name, null); - builder = builder.SetIsSampled(result); - traceOptions = builder.Build(); + if (result) + { + traceOptions |= ActivityTraceFlags.Recorded; + } } context = SpanContext.Create(traceId, spanId, traceOptions, parentContext.Tracestate); @@ -81,7 +84,7 @@ internal static bool ShouldSample(SpanContext parentContext, string name, ISampl return result; } - internal static SpanData ProfiledCommandToSpanData(SpanContext context, string name, SpanId parentSpanId, IProfiledCommand command) + internal static SpanData ProfiledCommandToSpanData(SpanContext context, string name, ActivitySpanId parentSpanId, IProfiledCommand command) { // use https://github.com/opentracing/specification/blob/master/semantic_conventions.md for now diff --git a/src/OpenTelemetry.Collector.StackExchangeRedis/StackExchangeRedisCallsCollector.cs b/src/OpenTelemetry.Collector.StackExchangeRedis/StackExchangeRedisCallsCollector.cs index 0194a3c97e0..c9d752905a6 100644 --- a/src/OpenTelemetry.Collector.StackExchangeRedis/StackExchangeRedisCallsCollector.cs +++ b/src/OpenTelemetry.Collector.StackExchangeRedis/StackExchangeRedisCallsCollector.cs @@ -86,8 +86,8 @@ public Func GetProfilerSessionsFactory() } // TODO: As a performance optimization the check for sampling may be implemented here - // The problem with this approach would be that SpanId cannot be generated here - // So if sampler uses SpanId in algorithm - results would be inconsistent + // The problem with this approach would be that ActivitySpanId cannot be generated here + // So if sampler uses ActivitySpanId in algorithm - results would be inconsistent var session = this.cache.GetOrAdd(span, (s) => new ProfilingSession(s)); return session; }; diff --git a/src/OpenTelemetry.Exporter.ApplicationInsights/Implementation/TraceExporterHandler.cs b/src/OpenTelemetry.Exporter.ApplicationInsights/Implementation/TraceExporterHandler.cs index 8f2e3ebdd51..e273ffad11e 100644 --- a/src/OpenTelemetry.Exporter.ApplicationInsights/Implementation/TraceExporterHandler.cs +++ b/src/OpenTelemetry.Exporter.ApplicationInsights/Implementation/TraceExporterHandler.cs @@ -73,7 +73,6 @@ public Task ExportAsync(IEnumerable spanDataList) foreach (var attr in span.Attributes.AttributeMap) { var key = attr.Key; - switch (attr.Key) { case "span.kind": @@ -123,8 +122,8 @@ public Task ExportAsync(IEnumerable spanDataList) var linkId = 0; foreach (var link in span.Links.Links) { - AddPropertyWithAdjustedName(props, "link" + linkId + "_traceId", link.Context.TraceId.ToLowerBase16()); - AddPropertyWithAdjustedName(props, "link" + linkId + "_spanId", link.Context.SpanId.ToLowerBase16()); + AddPropertyWithAdjustedName(props, "link" + linkId + "_traceId", link.Context.TraceId.ToHexString()); + AddPropertyWithAdjustedName(props, "link" + linkId + "_spanId", link.Context.SpanId.ToHexString()); foreach (var attr in link.Attributes) { @@ -273,12 +272,12 @@ private void ExtractGenericProperties(SpanData span, out SpanKind resultKind, ou props = new Dictionary(); - traceId = span.Context.TraceId.ToLowerBase16(); - spanId = span.Context.SpanId.ToLowerBase16(); + traceId = span.Context.TraceId.ToHexString(); + spanId = span.Context.SpanId.ToHexString(); parentId = null; - if (span.ParentSpanId != null && span.ParentSpanId.IsValid) + if (span.ParentSpanId != default) { - parentId = span.ParentSpanId.ToLowerBase16(); + parentId = span.ParentSpanId.ToHexString(); } resultCode = null; diff --git a/src/OpenTelemetry.Exporter.Ocagent/Implementation/SpanDataExtentions.cs b/src/OpenTelemetry.Exporter.Ocagent/Implementation/SpanDataExtensions.cs similarity index 81% rename from src/OpenTelemetry.Exporter.Ocagent/Implementation/SpanDataExtentions.cs rename to src/OpenTelemetry.Exporter.Ocagent/Implementation/SpanDataExtensions.cs index 628ed93cbc5..382583934e6 100644 --- a/src/OpenTelemetry.Exporter.Ocagent/Implementation/SpanDataExtentions.cs +++ b/src/OpenTelemetry.Exporter.Ocagent/Implementation/SpanDataExtensions.cs @@ -1,4 +1,4 @@ -// +// // Copyright 2018, OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -27,12 +27,27 @@ namespace OpenTelemetry.Exporter.Ocagent.Implementation using OpenTelemetry.Trace; using OpenTelemetry.Trace.Export; - internal static class SpanDataExtentions + internal static class SpanDataExtensions { internal static Span ToProtoSpan(this SpanData spanData) { try { + // protobuf doesn't understand Span yet: https://github.com/protocolbuffers/protobuf/issues/3431 + Span traceIdBytes = stackalloc byte[16]; + Span spanIdBytes = stackalloc byte[8]; + + spanData.Context.TraceId.CopyTo(traceIdBytes); + spanData.Context.SpanId.CopyTo(spanIdBytes); + + var parentSpanIdString = ByteString.Empty; + if (spanData.ParentSpanId != default) + { + Span parentSpanIdBytes = stackalloc byte[8]; + spanData.ParentSpanId.CopyTo(parentSpanIdBytes); + parentSpanIdString = ByteString.CopyFrom(parentSpanIdBytes.ToArray()); + } + return new Span { Name = new TruncatableString { Value = spanData.Name }, @@ -40,10 +55,9 @@ internal static Span ToProtoSpan(this SpanData spanData) // TODO: Utilize new Span.Types.SpanKind below when updated protos are incorporated, also confirm default for SpanKind.Internal Kind = spanData.Kind == SpanKind.Client || spanData.Kind == SpanKind.Producer ? Span.Types.SpanKind.Client : Span.Types.SpanKind.Server, - TraceId = ByteString.CopyFrom(spanData.Context.TraceId.Bytes), - SpanId = ByteString.CopyFrom(spanData.Context.SpanId.Bytes), - ParentSpanId = - ByteString.CopyFrom(spanData.ParentSpanId?.Bytes ?? new byte[0]), + TraceId = ByteString.CopyFrom(traceIdBytes.ToArray()), + SpanId = ByteString.CopyFrom(spanIdBytes.ToArray()), + ParentSpanId = parentSpanIdString, StartTime = new Timestamp { @@ -119,11 +133,18 @@ private static Span.Types.TimeEvents FromITimeEvents(ITimedEvents events private static Span.Types.Link FromILink(ILink source) { + // protobuf doesn't understand Span yet: https://github.com/protocolbuffers/protobuf/issues/3431 + Span traceIdBytes = stackalloc byte[16]; + Span spanIdBytes = stackalloc byte[8]; + + source.Context.TraceId.CopyTo(traceIdBytes); + source.Context.SpanId.CopyTo(spanIdBytes); + var result = new Span.Types.Link { Attributes = FromIAttributeMap(source.Attributes), - TraceId = ByteString.CopyFrom(source.Context.TraceId.Bytes), - SpanId = ByteString.CopyFrom(source.Context.SpanId.Bytes), + TraceId = ByteString.CopyFrom(traceIdBytes.ToArray()), + SpanId = ByteString.CopyFrom(spanIdBytes.ToArray()), }; return result; diff --git a/src/OpenTelemetry.Exporter.Prometheus/AssemblyInfo.cs b/src/OpenTelemetry.Exporter.Prometheus/AssemblyInfo.cs index 69dc126db66..23da982fdad 100644 --- a/src/OpenTelemetry.Exporter.Prometheus/AssemblyInfo.cs +++ b/src/OpenTelemetry.Exporter.Prometheus/AssemblyInfo.cs @@ -13,5 +13,3 @@ // See the License for the specific language governing permissions and // limitations under the License. // - -[assembly: System.CLSCompliant(true)] diff --git a/src/OpenTelemetry.Exporter.Stackdriver/Implementation/SpanExtensions.cs b/src/OpenTelemetry.Exporter.Stackdriver/Implementation/SpanExtensions.cs index f7ac0d61145..b0ceefcdecc 100644 --- a/src/OpenTelemetry.Exporter.Stackdriver/Implementation/SpanExtensions.cs +++ b/src/OpenTelemetry.Exporter.Stackdriver/Implementation/SpanExtensions.cs @@ -32,12 +32,12 @@ internal static class SpanExtensions /// . public static Google.Cloud.Trace.V2.Span ToSpan(this SpanData spanData, string projectId) { - var spanId = spanData.Context.SpanId.ToLowerBase16(); + var spanId = spanData.Context.SpanId.ToHexString(); // Base span settings var span = new Google.Cloud.Trace.V2.Span { - SpanName = new SpanName(projectId, spanData.Context.TraceId.ToLowerBase16(), spanId), + SpanName = new SpanName(projectId, spanData.Context.TraceId.ToHexString(), spanId), SpanId = spanId, DisplayName = new TruncatableString { Value = spanData.Name }, StartTime = spanData.StartTimestamp.ToTimestamp(), @@ -46,7 +46,7 @@ public static Google.Cloud.Trace.V2.Span ToSpan(this SpanData spanData, string p }; if (spanData.ParentSpanId != null) { - var parentSpanId = spanData.ParentSpanId.ToLowerBase16(); + var parentSpanId = spanData.ParentSpanId.ToHexString(); if (!string.IsNullOrEmpty(parentSpanId)) { span.ParentSpanId = parentSpanId; @@ -85,8 +85,8 @@ public static Google.Cloud.Trace.V2.Span ToSpan(this SpanData spanData, string p public static Google.Cloud.Trace.V2.Span.Types.Link ToLink(this ILink link) { var ret = new Google.Cloud.Trace.V2.Span.Types.Link(); - ret.SpanId = link.Context.SpanId.ToLowerBase16(); - ret.TraceId = link.Context.TraceId.ToLowerBase16(); + ret.SpanId = link.Context.SpanId.ToHexString(); + ret.TraceId = link.Context.TraceId.ToHexString(); if (link.Attributes != null) { diff --git a/src/OpenTelemetry.Exporter.Zipkin/AssemblyInfo.cs b/src/OpenTelemetry.Exporter.Zipkin/AssemblyInfo.cs index 19a0d2f9e69..23da982fdad 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/AssemblyInfo.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/AssemblyInfo.cs @@ -13,4 +13,3 @@ // See the License for the specific language governing permissions and // limitations under the License. // -[assembly: System.CLSCompliant(true)] diff --git a/src/OpenTelemetry.Exporter.Zipkin/Implementation/TraceExporterHandler.cs b/src/OpenTelemetry.Exporter.Zipkin/Implementation/TraceExporterHandler.cs index d5de756ab20..3239292ab96 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/Implementation/TraceExporterHandler.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/Implementation/TraceExporterHandler.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Implementation { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Sockets; @@ -76,7 +77,7 @@ internal ZipkinSpan GenerateSpan(SpanData spanData, ZipkinEndpoint localEndpoint var spanBuilder = ZipkinSpan.NewBuilder() - .TraceId(this.EncodeTraceId(context.TraceId)) + .ActivityTraceId(this.EncodeTraceId(context.TraceId)) .Id(this.EncodeSpanId(context.SpanId)) .Kind(this.ToSpanKind(spanData)) .Name(spanData.Name) @@ -84,7 +85,7 @@ internal ZipkinSpan GenerateSpan(SpanData spanData, ZipkinEndpoint localEndpoint .Duration(endTimestamp - startTimestamp) .LocalEndpoint(localEndpoint); - if (spanData.ParentSpanId != null && spanData.ParentSpanId.IsValid) + if (spanData.ParentSpanId != default) { spanBuilder.ParentId(this.EncodeSpanId(spanData.ParentSpanId)); } @@ -131,9 +132,9 @@ private string AttributeValueToString(IAttributeValue attributeValue) (arg) => { return null; }); } - private string EncodeTraceId(TraceId traceId) + private string EncodeTraceId(ActivityTraceId traceId) { - var id = traceId.ToLowerBase16(); + var id = traceId.ToHexString(); if (id.Length > 16 && this.options.UseShortTraceIds) { @@ -143,9 +144,9 @@ private string EncodeTraceId(TraceId traceId) return id; } - private string EncodeSpanId(SpanId spanId) + private string EncodeSpanId(ActivitySpanId spanId) { - return spanId.ToLowerBase16(); + return spanId.ToHexString(); } private ZipkinSpanKind ToSpanKind(SpanData spanData) diff --git a/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs b/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs index 48b9976fe81..07691a5c077 100644 --- a/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs +++ b/src/OpenTelemetry.Exporter.Zipkin/Implementation/ZipkinSpan.cs @@ -24,7 +24,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Implementation internal class ZipkinSpan { [JsonProperty("traceId")] - public string TraceId { get; set; } + public string ActivityTraceId { get; set; } [JsonProperty("parentId")] public string ParentId { get; set; } @@ -72,9 +72,9 @@ public class Builder { private readonly ZipkinSpan result = new ZipkinSpan(); - internal Builder TraceId(string val) + internal Builder ActivityTraceId(string val) { - this.result.TraceId = val; + this.result.ActivityTraceId = val; return this; } @@ -169,7 +169,7 @@ internal Builder AddAnnotation(long timestamp, string value) internal ZipkinSpan Build() { - if (this.result.TraceId == null) + if (this.result.ActivityTraceId == null) { throw new ArgumentException("Trace ID should not be null"); } diff --git a/src/OpenTelemetry/Context/Propagation/B3Format.cs b/src/OpenTelemetry/Context/Propagation/B3Format.cs index bcd2d38973f..a8d2928573b 100644 --- a/src/OpenTelemetry/Context/Propagation/B3Format.cs +++ b/src/OpenTelemetry/Context/Propagation/B3Format.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Context.Propagation { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using OpenTelemetry.Trace; @@ -32,8 +33,8 @@ public sealed class B3Format : ITextFormat internal static readonly string XB3Sampled = "X-B3-Sampled"; internal static readonly string XB3Flags = "X-B3-Flags"; - // Used as the upper TraceId.SIZE hex characters of the traceID. B3-propagation used to send - // TraceId.SIZE hex characters (8-bytes traceId) in the past. + // Used as the upper ActivityTraceId.SIZE hex characters of the traceID. B3-propagation used to send + // ActivityTraceId.SIZE hex characters (8-bytes traceId) in the past. internal static readonly string UpperTraceId = "0000000000000000"; // Sampled value via the X_B3_SAMPLED header. @@ -68,39 +69,39 @@ public SpanContext Extract(T carrier, Func> ge try { - TraceId traceId; + ActivityTraceId traceId; var traceIdStr = getter(carrier, XB3TraceId)?.FirstOrDefault(); if (traceIdStr != null) { - if (traceIdStr.Length == TraceId.Size) + if (traceIdStr.Length == 16) { // This is an 8-byte traceID. traceIdStr = UpperTraceId + traceIdStr; } - traceId = TraceId.FromLowerBase16(traceIdStr); + traceId = ActivityTraceId.CreateFromString(traceIdStr.AsSpan()); } else { throw new SpanContextParseException("Missing X_B3_TRACE_ID."); } - SpanId spanId; + ActivitySpanId spanId; var spanIdStr = getter(carrier, XB3SpanId)?.FirstOrDefault(); if (spanIdStr != null) { - spanId = SpanId.FromLowerBase16(spanIdStr); + spanId = ActivitySpanId.CreateFromString(spanIdStr.AsSpan()); } else { throw new SpanContextParseException("Missing X_B3_SPAN_ID."); } - var traceOptions = TraceOptions.Default; + var traceOptions = ActivityTraceFlags.None; if (SampledValue.Equals(getter(carrier, XB3Sampled)?.FirstOrDefault()) || FlagsValue.Equals(getter(carrier, XB3Flags)?.FirstOrDefault())) { - traceOptions = TraceOptions.Builder().SetIsSampled(true).Build(); + traceOptions |= ActivityTraceFlags.Recorded; } return SpanContext.Create(traceId, spanId, traceOptions, Tracestate.Empty); @@ -129,9 +130,9 @@ public void Inject(SpanContext spanContext, T carrier, Action -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace.Internal -{ - using System; - - internal class RandomGenerator : IRandomGenerator - { - private static readonly Random Global = new Random(); - - [ThreadStatic] - private static Random local; - - private readonly int seed; - private readonly bool sameSeed; - - internal RandomGenerator() - { - this.sameSeed = false; - } - - /// - /// This constructur uses the same seed for all the thread static random objects. - /// You might get the same values if a random is accessed from different threads. - /// Use only for unit tests... - /// - /// The seeds value for the rng. - internal RandomGenerator(int seed) - { - this.sameSeed = true; - this.seed = seed; - } - - public void NextBytes(byte[] bytes) - { - if (local == null) - { - local = new Random(this.sameSeed ? this.seed : Global.Next()); - } - - local.NextBytes(bytes); - } - } -} diff --git a/src/OpenTelemetry/Trace/Internal/StartEndHandler.cs b/src/OpenTelemetry/Trace/Internal/StartEndHandler.cs index 66027fb7b65..60f3e355ae5 100644 --- a/src/OpenTelemetry/Trace/Internal/StartEndHandler.cs +++ b/src/OpenTelemetry/Trace/Internal/StartEndHandler.cs @@ -16,6 +16,7 @@ namespace OpenTelemetry.Trace.Internal { + using System.Diagnostics; using OpenTelemetry.Internal; using OpenTelemetry.Trace.Export; @@ -42,7 +43,7 @@ public StartEndHandler(ISpanExporter spanExporter, IRunningSpanStore runningSpan public void OnEnd(ISpan span) { if ((span.IsRecordingEvents && this.enqueueEventForNonSampledSpans) - || span.Context.TraceOptions.IsSampled) + || (span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0) { this.eventQueue.Enqueue(new SpanEndEvent(span, this.spanExporter, this.runningSpanStore, this.sampledSpanStore)); } @@ -97,7 +98,7 @@ public SpanEndEvent( public void Process() { - if (this.span.Context.TraceOptions.IsSampled) + if ((this.span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0) { this.spanExporter.AddSpan(this.span); } diff --git a/src/OpenTelemetry/Trace/Sampler/ProbabilitySampler.cs b/src/OpenTelemetry/Trace/Sampler/ProbabilitySampler.cs index 60e99c7903e..06a13a0322f 100644 --- a/src/OpenTelemetry/Trace/Sampler/ProbabilitySampler.cs +++ b/src/OpenTelemetry/Trace/Sampler/ProbabilitySampler.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Trace.Sampler { using System; using System.Collections.Generic; + using System.Diagnostics; using OpenTelemetry.Utils; /// @@ -66,10 +67,10 @@ public static ProbabilitySampler Create(double probability) } /// - public bool ShouldSample(SpanContext parentContext, TraceId traceId, SpanId spanId, string name, IEnumerable links) + public bool ShouldSample(SpanContext parentContext, ActivityTraceId traceId, ActivitySpanId spanId, string name, IEnumerable links) { // If the parent is sampled keep the sampling decision. - if (parentContext != null && parentContext.TraceOptions.IsSampled) + if (parentContext != null && (parentContext.TraceOptions & ActivityTraceFlags.Recorded) != 0) { return true; } @@ -79,7 +80,7 @@ public bool ShouldSample(SpanContext parentContext, TraceId traceId, SpanId span // If any parent link is sampled keep the sampling decision. foreach (var parentLink in links) { - if (parentLink.Context.TraceOptions.IsSampled) + if ((parentLink.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0) { return true; } @@ -93,7 +94,9 @@ public bool ShouldSample(SpanContext parentContext, TraceId traceId, SpanId span // while allowing for a (very) small chance of *not* sampling if the id == Long.MAX_VALUE. // This is considered a reasonable tradeoff for the simplicity/performance requirements (this // code is executed in-line for every Span creation). - return Math.Abs(traceId.LowerLong) < this.IdUpperBound; + Span traceIdBytes = stackalloc byte[16]; + traceId.CopyTo(traceIdBytes); + return Math.Abs(this.GetLowerLong(traceIdBytes)) < this.IdUpperBound; } /// @@ -132,5 +135,19 @@ public override int GetHashCode() h ^= (this.IdUpperBound >> 32) ^ this.IdUpperBound; return (int)h; } + + public long GetLowerLong(ReadOnlySpan bytes) + { + long result = 0; + for (var i = 0; i < 8; i++) + { + result <<= 8; +#pragma warning disable CS0675 // Bitwise-or operator used on a sign-extended operand + result |= bytes[i] & 0xff; +#pragma warning restore CS0675 // Bitwise-or operator used on a sign-extended operand + } + + return result; + } } } diff --git a/src/OpenTelemetry/Trace/Span.cs b/src/OpenTelemetry/Trace/Span.cs index e68a8fc0a5d..0ea7dee2401 100644 --- a/src/OpenTelemetry/Trace/Span.cs +++ b/src/OpenTelemetry/Trace/Span.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Trace { using System; using System.Collections.Generic; + using System.Diagnostics; using OpenTelemetry.Common; using OpenTelemetry.Internal; using OpenTelemetry.Resources; @@ -30,7 +31,7 @@ namespace OpenTelemetry.Trace /// public sealed class Span : ISpan, IElement { - private readonly SpanId parentSpanId; + private readonly ActivitySpanId parentSpanId; private readonly ITraceParams traceParams; private readonly IStartEndHandler startEndHandler; private readonly DateTimeOffset startTime; @@ -48,7 +49,7 @@ private Span( SpanOptions options, string name, SpanKind spanKind, - SpanId parentSpanId, + ActivitySpanId parentSpanId, ITraceParams traceParams, IStartEndHandler startEndHandler, Timer timestampConverter) @@ -171,7 +172,7 @@ public bool IsSampleToLocalSpanStore } } - public SpanId ParentSpanId => this.parentSpanId; + public ActivitySpanId ParentSpanId => this.parentSpanId; public bool HasEnded => this.hasBeenEnded; @@ -225,7 +226,7 @@ private TraceEvents InitializedLinks } } - private Status StatusWithDefault => this.status ?? Trace.Status.Ok; + private Status StatusWithDefault => this.status ?? Status.Ok; /// public void UpdateName(string name) @@ -503,7 +504,7 @@ internal static ISpan StartSpan( SpanOptions options, string name, SpanKind spanKind, - SpanId parentSpanId, + ActivitySpanId parentSpanId, ITraceParams traceParams, IStartEndHandler startEndHandler, Timer timestampConverter) diff --git a/src/OpenTelemetry/Trace/SpanBuilder.cs b/src/OpenTelemetry/Trace/SpanBuilder.cs index 7b6f11eeed9..397ae59d2e9 100644 --- a/src/OpenTelemetry/Trace/SpanBuilder.cs +++ b/src/OpenTelemetry/Trace/SpanBuilder.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Trace { using System; using System.Collections.Generic; + using System.Diagnostics; using OpenTelemetry.Internal; using OpenTelemetry.Trace.Config; @@ -149,41 +150,44 @@ public ISpan StartSpan() { SpanContext parentContext = FindParent(this.parentType, this.parent, this.parentSpanContext); var activeTraceParams = this.options.TraceConfig.ActiveTraceParams; - var random = this.options.RandomHandler; - TraceId traceId; - var spanId = SpanId.GenerateRandomId(random); - SpanId parentSpanId = null; - TraceOptionsBuilder traceOptionsBuilder; + ActivityTraceId traceId; + var spanId = ActivitySpanId.CreateRandom(); + + ActivitySpanId parentSpanId = default; + ActivityTraceFlags traceOptions = ActivityTraceFlags.None; + if (parentContext == null || !parentContext.IsValid) { // New root span. - traceId = TraceId.GenerateRandomId(random); - traceOptionsBuilder = TraceOptions.Builder(); + traceId = ActivityTraceId.CreateRandom(); } else { // New child span. traceId = parentContext.TraceId; parentSpanId = parentContext.SpanId; - traceOptionsBuilder = TraceOptions.Builder(parentContext.TraceOptions); + traceOptions = parentContext.TraceOptions; } - traceOptionsBuilder.SetIsSampled( - MakeSamplingDecision( + bool sampledIn = MakeSamplingDecision( parentContext, this.name, this.sampler, this.links, traceId, spanId, - activeTraceParams)); - var traceOptions = traceOptionsBuilder.Build(); - var spanOptions = SpanOptions.None; + activeTraceParams); - if (traceOptions.IsSampled || this.recordEvents) + var spanOptions = SpanOptions.None; + if (sampledIn || this.recordEvents) { + traceOptions |= ActivityTraceFlags.Recorded; spanOptions = SpanOptions.RecordEvents; } + else + { + traceOptions &= ~ActivityTraceFlags.Recorded; + } var span = Span.StartSpan( SpanContext.Create(traceId, spanId, traceOptions, parentContext?.Tracestate ?? Tracestate.Empty), @@ -204,7 +208,7 @@ private static bool IsAnyParentLinkSampled(List parentLinks) { foreach (var parentLink in parentLinks) { - if (parentLink.Context.TraceOptions.IsSampled) + if ((parentLink.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0) { return true; } @@ -230,8 +234,8 @@ private static bool MakeSamplingDecision( string name, ISampler sampler, List parentLinks, - TraceId traceId, - SpanId spanId, + ActivityTraceId traceId, + ActivitySpanId spanId, ITraceParams activeTraceParams) { // If users set a specific sampler in the SpanBuilder, use it. @@ -250,7 +254,7 @@ private static bool MakeSamplingDecision( } // Parent is always different than null because otherwise we use the default sampler. - return parent.TraceOptions.IsSampled || IsAnyParentLinkSampled(parentLinks); + return (parent.TraceOptions & ActivityTraceFlags.Recorded) != 0 || IsAnyParentLinkSampled(parentLinks); } private static SpanContext FindParent(ParentType parentType, ISpan explicitParent, SpanContext remoteParent) diff --git a/src/OpenTelemetry/Trace/SpanBuilderOptions.cs b/src/OpenTelemetry/Trace/SpanBuilderOptions.cs index b1acd82c022..f1ff88707d9 100644 --- a/src/OpenTelemetry/Trace/SpanBuilderOptions.cs +++ b/src/OpenTelemetry/Trace/SpanBuilderOptions.cs @@ -20,15 +20,12 @@ namespace OpenTelemetry.Trace internal class SpanBuilderOptions { - internal SpanBuilderOptions(IRandomGenerator randomGenerator, IStartEndHandler startEndHandler, ITraceConfig traceConfig) + internal SpanBuilderOptions(IStartEndHandler startEndHandler, ITraceConfig traceConfig) { - this.RandomHandler = randomGenerator; this.StartEndHandler = startEndHandler; this.TraceConfig = traceConfig; } - internal IRandomGenerator RandomHandler { get; } - internal IStartEndHandler StartEndHandler { get; } internal ITraceConfig TraceConfig { get; } diff --git a/src/OpenTelemetry/Trace/TraceComponent.cs b/src/OpenTelemetry/Trace/TraceComponent.cs index 9eed9a59a02..adda5bee61b 100644 --- a/src/OpenTelemetry/Trace/TraceComponent.cs +++ b/src/OpenTelemetry/Trace/TraceComponent.cs @@ -30,16 +30,15 @@ public sealed class TraceComponent : ITraceComponent /// Initializes a new instance of the class. /// public TraceComponent() - : this(new RandomGenerator(), new SimpleEventQueue()) + : this(new SimpleEventQueue()) { } /// /// Initializes a new instance of the class. /// - /// Random numbers generator. /// Event queue to use before the exporter. - public TraceComponent(IRandomGenerator randomHandler, IEventQueue eventQueue) + public TraceComponent(IEventQueue eventQueue) { this.TraceConfig = new Config.TraceConfig(); @@ -59,7 +58,7 @@ public TraceComponent(IRandomGenerator randomHandler, IEventQueue eventQueue) ((ExportComponent)this.ExportComponent).RunningSpanStore, ((ExportComponent)this.ExportComponent).SampledSpanStore, eventQueue); - this.Tracer = new Tracer(randomHandler, startEndHandler, this.TraceConfig, null); + this.Tracer = new Tracer(startEndHandler, this.TraceConfig, null); } /// diff --git a/src/OpenTelemetry/Trace/Tracer.cs b/src/OpenTelemetry/Trace/Tracer.cs index b44c8d9aa36..2e56a94debc 100644 --- a/src/OpenTelemetry/Trace/Tracer.cs +++ b/src/OpenTelemetry/Trace/Tracer.cs @@ -30,14 +30,14 @@ public sealed class Tracer : ITracer private readonly SpanBuilderOptions spanBuilderOptions; private readonly IExportComponent exportComponent; - public Tracer(IRandomGenerator randomGenerator, IStartEndHandler startEndHandler, ITraceConfig traceConfig, IExportComponent exportComponent) - : this(randomGenerator, startEndHandler, traceConfig, exportComponent, null, null) + public Tracer(IStartEndHandler startEndHandler, ITraceConfig traceConfig, IExportComponent exportComponent) + : this(startEndHandler, traceConfig, exportComponent, null, null) { } - public Tracer(IRandomGenerator randomGenerator, IStartEndHandler startEndHandler, ITraceConfig traceConfig, IExportComponent exportComponent, IBinaryFormat binaryFormat, ITextFormat textFormat) + public Tracer(IStartEndHandler startEndHandler, ITraceConfig traceConfig, IExportComponent exportComponent, IBinaryFormat binaryFormat, ITextFormat textFormat) { - this.spanBuilderOptions = new SpanBuilderOptions(randomGenerator, startEndHandler, traceConfig); + this.spanBuilderOptions = new SpanBuilderOptions(startEndHandler, traceConfig); this.BinaryFormat = binaryFormat ?? new BinaryFormat(); this.TextFormat = textFormat ?? new TraceContextFormat(); this.exportComponent = exportComponent; diff --git a/src/OpenTelemetry/Trace/Tracing.cs b/src/OpenTelemetry/Trace/Tracing.cs index e76782bd280..40d7dadc823 100644 --- a/src/OpenTelemetry/Trace/Tracing.cs +++ b/src/OpenTelemetry/Trace/Tracing.cs @@ -32,7 +32,7 @@ public sealed class Tracing internal Tracing() { - this.traceComponent = new TraceComponent(new RandomGenerator(), new SimpleEventQueue()); + this.traceComponent = new TraceComponent(new SimpleEventQueue()); } /// diff --git a/test/OpenTelemetry.Collector.AspNetCore.Tests/BasicTests.cs b/test/OpenTelemetry.Collector.AspNetCore.Tests/BasicTests.cs index a6f81f5850f..2f8b9380315 100644 --- a/test/OpenTelemetry.Collector.AspNetCore.Tests/BasicTests.cs +++ b/test/OpenTelemetry.Collector.AspNetCore.Tests/BasicTests.cs @@ -27,6 +27,7 @@ namespace OpenTelemetry.Collector.AspNetCore.Tests using Moq; using Microsoft.AspNetCore.TestHost; using System; + using System.Diagnostics; using OpenTelemetry.Context.Propagation; using Microsoft.AspNetCore.Http; using System.Collections.Generic; @@ -47,7 +48,7 @@ public BasicTests(WebApplicationFactory factory) public async Task SuccesfulTemplateControllerCallGeneratesASpan() { var startEndHandler = new Mock(); - var tracer = new Tracer(new RandomGenerator(), startEndHandler.Object, new TraceConfig(), null); + var tracer = new Tracer(startEndHandler.Object, new TraceConfig(), null); void ConfigureTestServices(IServiceCollection services) => services.AddSingleton(tracer); @@ -92,18 +93,18 @@ public async Task SuccesfulTemplateControllerCallUsesParentContext() { var startEndHandler = new Mock(); - var expectedTraceId = TraceId.GenerateRandomId(new RandomGenerator()); - var expectedSpanId = SpanId.GenerateRandomId(new RandomGenerator()); + var expectedTraceId = ActivityTraceId.CreateRandom(); + var expectedSpanId = ActivitySpanId.CreateRandom(); var tf = new Mock(); tf.Setup(m => m.Extract(It.IsAny(), It.IsAny>>())).Returns(SpanContext.Create( expectedTraceId, expectedSpanId, - TraceOptions.Default, + ActivityTraceFlags.None, Tracestate.Empty )); - var tracer = new Tracer(new RandomGenerator(), startEndHandler.Object, new TraceConfig(), null, null, tf.Object); + var tracer = new Tracer(startEndHandler.Object, new TraceConfig(), null, null, tf.Object); // Arrange using (var client = this.factory diff --git a/test/OpenTelemetry.Collector.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs b/test/OpenTelemetry.Collector.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs index 90cb12b4bc0..2a8a091e116 100644 --- a/test/OpenTelemetry.Collector.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs +++ b/test/OpenTelemetry.Collector.AspNetCore.Tests/IncomingRequestsCollectionsIsAccordingToTheSpecTests.cs @@ -55,7 +55,7 @@ public override async Task ProcessAsync(HttpContext context) public async Task SuccesfulTemplateControllerCallGeneratesASpan() { var startEndHandler = new Mock(); - var tracer = new Tracer(new RandomGenerator(), startEndHandler.Object, new TraceConfig(), null); + var tracer = new Tracer(startEndHandler.Object, new TraceConfig(), null); // Arrange using (var client = this.factory diff --git a/test/OpenTelemetry.Collector.Dependencies.Tests/BasicTests.cs b/test/OpenTelemetry.Collector.Dependencies.Tests/BasicTests.cs index 29f5f1d2f77..ebb496df0e7 100644 --- a/test/OpenTelemetry.Collector.Dependencies.Tests/BasicTests.cs +++ b/test/OpenTelemetry.Collector.Dependencies.Tests/BasicTests.cs @@ -23,6 +23,7 @@ namespace OpenTelemetry.Collector.Dependencies.Tests using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace.Sampler; using System; + using System.Diagnostics; using System.Net.Http; using System.Threading.Tasks; using Xunit; @@ -45,8 +46,8 @@ public async Task HttpDepenenciesCollectorInjectsHeadersAsync() var url = $"http://{host}:{port}/"; - var expectedTraceId = TraceId.Invalid; - var expectedSpanId = SpanId.Invalid; + ActivityTraceId expectedTraceId = default; + ActivitySpanId expectedSpanId = default; using (serverLifeTime) { @@ -59,7 +60,7 @@ public async Task HttpDepenenciesCollectorInjectsHeadersAsync() expectedSpanId = sc.SpanId; }); - var tracer = new Tracer(new RandomGenerator(), startEndHandler.Object, new TraceConfig(), null, null, tf.Object); + var tracer = new Tracer(startEndHandler.Object, new TraceConfig(), null, null, tf.Object); using (var dc = new DependenciesCollector(new DependenciesCollectorOptions(), tracer, Samplers.AlwaysSample)) { diff --git a/test/OpenTelemetry.Collector.Dependencies.Tests/HttpClientTests.cs b/test/OpenTelemetry.Collector.Dependencies.Tests/HttpClientTests.cs index d2a5c1cb8ca..3a01b3aa740 100644 --- a/test/OpenTelemetry.Collector.Dependencies.Tests/HttpClientTests.cs +++ b/test/OpenTelemetry.Collector.Dependencies.Tests/HttpClientTests.cs @@ -99,7 +99,7 @@ public async Task HttpOutCallsAreCollectedSuccesfullyAsync(HttpOutTestCase tc) out var port); var startEndHandler = new Mock(); - var tracer = new Tracer(new RandomGenerator(), startEndHandler.Object, new TraceConfig(), null); + var tracer = new Tracer(startEndHandler.Object, new TraceConfig(), null); tc.url = NormaizeValues(tc.url, host, port); using (serverLifeTime) diff --git a/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterSamplingTests.cs b/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterSamplingTests.cs index 3593e9ec80b..50cf6593012 100644 --- a/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterSamplingTests.cs +++ b/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterSamplingTests.cs @@ -16,6 +16,7 @@ namespace OpenTelemetry.Collector.StackExchangeRedis.Implementation { + using System.Diagnostics; using Moq; using OpenTelemetry.Trace; using OpenTelemetry.Trace.Internal; @@ -30,8 +31,8 @@ public void ShouldSampleRespectsSamplerChoice() var m = new Mock(); m.Setup(x => x.ShouldSample( It.IsAny(), - It.IsAny(), - It.IsAny(), + It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny>())).Returns(true); @@ -40,8 +41,8 @@ public void ShouldSampleRespectsSamplerChoice() m = new Mock(); m.Setup(x => x.ShouldSample( It.IsAny(), - It.IsAny(), - It.IsAny(), + It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny>())).Returns(false); @@ -58,15 +59,14 @@ public void ShouldSampleDoesntThrowWithoutSampler() public void ShouldSamplePassesArgumentsToSamplerAndReturnsInContext() { var m = new Mock(); - var r = new RandomGenerator(); - var traceId = TraceId.GenerateRandomId(r); - var parentContext = SpanContext.Create(traceId, SpanId.GenerateRandomId(r), TraceOptions.Sampled, Tracestate.Builder.Set("a", "b").Build()); + var traceId = ActivityTraceId.CreateRandom(); + var parentContext = SpanContext.Create(traceId, ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded, Tracestate.Builder.Set("a", "b").Build()); RedisProfilerEntryToSpanConverter.ShouldSample(parentContext, "SET", m.Object, out var context, out var parentId); m.Verify(x => x.ShouldSample( It.Is(y => y == parentContext), - It.Is(y => y == traceId && y == context.TraceId), - It.Is(y => y.IsValid && y == context.SpanId), + It.Is(y => y == traceId && y == context.TraceId), + It.Is(y => y != default && y == context.SpanId), It.Is(y => y == "SET"), It.Is>(y => y == null))); } @@ -77,21 +77,21 @@ public void ShouldSampleGeneratesNewTraceIdForInvalidContext() var m = new Mock(); m.Setup(x => x.ShouldSample( It.IsAny(), - It.IsAny(), - It.IsAny(), + It.IsAny(), + It.IsAny(), It.IsAny(), - It.IsAny>())).Returns((SpanContext parentContext, TraceId traceId, SpanId spanId, string name, IEnumerable parentLinks) => parentContext.TraceOptions.IsSampled); + It.IsAny>())).Returns((SpanContext parentContext, ActivityTraceId traceId, ActivitySpanId spanId, string name, IEnumerable parentLinks) => (parentContext.TraceOptions & ActivityTraceFlags.Recorded) != 0); RedisProfilerEntryToSpanConverter.ShouldSample(SpanContext.Blank, "SET", m.Object, out var context, out var parentId); m.Verify(x => x.ShouldSample( It.Is(y => y == SpanContext.Blank), - It.Is(y => y.IsValid && y == context.TraceId), - It.Is(y => y.IsValid && y == context.SpanId), + It.Is(y => y != default && y == context.TraceId), + It.Is(y => y != default && y == context.SpanId), It.Is(y => y == "SET"), It.Is>(y => y == null))); - Assert.Equal(TraceOptions.Default, context.TraceOptions); + Assert.Equal(ActivityTraceFlags.None, context.TraceOptions); } } } diff --git a/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterTests.cs b/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterTests.cs index 4cc7cade42f..b1ae129ffb0 100644 --- a/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterTests.cs +++ b/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/Implementation/RedisProfilerEntryToSpanConverterTests.cs @@ -20,8 +20,8 @@ namespace OpenTelemetry.Collector.StackExchangeRedis.Implementation using Moq; using StackExchange.Redis.Profiling; using Xunit; - using OpenTelemetry.Trace.Internal; using System; + using System.Diagnostics; using OpenTelemetry.Common; using System.Collections.Generic; @@ -33,7 +33,7 @@ public void DrainSessionUsesCommandAsName() var parentSpan = BlankSpan.Instance; var profiledCommand = new Mock(); var sampler = new Mock(); - sampler.Setup(x => x.ShouldSample(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>())).Returns(true); + sampler.Setup(x => x.ShouldSample(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>())).Returns(true); profiledCommand.Setup(m => m.Command).Returns("SET"); var result = new List(); RedisProfilerEntryToSpanConverter.DrainSession(parentSpan, new IProfiledCommand[] { profiledCommand.Object }, sampler.Object, result); @@ -47,7 +47,7 @@ public void ProfiledCommandToSpanDataUsesTimestampAsStartTime() var profiledCommand = new Mock(); var now = DateTimeOffset.Now; profiledCommand.Setup(m => m.CommandCreated).Returns(now.DateTime); - var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "SET", SpanId.Invalid, profiledCommand.Object); + var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "SET", default, profiledCommand.Object); Assert.Equal(Timestamp.FromMillis(now.ToUnixTimeMilliseconds()), result.StartTimestamp); } @@ -55,7 +55,7 @@ public void ProfiledCommandToSpanDataUsesTimestampAsStartTime() public void ProfiledCommandToSpanDataSetsDbTypeAttributeAsRedis() { var profiledCommand = new Mock(); - var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "SET", SpanId.Invalid, profiledCommand.Object); + var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "SET", default, profiledCommand.Object); Assert.Contains("db.type", result.Attributes.AttributeMap.Keys); Assert.Equal(AttributeValue.StringAttributeValue("redis"), result.Attributes.AttributeMap["db.type"]); } @@ -65,7 +65,7 @@ public void ProfiledCommandToSpanDataUsesCommandAsDbStatementAttribute() { var profiledCommand = new Mock(); profiledCommand.Setup(m => m.Command).Returns("SET"); - var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "another name", SpanId.Invalid, profiledCommand.Object); + var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "another name", default, profiledCommand.Object); Assert.Contains("db.statement", result.Attributes.AttributeMap.Keys); Assert.Equal(AttributeValue.StringAttributeValue("SET"), result.Attributes.AttributeMap["db.statement"]); } @@ -76,7 +76,7 @@ public void ProfiledCommandToSpanDataUsesFlagsForFlagsAttribute() var profiledCommand = new Mock(); var expectedFlags = StackExchange.Redis.CommandFlags.FireAndForget | StackExchange.Redis.CommandFlags.NoRedirect; profiledCommand.Setup(m => m.Flags).Returns(expectedFlags); - var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "SET", SpanId.Invalid, profiledCommand.Object); + var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Blank, "SET", default, profiledCommand.Object); Assert.Contains("redis.flags", result.Attributes.AttributeMap.Keys); Assert.Equal(AttributeValue.StringAttributeValue("None, FireAndForget, NoRedirect"), result.Attributes.AttributeMap["redis.flags"]); } diff --git a/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/StackExchangeRedisCallsCollectorTests.cs b/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/StackExchangeRedisCallsCollectorTests.cs index 235d15160ca..2cc7074ee50 100644 --- a/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/StackExchangeRedisCallsCollectorTests.cs +++ b/test/OpenTelemetry.Collector.StackExchangeRedis.Tests/StackExchangeRedisCallsCollectorTests.cs @@ -30,7 +30,7 @@ public class StackExchangeRedisCallsCollectorTests public async void ProfilerSessionUsesTheSameDefault() { var startEndHandler = new Mock(); - var tracer = new Tracer(new RandomGenerator(), startEndHandler.Object, new TraceConfig(), null); + var tracer = new Tracer(startEndHandler.Object, new TraceConfig(), null); using (var collector = new StackExchangeRedisCallsCollector(tracer, null, null)) { diff --git a/test/OpenTelemetry.Exporter.ApplicationInsights.Tests/Implementation/TraceExporterHandlerTests.cs b/test/OpenTelemetry.Exporter.ApplicationInsights.Tests/Implementation/TraceExporterHandlerTests.cs index d419f82cf42..f5e2189d56f 100644 --- a/test/OpenTelemetry.Exporter.ApplicationInsights.Tests/Implementation/TraceExporterHandlerTests.cs +++ b/test/OpenTelemetry.Exporter.ApplicationInsights.Tests/Implementation/TraceExporterHandlerTests.cs @@ -27,6 +27,7 @@ namespace OpenTelemetry.Exporter.ApplicationInsights.Tests using System; using System.Collections.Concurrent; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using System.Threading; using Xunit; @@ -43,13 +44,7 @@ public class OpenTelemetryTelemetryConverterTests private DateTimeOffset nowDateTimeOffset; - private Timestamp NowTimestamp - { - get - { - return Timestamp.FromDateTimeOffset(nowDateTimeOffset); - } - } + private Timestamp NowTimestamp => Timestamp.FromDateTimeOffset(nowDateTimeOffset); public OpenTelemetryTelemetryConverterTests() { @@ -142,7 +137,7 @@ public void OpenTelemetryTelemetryConverterTests_TracksRequestWithParent() // ARRANGE this.GetDefaults(out var context, out var parentSpanId, out var resource, out var name, out var startTimestamp, out var attributes, out var events, out var links, out var childSpanCount, out var status, out var kind, out var endTimestamp); - parentSpanId = SpanId.FromBytes(this.testParentSpanIdBytes); + parentSpanId = ActivitySpanId.CreateFromBytes(this.testParentSpanIdBytes); var span = SpanData.Create(context, parentSpanId, resource, name, startTimestamp, attributes, events, links, childSpanCount, status, kind, endTimestamp); @@ -159,7 +154,7 @@ public void OpenTelemetryTelemetryConverterTests_TracksRequestWithInvalidParent( // ARRANGE this.GetDefaults(out var context, out var parentSpanId, out var resource, out var name, out var startTimestamp, out var attributes, out var events, out var links, out var childSpanCount, out var status, out var kind, out var endTimestamp); - parentSpanId = SpanId.Invalid; + parentSpanId = default; var span = SpanData.Create(context, parentSpanId, resource, name, startTimestamp, attributes, events, links, childSpanCount, status, kind, endTimestamp); @@ -433,7 +428,7 @@ public void OpenTelemetryTelemetryConverterTests_TracksDependencyWithParent() // ARRANGE this.GetDefaults(out var context, out var parentSpanId, out var resource, out var name, out var startTimestamp, out var attributes, out var events, out var links, out var childSpanCount, out var status, out var kind, out var endTimestamp); kind = SpanKind.Client; - parentSpanId = SpanId.FromBytes(this.testParentSpanIdBytes); + parentSpanId = ActivitySpanId.CreateFromBytes(this.testParentSpanIdBytes); var span = SpanData.Create(context, parentSpanId, resource, name, startTimestamp, attributes, events, links, childSpanCount, status, kind, endTimestamp); // ACT @@ -599,7 +594,7 @@ public void OpenTelemetryTelemetryConverterTests_TracksRequestBasedOnOtherSpanKi public void OpenTelemetryTelemetryConverterTests_TracksRequestBasedOnSpanKindProperty() { this.GetDefaults(out var context, out var parentSpanId, out var resource, out var name, out var startTimestamp, out var attributes, out var events, out var links, out var childSpanCount, out var status, out var kind, out var endTimestamp); - parentSpanId = SpanId.FromBytes(this.testParentSpanIdBytes); + parentSpanId = ActivitySpanId.CreateFromBytes(this.testParentSpanIdBytes); var span = SpanData.Create(context, parentSpanId, resource, name, startTimestamp, attributes, events, links, childSpanCount, status, kind, endTimestamp); var sentItems = this.ConvertSpan(span); @@ -612,7 +607,7 @@ public void OpenTelemetryTelemetryConverterTests_TracksDependencyBasedOnSpanKind { this.GetDefaults(out var context, out var parentSpanId, out var resource, out var name, out var startTimestamp, out var attributes, out var events, out var links, out var childSpanCount, out var status, out var kind, out var endTimestamp); kind = SpanKind.Client; - parentSpanId = SpanId.FromBytes(this.testParentSpanIdBytes); + parentSpanId = ActivitySpanId.CreateFromBytes(this.testParentSpanIdBytes); var span = SpanData.Create(context, parentSpanId, resource, name, startTimestamp, attributes, events, links, childSpanCount, status, kind, endTimestamp); var sentItems = this.ConvertSpan(span); @@ -1293,11 +1288,11 @@ public void OpenTelemetryTelemetryConverterTests_TracksDependencyWithLinks() new List() { Link.FromSpanContext( - SpanContext.Create(TraceId.FromBytes(link0TraceIdBytes), SpanId.FromBytes(link0SpanIdBytes), TraceOptions.Default, Tracestate.Empty)), + SpanContext.Create(ActivityTraceId.CreateFromBytes(link0TraceIdBytes), ActivitySpanId.CreateFromBytes(link0SpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty)), Link.FromSpanContext( - SpanContext.Create(TraceId.FromBytes(link1TraceIdBytes), SpanId.FromBytes(link1SpanIdBytes), TraceOptions.Default, Tracestate.Empty)), + SpanContext.Create(ActivityTraceId.CreateFromBytes(link1TraceIdBytes), ActivitySpanId.CreateFromBytes(link1SpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty)), Link.FromSpanContext( - SpanContext.Create(TraceId.FromBytes(link2TraceIdBytes), SpanId.FromBytes(link2SpanIdBytes), TraceOptions.Default, Tracestate.Empty)), + SpanContext.Create(ActivityTraceId.CreateFromBytes(link2TraceIdBytes), ActivitySpanId.CreateFromBytes(link2SpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty)), }, 0); var span = SpanData.Create(context, parentSpanId, resource, name, startTimestamp, attributes, events, links, childSpanCount, status, kind, endTimestamp); @@ -1336,9 +1331,9 @@ public void OpenTelemetryTelemetryConverterTests_TracksDependencyWithLinksAndAtt { Link.FromSpanContext( SpanContext.Create( - TraceId.FromBytes(GenerateRandomId(16).Item2), - SpanId.FromBytes(GenerateRandomId(8).Item2), - TraceOptions.Default, + ActivityTraceId.CreateFromBytes(GenerateRandomId(16).Item2), + ActivitySpanId.CreateFromBytes(GenerateRandomId(8).Item2), + ActivityTraceFlags.None, Tracestate.Empty), new Dictionary() { @@ -1384,11 +1379,11 @@ public void OpenTelemetryTelemetryConverterTests_TracksRequestWithLinks() links = LinkList.Create(new List() { Link.FromSpanContext( - SpanContext.Create(TraceId.FromBytes(link0TraceIdBytes), SpanId.FromBytes(link0SpanIdBytes), TraceOptions.Default, Tracestate.Empty)), + SpanContext.Create(ActivityTraceId.CreateFromBytes(link0TraceIdBytes), ActivitySpanId.CreateFromBytes(link0SpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty)), Link.FromSpanContext( - SpanContext.Create(TraceId.FromBytes(link1TraceIdBytes), SpanId.FromBytes(link1SpanIdBytes), TraceOptions.Default, Tracestate.Empty)), + SpanContext.Create(ActivityTraceId.CreateFromBytes(link1TraceIdBytes), ActivitySpanId.CreateFromBytes(link1SpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty)), Link.FromSpanContext( - SpanContext.Create(TraceId.FromBytes(link2TraceIdBytes), SpanId.FromBytes(link2SpanIdBytes), TraceOptions.Default, Tracestate.Empty)), + SpanContext.Create(ActivityTraceId.CreateFromBytes(link2TraceIdBytes), ActivitySpanId.CreateFromBytes(link2SpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty)), }, 0); var span = SpanData.Create(context, parentSpanId, resource, name, startTimestamp, attributes, events, links, childSpanCount, status, kind, endTimestamp); @@ -1427,9 +1422,9 @@ public void OpenTelemetryTelemetryConverterTests_TracksRequestWithLinksAndAttrib { Link.FromSpanContext( SpanContext.Create( - TraceId.FromBytes(GenerateRandomId(16).Item2), - SpanId.FromBytes(GenerateRandomId(8).Item2), - TraceOptions.Default, + ActivityTraceId.CreateFromBytes(GenerateRandomId(16).Item2), + ActivitySpanId.CreateFromBytes(GenerateRandomId(8).Item2), + ActivityTraceFlags.None, Tracestate.Empty), new Dictionary() { @@ -1864,7 +1859,7 @@ internal static string GetAssemblyVersionString() private void GetDefaults( out SpanContext context, - out SpanId parentSpanId, + out ActivitySpanId parentSpanId, out Resource resource, out string name, out Timestamp startTimestamp, @@ -1876,8 +1871,8 @@ private void GetDefaults( out SpanKind kind, out Timestamp endTimestamp) { - context = SpanContext.Create(TraceId.FromBytes(this.testTraceIdBytes), SpanId.FromBytes(this.testSpanIdBytes), TraceOptions.Default, Tracestate.Empty); - parentSpanId = SpanId.Invalid; + context = SpanContext.Create(ActivityTraceId.CreateFromBytes(this.testTraceIdBytes), ActivitySpanId.CreateFromBytes(this.testSpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty); + parentSpanId = default; resource = Resource.Empty; name = "spanName"; startTimestamp = NowTimestamp.AddDuration(Duration.Create(TimeSpan.FromSeconds(-1))); diff --git a/test/OpenTelemetry.Tests/Impl/Trace/CurrentSpanUtilsTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/CurrentSpanUtilsTest.cs index e6163921fd0..c1ecfbc134e 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/CurrentSpanUtilsTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/CurrentSpanUtilsTest.cs @@ -16,25 +16,24 @@ namespace OpenTelemetry.Trace.Test { + using System.Diagnostics; using Moq; using OpenTelemetry.Trace.Internal; using Xunit; public class CurrentSpanUtilsTest { - private readonly ISpan span; - private readonly RandomGenerator random; - private readonly SpanContext spanContext; - private readonly SpanOptions spanOptions; + private ISpan span; + private SpanContext spanContext; + private SpanOptions spanOptions; public CurrentSpanUtilsTest() { - random = new RandomGenerator(1234); spanContext = SpanContext.Create( - TraceId.GenerateRandomId(random), - SpanId.GenerateRandomId(random), - TraceOptions.Builder().SetIsSampled(true).Build(), + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.Recorded, Tracestate.Empty); spanOptions = SpanOptions.RecordEvents; diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessRunningSpanStoreTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessRunningSpanStoreTest.cs index ed3f29d1cfb..fef31b33af6 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessRunningSpanStoreTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessRunningSpanStoreTest.cs @@ -16,6 +16,7 @@ namespace OpenTelemetry.Trace.Export.Test { + using System.Diagnostics; using OpenTelemetry.Common; using OpenTelemetry.Internal; using OpenTelemetry.Trace.Config; @@ -24,10 +25,8 @@ namespace OpenTelemetry.Trace.Export.Test public class InProcessRunningSpanStoreTest { - - private static readonly string SPAN_NAME_1 = "MySpanName/1"; - private static readonly string SPAN_NAME_2 = "MySpanName/2"; - private readonly RandomGenerator random = new RandomGenerator(1234); + private const string SpanName1 = "MySpanName/1"; + private const string SpanName2 = "MySpanName/2"; private readonly ISpanExporter sampledSpansServiceExporter = SpanExporter.Create(4, Duration.Create(1, 0)); private readonly InProcessRunningSpanStore activeSpansExporter = new InProcessRunningSpanStore(); private readonly StartEndHandler startEndHandler; @@ -42,15 +41,15 @@ private ISpan CreateSpan(string spanName) { var spanContext = SpanContext.Create( - TraceId.GenerateRandomId(random), - SpanId.GenerateRandomId(random), - TraceOptions.Default, Tracestate.Empty); + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty); return Span.StartSpan( spanContext, recordSpanOptions, spanName, SpanKind.Internal, - SpanId.GenerateRandomId(random), + ActivitySpanId.CreateRandom(), TraceParams.Default, startEndHandler, null); @@ -59,26 +58,26 @@ private ISpan CreateSpan(string spanName) [Fact] public void GetSummary_SpansWithDifferentNames() { - var span1 = CreateSpan(SPAN_NAME_1); - var span2 = CreateSpan(SPAN_NAME_2); + var span1 = CreateSpan(SpanName1); + var span2 = CreateSpan(SpanName2); Assert.Equal(2, activeSpansExporter.Summary.PerSpanNameSummary.Count); Assert.Equal(1, activeSpansExporter .Summary - .PerSpanNameSummary[SPAN_NAME_1] + .PerSpanNameSummary[SpanName1] .NumRunningSpans); Assert.Equal(1, activeSpansExporter .Summary - .PerSpanNameSummary[SPAN_NAME_2] + .PerSpanNameSummary[SpanName2] .NumRunningSpans); span1.End(); Assert.Equal(1, activeSpansExporter.Summary.PerSpanNameSummary.Count); - Assert.False(activeSpansExporter.Summary.PerSpanNameSummary.ContainsKey(SPAN_NAME_1)); + Assert.False(activeSpansExporter.Summary.PerSpanNameSummary.ContainsKey(SpanName1)); Assert.Equal(1, activeSpansExporter .Summary - .PerSpanNameSummary[SPAN_NAME_2] + .PerSpanNameSummary[SpanName2] .NumRunningSpans); span2.End(); Assert.Equal(0, activeSpansExporter.Summary.PerSpanNameSummary.Count); @@ -87,28 +86,28 @@ public void GetSummary_SpansWithDifferentNames() [Fact] public void GetSummary_SpansWithSameName() { - var span1 = CreateSpan(SPAN_NAME_1); - var span2 = CreateSpan(SPAN_NAME_1); - var span3 = CreateSpan(SPAN_NAME_1); + var span1 = CreateSpan(SpanName1); + var span2 = CreateSpan(SpanName1); + var span3 = CreateSpan(SpanName1); Assert.Equal(1, activeSpansExporter.Summary.PerSpanNameSummary.Count); Assert.Equal(3, activeSpansExporter .Summary - .PerSpanNameSummary[SPAN_NAME_1] + .PerSpanNameSummary[SpanName1] .NumRunningSpans); span1.End(); Assert.Equal(1, activeSpansExporter.Summary.PerSpanNameSummary.Count); Assert.Equal(2, activeSpansExporter .Summary - .PerSpanNameSummary[SPAN_NAME_1] + .PerSpanNameSummary[SpanName1] .NumRunningSpans); span2.End(); Assert.Equal(1, activeSpansExporter.Summary.PerSpanNameSummary.Count); Assert.Equal(1, activeSpansExporter .Summary - .PerSpanNameSummary[SPAN_NAME_1] + .PerSpanNameSummary[SpanName1] .NumRunningSpans); span3.End(); Assert.Equal(0, activeSpansExporter.Summary.PerSpanNameSummary.Count); @@ -117,11 +116,11 @@ public void GetSummary_SpansWithSameName() [Fact] public void GetActiveSpans_SpansWithDifferentNames() { - var span1 = CreateSpan(SPAN_NAME_1) as Span; - var span2 = CreateSpan(SPAN_NAME_2) as Span; - Assert.Contains(span1.ToSpanData(), activeSpansExporter.GetRunningSpans(RunningSpanStoreFilter.Create(SPAN_NAME_1, 0))); - Assert.Contains(span1.ToSpanData(), activeSpansExporter.GetRunningSpans(RunningSpanStoreFilter.Create(SPAN_NAME_1, 2))); - Assert.Contains(span2.ToSpanData(), activeSpansExporter.GetRunningSpans(RunningSpanStoreFilter.Create(SPAN_NAME_2, 0))); + var span1 = CreateSpan(SpanName1) as Span; + var span2 = CreateSpan(SpanName2) as Span; + Assert.Contains(span1.ToSpanData(), activeSpansExporter.GetRunningSpans(RunningSpanStoreFilter.Create(SpanName1, 0))); + Assert.Contains(span1.ToSpanData(), activeSpansExporter.GetRunningSpans(RunningSpanStoreFilter.Create(SpanName1, 2))); + Assert.Contains(span2.ToSpanData(), activeSpansExporter.GetRunningSpans(RunningSpanStoreFilter.Create(SpanName2, 0))); span1.End(); span2.End(); } diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessSampledSpanStoreTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessSampledSpanStoreTest.cs index a2d1c1ddf0d..229fea3d6e9 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessSampledSpanStoreTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Export/InProcessSampledSpanStoreTest.cs @@ -18,24 +18,23 @@ namespace OpenTelemetry.Trace.Export.Test { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using OpenTelemetry.Common; using OpenTelemetry.Internal; using OpenTelemetry.Trace.Config; - using OpenTelemetry.Trace.Internal; using OpenTelemetry.Utils; using Xunit; public class InProcessSampledSpanStoreTest { - private static readonly String REGISTERED_SPAN_NAME = "MySpanName/1"; - private static readonly String NOT_REGISTERED_SPAN_NAME = "MySpanName/2"; - private readonly RandomGenerator random = new RandomGenerator(1234); + private static readonly string REGISTERED_SPAN_NAME = "MySpanName/1"; + private static readonly string NOT_REGISTERED_SPAN_NAME = "MySpanName/2"; private readonly SpanContext sampledSpanContext; private readonly SpanContext notSampledSpanContext; - private readonly SpanId parentSpanId; + private readonly ActivitySpanId parentSpanId; private readonly SpanOptions recordSpanOptions = SpanOptions.RecordEvents; private TimeSpan interval = TimeSpan.FromMilliseconds(0); private readonly DateTimeOffset startTime = DateTimeOffset.Now; @@ -51,15 +50,13 @@ public InProcessSampledSpanStoreTest() { timestamp = Timestamp.FromDateTimeOffset(startTime); timestampConverter = Timer.StartNew(startTime, () => interval); - sampledSpanContext = SpanContext.Create(TraceId.GenerateRandomId(random), SpanId.GenerateRandomId(random), TraceOptions.Builder().SetIsSampled(true).Build(), Tracestate.Empty); - notSampledSpanContext = SpanContext.Create(TraceId.GenerateRandomId(random), SpanId.GenerateRandomId(random), TraceOptions.Default, Tracestate.Empty); - parentSpanId = SpanId.GenerateRandomId(random); + sampledSpanContext = SpanContext.Create(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded, Tracestate.Empty); + notSampledSpanContext = SpanContext.Create(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Empty); + parentSpanId = ActivitySpanId.CreateRandom(); startEndHandler = new TestStartEndHandler(sampleStore); sampleStore.RegisterSpanNamesForCollection(new List() { REGISTERED_SPAN_NAME }); } - - [Fact] public void AddSpansWithRegisteredNamesInAllLatencyBuckets() { diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanDataTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanDataTest.cs index 9c594fc793c..7023dfacd19 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanDataTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanDataTest.cs @@ -17,6 +17,7 @@ namespace OpenTelemetry.Trace.Export.Test { using System.Collections.Generic; + using System.Diagnostics; using OpenTelemetry.Common; using OpenTelemetry.Resources; using OpenTelemetry.Trace.Internal; @@ -35,9 +36,8 @@ public class SpanDataTest private static readonly Timestamp endTimestamp = Timestamp.Create(123, 460); private static readonly IEvent spanEvent = Event.Create(EVENT_TEXT); private static readonly Status status = Status.DeadlineExceeded.WithDescription("TooSlow"); - private readonly IRandomGenerator random = new RandomGenerator(1234); private readonly SpanContext spanContext; - private readonly SpanId parentSpanId; + private readonly ActivitySpanId parentSpanId; private readonly Resource resource = Resource.Empty; private readonly IDictionary attributesMap = new Dictionary(); private readonly List> eventList = new List>(); @@ -49,8 +49,8 @@ public class SpanDataTest public SpanDataTest() { - spanContext = SpanContext.Create(TraceId.GenerateRandomId(random), SpanId.GenerateRandomId(random), TraceOptions.Default, Tracestate.Empty); - parentSpanId = SpanId.GenerateRandomId(random); + spanContext = SpanContext.Create(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Empty); + parentSpanId = ActivitySpanId.CreateRandom(); attributesMap.Add("MyAttributeKey1", AttributeValue.LongAttributeValue(10)); attributesMap.Add("MyAttributeKey2", AttributeValue.BooleanAttributeValue(true)); @@ -100,7 +100,7 @@ public void SpanData_RootActiveSpan() var spanData = SpanData.Create( spanContext, - null, + default, resource, SPAN_NAME, startTimestamp, @@ -112,7 +112,7 @@ public void SpanData_RootActiveSpan() SPAN_KIND, null); Assert.Equal(spanContext, spanData.Context); - Assert.Null(spanData.ParentSpanId); + Assert.True(spanData.ParentSpanId == default); Assert.Equal(resource, spanData.Resource); Assert.Equal(SPAN_NAME, spanData.Name); Assert.Equal(startTimestamp, spanData.StartTimestamp); diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanExporterTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanExporterTest.cs index 81bae9d0fe8..37f7a5d98b6 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanExporterTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Export/SpanExporterTest.cs @@ -18,6 +18,7 @@ namespace OpenTelemetry.Trace.Export.Test { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -33,7 +34,6 @@ public class SpanExporterTest { private const String SPAN_NAME_1 = "MySpanName/1"; private const String SPAN_NAME_2 = "MySpanName/2"; - private readonly RandomGenerator random = new RandomGenerator(1234); private readonly SpanContext sampledSpanContext; private readonly SpanContext notSampledSpanContext; private readonly ISpanExporter spanExporter = SpanExporter.Create(4, Duration.Create(1, 0)); @@ -45,8 +45,8 @@ public class SpanExporterTest public SpanExporterTest() { - sampledSpanContext = SpanContext.Create(TraceId.GenerateRandomId(random), SpanId.GenerateRandomId(random), TraceOptions.Builder().SetIsSampled(true).Build(), Tracestate.Empty); - notSampledSpanContext = SpanContext.Create(TraceId.GenerateRandomId(random), SpanId.GenerateRandomId(random), TraceOptions.Default, Tracestate.Empty); + sampledSpanContext = SpanContext.Create(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded, Tracestate.Empty); + notSampledSpanContext = SpanContext.Create(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Empty); startEndHandler = new StartEndHandler(spanExporter, runningSpanStore, null, new SimpleEventQueue()); spanExporter.RegisterHandler("test.service", serviceHandler); @@ -60,7 +60,7 @@ private Span CreateSampledEndedSpan(string spanName) recordSpanOptions, spanName, SpanKind.Internal, - null, + default, TraceParams.Default, startEndHandler, null); @@ -76,7 +76,7 @@ private Span CreateNotSampledEndedSpan(string spanName) recordSpanOptions, spanName, SpanKind.Internal, - null, + default, TraceParams.Default, startEndHandler, null); diff --git a/test/OpenTelemetry.Tests/Impl/Trace/LinkTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/LinkTest.cs index 159542b41f0..a27dad9cf1e 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/LinkTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/LinkTest.cs @@ -17,6 +17,7 @@ namespace OpenTelemetry.Trace.Test { using System.Collections.Generic; + using System.Diagnostics; using OpenTelemetry.Trace.Internal; using OpenTelemetry.Utils; using Xunit; @@ -24,13 +25,12 @@ namespace OpenTelemetry.Trace.Test public class LinkTest { private readonly IDictionary attributesMap = new Dictionary(); - private readonly IRandomGenerator random = new RandomGenerator(1234); private readonly SpanContext spanContext; public LinkTest() { - spanContext = SpanContext.Create(TraceId.GenerateRandomId(random), SpanId.GenerateRandomId(random), TraceOptions.Default, Tracestate.Empty); ; + spanContext = SpanContext.Create(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Empty); ; attributesMap.Add("MyAttributeKey0", AttributeValue.Create("MyStringAttribute")); attributesMap.Add("MyAttributeKey1", AttributeValue.Create(10)); attributesMap.Add("MyAttributeKey2", AttributeValue.Create(true)); diff --git a/test/OpenTelemetry.Tests/Impl/Trace/NoopTracerTests.cs b/test/OpenTelemetry.Tests/Impl/Trace/NoopTracerTests.cs index b1e38a0ce44..57f1e69fbb7 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/NoopTracerTests.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/NoopTracerTests.cs @@ -59,7 +59,7 @@ public void NoopTracer_RecordData() Assert.Throws(() => NoopTracer.Instance.RecordSpanData(null)); // does not throw - NoopTracer.Instance.RecordSpanData(SpanData.Create(SpanContext.Blank, null, Resource.Empty, "foo", Timestamp.Zero, null, null, null, null, Status.Ok, SpanKind.Internal, Timestamp.Zero)); + NoopTracer.Instance.RecordSpanData(SpanData.Create(SpanContext.Blank, default, Resource.Empty, "foo", Timestamp.Zero, null, null, null, null, Status.Ok, SpanKind.Internal, Timestamp.Zero)); } } } diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Propagation/B3FormatTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Propagation/B3FormatTest.cs index 0409754739a..ccdf656c0da 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Propagation/B3FormatTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Propagation/B3FormatTest.cs @@ -18,20 +18,21 @@ namespace OpenTelemetry.Context.Propagation.Test { using System; using System.Collections.Generic; + using System.Diagnostics; using OpenTelemetry.Trace; using Xunit; using Xunit.Abstractions; public class B3FormatTest { - private static readonly string TRACE_ID_BASE16 = "ff000000000000000000000000000041"; - private static readonly TraceId TRACE_ID = TraceId.FromLowerBase16(TRACE_ID_BASE16); - private static readonly string TRACE_ID_BASE16_EIGHT_BYTES = "0000000000000041"; - private static readonly TraceId TRACE_ID_EIGHT_BYTES = TraceId.FromLowerBase16("0000000000000000" + TRACE_ID_BASE16_EIGHT_BYTES); - private static readonly string SPAN_ID_BASE16 = "ff00000000000041"; - private static readonly SpanId SPAN_ID = SpanId.FromLowerBase16(SPAN_ID_BASE16); - private static readonly byte[] TRACE_OPTIONS_BYTES = new byte[] { 1 }; - private static readonly TraceOptions TRACE_OPTIONS = TraceOptions.FromBytes(TRACE_OPTIONS_BYTES); + private static readonly string TraceIdBase16 = "ff000000000000000000000000000041"; + private static readonly ActivityTraceId TraceId = ActivityTraceId.CreateFromString(TraceIdBase16.AsSpan()); + private static readonly string TraceIdBase16EightBytes = "0000000000000041"; + private static readonly ActivityTraceId TraceIdEightBytes = ActivityTraceId.CreateFromString(("0000000000000000" + TraceIdBase16EightBytes).AsSpan()); + private static readonly string SpanIdBase16 = "ff00000000000041"; + private static readonly ActivitySpanId SpanId = ActivitySpanId.CreateFromString(SpanIdBase16.AsSpan()); + + private static readonly ActivityTraceFlags TraceOptions = ActivityTraceFlags.Recorded; private readonly B3Format b3Format = new B3Format(); @@ -49,27 +50,27 @@ public B3FormatTest(ITestOutputHelper output) public void Serialize_SampledContext() { IDictionary carrier = new Dictionary(); - b3Format.Inject(SpanContext.Create(TRACE_ID, SPAN_ID, TRACE_OPTIONS, Tracestate.Empty), carrier, setter); - ContainsExactly(carrier, new Dictionary() { { B3Format.XB3TraceId, TRACE_ID_BASE16 }, { B3Format.XB3SpanId, SPAN_ID_BASE16 }, { B3Format.XB3Sampled, "1" } }); + b3Format.Inject(SpanContext.Create(TraceId, SpanId, TraceOptions, Tracestate.Empty), carrier, setter); + ContainsExactly(carrier, new Dictionary() { { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 }, { B3Format.XB3Sampled, "1" } }); } [Fact] public void Serialize_NotSampledContext() { IDictionary carrier = new Dictionary(); - var context = SpanContext.Create(TRACE_ID, SPAN_ID, TraceOptions.Default, Tracestate.Empty); + var context = SpanContext.Create(TraceId, SpanId, ActivityTraceFlags.None, Tracestate.Empty); _output.WriteLine(context.ToString()); b3Format.Inject(context, carrier, setter); - ContainsExactly(carrier, new Dictionary() { { B3Format.XB3TraceId, TRACE_ID_BASE16 }, { B3Format.XB3SpanId, SPAN_ID_BASE16 } }); + ContainsExactly(carrier, new Dictionary() { { B3Format.XB3TraceId, TraceIdBase16 }, { B3Format.XB3SpanId, SpanIdBase16 } }); } [Fact] public void ParseMissingSampledAndMissingFlag() { IDictionary headersNotSampled = new Dictionary(); - headersNotSampled.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); - headersNotSampled.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); - var spanContext = SpanContext.Create(TRACE_ID, SPAN_ID, TraceOptions.Default, Tracestate.Empty); + headersNotSampled.Add(B3Format.XB3TraceId, TraceIdBase16); + headersNotSampled.Add(B3Format.XB3SpanId, SpanIdBase16); + var spanContext = SpanContext.Create(TraceId, SpanId, ActivityTraceFlags.None, Tracestate.Empty); Assert.Equal(spanContext, b3Format.Extract(headersNotSampled, getter)); } @@ -77,59 +78,59 @@ public void ParseMissingSampledAndMissingFlag() public void ParseSampled() { IDictionary headersSampled = new Dictionary(); - headersSampled.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); - headersSampled.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + headersSampled.Add(B3Format.XB3TraceId, TraceIdBase16); + headersSampled.Add(B3Format.XB3SpanId, SpanIdBase16); headersSampled.Add(B3Format.XB3Sampled, "1"); - Assert.Equal(SpanContext.Create(TRACE_ID, SPAN_ID, TRACE_OPTIONS, Tracestate.Empty), b3Format.Extract(headersSampled, getter)); + Assert.Equal(SpanContext.Create(TraceId, SpanId, TraceOptions, Tracestate.Empty), b3Format.Extract(headersSampled, getter)); } [Fact] public void ParseZeroSampled() { IDictionary headersNotSampled = new Dictionary(); - headersNotSampled.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); - headersNotSampled.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + headersNotSampled.Add(B3Format.XB3TraceId, TraceIdBase16); + headersNotSampled.Add(B3Format.XB3SpanId, SpanIdBase16); headersNotSampled.Add(B3Format.XB3Sampled, "0"); - Assert.Equal(SpanContext.Create(TRACE_ID, SPAN_ID, TraceOptions.Default, Tracestate.Empty), b3Format.Extract(headersNotSampled, getter)); + Assert.Equal(SpanContext.Create(TraceId, SpanId, ActivityTraceFlags.None, Tracestate.Empty), b3Format.Extract(headersNotSampled, getter)); } [Fact] public void ParseFlag() { IDictionary headersFlagSampled = new Dictionary(); - headersFlagSampled.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); - headersFlagSampled.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + headersFlagSampled.Add(B3Format.XB3TraceId, TraceIdBase16); + headersFlagSampled.Add(B3Format.XB3SpanId, SpanIdBase16); headersFlagSampled.Add(B3Format.XB3Flags, "1"); - Assert.Equal(SpanContext.Create(TRACE_ID, SPAN_ID, TRACE_OPTIONS, Tracestate.Empty), b3Format.Extract(headersFlagSampled, getter)); + Assert.Equal(SpanContext.Create(TraceId, SpanId, TraceOptions, Tracestate.Empty), b3Format.Extract(headersFlagSampled, getter)); } [Fact] public void ParseZeroFlag() { IDictionary headersFlagNotSampled = new Dictionary(); - headersFlagNotSampled.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); - headersFlagNotSampled.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + headersFlagNotSampled.Add(B3Format.XB3TraceId, TraceIdBase16); + headersFlagNotSampled.Add(B3Format.XB3SpanId, SpanIdBase16); headersFlagNotSampled.Add(B3Format.XB3Flags, "0"); - Assert.Equal(SpanContext.Create(TRACE_ID, SPAN_ID, TraceOptions.Default, Tracestate.Empty), b3Format.Extract(headersFlagNotSampled, getter)); + Assert.Equal(SpanContext.Create(TraceId, SpanId, ActivityTraceFlags.None, Tracestate.Empty), b3Format.Extract(headersFlagNotSampled, getter)); } [Fact] public void ParseEightBytesTraceId() { IDictionary headersEightBytes = new Dictionary(); - headersEightBytes.Add(B3Format.XB3TraceId, TRACE_ID_BASE16_EIGHT_BYTES); - headersEightBytes.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + headersEightBytes.Add(B3Format.XB3TraceId, TraceIdBase16EightBytes); + headersEightBytes.Add(B3Format.XB3SpanId, SpanIdBase16); headersEightBytes.Add(B3Format.XB3Sampled, "1"); - Assert.Equal(SpanContext.Create(TRACE_ID_EIGHT_BYTES, SPAN_ID, TRACE_OPTIONS, Tracestate.Empty), b3Format.Extract(headersEightBytes, getter)); + Assert.Equal(SpanContext.Create(TraceIdEightBytes, SpanId, TraceOptions, Tracestate.Empty), b3Format.Extract(headersEightBytes, getter)); } [Fact] public void ParseEightBytesTraceId_NotSampledSpanContext() { IDictionary headersEightBytes = new Dictionary(); - headersEightBytes.Add(B3Format.XB3TraceId, TRACE_ID_BASE16_EIGHT_BYTES); - headersEightBytes.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); - Assert.Equal(SpanContext.Create(TRACE_ID_EIGHT_BYTES, SPAN_ID, TraceOptions.Default, Tracestate.Empty), b3Format.Extract(headersEightBytes, getter)); + headersEightBytes.Add(B3Format.XB3TraceId, TraceIdBase16EightBytes); + headersEightBytes.Add(B3Format.XB3SpanId, SpanIdBase16); + Assert.Equal(SpanContext.Create(TraceIdEightBytes, SpanId, ActivityTraceFlags.None, Tracestate.Empty), b3Format.Extract(headersEightBytes, getter)); } [Fact] @@ -137,7 +138,7 @@ public void ParseInvalidTraceId() { IDictionary invalidHeaders = new Dictionary(); invalidHeaders.Add(B3Format.XB3TraceId, "abcdefghijklmnop"); - invalidHeaders.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + invalidHeaders.Add(B3Format.XB3SpanId, SpanIdBase16); Assert.Throws(() => b3Format.Extract(invalidHeaders, getter)); } @@ -146,7 +147,7 @@ public void ParseInvalidTraceId_Size() { IDictionary invalidHeaders = new Dictionary(); invalidHeaders.Add(B3Format.XB3TraceId, "0123456789abcdef00"); - invalidHeaders.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + invalidHeaders.Add(B3Format.XB3SpanId, SpanIdBase16); Assert.Throws(() => b3Format.Extract(invalidHeaders, getter)); } @@ -154,7 +155,7 @@ public void ParseInvalidTraceId_Size() public void ParseMissingTraceId() { IDictionary invalidHeaders = new Dictionary(); - invalidHeaders.Add(B3Format.XB3SpanId, SPAN_ID_BASE16); + invalidHeaders.Add(B3Format.XB3SpanId, SpanIdBase16); Assert.Throws(() => b3Format.Extract(invalidHeaders, getter)); } @@ -162,7 +163,7 @@ public void ParseMissingTraceId() public void ParseInvalidSpanId() { IDictionary invalidHeaders = new Dictionary(); - invalidHeaders.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); + invalidHeaders.Add(B3Format.XB3TraceId, TraceIdBase16); invalidHeaders.Add(B3Format.XB3SpanId, "abcdefghijklmnop"); Assert.Throws(() => b3Format.Extract(invalidHeaders, getter)); } @@ -171,7 +172,7 @@ public void ParseInvalidSpanId() public void ParseInvalidSpanId_Size() { IDictionary invalidHeaders = new Dictionary(); - invalidHeaders.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); + invalidHeaders.Add(B3Format.XB3TraceId, TraceIdBase16); invalidHeaders.Add(B3Format.XB3SpanId, "0123456789abcdef00"); Assert.Throws(() => b3Format.Extract(invalidHeaders, getter)); } @@ -180,7 +181,7 @@ public void ParseInvalidSpanId_Size() public void ParseMissingSpanId() { IDictionary invalidHeaders = new Dictionary(); - invalidHeaders.Add(B3Format.XB3TraceId, TRACE_ID_BASE16); + invalidHeaders.Add(B3Format.XB3TraceId, TraceIdBase16); Assert.Throws(() => b3Format.Extract(invalidHeaders, getter)); } diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Propagation/BinaryFormatTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Propagation/BinaryFormatTest.cs index 1f9989988bc..dd85bb1d9ab 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Propagation/BinaryFormatTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Propagation/BinaryFormatTest.cs @@ -16,6 +16,7 @@ namespace OpenTelemetry.Context.Propagation.Test { + using System.Diagnostics; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; using System; @@ -23,16 +24,16 @@ namespace OpenTelemetry.Context.Propagation.Test public class BinaryFormatTest { - private static readonly byte[] TRACE_ID_BYTES = new byte[] { 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79 }; - private static readonly TraceId TRACE_ID = TraceId.FromBytes(TRACE_ID_BYTES); - private static readonly byte[] SPAN_ID_BYTES = new byte[] { 97, 98, 99, 100, 101, 102, 103, 104 }; - private static readonly SpanId SPAN_ID = SpanId.FromBytes(SPAN_ID_BYTES); - private static readonly byte[] TRACE_OPTIONS_BYTES = new byte[] { 1 }; - private static readonly TraceOptions TRACE_OPTIONS = TraceOptions.FromBytes(TRACE_OPTIONS_BYTES); - private static readonly byte[] EXAMPLE_BYTES = + private static readonly byte[] TraceIdBytes = new byte[] { 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79 }; + private static readonly ActivityTraceId TraceId = ActivityTraceId.CreateFromBytes(TraceIdBytes); + private static readonly byte[] SpanIdBytes = new byte[] { 97, 98, 99, 100, 101, 102, 103, 104 }; + private static readonly ActivitySpanId SpanId = ActivitySpanId.CreateFromBytes(SpanIdBytes); + private static readonly byte[] TraceOptionsBytes = new byte[] { 1 }; + private static readonly ActivityTraceFlags TraceOptions = ActivityTraceFlags.Recorded; + private static readonly byte[] ExampleBytes = new byte[] {0, 0, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 1, 97, 98, 99, 100,101, 102, 103, 104, 2, 1}; - private static readonly SpanContext EXAMPLE_SPAN_CONTEXT = SpanContext.Create(TRACE_ID, SPAN_ID, TRACE_OPTIONS, Tracestate.Empty); + private static readonly SpanContext ExampleSpanContext = SpanContext.Create(TraceId, SpanId, TraceOptions, Tracestate.Empty); private readonly BinaryFormat binaryFormat = new BinaryFormat(); @@ -46,13 +47,13 @@ private void TestSpanContextConversion(SpanContext spanContext) public void Propagate_SpanContextTracingEnabled() { TestSpanContextConversion( - SpanContext.Create(TRACE_ID, SPAN_ID, TraceOptions.Builder().SetIsSampled(true).Build(), Tracestate.Empty)); + SpanContext.Create(TraceId, SpanId, ActivityTraceFlags.Recorded, Tracestate.Empty)); } [Fact] public void Propagate_SpanContextNoTracing() { - TestSpanContextConversion(SpanContext.Create(TRACE_ID, SPAN_ID, TraceOptions.Default, Tracestate.Empty)); + TestSpanContextConversion(SpanContext.Create(TraceId, SpanId, ActivityTraceFlags.None, Tracestate.Empty)); } [Fact] @@ -73,7 +74,7 @@ public void ToBinaryValue_InvalidSpanContext() [Fact] public void FromBinaryValue_BinaryExampleValue() { - Assert.Equal(EXAMPLE_SPAN_CONTEXT, binaryFormat.FromByteArray(EXAMPLE_BYTES)); + Assert.Equal(ExampleSpanContext, binaryFormat.FromByteArray(ExampleBytes)); } [Fact] @@ -103,7 +104,7 @@ public void FromBinaryValue_UnsupportedVersionId() public void FromBinaryValue_UnsupportedFieldIdFirst() { Assert.Equal( - SpanContext.Create(TraceId.Invalid, SpanId.Invalid, TraceOptions.Default, Tracestate.Empty), + SpanContext.Create(default, default, ActivityTraceFlags.None, Tracestate.Empty), binaryFormat.FromByteArray( new byte[] { @@ -117,9 +118,9 @@ public void FromBinaryValue_UnsupportedFieldIdSecond() { Assert.Equal( SpanContext.Create( - TraceId.FromBytes(new byte[] { 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79 }), - SpanId.Invalid, - TraceOptions.Default, Tracestate.Empty), + ActivityTraceId.CreateFromBytes(new byte[] { 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79 }), + default, + ActivityTraceFlags.None, Tracestate.Empty), binaryFormat.FromByteArray( new byte[] { diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Propagation/TraceContextTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Propagation/TraceContextTest.cs index 9e322ebbb5b..a10eb193def 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Propagation/TraceContextTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Propagation/TraceContextTest.cs @@ -14,9 +14,12 @@ // limitations under the License. // +using System; + namespace OpenTelemetry.Impl.Trace.Propagation { using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using OpenTelemetry.Trace; using OpenTelemetry.Context.Propagation; @@ -39,9 +42,9 @@ public void TraceContextFormatCanParseExampleFromSpec() var f = new TraceContextFormat(); var ctx = f.Extract(headers, (h, n) => new string[] {h[n]}); - Assert.Equal(TraceId.FromLowerBase16("0af7651916cd43dd8448eb211c80319c"), ctx.TraceId); - Assert.Equal(SpanId.FromLowerBase16("b9c7c989f97918e1"), ctx.SpanId); - Assert.True(ctx.TraceOptions.IsSampled); + Assert.Equal(ActivityTraceId.CreateFromString("0af7651916cd43dd8448eb211c80319c".AsSpan()), ctx.TraceId); + Assert.Equal(ActivitySpanId.CreateFromString("b9c7c989f97918e1".AsSpan()), ctx.SpanId); + Assert.True((ctx.TraceOptions & ActivityTraceFlags.Recorded) != 0); Assert.Equal(2, ctx.Tracestate.Entries.Count()); diff --git a/test/OpenTelemetry.Tests/Impl/Trace/Sampler/SamplersTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/Sampler/SamplersTest.cs index 74f3d80dd65..8cc384ee9db 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/Sampler/SamplersTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/Sampler/SamplersTest.cs @@ -17,6 +17,7 @@ namespace OpenTelemetry.Trace.Sampler.Test { using System; + using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using OpenTelemetry.Trace.Internal; @@ -27,21 +28,20 @@ public class SamplersTest { private static readonly String SPAN_NAME = "MySpanName"; private static readonly int NUM_SAMPLE_TRIES = 1000; - private readonly IRandomGenerator random = new RandomGenerator(1234); - private readonly TraceId traceId; - private readonly SpanId parentSpanId; - private readonly SpanId spanId; + private readonly ActivityTraceId traceId; + private readonly ActivitySpanId parentSpanId; + private readonly ActivitySpanId spanId; private readonly SpanContext sampledSpanContext; private readonly SpanContext notSampledSpanContext; private readonly ILink sampledLink; public SamplersTest() { - traceId = TraceId.GenerateRandomId(random); - parentSpanId = SpanId.GenerateRandomId(random); - spanId = SpanId.GenerateRandomId(random); - sampledSpanContext = SpanContext.Create(traceId, parentSpanId, TraceOptions.Builder().SetIsSampled(true).Build(), Tracestate.Empty); - notSampledSpanContext = SpanContext.Create(traceId, parentSpanId, TraceOptions.Default, Tracestate.Empty); + traceId = ActivityTraceId.CreateRandom(); + parentSpanId = ActivitySpanId.CreateRandom(); + spanId = ActivitySpanId.CreateRandom(); + sampledSpanContext = SpanContext.Create(traceId, parentSpanId, ActivityTraceFlags.Recorded, Tracestate.Empty); + notSampledSpanContext = SpanContext.Create(traceId, parentSpanId, ActivityTraceFlags.None, Tracestate.Empty); sampledLink = Link.FromSpanContext(sampledSpanContext); } @@ -185,7 +185,7 @@ public void ProbabilitySampler_SampleBasedOnTraceId() // This traceId will not be sampled by the ProbabilitySampler because the first 8 bytes as long // is not less than probability * Long.MAX_VALUE; var notSampledtraceId = - TraceId.FromBytes( + ActivityTraceId.CreateFromBytes( new byte[] { 0x8F, @@ -209,13 +209,13 @@ public void ProbabilitySampler_SampleBasedOnTraceId() defaultProbability.ShouldSample( null, notSampledtraceId, - SpanId.GenerateRandomId(random), + ActivitySpanId.CreateRandom(), SPAN_NAME, null)); // This traceId will be sampled by the ProbabilitySampler because the first 8 bytes as long // is less than probability * Long.MAX_VALUE; var sampledtraceId = - TraceId.FromBytes( + ActivityTraceId.CreateFromBytes( new byte[] { 0x00, @@ -239,7 +239,7 @@ public void ProbabilitySampler_SampleBasedOnTraceId() defaultProbability.ShouldSample( null, sampledtraceId, - SpanId.GenerateRandomId(random), + ActivitySpanId.CreateRandom(), SPAN_NAME, null)); } @@ -247,7 +247,7 @@ public void ProbabilitySampler_SampleBasedOnTraceId() [Fact] public void ProbabilitySampler_getDescription() { - Assert.Equal(String.Format("ProbabilitySampler({0:F6})", 0.5), ProbabilitySampler.Create(0.5).Description); + Assert.Equal($"ProbabilitySampler({0.5:F6})", ProbabilitySampler.Create(0.5).Description); } [Fact] @@ -261,14 +261,13 @@ public void ProbabilitySampler_ToString() private static void AssertSamplerSamplesWithProbability( ISampler sampler, SpanContext parent, List links, double probability) { - var random = new RandomGenerator(1234); var count = 0; // Count of spans with sampling enabled for (var i = 0; i < NUM_SAMPLE_TRIES; i++) { if (sampler.ShouldSample( parent, - TraceId.GenerateRandomId(random), - SpanId.GenerateRandomId(random), + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), SPAN_NAME, links)) { diff --git a/test/OpenTelemetry.Tests/Impl/Trace/SpanBuilderTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/SpanBuilderTest.cs index 135efbb4042..c50f7dc6c91 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/SpanBuilderTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/SpanBuilderTest.cs @@ -17,6 +17,7 @@ namespace OpenTelemetry.Trace.Test { using System; + using System.Diagnostics; using Moq; using OpenTelemetry.Common; using OpenTelemetry.Trace.Config; @@ -27,8 +28,10 @@ public class SpanBuilderTest { private static readonly string SpanName = "MySpanName"; private readonly SpanBuilderOptions spanBuilderOptions; - private readonly TraceParams alwaysSampleTraceParams = TraceParams.Default.ToBuilder().SetSampler(Samplers.AlwaysSample).Build(); - private readonly IRandomGenerator randomHandler = new FakeRandomHandler(); + + private readonly TraceParams alwaysSampleTraceParams = + TraceParams.Default.ToBuilder().SetSampler(Samplers.AlwaysSample).Build(); + private readonly IStartEndHandler startEndHandler = Mock.Of(); private readonly ITraceConfig traceConfig = Mock.Of(); @@ -36,7 +39,7 @@ public SpanBuilderTest() { // MockitoAnnotations.initMocks(this); spanBuilderOptions = - new SpanBuilderOptions(randomHandler, startEndHandler, traceConfig); + new SpanBuilderOptions(startEndHandler, traceConfig); var configMock = Mock.Get(traceConfig); configMock.Setup((c) => c.ActiveTraceParams).Returns(alwaysSampleTraceParams); // when(traceConfig.getActiveTraceParams()).thenReturn(alwaysSampleTraceParams); @@ -51,10 +54,12 @@ public void StartSpanNullParent() .StartSpan(); Assert.True(span.Context.IsValid); Assert.True(span.IsRecordingEvents); - Assert.True(span.Context.TraceOptions.IsSampled); + Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); var spanData = ((Span)span).ToSpanData(); - Assert.Null(spanData.ParentSpanId); - Assert.InRange(spanData.StartTimestamp, Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(-1, 0)), Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(1, 0))); + Assert.True(spanData.ParentSpanId == default); + Assert.InRange(spanData.StartTimestamp, + Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(-1, 0)), + Timestamp.FromDateTimeOffset(DateTimeOffset.Now).AddDuration(Duration.Create(1, 0))); Assert.Equal(SpanName, spanData.Name); } @@ -63,11 +68,11 @@ public void StartSpanLastParentWins1() { var spanContext = SpanContext.Create( - TraceId.GenerateRandomId(randomHandler), - SpanId.GenerateRandomId(randomHandler), - TraceOptions.Default, Tracestate.Empty); + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty); - var span = (Span) new SpanBuilder(SpanName, spanBuilderOptions) + var span = (Span)new SpanBuilder(SpanName, spanBuilderOptions) .SetNoParent() .SetParent(spanContext) .StartSpan(); @@ -82,9 +87,9 @@ public void StartSpanLastParentWins2() { var spanContext = SpanContext.Create( - TraceId.GenerateRandomId(randomHandler), - SpanId.GenerateRandomId(randomHandler), - TraceOptions.Default, Tracestate.Empty); + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty); var span = (Span)new SpanBuilder(SpanName, spanBuilderOptions) .SetParent(spanContext) @@ -93,7 +98,7 @@ public void StartSpanLastParentWins2() Assert.True(span.Context.IsValid); Assert.NotEqual(spanContext.TraceId, span.Context.TraceId); - Assert.Null(span.ParentSpanId); + Assert.True(span.ParentSpanId == default); } [Fact] @@ -101,9 +106,9 @@ public void StartSpanLastParentWins3() { var spanContext = SpanContext.Create( - TraceId.GenerateRandomId(randomHandler), - SpanId.GenerateRandomId(randomHandler), - TraceOptions.Default, Tracestate.Empty); + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty); var rootSpan = (Span)new SpanBuilder(SpanName, spanBuilderOptions) .StartSpan(); @@ -122,9 +127,9 @@ public void StartSpanLastParentWins4() { var spanContext = SpanContext.Create( - TraceId.GenerateRandomId(randomHandler), - SpanId.GenerateRandomId(randomHandler), - TraceOptions.Default, Tracestate.Empty); + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty); var rootSpan = (Span)new SpanBuilder(SpanName, spanBuilderOptions) .StartSpan(); @@ -149,9 +154,9 @@ public void StartSpanNullParentWithRecordEvents() .StartSpan(); Assert.True(span.Context.IsValid); Assert.True(span.IsRecordingEvents); - Assert.False(span.Context.TraceOptions.IsSampled); + Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); var spanData = ((Span)span).ToSpanData(); - Assert.Null(spanData.ParentSpanId); + Assert.True(spanData.ParentSpanId == default); } [Fact] @@ -164,7 +169,7 @@ public void StartSpanNullParentNoRecordOptions() .StartSpan(); Assert.True(span.Context.IsValid); Assert.False(span.IsRecordingEvents); - Assert.False(span.Context.TraceOptions.IsSampled); + Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); } [Fact] @@ -176,10 +181,10 @@ public void StartChildSpan() .StartSpan(); Assert.True(rootSpan.Context.IsValid); Assert.True(rootSpan.IsRecordingEvents); - Assert.True(rootSpan.Context.TraceOptions.IsSampled); + Assert.True((rootSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); var childSpan = new SpanBuilder(SpanName, spanBuilderOptions) - .SetSpanKind(Trace.SpanKind.Internal) + .SetSpanKind(SpanKind.Internal) .SetParent(rootSpan) .StartSpan(); @@ -199,9 +204,9 @@ public void StartSpan_ExplicitNoParent() Assert.True(span.Context.IsValid); Assert.True(span.IsRecordingEvents); - Assert.True(span.Context.TraceOptions.IsSampled); + Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); var spanData = ((Span)span).ToSpanData(); - Assert.Null(spanData.ParentSpanId); + Assert.True(spanData.ParentSpanId == default); } [Fact] @@ -213,9 +218,9 @@ public void StartSpan_NoParent() Assert.True(span.Context.IsValid); Assert.True(span.IsRecordingEvents); - Assert.True(span.Context.TraceOptions.IsSampled); + Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); var spanData = ((Span)span).ToSpanData(); - Assert.Null(spanData.ParentSpanId); + Assert.True(spanData.ParentSpanId == default); } [Fact] @@ -225,7 +230,7 @@ public void StartSpan_CurrentSpanParent() .StartSpan(); using (CurrentSpanUtils.WithSpan(rootSpan, true)) { - var childSpan = (Span) new SpanBuilder(SpanName, spanBuilderOptions) + var childSpan = (Span)new SpanBuilder(SpanName, spanBuilderOptions) .StartSpan(); Assert.True(childSpan.Context.IsValid); @@ -247,7 +252,7 @@ public void StartSpan_NoParentInScopeOfCurrentSpan() Assert.True(childSpan.Context.IsValid); Assert.NotEqual(rootSpan.Context.TraceId, childSpan.Context.TraceId); - Assert.Null(childSpan.ParentSpanId); + Assert.True(childSpan.ParentSpanId == default); } } @@ -260,9 +265,9 @@ public void StartSpanInvalidParent() .StartSpan(); Assert.True(span.Context.IsValid); Assert.True(span.IsRecordingEvents); - Assert.True(span.Context.TraceOptions.IsSampled); + Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); var spanData = ((Span)span).ToSpanData(); - Assert.Null(spanData.ParentSpanId); + Assert.True(spanData.ParentSpanId == default); } [Fact] @@ -270,9 +275,9 @@ public void StartRemoteSpan() { var spanContext = SpanContext.Create( - TraceId.GenerateRandomId(randomHandler), - SpanId.GenerateRandomId(randomHandler), - TraceOptions.Default, Tracestate.Empty); + ActivityTraceId.CreateRandom(), + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty); var span = new SpanBuilder(SpanName, spanBuilderOptions) .SetSpanKind(SpanKind.Internal) @@ -282,7 +287,7 @@ public void StartRemoteSpan() Assert.True(span.Context.IsValid); Assert.Equal(spanContext.TraceId, span.Context.TraceId); - Assert.False(span.Context.TraceOptions.IsSampled); + Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); var spanData = ((Span)span).ToSpanData(); Assert.Equal(spanContext.SpanId, spanData.ParentSpanId); } @@ -298,7 +303,7 @@ public void StartRootSpan_WithSpecifiedSampler() .StartSpan(); Assert.True(rootSpan.Context.IsValid); - Assert.False(rootSpan.Context.TraceOptions.IsSampled); + Assert.True((rootSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); } [Fact] @@ -311,7 +316,7 @@ public void StartRootSpan_WithoutSpecifiedSampler() .StartSpan(); Assert.True(rootSpan.Context.IsValid); - Assert.True(rootSpan.Context.TraceOptions.IsSampled); + Assert.True((rootSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); } [Fact] @@ -324,7 +329,7 @@ public void StartRemoteChildSpan_WithSpecifiedSampler() .StartSpan(); Assert.True(rootSpan.Context.IsValid); - Assert.True(rootSpan.Context.TraceOptions.IsSampled); + Assert.True((rootSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); // Apply given sampler before default sampler for spans with remote parent. var childSpan = new SpanBuilder(SpanName, spanBuilderOptions) .SetSpanKind(SpanKind.Internal) @@ -334,7 +339,7 @@ public void StartRemoteChildSpan_WithSpecifiedSampler() Assert.True(childSpan.Context.IsValid); Assert.Equal(rootSpan.Context.TraceId, childSpan.Context.TraceId); - Assert.False(childSpan.Context.TraceOptions.IsSampled); + Assert.True((childSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); } [Fact] @@ -347,7 +352,7 @@ public void StartRemoteChildSpan_WithoutSpecifiedSampler() .StartSpan(); Assert.True(rootSpan.Context.IsValid); - Assert.False(rootSpan.Context.TraceOptions.IsSampled); + Assert.True((rootSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); // Apply default sampler (always true in the tests) for spans with remote parent. var childSpan = new SpanBuilder(SpanName, spanBuilderOptions) .SetSpanKind(SpanKind.Internal) @@ -356,7 +361,7 @@ public void StartRemoteChildSpan_WithoutSpecifiedSampler() Assert.True(childSpan.Context.IsValid); Assert.Equal(rootSpan.Context.TraceId, childSpan.Context.TraceId); - Assert.False(childSpan.Context.TraceOptions.IsSampled); + Assert.True((childSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); } [Fact] @@ -369,7 +374,7 @@ public void StartChildSpan_WithSpecifiedSampler() .StartSpan(); Assert.True(rootSpan.Context.IsValid); - Assert.True(rootSpan.Context.TraceOptions.IsSampled); + Assert.True((rootSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); // Apply the given sampler for child spans. var childSpan = new SpanBuilder(SpanName, spanBuilderOptions) @@ -380,7 +385,7 @@ public void StartChildSpan_WithSpecifiedSampler() Assert.True(childSpan.Context.IsValid); Assert.Equal(rootSpan.Context.TraceId, childSpan.Context.TraceId); - Assert.False(childSpan.Context.TraceOptions.IsSampled); + Assert.True((childSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); } [Fact] @@ -393,7 +398,8 @@ public void StartChildSpan_WithoutSpecifiedSampler() .StartSpan(); Assert.True(rootSpan.Context.IsValid); - Assert.False(rootSpan.Context.TraceOptions.IsSampled); + Assert.True((rootSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); + // Don't apply the default sampler (always true) for child spans. var childSpan = new SpanBuilder(SpanName, spanBuilderOptions) .SetSpanKind(SpanKind.Internal) @@ -402,7 +408,7 @@ public void StartChildSpan_WithoutSpecifiedSampler() Assert.True(childSpan.Context.IsValid); Assert.Equal(rootSpan.Context.TraceId, childSpan.Context.TraceId); - Assert.False(childSpan.Context.TraceOptions.IsSampled); + Assert.True((childSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); } [Fact] @@ -413,8 +419,8 @@ public void StartChildSpan_SampledLinkedParent() .SetSampler(Samplers.NeverSample) .SetNoParent() .StartSpan(); - - Assert.False(rootSpanUnsampled.Context.TraceOptions.IsSampled); + + Assert.True((rootSpanUnsampled.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); var rootSpanSampled = new SpanBuilder(SpanName, spanBuilderOptions) .SetSpanKind(SpanKind.Internal) @@ -422,7 +428,7 @@ public void StartChildSpan_SampledLinkedParent() .SetNoParent() .StartSpan(); - Assert.True(rootSpanSampled.Context.TraceOptions.IsSampled); + Assert.True((rootSpanSampled.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); // Sampled because the linked parent is sampled. var childSpan = new SpanBuilder(SpanName, spanBuilderOptions) .SetSpanKind(SpanKind.Internal) @@ -432,7 +438,7 @@ public void StartChildSpan_SampledLinkedParent() Assert.True(childSpan.Context.IsValid); Assert.Equal(rootSpanUnsampled.Context.TraceId, childSpan.Context.TraceId); - Assert.True(childSpan.Context.TraceOptions.IsSampled); + Assert.True((childSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); } [Fact] @@ -443,26 +449,8 @@ public void StartRemoteChildSpan_WithProbabilitySamplerDefaultSampler() // This traceId will not be sampled by the ProbabilitySampler because the first 8 bytes as long // is not less than probability * Long.MAX_VALUE; var traceId = - TraceId.FromBytes( - new byte[] - { - 0x8F, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - }); + ActivityTraceId.CreateFromBytes( + new byte[] {0x8F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0,}); // If parent is sampled then the remote child must be sampled. var childSpan = @@ -470,13 +458,14 @@ public void StartRemoteChildSpan_WithProbabilitySamplerDefaultSampler() .SetSpanKind(SpanKind.Internal) .SetParent(SpanContext.Create( traceId, - SpanId.GenerateRandomId(randomHandler), - TraceOptions.Builder().SetIsSampled(true).Build(), Tracestate.Empty)) + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.Recorded, + Tracestate.Empty)) .StartSpan(); Assert.True(childSpan.Context.IsValid); Assert.Equal(traceId, childSpan.Context.TraceId); - Assert.True(childSpan.Context.TraceOptions.IsSampled); + Assert.True((childSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); childSpan.End(); Assert.Equal(TraceParams.Default, traceConfig.ActiveTraceParams); @@ -487,14 +476,14 @@ public void StartRemoteChildSpan_WithProbabilitySamplerDefaultSampler() .SetSpanKind(SpanKind.Internal) .SetParent(SpanContext.Create( traceId, - SpanId.GenerateRandomId(randomHandler), - TraceOptions.Default, + ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty)) .StartSpan(); Assert.True(childSpan.Context.IsValid); Assert.Equal(traceId, childSpan.Context.TraceId); - Assert.False(childSpan.Context.TraceOptions.IsSampled); + Assert.True((childSpan.Context.TraceOptions & ActivityTraceFlags.Recorded) == 0); childSpan.End(); } @@ -511,26 +500,5 @@ public void SpanBuilder_BadArguments() Assert.Throws(() => spanBuilder.AddLink(null, null)); Assert.Throws(() => spanBuilder.AddLink(SpanContext.Blank, null)); } - - class FakeRandomHandler : IRandomGenerator - { - private readonly Random random; - - public FakeRandomHandler() - { - this.random = new Random(1234); - } - - public Random Current() - { - return random; - } - - public void NextBytes(byte[] bytes) - { - random.NextBytes(bytes); - } - } } - } diff --git a/test/OpenTelemetry.Tests/Impl/Trace/SpanContextTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/SpanContextTest.cs index 3eaa4ef7349..630bcb3aa87 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/SpanContextTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/SpanContextTest.cs @@ -16,6 +16,7 @@ namespace OpenTelemetry.Trace.Test { + using System.Diagnostics; using Xunit; public class SpanContextTest @@ -30,22 +31,22 @@ public class SpanContextTest private static readonly byte[] secondSpanIdBytes = new byte[] { (byte)'0', 0, 0, 0, 0, 0, 0, 0 }; private static readonly SpanContext first = SpanContext.Create( - TraceId.FromBytes(firstTraceIdBytes), - SpanId.FromBytes(firstSpanIdBytes), - TraceOptions.Default, Tracestate.Empty); + ActivityTraceId.CreateFromBytes(firstTraceIdBytes), + ActivitySpanId.CreateFromBytes(firstSpanIdBytes), + ActivityTraceFlags.None, Tracestate.Empty); private static readonly SpanContext second = SpanContext.Create( - TraceId.FromBytes(secondTraceIdBytes), - SpanId.FromBytes(secondSpanIdBytes), - TraceOptions.Builder().SetIsSampled(true).Build(), Tracestate.Empty); + ActivityTraceId.CreateFromBytes(secondTraceIdBytes), + ActivitySpanId.CreateFromBytes(secondSpanIdBytes), + ActivityTraceFlags.Recorded, Tracestate.Empty); [Fact] public void InvalidSpanContext() { - Assert.Equal(TraceId.Invalid, SpanContext.Blank.TraceId); - Assert.Equal(SpanId.Invalid, SpanContext.Blank.SpanId); - Assert.Equal(TraceOptions.Default, SpanContext.Blank.TraceOptions); + Assert.Equal(default, SpanContext.Blank.TraceId); + Assert.Equal(default, SpanContext.Blank.SpanId); + Assert.Equal(ActivityTraceFlags.None, SpanContext.Blank.TraceOptions); } [Fact] @@ -54,11 +55,11 @@ public void IsValid() Assert.False(SpanContext.Blank.IsValid); Assert.False( SpanContext.Create( - TraceId.FromBytes(firstTraceIdBytes), SpanId.Invalid, TraceOptions.Default, Tracestate.Empty) + ActivityTraceId.CreateFromBytes(firstTraceIdBytes), default, ActivityTraceFlags.None, Tracestate.Empty) .IsValid); Assert.False( SpanContext.Create( - TraceId.Invalid, SpanId.FromBytes(firstSpanIdBytes), TraceOptions.Default, Tracestate.Empty) + default, ActivitySpanId.CreateFromBytes(firstSpanIdBytes), ActivityTraceFlags.None, Tracestate.Empty) .IsValid); Assert.True(first.IsValid); Assert.True(second.IsValid); @@ -67,22 +68,22 @@ public void IsValid() [Fact] public void GetTraceId() { - Assert.Equal(TraceId.FromBytes(firstTraceIdBytes), first.TraceId); - Assert.Equal(TraceId.FromBytes(secondTraceIdBytes), second.TraceId); + Assert.Equal(ActivityTraceId.CreateFromBytes(firstTraceIdBytes), first.TraceId); + Assert.Equal(ActivityTraceId.CreateFromBytes(secondTraceIdBytes), second.TraceId); } [Fact] public void GetSpanId() { - Assert.Equal(SpanId.FromBytes(firstSpanIdBytes), first.SpanId); - Assert.Equal(SpanId.FromBytes(secondSpanIdBytes), second.SpanId); + Assert.Equal(ActivitySpanId.CreateFromBytes(firstSpanIdBytes), first.SpanId); + Assert.Equal(ActivitySpanId.CreateFromBytes(secondSpanIdBytes), second.SpanId); } [Fact] public void GetTraceOptions() { - Assert.Equal(TraceOptions.Default, first.TraceOptions); - Assert.Equal(TraceOptions.Builder().SetIsSampled(true).Build(), second.TraceOptions); + Assert.Equal(ActivityTraceFlags.None, first.TraceOptions); + Assert.Equal(ActivityTraceFlags.Recorded, second.TraceOptions); } [Fact] @@ -92,18 +93,18 @@ public void SpanContext_EqualsAndHashCode() // tester.addEqualityGroup( // first, // SpanContext.create( - // TraceId.FromBytes(firstTraceIdBytes), - // SpanId.FromBytes(firstSpanIdBytes), + // ActivityTraceId.CreateFromBytes(firstTraceIdBytes), + // ActivitySpanId.CreateFromBytes(firstSpanIdBytes), // TraceOptions.DEFAULT), // SpanContext.create( - // TraceId.FromBytes(firstTraceIdBytes), - // SpanId.FromBytes(firstSpanIdBytes), + // ActivityTraceId.CreateFromBytes(firstTraceIdBytes), + // ActivitySpanId.CreateFromBytes(firstSpanIdBytes), // TraceOptions.builder().setIsSampled(false).build())); // tester.addEqualityGroup( // second, // SpanContext.create( - // TraceId.FromBytes(secondTraceIdBytes), - // SpanId.FromBytes(secondSpanIdBytes), + // ActivityTraceId.CreateFromBytes(secondTraceIdBytes), + // ActivitySpanId.CreateFromBytes(secondSpanIdBytes), // TraceOptions.builder().setIsSampled(true).build())); // tester.testEquals(); } @@ -111,12 +112,12 @@ public void SpanContext_EqualsAndHashCode() [Fact] public void SpanContext_ToString() { - Assert.Contains(TraceId.FromBytes(firstTraceIdBytes).ToString(), first.ToString()); - Assert.Contains(SpanId.FromBytes(firstSpanIdBytes).ToString(), first.ToString()); - Assert.Contains(TraceOptions.Default.ToString(), first.ToString()); - Assert.Contains(TraceId.FromBytes(secondTraceIdBytes).ToString(), second.ToString()); - Assert.Contains(SpanId.FromBytes(secondSpanIdBytes).ToString(), second.ToString()); - Assert.Contains(TraceOptions.Builder().SetIsSampled(true).Build().ToString(), second.ToString()); + Assert.Contains(ActivityTraceId.CreateFromBytes(firstTraceIdBytes).ToString(), first.ToString()); + Assert.Contains(ActivitySpanId.CreateFromBytes(firstSpanIdBytes).ToString(), first.ToString()); + Assert.Contains(ActivityTraceFlags.None.ToString(), first.ToString()); + Assert.Contains(ActivityTraceId.CreateFromBytes(secondTraceIdBytes).ToString(), second.ToString()); + Assert.Contains(ActivitySpanId.CreateFromBytes(secondSpanIdBytes).ToString(), second.ToString()); + Assert.Contains(ActivityTraceFlags.Recorded.ToString(), second.ToString()); } } } diff --git a/test/OpenTelemetry.Tests/Impl/Trace/SpanIdTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/SpanIdTest.cs deleted file mode 100644 index 08f8aba260d..00000000000 --- a/test/OpenTelemetry.Tests/Impl/Trace/SpanIdTest.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace.Test -{ - using Xunit; - - public class SpanIdTest - { - private static readonly byte[] firstBytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte)'a' }; - private static readonly byte[] secondBytes = new byte[] { 0xFF, 0, 0, 0, 0, 0, 0, (byte)'A' }; - private static readonly SpanId first = SpanId.FromBytes(firstBytes); - private static readonly SpanId second = SpanId.FromBytes(secondBytes); - - [Fact] - public void invalidSpanId() - { - Assert.Equal(new byte[8], SpanId.Invalid.Bytes); - } - - [Fact] - public void IsValid() - { - Assert.False(SpanId.Invalid.IsValid); - Assert.True(first.IsValid); - Assert.True(second.IsValid); - } - - [Fact] - public void FromLowerBase16() - { - Assert.Equal(SpanId.Invalid, SpanId.FromLowerBase16("0000000000000000")); - Assert.Equal(first, SpanId.FromLowerBase16("0000000000000061")); - Assert.Equal(second, SpanId.FromLowerBase16("ff00000000000041")); - } - - [Fact] - public void ToLowerBase16() - { - Assert.Equal("0000000000000000", SpanId.Invalid.ToLowerBase16()); - Assert.Equal("0000000000000061", first.ToLowerBase16()); - Assert.Equal("ff00000000000041", second.ToLowerBase16()); - } - - [Fact] - public void Bytes() - { - Assert.Equal(firstBytes, first.Bytes); - Assert.Equal(secondBytes, second.Bytes); - - } - - [Fact] - public void SpanId_CompareTo() - { - Assert.Equal(1, first.CompareTo(second)); - Assert.Equal(-1, second.CompareTo(first)); - Assert.Equal(0, first.CompareTo(SpanId.FromBytes(firstBytes))); - } - - [Fact] - public void SpanId_EqualsAndHashCode() - { - // EqualsTester tester = new EqualsTester(); - // tester.addEqualityGroup(SpanId.INVALID, SpanId.INVALID); - // tester.addEqualityGroup(first, SpanId.fromBytes(Arrays.copyOf(firstBytes, firstBytes.length))); - // tester.addEqualityGroup( - // second, SpanId.fromBytes(Arrays.copyOf(secondBytes, secondBytes.length))); - // tester.testEquals(); - } - - [Fact] - public void SpanId_ToString() - { - Assert.Contains("0000000000000000", SpanId.Invalid.ToString()); - Assert.Contains("0000000000000061", first.ToString()); - Assert.Contains("ff00000000000041", second.ToString()); - } - } -} diff --git a/test/OpenTelemetry.Tests/Impl/Trace/SpanTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/SpanTest.cs index 369714c4dd9..fe2e3e4761a 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/SpanTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/SpanTest.cs @@ -18,21 +18,22 @@ namespace OpenTelemetry.Trace.Test { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Linq; using Moq; using OpenTelemetry.Common; using OpenTelemetry.Internal; + using OpenTelemetry.Trace; using OpenTelemetry.Trace.Config; using OpenTelemetry.Trace.Internal; using Xunit; public class SpanTest { - private static readonly String SPAN_NAME = "MySpanName"; - private static readonly String EVENT_DESCRIPTION = "MyEvent"; - private readonly RandomGenerator random = new RandomGenerator(1234); + private const string SpanName = "MySpanName"; + private const string EventDescription = "MyEvent"; private readonly SpanContext spanContext; - private readonly SpanId parentSpanId; + private readonly ActivitySpanId parentSpanId; private TimeSpan interval = TimeSpan.FromMilliseconds(0); private readonly DateTimeOffset startTime = DateTimeOffset.Now; private readonly Timestamp timestamp; @@ -47,9 +48,9 @@ public SpanTest() { timestamp = Timestamp.FromDateTimeOffset(startTime); timestampConverter = Timer.StartNew(startTime, () => interval); - spanContext = SpanContext.Create(TraceId.GenerateRandomId(random), SpanId.GenerateRandomId(random), - OpenTelemetry.Trace.TraceOptions.Default, Tracestate.Empty); - parentSpanId = SpanId.GenerateRandomId(random); + spanContext = SpanContext.Create(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), + ActivityTraceFlags.None, Tracestate.Empty); + parentSpanId = ActivitySpanId.CreateRandom(); attributes.Add( "MyStringAttributeKey", AttributeValue.StringAttributeValue("MyStringAttributeValue")); attributes.Add("MyLongAttributeKey", AttributeValue.LongAttributeValue(123L)); @@ -67,7 +68,7 @@ public void ToSpanData_NoRecordEvents() Span.StartSpan( spanContext, noRecordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -79,8 +80,8 @@ public void ToSpanData_NoRecordEvents() span.SetAttribute(attribute.Key, attribute.Value); } - span.AddEvent(Event.Create(EVENT_DESCRIPTION)); - span.AddEvent(EVENT_DESCRIPTION, attributes); + span.AddEvent(Event.Create(EventDescription)); + span.AddEvent(EventDescription, attributes); span.AddLink(Link.FromSpanContext(spanContext)); span.End(); // exception.expect(IllegalStateException); @@ -94,7 +95,7 @@ public void NoEventsRecordedAfterEnd() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -111,8 +112,8 @@ public void NoEventsRecordedAfterEnd() span.SetAttribute( "MySingleStringAttributeKey", AttributeValue.StringAttributeValue("MySingleStringAttributeValue")); - span.AddEvent(Event.Create(EVENT_DESCRIPTION)); - span.AddEvent(EVENT_DESCRIPTION, attributes); + span.AddEvent(Event.Create(EventDescription)); + span.AddEvent(EventDescription, attributes); span.AddLink(Link.FromSpanContext(spanContext)); var spanData = ((Span)span).ToSpanData(); Assert.Equal(timestamp, spanData.StartTimestamp); @@ -130,7 +131,7 @@ public void ToSpanData_ActiveSpan() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -146,16 +147,16 @@ public void ToSpanData_ActiveSpan() } interval = TimeSpan.FromMilliseconds(100); - span.AddEvent(Event.Create(EVENT_DESCRIPTION)); + span.AddEvent(Event.Create(EventDescription)); interval = TimeSpan.FromMilliseconds(200); - span.AddEvent(EVENT_DESCRIPTION, attributes); + span.AddEvent(EventDescription, attributes); interval = TimeSpan.FromMilliseconds(300); interval = TimeSpan.FromMilliseconds(400); var link = Link.FromSpanContext(spanContext); span.AddLink(link); var spanData = ((Span)span).ToSpanData(); Assert.Equal(spanContext, spanData.Context); - Assert.Equal(SPAN_NAME, spanData.Name); + Assert.Equal(SpanName, spanData.Name); Assert.Equal(parentSpanId, spanData.ParentSpanId); Assert.Equal(0, spanData.Attributes.DroppedAttributesCount); Assert.Equal(expectedAttributes, spanData.Attributes.AttributeMap); @@ -163,10 +164,10 @@ public void ToSpanData_ActiveSpan() Assert.Equal(2, spanData.Events.Events.Count()); Assert.Equal(timestamp.AddDuration(Duration.Create(TimeSpan.FromMilliseconds(100))), spanData.Events.Events.ToList()[0].Timestamp); - Assert.Equal(Event.Create(EVENT_DESCRIPTION), spanData.Events.Events.ToList()[0].Event); + Assert.Equal(Event.Create(EventDescription), spanData.Events.Events.ToList()[0].Event); Assert.Equal(timestamp.AddDuration(Duration.Create(TimeSpan.FromMilliseconds(200))), spanData.Events.Events.ToList()[1].Timestamp); - Assert.Equal(Event.Create(EVENT_DESCRIPTION, attributes), spanData.Events.Events.ToList()[1].Event); + Assert.Equal(Event.Create(EventDescription, attributes), spanData.Events.Events.ToList()[1].Event); Assert.Equal(0, spanData.Links.DroppedLinksCount); Assert.Single(spanData.Links.Links); Assert.Equal(link, spanData.Links.Links.First()); @@ -185,7 +186,7 @@ public void GoSpanData_EndedSpan() (Span)Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -201,9 +202,9 @@ public void GoSpanData_EndedSpan() } interval = TimeSpan.FromMilliseconds(100); - span.AddEvent(Event.Create(EVENT_DESCRIPTION)); + span.AddEvent(Event.Create(EventDescription)); interval = TimeSpan.FromMilliseconds(200); - span.AddEvent(EVENT_DESCRIPTION, attributes); + span.AddEvent(EventDescription, attributes); interval = TimeSpan.FromMilliseconds(300); var link = Link.FromSpanContext(spanContext); span.AddLink(link); @@ -213,7 +214,7 @@ public void GoSpanData_EndedSpan() var spanData = ((Span)span).ToSpanData(); Assert.Equal(spanContext, spanData.Context); - Assert.Equal(SPAN_NAME, spanData.Name); + Assert.Equal(SpanName, spanData.Name); Assert.Equal(parentSpanId, spanData.ParentSpanId); Assert.Equal(0, spanData.Attributes.DroppedAttributesCount); Assert.Equal(expectedAttributes, spanData.Attributes.AttributeMap); @@ -221,10 +222,10 @@ public void GoSpanData_EndedSpan() Assert.Equal(2, spanData.Events.Events.Count()); Assert.Equal(timestamp.AddDuration(Duration.Create(TimeSpan.FromMilliseconds(100))), spanData.Events.Events.ToList()[0].Timestamp); - Assert.Equal(Event.Create(EVENT_DESCRIPTION), spanData.Events.Events.ToList()[0].Event); + Assert.Equal(Event.Create(EventDescription), spanData.Events.Events.ToList()[0].Event); Assert.Equal(timestamp.AddDuration(Duration.Create(TimeSpan.FromMilliseconds(200))), spanData.Events.Events.ToList()[1].Timestamp); - Assert.Equal(Event.Create(EVENT_DESCRIPTION, attributes), spanData.Events.Events.ToList()[1].Event); + Assert.Equal(Event.Create(EventDescription, attributes), spanData.Events.Events.ToList()[1].Event); Assert.Equal(0, spanData.Links.DroppedLinksCount); Assert.Single(spanData.Links.Links); Assert.Equal(link, spanData.Links.Links.First()); @@ -244,7 +245,7 @@ public void Status_ViaSetStatus() (Span)Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -268,7 +269,7 @@ public void status_ViaEndSpanOptions() (Span)Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -296,7 +297,7 @@ public void DroppingAttributes() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, traceParams, @@ -349,7 +350,7 @@ public void DroppingAndAddingAttributes() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, traceParams, @@ -420,13 +421,13 @@ public void DroppingEvents() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, traceParams, startEndHandler, timestampConverter); - var testEvent = Event.Create(EVENT_DESCRIPTION); + var testEvent = Event.Create(EventDescription); var i = 0; for (i = 0; i < 2 * maxNumberOfEvents; i++) { @@ -472,7 +473,7 @@ public void DroppingLinks() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, traceParams, @@ -509,7 +510,7 @@ public void SampleToLocalSpanStore() (Span)Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -523,7 +524,7 @@ public void SampleToLocalSpanStore() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -546,7 +547,7 @@ public void SampleToLocalSpanStore_RunningSpan() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -563,7 +564,7 @@ public void BadArguments() Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, @@ -590,7 +591,7 @@ public void SetSampleTo() var span = (Span)Span.StartSpan( spanContext, recordSpanOptions, - SPAN_NAME, + SpanName, SpanKind.Internal, parentSpanId, TraceParams.Default, diff --git a/test/OpenTelemetry.Tests/Impl/Trace/TraceComponentTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/TraceComponentTest.cs index 110a9804d8b..b341e2e543b 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/TraceComponentTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/TraceComponentTest.cs @@ -23,7 +23,7 @@ namespace OpenTelemetry.Trace.Test public class TraceComponentTest { - private readonly TraceComponent traceComponent = new TraceComponent(new RandomGenerator(), new SimpleEventQueue()); + private readonly TraceComponent traceComponent = new TraceComponent(new SimpleEventQueue()); [Fact] public void ImplementationOfTracer() diff --git a/test/OpenTelemetry.Tests/Impl/Trace/TraceIdTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/TraceIdTest.cs deleted file mode 100644 index 74e2c3433e6..00000000000 --- a/test/OpenTelemetry.Tests/Impl/Trace/TraceIdTest.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace.Test -{ - using Xunit; - - public class TraceIdTest - { - private static readonly byte[] firstBytes = - new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte)'a' }; - - private static readonly byte[] secondBytes = - new byte[] { 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte)'A' }; - - private static readonly TraceId first = TraceId.FromBytes(firstBytes); - private static readonly TraceId second = TraceId.FromBytes(secondBytes); - - [Fact] - public void invalidTraceId() - { - Assert.Equal(new byte[16], TraceId.Invalid.Bytes); - } - - [Fact] - public void IsValid() - { - Assert.False(TraceId.Invalid.IsValid); - Assert.True(first.IsValid); - Assert.True(second.IsValid); - } - - [Fact] - public void Bytes() - { - Assert.Equal(firstBytes, first.Bytes); - Assert.Equal(secondBytes, second.Bytes); - } - - [Fact] - public void FromLowerBase16() - { - Assert.Equal(TraceId.Invalid, TraceId.FromLowerBase16("00000000000000000000000000000000")); - Assert.Equal(first, TraceId.FromLowerBase16("00000000000000000000000000000061")); - Assert.Equal(second, TraceId.FromLowerBase16("ff000000000000000000000000000041")); - } - - [Fact] - public void ToLowerBase16() - { - Assert.Equal("00000000000000000000000000000000", TraceId.Invalid.ToLowerBase16()); - Assert.Equal("00000000000000000000000000000061", first.ToLowerBase16()); - Assert.Equal("ff000000000000000000000000000041", second.ToLowerBase16()); - } - - [Fact] - public void TraceId_CompareTo() - { - Assert.Equal(1, first.CompareTo(second)); - Assert.Equal(-1, second.CompareTo(first)); - Assert.Equal(0, first.CompareTo(TraceId.FromBytes(firstBytes))); - } - - [Fact] - public void TraceId_EqualsAndHashCode() - { - // EqualsTester tester = new EqualsTester(); - // tester.addEqualityGroup(TraceId.INVALID, TraceId.INVALID); - // tester.addEqualityGroup(first, TraceId.fromBytes(Arrays.copyOf(firstBytes, firstBytes.length))); - // tester.addEqualityGroup( - // second, TraceId.fromBytes(Arrays.copyOf(secondBytes, secondBytes.length))); - // tester.testEquals(); - } - - [Fact] - public void TraceId_ToString() - { - Assert.Contains("00000000000000000000000000000000", TraceId.Invalid.ToString()); - Assert.Contains("00000000000000000000000000000061", first.ToString()); - Assert.Contains("ff000000000000000000000000000041", second.ToString()); - } - } -} diff --git a/test/OpenTelemetry.Tests/Impl/Trace/TraceOptionsTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/TraceOptionsTest.cs deleted file mode 100644 index 90d14f18cd1..00000000000 --- a/test/OpenTelemetry.Tests/Impl/Trace/TraceOptionsTest.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -// Copyright 2018, OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -namespace OpenTelemetry.Trace.Test -{ - using Xunit; - - public class TraceOptionsTest - { - private static readonly byte[] firstBytes = { 0xff }; - private static readonly byte[] secondBytes = { 1 }; - private static readonly byte[] thirdBytes = { 6 }; - - [Fact] - public void getOptions() - { - Assert.Equal(0, TraceOptions.Default.Options); - Assert.Equal(0, TraceOptions.Builder().SetIsSampled(false).Build().Options); - Assert.Equal(1, TraceOptions.Builder().SetIsSampled(true).Build().Options); - Assert.Equal(0, TraceOptions.Builder().SetIsSampled(true).SetIsSampled(false).Build().Options); - Assert.Equal(-1, TraceOptions.FromBytes(firstBytes).Options); - Assert.Equal(1, TraceOptions.FromBytes(secondBytes).Options); - Assert.Equal(6, TraceOptions.FromBytes(thirdBytes).Options); - } - - [Fact] - public void IsSampled() - { - Assert.False(TraceOptions.Default.IsSampled); - Assert.True(TraceOptions.Builder().SetIsSampled(true).Build().IsSampled); - } - - [Fact] - public void ToFromBytes() - { - Assert.Equal(firstBytes, TraceOptions.FromBytes(firstBytes).Bytes); - Assert.Equal(secondBytes, TraceOptions.FromBytes(secondBytes).Bytes); - Assert.Equal(thirdBytes, TraceOptions.FromBytes(thirdBytes).Bytes); - } - - [Fact] - public void Builder_FromOptions() - { - Assert.Equal(6 | 1, - TraceOptions.Builder(TraceOptions.FromBytes(thirdBytes)) - .SetIsSampled(true) - .Build() - .Options); - } - - [Fact] - public void traceOptions_EqualsAndHashCode() - { - // EqualsTester tester = new EqualsTester(); - // tester.addEqualityGroup(TraceOptions.DEFAULT); - // tester.addEqualityGroup( - // TraceOptions.FromBytes(secondBytes), TraceOptions.Builder().SetIsSampled(true).build()); - // tester.addEqualityGroup(TraceOptions.FromBytes(firstBytes)); - // tester.testEquals(); - } - - [Fact] - public void traceOptions_ToString() - { - Assert.Contains("sampled=False", TraceOptions.Default.ToString()); - Assert.Contains("sampled=True", TraceOptions.Builder().SetIsSampled(true).Build().ToString()); - } - } -} diff --git a/test/OpenTelemetry.Tests/Impl/Trace/TracerTest.cs b/test/OpenTelemetry.Tests/Impl/Trace/TracerTest.cs index 66f7fad7323..ab5c19dfab1 100644 --- a/test/OpenTelemetry.Tests/Impl/Trace/TracerTest.cs +++ b/test/OpenTelemetry.Tests/Impl/Trace/TracerTest.cs @@ -36,7 +36,7 @@ public TracerTest() { startEndHandler = Mock.Of(); traceConfig = Mock.Of(); - tracer = new Tracer(new RandomGenerator(), startEndHandler, traceConfig, null); + tracer = new Tracer(startEndHandler, traceConfig, null); } [Fact]