Ejemplo n.º 1
0
 public Span(string operationName, DateTimeOffset startTimestamp, ISpanContext spanContext, ISpanRecorder spanRecorder)
 {
     _state         = 0;
     _spanRecorder  = spanRecorder ?? throw new ArgumentNullException(nameof(spanRecorder));
     SpanContext    = spanContext ?? throw new ArgumentNullException(nameof(spanContext));
     Tags           = new TagCollection();
     Logs           = new LogCollection();
     OperationName  = operationName;
     StartTimestamp = startTimestamp;
 }
Ejemplo n.º 2
0
        public static ILink FromSpanContext(ISpanContext context, LinkType type, IDictionary <string, IAttributeValue> attributes)
        {
            IDictionary <string, IAttributeValue> copy = new Dictionary <string, IAttributeValue>(attributes);

            return(new Link(
                       context.TraceId,
                       context.SpanId,
                       type,
                       new ReadOnlyDictionary <string, IAttributeValue>(copy)));
        }
Ejemplo n.º 3
0
 internal SpanData(
     ISpanContext context,
     ISpanId parentSpanId,
     bool?hasRemoteParent,
     string name,
     ITimestamp startTimestamp,
     IAttributes attributes,
     ITimedEvents <IAnnotation> annotations,
     ITimedEvents <IMessageEvent> messageEvents,
     ILinks links,
     int?childSpanCount,
     Status status,
     ITimestamp endTimestamp)
 {
     if (context == null)
     {
         throw new ArgumentNullException(nameof(context));
     }
     this.Context         = context;
     this.ParentSpanId    = parentSpanId;
     this.HasRemoteParent = hasRemoteParent;
     if (name == null)
     {
         throw new ArgumentNullException(nameof(name));
     }
     this.Name = name;
     if (startTimestamp == null)
     {
         throw new ArgumentNullException(nameof(startTimestamp));
     }
     this.StartTimestamp = startTimestamp;
     if (attributes == null)
     {
         throw new ArgumentNullException(nameof(attributes));
     }
     this.Attributes = attributes;
     if (annotations == null)
     {
         throw new ArgumentNullException(nameof(annotations));
     }
     this.Annotations = annotations;
     if (messageEvents == null)
     {
         throw new ArgumentNullException(nameof(messageEvents));
     }
     this.MessageEvents = messageEvents;
     if (links == null)
     {
         throw new ArgumentNullException(nameof(links));
     }
     this.Links          = links;
     this.ChildSpanCount = childSpanCount;
     this.Status         = status;
     this.EndTimestamp   = endTimestamp;
 }
Ejemplo n.º 4
0
        public ISpanBuilder AddReference(string referenceType, ISpanContext referencedContext)
        {
            if (referencedContext is null)
            {
                return(this);
            }

            _references.Add(new Reference(referencedContext, referenceType));

            return(this);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpanContext"/> class
 /// that is the child of the specified parent context.
 /// </summary>
 /// <param name="parent">The parent context.</param>
 /// <param name="traceContext">The trace context.</param>
 /// <param name="serviceName">The service name to propagate to child spans.</param>
 internal SpanContext(ISpanContext parent, ITraceContext traceContext, string serviceName)
     : this(parent?.TraceId, serviceName)
 {
     SpanId       = SpanIdGenerator.CreateNew();
     Parent       = parent;
     TraceContext = traceContext;
     if (parent is SpanContext spanContext)
     {
         Origin = spanContext.Origin;
     }
 }
        /// <inheritdoc />
        public void Inject <TCarrier>(
            ISpanContext spanContext, IFormat <TCarrier> format, TCarrier carrier)
        {
            var propagator = registry.Get(format);

            if (propagator == null)
            {
                throw new ArgumentException("invalid format: " + format);
            }
            propagator.Inject((WavefrontSpanContext)spanContext, carrier);
        }
Ejemplo n.º 7
0
        public void ParseMissingSampledAndMissingFlag()
        {
            IDictionary <string, string> headersNotSampled = new Dictionary <string, string>
            {
                { B3Format.X_B3_TRACE_ID, TRACE_ID_BASE16 },
                { B3Format.X_B3_SPAN_ID, SPAN_ID_BASE16 }
            };
            ISpanContext spanContext = SpanContext.Create(TRACE_ID, SPAN_ID, TraceOptions.DEFAULT);

            Assert.Equal(spanContext, b3Format.Extract(headersNotSampled, Getter));
        }
        private string GetTraceId(TracingOptions options, ISpanContext context)
        {
            var traceId = context.TraceId.ToLowerBase16();

            if (traceId.Length > 16 && options.UseShortTraceIds)
            {
                traceId = traceId.Substring(traceId.Length - 16, 16);
            }

            return(traceId);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SpanContext"/> class
 /// that is the child of the specified parent context.
 /// </summary>
 /// <param name="parent">The parent context.</param>
 /// <param name="traceContext">The trace context.</param>
 /// <param name="serviceName">The service name to propagate to child spans.</param>
 /// <param name="spanId">The propagated span id.</param>
 internal SpanContext(ISpanContext parent, ITraceContext traceContext, string serviceName, ulong?spanId = null)
     : this(parent?.TraceId, serviceName)
 {
     SpanId       = spanId ?? SpanIdGenerator.ThreadInstance.CreateNew();
     Parent       = parent;
     TraceContext = traceContext;
     if (parent is SpanContext spanContext)
     {
         Origin = spanContext.Origin;
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpanContext"/> class
 /// that is the child of the specified parent context.
 /// </summary>
 /// <param name="parent">The parent context.</param>
 /// <param name="traceContext">The trace context.</param>
 /// <param name="serviceName">The service name to propagate to child spans.</param>
 internal SpanContext(ISpanContext parent, ITraceContext traceContext, string serviceName)
     : this(parent?.TraceId, serviceName)
 {
     SpanId       = _random.Value.NextUInt63();
     Parent       = parent;
     TraceContext = traceContext;
     if (parent is SpanContext spanContext)
     {
         Origin = spanContext.Origin;
     }
 }
Ejemplo n.º 11
0
        public ISpanBuilder AddReference(string referenceType, ISpanContext referencedContext)
        {
            if (referencedContext == null)
            {
                return(this);
            }

            references = references ?? new List <Reference>();
            references.Add(new Reference(referenceType, referencedContext));
            return(this);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SpanContext"/> class
        /// that is the child of the specified parent context.
        /// </summary>
        /// <param name="parent">The parent context.</param>
        /// <param name="traceContext">The trace context.</param>
        /// <param name="serviceName">The service name to propagate to child spans.</param>
        internal SpanContext(ISpanContext parent, ITraceContext traceContext, string serviceName)
            : this(parent?.TraceId, serviceName)
        {
            Parent       = parent;
            TraceContext = traceContext;

            if (SpanId == 0)
            {
                SpanId = GenerateId();
            }
        }
Ejemplo n.º 13
0
        public Span(string operationName, ISpanContext spanContext, ISpanRecorder spanChannel)
        {
            SpanContext   = spanContext ?? throw new ArgumentNullException(nameof(spanContext));
            Baggage       = spanContext.Baggage;
            Tags          = new TagCollection();
            OperationName = operationName;

            _spanChannel    = spanChannel ?? throw new ArgumentNullException(nameof(spanChannel));
            _state          = 0;
            _startTimestamp = Stopwatch.GetTimestamp();
        }
Ejemplo n.º 14
0
 public InProcessSampledSpanStoreTest()
 {
     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);
     startEndHandler       = new TestStartEndHandler(sampleStore);
     sampleStore.RegisterSpanNamesForCollection(new List <string>()
     {
         REGISTERED_SPAN_NAME
     });
 }
Ejemplo n.º 15
0
        private SpanBuilder(string name, SpanBuilderOptions options, ISpanContext remoteParentSpanContext = null, ISpan parent = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            Name   = name;
            Parent = parent;
            RemoteParentSpanContext = remoteParentSpanContext;
            Options = options;
        }
        public void Inject <TCarrier>(ISpanContext spanContext, IFormat <TCarrier> format, TCarrier carrier)
        {
            if ((format == BuiltinFormats.TextMap || format == BuiltinFormats.HttpHeaders) &&
                carrier is ITextMap textMap)
            {
                _propagator.Inject((SpanContext)spanContext, textMap);
                return;
            }

            throw new ZipkinFormatException(
                      $"Unrecognized carrier format [{format}]. Only ITextMap is supported by this driver.");
        }
Ejemplo n.º 17
0
        public void Inject <TCarrier>(ISpanContext spanContext, IFormat <TCarrier> format, TCarrier carrier)
        {
            var formatString = format.ToString();

            if (_injectors.ContainsKey(formatString))
            {
                _injectors[formatString].Inject(spanContext, carrier);
                return;
            }

            throw new ArgumentException($"{formatString} is not a supported injection format", nameof(format));
        }
        private void Process(Message message)
        {
            ISpanContext context = _tracer.Extract(BuiltinFormats.TextMap, new TextMapExtractAdapter(message));

            using (IScope scope = _tracer.BuildSpan("receive")
                                  .WithTag(Tags.SpanKind.Key, Tags.SpanKindServer)
                                  .WithTag(Tags.Component.Key, "example-server")
                                  .AsChildOf(context)
                                  .StartActive(finishSpanOnDispose: true))
            {
            }
        }
Ejemplo n.º 19
0
        public ISpan StartManual()
        {
            LambdaTracer tracer     = LambdaTracer.Instance as LambdaTracer;
            ISpan        activeSpan = tracer.ActiveSpan;

            ISpanContext parentSpanContext = null;

            if (!_ignoreActiveSpan && _parent == null && activeSpan != null)
            {
                AddReference(References.ChildOf, activeSpan.Context);
                parentSpanContext = activeSpan.Context;
            }
            else if (_parent != null)
            {
                parentSpanContext = _parent;
            }

            LambdaSpan parentSpan = null;

            if (parentSpanContext is LambdaSpanContext)
            {
                parentSpan = ((LambdaSpanContext)parentSpanContext).GetSpan();
            }

            var        guid = GuidGenerator.GenerateNewRelicGuid();
            LambdaSpan newSpan;

            if (parentSpan != null)
            {
                newSpan = new LambdaSpan(_operationName, DateTimeOffset.UtcNow, _tags, parentSpan, guid);
            }
            else
            {
                var rootSpan = new LambdaRootSpan(_operationName, DateTimeOffset.UtcNow, _tags, guid, new DataCollector(_logger, tracer.DebugMode), new TransactionState(), new PrioritySamplingState(), new DistributedTracingState());

                if (parentSpanContext is LambdaPayloadContext payloadContext)
                {
                    rootSpan.ApplyLambdaPayloadContext(payloadContext);
                }
                else
                {
                    rootSpan.ApplyAdaptiveSampling(tracer.AdaptiveSampler);
                }

                newSpan = rootSpan;
            }

            LambdaSpanContext spanContext = new LambdaSpanContext(newSpan);

            newSpan.SetContext(spanContext);

            return(newSpan);
        }
        private static ISpanBuilder CreateSpan(ITracer tracer, string operationName, ISpanContext parentSpanCtx)
        {
            ISpanBuilder spanBuilder;

            spanBuilder = tracer.BuildSpan(operationName);
            if (parentSpanCtx != null)
            {
                spanBuilder = spanBuilder.AsChildOf(parentSpanCtx);
            }

            return(spanBuilder);
        }
Ejemplo n.º 21
0
 public Task InjectAsync(ISpanContext spanContext, ICarrierWriter carrierWriter, ICarrier carrier)
 {
     if (carrierWriter == null)
     {
         throw new ArgumentNullException(nameof(carrierWriter));
     }
     if (spanContext == null)
     {
         throw new ArgumentNullException(nameof(spanContext));
     }
     return(carrierWriter.WriteAsync(spanContext.Package(), carrier));
 }
Ejemplo n.º 22
0
 public void Inject(ISpanContext spanContext, ICarrierWriter carrierWriter, ICarrier carrier)
 {
     if (carrierWriter == null)
     {
         throw new ArgumentNullException(nameof(carrierWriter));
     }
     if (spanContext == null)
     {
         throw new ArgumentNullException(nameof(spanContext));
     }
     carrierWriter.Write(spanContext.Package(), carrier);
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a new <see cref="Span"/> with the specified parameters.
        /// </summary>
        /// <param name="operationName">The span's operation name</param>
        /// <param name="parent">The span's parent</param>
        /// <param name="serviceName">The span's service name</param>
        /// <param name="startTime">An explicit start time for that span</param>
        /// <param name="ignoreActiveScope">If set the span will not be a child of the currently active span</param>
        /// <returns>The newly created span</returns>
        public Span StartSpan(string operationName, ISpanContext parent = null, string serviceName = null, DateTimeOffset?startTime = null, bool ignoreActiveScope = false)
        {
            if (parent == null && !ignoreActiveScope)
            {
                parent = _scopeManager.Active?.Span?.Context;
            }

            ITraceContext traceContext;

            // try to get the trace context (from local spans) or
            // sampling priority (from propagated spans),
            // otherwise start a new trace context
            if (parent is SpanContext parentSpanContext)
            {
                traceContext = parentSpanContext.TraceContext ??
                               new TraceContext(this)
                {
                    SamplingPriority = parentSpanContext.SamplingPriority
                };
            }
            else
            {
                traceContext = new TraceContext(this);
            }

            var finalServiceName = serviceName ?? parent?.ServiceName ?? DefaultServiceName;
            var spanContext      = new SpanContext(parent, traceContext, finalServiceName);

            var span = new Span(spanContext, startTime)
            {
                OperationName = operationName,
            };

            var env = Settings.Environment;

            // automatically add the "env" tag if defined
            if (!string.IsNullOrWhiteSpace(env))
            {
                span.SetTag(Tags.Env, env);
            }

            // Apply any global tags
            if (Settings.GlobalTags.Count > 0)
            {
                foreach (var entry in Settings.GlobalTags)
                {
                    span.SetTag(entry.Key, entry.Value);
                }
            }

            traceContext.AddSpan(span);
            return(span);
        }
        public void ShouldFallbackWhenInjectingWithFaultyCodec()
        {
            Tracer tracer = new Tracer.Builder("TracerResiliencyTestService")
                            .WithReporter(new InMemoryReporter())
                            .WithSampler(new ConstSampler(true))
                            .RegisterCodec(BuiltinFormats.TextMap, new FaultyCodec())
                            .Build();

            ISpanContext context = tracer.BuildSpan("test-span").Start().Context;

            tracer.Inject(context, BuiltinFormats.TextMap, new NoopTextMap());
        }
        public void ShouldFallbackWhenExtractingWithFaultyCodec()
        {
            Tracer tracer = new Tracer.Builder("TracerResiliencyTestService")
                            .WithReporter(new InMemoryReporter())
                            .WithSampler(new ConstSampler(true))
                            .RegisterCodec(BuiltinFormats.TextMap, new FaultyCodec())
                            .Build();

            ISpanContext spanContext = tracer.Extract(BuiltinFormats.TextMap, new NoopTextMap());

            Assert.Null(spanContext);
        }
        internal ZipkinSpan GenerateSpan(ISpanData spanData, ZipkinEndpoint localEndpoint)
        {
            ISpanContext context        = spanData.Context;
            long         startTimestamp = ToEpochMicros(spanData.StartTimestamp);

            long endTimestamp = ToEpochMicros(spanData.EndTimestamp);

            ZipkinSpan.Builder spanBuilder =
                ZipkinSpan.NewBuilder()
                .TraceId(EncodeTraceId(context.TraceId))
                .Id(EncodeSpanId(context.SpanId))
                .Kind(ToSpanKind(spanData))
                .Name(spanData.Name)
                .Timestamp(ToEpochMicros(spanData.StartTimestamp))
                .Duration(endTimestamp - startTimestamp)
                .LocalEndpoint(localEndpoint);

            if (spanData.ParentSpanId != null && spanData.ParentSpanId.IsValid)
            {
                spanBuilder.ParentId(EncodeSpanId(spanData.ParentSpanId));
            }

            foreach (var label in spanData.Attributes.AttributeMap)
            {
                spanBuilder.PutTag(label.Key, AttributeValueToString(label.Value));
            }

            Status status = spanData.Status;

            if (status != null)
            {
                spanBuilder.PutTag(STATUS_CODE, status.CanonicalCode.ToString());
                if (status.Description != null)
                {
                    spanBuilder.PutTag(STATUS_DESCRIPTION, status.Description);
                }
            }

            foreach (var annotation in spanData.Annotations.Events)
            {
                spanBuilder.AddAnnotation(
                    ToEpochMicros(annotation.Timestamp), annotation.Event.Description);
            }

            foreach (var networkEvent in spanData.MessageEvents.Events)
            {
                spanBuilder.AddAnnotation(
                    ToEpochMicros(networkEvent.Timestamp), networkEvent.Event.Type.ToString());
            }

            return(spanBuilder.Build());
        }
 private ISpanContext TryExtractSpanContext(HttpRequest request)
 {
     try
     {
         ISpanContext spanContext = Tracer.Extract(BuiltinFormats.HttpHeaders, new HeaderDictionaryCarrier(request.Headers));
         return(spanContext);
     }
     catch (Exception ex)
     {
         Logger.LogError(0, ex, "Extracting SpanContext failed");
         return(null);
     }
 }
Ejemplo n.º 28
0
 public ISpanBuilder AddReference(string referenceType, ISpanContext referencedContext)
 {
     if (!referencedContext.IsAppInsightsSpan())
     {
         return(this);                                        // stop execution here
     }
     if (_references == null)
     {
         _references = new List <SpanReference>();
     }
     _references.Add(new SpanReference(referenceType, referencedContext));
     return(this);
 }
Ejemplo n.º 29
0
 public ISpanBuilder AddReference(string referenceType, ISpanContext referencedContext)
 {
     if (referencedContext is SpanContext context)
     {
         if (!string.Equals(References.ChildOf, referenceType) &&
             !string.Equals(References.FollowsFrom, referenceType))
         {
             return(this);
         }
         references.Add(new Reference(context, referenceType));
     }
     return(this);
 }
Ejemplo n.º 30
0
 protected SpanBase(ISpanContext context, SpanOptions options = SpanOptions.NONE)
 {
     if (context == null)
     {
         throw new ArgumentNullException(nameof(context));
     }
     if (context.TraceOptions.IsSampled && !options.HasFlag(SpanOptions.RECORD_EVENTS))
     {
         throw new ArgumentOutOfRangeException("Span is sampled, but does not have RECORD_EVENTS set.");
     }
     Context = context;
     Options = options;
 }