コード例 #1
0
        private Trace ResolveTraceSpan(ServerCallContext context)
        {
            try
            {
                var dictionary = new Dictionary <string, string>();
                var headers    = context.RequestHeaders.GetEnumerator();
                while (headers.MoveNext())
                {
                    dictionary.Add(headers.Current.Key, headers.Current.Value);
                }
                headers.Reset();

                if (!dictionary.ContainsKey("zipkin_traceid"))
                {
                    return(null);
                }
                if (dictionary.ContainsKey("zipkin_parentspanid"))
                {
                    return(Trace.CreateFromId(new SpanState(long.Parse(dictionary["zipkin_traceid"]), long.Parse(dictionary["zipkin_parentspanid"]), long.Parse(dictionary["zipkin_spanid"]), SpanFlags.Sampled | SpanFlags.SamplingKnown)));
                }

                return(Trace.CreateFromId(new SpanState(long.Parse(dictionary["zipkin_traceid"]), null, long.Parse(dictionary["zipkin_spanid"]), SpanFlags.Sampled | SpanFlags.SamplingKnown)));
            }
            catch
            {
                return(null);
            }
        }
コード例 #2
0
        public static void UseTracing(this IApplicationBuilder app, string serviceName,
                                      Func <HttpContext, string> getRpc = null)
        {
            getRpc = getRpc ?? (context => context.Request.Method);
            var extractor = Propagations.B3String.Extractor <IHeaderDictionary>((carrier, key) => carrier[key]);

            app.Use(async(context, next) =>
            {
                var request      = context.Request;
                var traceContext = extractor.Extract(request.Headers);

                var trace     = traceContext == null ? Trace.Create() : Trace.CreateFromId(traceContext);
                Trace.Current = trace;
                using (var serverTrace = new ServerTrace(serviceName, getRpc(context)))
                {
                    if (request.Host.HasValue)
                    {
                        trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
                    }
                    trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
                    trace.Record(Annotations.Tag("http.path", request.Path));
                    await serverTrace.TracedActionAsync(next());
                }
            });
        }
コード例 #3
0
        /// <summary>
        /// 注册服务
        /// </summary>
        public static void RegisterService(Func <HttpContext, string> getRpc = null)
        {
            getRpc = getRpc ?? (c => c.Request.Method);
            var extractor = Propagations.B3String.Extractor <IHeaderDictionary>((carrier, key) => carrier[key]);

            var request      = ZipkinServiceHttpContext.Current.Request;
            var traceContext = extractor.Extract(request.Headers);

            var trace = traceContext == null?Trace.Create() : Trace.CreateFromId(traceContext);

            Trace.Current = trace;

            using (var serverTrace = new ServerTrace(ServiceName, getRpc(ZipkinServiceHttpContext.Current)))
            {
                if (request.Host.HasValue)
                {
                    trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
                }
                trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
                trace.Record(Annotations.Tag("http.path", request.Path));
                trace.Record(Annotations.Tag("Execute.Time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")));
                trace.Record(Annotations.Tag("Request.Body", JSONHelper.SerializeObject(request.Body)));
                serverTrace.AddAnnotation(Annotations.ServiceName(ServiceName));
            }
        }
コード例 #4
0
        private static Trace ExtractTracing(Message message)
        {
            var extractor = Propagations.B3String.Extractor <IReadOnlyDictionary <string, byte[]> >((carrier, key) => carrier.TryGetValue(key, out var value) ? Encoding.UTF8.GetString(value) : null);

            var traceContext = extractor.Extract(message.Headers);

            return(traceContext == null?Trace.Create() : Trace.CreateFromId(traceContext));
        }
コード例 #5
0
        /// <summary>
        ///
        /// <para>On_FromGatewayToService_Sent:</para>
        ///
        /// <para>Check <seealso cref="IBTracingServiceInterface.On_FromGatewayToService_Sent"/> for detailed documentation</para>
        ///
        /// </summary>
        public void On_FromGatewayToService_Sent(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            var TraceContext = TraceExtractor.Extract(_Context.Request.Headers);
            var CreatedTrace = TraceContext == null?Trace.Create() : Trace.CreateFromId(TraceContext).Child();

            CommonHttpTraceAnnotations(CreatedTrace, _Context);
            CreatedTrace.Record(Annotations.LocalOperationStop());
        }
コード例 #6
0
        /// <summary>
        ///
        /// <para>On_FromServiceToGateway_Received:</para>
        ///
        /// <para>Check <seealso cref="IBTracingServiceInterface.On_FromGatewayToService_Received"/> for detailed documentation</para>
        ///
        /// </summary>
        public void On_FromServiceToGateway_Received(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            var TraceContext = TraceExtractor.Extract(_Context.Request.Headers);
            var CreatedTrace = TraceContext == null?Trace.Create() : Trace.CreateFromId(TraceContext).Child();

            CommonHttpTraceAnnotations(CreatedTrace, _Context);
            CreatedTrace.Record(Annotations.LocalOperationStart(ProgramUniqueID + "->" + _Context.Request.Url.AbsolutePath));
        }
コード例 #7
0
ファイル: T_Trace.cs プロジェクト: ziphrax/zipkin4net
        public void TraceSamplingForced(bool?isSampled)
        {
            var spanState = new SpanState(1, 0, 1, isSampled: isSampled, isDebug: false);
            var trace     = Trace.CreateFromId(spanState);

            trace.ForceSampled();

            Assert.IsTrue(trace.CurrentSpan.Sampled);
        }
コード例 #8
0
ファイル: T_Trace.cs プロジェクト: aliostad/zipkin4net
        public void TraceSamplingForced(SpanFlags initialFlags)
        {
            var spanState = new SpanState(1, 0, 1, initialFlags);
            var trace     = Trace.CreateFromId(spanState);

            trace.ForceSampled();

            Assert.AreEqual(SamplingStatus.Sampled, trace.CurrentSpan.SamplingStatus);
        }
コード例 #9
0
 private static bool TryCreateTraceFromTraceContext(ITraceContext traceContext, out Trace trace)
 {
     if (traceContext == default(SpanState))
     {
         trace = default(Trace);
         return(false);
     }
     trace = Trace.CreateFromId(traceContext);
     return(true);
 }
コード例 #10
0
ファイル: T_Trace.cs プロジェクト: aliostad/zipkin4net
        public void FlagUnsetShouldForwardForBackwardCompatibility()
        {
            var dispatcher = new Mock <IRecordDispatcher>();

            TraceManager.Start(new VoidLogger(), dispatcher.Object);

            var spanState = new SpanState(1, 0, 1, SpanFlags.None);
            var trace     = Trace.CreateFromId(spanState);

            trace.Record(Annotations.ClientRecv());

            dispatcher.Verify(d => d.Dispatch(It.IsAny <Record>()), Times.Once());
        }
コード例 #11
0
ファイル: T_Trace.cs プロジェクト: aliostad/zipkin4net
        public void FlagNotSampledShouldNotForward()
        {
            var dispatcher = new Mock <IRecordDispatcher>();

            TraceManager.Start(new VoidLogger(), dispatcher.Object);

            var spanState = new SpanState(1, 0, 1, SpanFlags.SamplingKnown);
            var trace     = Trace.CreateFromId(spanState);

            trace.Record(Annotations.ClientRecv());

            dispatcher.Verify(d => d.Dispatch(It.IsAny <Record>()), Times.Never);
        }
コード例 #12
0
ファイル: T_Trace.cs プロジェクト: ziphrax/zipkin4net
        public void FlagSampledShouldForward()
        {
            var dispatcher = new Mock <IRecordDispatcher>();

            TraceManager.Start(new VoidLogger(), dispatcher.Object);

            var spanState = new SpanState(1, 0, 1, isSampled: true, isDebug: false);
            var trace     = Trace.CreateFromId(spanState);

            trace.Record(Annotations.ClientRecv());

            dispatcher.Verify(d => d.Dispatch(It.IsAny <Record>()), Times.Once());
        }
コード例 #13
0
ファイル: OtTracer.cs プロジェクト: gameoft/csharp-netcore
        public ISpanContext Extract <TCarrier>(IFormat <TCarrier> format, TCarrier carrier)
        {
            VerifySupportedFormat(format);

            ITextMap implCarrier = GetRealCarrier(carrier);

            ITraceContext traceContext = _extractor.Extract(implCarrier);

            if (traceContext == null)
            {
                return(null);
            }

            return(new OtSpanContext(Trace.CreateFromId(traceContext)));
        }
コード例 #14
0
        public void HeadersAreCorrectlySet(string expectedTraceId, long?parentSpanId, string expectedParentSpanId, string expectedSpanId, bool setSampled, string expectedFlags, string expectedSampled, int expectedCount)
        {
            var spanState = new SpanState(1, parentSpanId, 250, setSampled ? (SpanFlags.SamplingKnown | SpanFlags.Sampled) : SpanFlags.None);
            var trace     = Trace.CreateFromId(spanState);

            var headersNvc = new NameValueCollection();

            _injector.Inject(trace, headersNvc);
            CheckHeaders(headersNvc, expectedTraceId, expectedParentSpanId, expectedSpanId, expectedFlags, expectedSampled, expectedCount);

            var headersDict = new Dictionary <string, string>();

            _injector.Inject(trace, headersDict);
            CheckHeaders(headersDict, expectedTraceId, expectedParentSpanId, expectedSpanId, expectedFlags, expectedSampled, expectedCount);
        }
コード例 #15
0
        public override async Task Invoke(IOwinContext context)
        {
            var traceContext = traceExtractor.Extract(context.Request.Headers);
            var trace        = traceContext == null?Trace.Create() : Trace.CreateFromId(traceContext);

            Trace.Current = trace;

            using (var serverTrace = new ServerTrace(this.serviceName, context.Request.Method))
            {
                trace.Record(Annotations.Tag("http.host", context.Request.Host.Value));
                trace.Record(Annotations.Tag("http.url", context.Request.Uri.AbsoluteUri));
                trace.Record(Annotations.Tag("http.path", context.Request.Uri.AbsolutePath));

                await serverTrace.TracedActionAsync(Next.Invoke(context));
            }
        }
コード例 #16
0
        private static void CheckSetHeadersThenGetTrace_NVC(long?parentSpanId)
        {
            var spanState     = new SpanState(2, 1, parentSpanId, 2, isSampled: null, isDebug: false);
            var originalTrace = Trace.CreateFromId(spanState);

            var headers = new NameValueCollection();
            var zipkinHttpTraceInjector = new ZipkinHttpTraceInjector();

            zipkinHttpTraceInjector.Inject(originalTrace, headers);

            Trace deserializedTrace;
            var   extractor = new ZipkinHttpTraceExtractor();

            Assert.True(extractor.TryExtract(headers, out deserializedTrace));

            Assert.AreEqual(originalTrace, deserializedTrace);
        }
コード例 #17
0
        private static void CheckSetHeadersThenGetTrace_Dict(long?parentSpanId)
        {
            var spanState     = new SpanState(2, 1, parentSpanId, 2, SpanFlags.None);
            var originalTrace = Trace.CreateFromId(spanState);

            var headers = new Dictionary <string, string>();
            var zipkinHttpTraceInjector = new ZipkinHttpTraceInjector();

            zipkinHttpTraceInjector.Inject(originalTrace, headers);

            Trace deserializedTrace;
            var   extractor = new ZipkinHttpTraceExtractor();

            Assert.True(extractor.TryExtract(headers, out deserializedTrace));

            Assert.AreEqual(originalTrace, deserializedTrace);
        }
コード例 #18
0
        public void SampledHeaderFollowFlagsValueForCompatibility(SpanFlags flags, string expectedHeader)
        {
            var spanFlagNotSampled = Trace.CreateFromId(new SpanState(1, 2, 250, flags));

            var headers = new Dictionary <string, string>();

            _injector.Inject(spanFlagNotSampled, headers);

            if (expectedHeader != null)
            {
                Assert.AreEqual(expectedHeader, headers[ZipkinHttpHeaders.Sampled]);
            }
            else
            {
                Assert.IsFalse(headers.ContainsKey(ZipkinHttpHeaders.Sampled));
            }
        }
コード例 #19
0
        private static bool TryGetTrace(HttpContext httpContext, out Trace trace)
        {
            var traceContext = Extractor.Extract(httpContext.Request.Headers);

            if (!_zipkinManager.Options.Enabled || traceContext == null)
            {
                trace = null;
                return(false);
            }

            trace = Trace.Current = Trace.CreateFromId(traceContext);

            trace.Record(Annotations.ServiceName(_zipkinManager.Options.ServiceName));
            trace.Record(Annotations.ServerRecv());
            trace.Record(Annotations.Tag("http.host", httpContext.Request.Host.ToString()));
            trace.Record(Annotations.Tag("http.uri", GetDisplayUrl(httpContext.Request)));
            trace.Record(Annotations.Tag("http.method", httpContext.Request.Method));

            return(true);
        }
コード例 #20
0
        public static bool TryParseTrace(string encodedTraceId, string encodedSpanId, string encodedParentSpanId, string sampledStr, string flagsStr, out Trace trace)
        {
            if (string.IsNullOrWhiteSpace(encodedTraceId) ||
                string.IsNullOrWhiteSpace(encodedSpanId))
            {
                trace = default(Trace);
                return(false);
            }

            try
            {
                var traceIdHigh  = ExtractTraceIdHigh(encodedTraceId);
                var traceId      = ExtractTraceId(encodedTraceId);
                var spanId       = NumberUtils.DecodeHexString(encodedSpanId);
                var parentSpanId = string.IsNullOrWhiteSpace(encodedParentSpanId) ? null : (long?)NumberUtils.DecodeHexString(encodedParentSpanId);
                var flags        = ZipkinHttpHeaders.ParseFlagsHeader(flagsStr);
                var sampled      = ZipkinHttpHeaders.ParseSampledHeader(sampledStr);

                if (sampled != null)
                {
                    // When "sampled" header exists, it overrides any existing flags
                    flags = SpanFlags.SamplingKnown;
                    if (sampled.Value)
                    {
                        flags = flags | SpanFlags.Sampled;
                    }
                }


                var state = new SpanState(traceIdHigh, traceId, parentSpanId, spanId, flags);
                trace = Trace.CreateFromId(state);
                return(true);
            }
            catch (Exception ex)
            {
                TraceManager.Logger.LogWarning("Couldn't parse trace context. Trace is ignored. Message:" + ex.Message);
            }

            trace = default(Trace);
            return(false);
        }
コード例 #21
0
        public ITrace ExtractTrace(Func <string, string> extractKey)
        {
            var traceContext = s_w3cExtractor.Extract(extractKey) ?? s_b3Extractor.Extract(extractKey);

            return(traceContext == null ? null : new ZipkinTrace(this, Trace.CreateFromId(traceContext), TraceKind.Server));
        }
コード例 #22
0
 private Trace CreateFromContext(ITraceContext traceContext)
 {
     return(traceContext == null?Trace.Create() : Trace.CreateFromId(traceContext));
 }