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); } }
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()); } }); }
/// <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)); } }
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)); }
/// <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()); }
/// <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)); }
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); }
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); }
private static bool TryCreateTraceFromTraceContext(ITraceContext traceContext, out Trace trace) { if (traceContext == default(SpanState)) { trace = default(Trace); return(false); } trace = Trace.CreateFromId(traceContext); return(true); }
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()); }
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); }
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()); }
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))); }
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); }
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)); } }
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); }
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); }
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)); } }
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); }
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); }
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)); }
private Trace CreateFromContext(ITraceContext traceContext) { return(traceContext == null?Trace.Create() : Trace.CreateFromId(traceContext)); }