private async Task UploadAsync( Task uploadTask, Task updateUiTask, ClientMetrics metrics, View cancelButton, View uploadButton, ISpan span, CancellationTokenSource source) { var container = base.FindViewById(Resource.Id.metrics_container) !; container.Visibility = ViewStates.Visible; var doneText = (TextView)base.FindViewById(Resource.Id.done_text) !; var ranForLabel = (TextView)base.FindViewById(Resource.Id.ran_for_label) !; var ranForContainer = base.FindViewById(Resource.Id.ran_for_container) !; var ranForView = base.FindViewById(Resource.Id.ran_for_view) !; try { cancelButton.Enabled = true; await Task.WhenAny(uploadTask, updateUiTask); if (uploadTask.IsCompletedSuccessfully) { cancelButton.Enabled = false; uploadButton.Enabled = false; doneText.Visibility = ViewStates.Visible; ranForView.Visibility = ViewStates.Visible; ranForContainer.Visibility = ViewStates.Visible; ranForLabel.Text = metrics.RanFor.ToString(); span.Finish(SpanStatus.Ok); } else if (uploadTask.IsFaulted) { ShowError(uploadTask.Exception); span.Finish(SpanStatus.InternalError); } else { cancelButton.Enabled = false; uploadButton.Enabled = true; span.Finish(SpanStatus.Cancelled); } } catch (Exception e) { ShowError(e); span.Finish(e); } finally { source.Cancel(); } }
public void Finish() { _innerSpan.Finish(); if (_active) { _traceContext.TryPop(); _active = false; } }
public static void FinalizeTrace(this ISpan spanToFinish, IDictionary <string, object> log) { if (log is null) { spanToFinish.Finish(); } spanToFinish.Log(DateTimeOffset.UtcNow, log); spanToFinish.Finish(); }
public IEnumerator <ViewRow> GetEnumerator() { if (HasFinishedReading) { throw new StreamAlreadyReadException(); } // make sure we're are the 'rows' element in the stream if (ReadToRows()) { while (_reader.Read()) { if (_reader.TokenType == JsonToken.StartObject) { var json = JToken.ReadFrom(_reader); yield return(new ViewRow { Id = json.Value <string>("id"), KeyToken = json["key"], ValueToken = json["value"] }); } } } // we've reached the end of the stream, so mark it as finished reading HasFinishedReading = true; // if we have a decode span, finish it _decodeSpan?.Finish(); }
public IEnumerator <ViewRow <T> > GetEnumerator() { if (_hasFinishedReading) { throw new StreamAlreadyReadException(); } // make sure we're are the 'rows' element in the stream if (ReadToRows()) { while (_reader.Read()) { if (_reader.TokenType == JsonToken.StartObject) { yield return(JToken.ReadFrom(_reader).ToObject <ViewRow <T> >(_jsonSerializer)); } } } // we've reached the end of the stream, so mark it as finished reading _hasFinishedReading = true; // if we have a decode span, finish it _decodeSpan?.Finish(); }
public void TestNoAutoRefWithExistingRefs() { InMemoryReporter reporter = new InMemoryReporter(); Tracer tracer = new Tracer.Builder("test") .WithReporter(reporter) .WithSampler(new ConstSampler(true)) .Build(); ISpan initialSpan = tracer.BuildSpan("initial").Start(); using (IScope parent = tracer.BuildSpan("parent").StartActive(finishSpanOnDispose: true)) { tracer.BuildSpan("child").AsChildOf(initialSpan.Context).StartActive(finishSpanOnDispose: true).Dispose(); } initialSpan.Finish(); Assert.Equal(3, reporter.GetSpans().Count); Span childSpan = reporter.GetSpans()[0]; Span parentSpan = reporter.GetSpans()[1]; Span initSpan = reporter.GetSpans()[2]; Assert.Empty(initSpan.GetReferences()); Assert.Empty(parentSpan.GetReferences()); Assert.Equal(initSpan.Context.TraceId, childSpan.Context.TraceId); Assert.Equal(initSpan.Context.SpanId, childSpan.Context.ParentId); Assert.Equal(0L, initSpan.Context.ParentId); Assert.Equal(0L, parentSpan.Context.ParentId); }
/// <summary> /// <para>This method will return the bottom-span from the stack. /// If there's more than one span on the stack, it will call <see cref="ISpan.Finish"/> on them.</para> /// <para>This should be called by outermost handlers who create root spans and want to finish all open spans.</para> /// </summary> private ISpan PopAndFinishOrphaned() { ISpan last = null; while (TraceContext.Count > 0) { last = TraceContext.TryPop(); // if it hasn't been the last, it's orphaned and must be finished. if (TraceContext.Count > 0) { Logger.LogError("Orphaned span detected. {SpanContext}", last.Context); last.SetTag(Tags.Error, true); last.SetTag("error.message", "orphaned span"); last.Finish(); } } if (last == null) { Logger.LogError("Span not found"); } return(last); }
public void Report_WithValidSpan() { string expectedOperationName = "Operationname-4Head"; string address = "localhost"; int agentport = 13337; int reporterport = 13338; // Setup Recieving Endpoint before Tracer.Reporter Connects to this Client and before Span Finish() is Called Task agentTast = Task.Run(() => { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); UdpClient agent = new UdpClient(agentport); Byte[] recieveBytes = agent.Receive(ref RemoteIpEndPoint); string spanContent = Encoding.UTF8.GetString(recieveBytes); // Uses the IPEndPoint object to determine which of these two hosts responded. // Output can be used to comprehend the communication Console.WriteLine("This is the message you received " + spanContent.ToString()); Console.WriteLine("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString()); Assert.AreEqual(expectedOperationName, spanContent.ToString().Split(";")[0]); Assert.IsNotNull(DateTime.Parse(spanContent.ToString().Split(";")[5])); }); Tracer tracer = new Tracer(); //Cautions: Test run parallel -> Portusage needs to vary between tests tracer.Configure(address, agentport, reporterport); IScope scope = tracer.BuildSpan(expectedOperationName).StartActive(); ISpan span = scope.Span; span.Finish(); agentTast.Wait(); Assert.AreNotEqual(DateTime.MinValue, DateTime.Parse(span.ToString().Split(";")[5])); }
public void TestTextMapPropagatorTextMap() { MockTracer tracer = new MockTracer(Propagators.TextMap); var injectMap = new Dictionary <string, string> { { "foobag", "donttouch" } }; { ISpan parentSpan = tracer.BuildSpan("foo") .Start(); parentSpan.SetBaggageItem("foobag", "fooitem"); parentSpan.Finish(); tracer.Inject(parentSpan.Context, BuiltinFormats.TextMap, new TextMapInjectAdapter(injectMap)); ISpanContext extract = tracer.Extract(BuiltinFormats.TextMap, new TextMapExtractAdapter(injectMap)); ISpan childSpan = tracer.BuildSpan("bar") .AsChildOf(extract) .Start(); childSpan.SetBaggageItem("barbag", "baritem"); childSpan.Finish(); } List <MockSpan> finishedSpans = tracer.FinishedSpans(); Assert.Equal(2, finishedSpans.Count); Assert.Equal(finishedSpans[0].Context.TraceId, finishedSpans[1].Context.TraceId); Assert.Equal(finishedSpans[0].Context.SpanId, finishedSpans[1].ParentId); Assert.Equal("fooitem", finishedSpans[0].GetBaggageItem("foobag")); Assert.Null(finishedSpans[0].GetBaggageItem("barbag")); Assert.Equal("fooitem", finishedSpans[1].GetBaggageItem("foobag")); Assert.Equal("baritem", finishedSpans[1].GetBaggageItem("barbag")); Assert.Equal("donttouch", injectMap["foobag"]); }
public void TestTextMapPropagatorHttpHeaders() { MockTracer tracer = new MockTracer(Propagators.TextMap); { ISpan parentSpan = tracer.BuildSpan("foo") .Start(); parentSpan.Finish(); var injectMap = new Dictionary <string, string>(); tracer.Inject(parentSpan.Context, BuiltinFormats.HttpHeaders, new TextMapInjectAdapter(injectMap)); ISpanContext extract = tracer.Extract(BuiltinFormats.HttpHeaders, new TextMapExtractAdapter(injectMap)); tracer.BuildSpan("bar") .AsChildOf(extract) .Start() .Finish(); } List <MockSpan> finishedSpans = tracer.FinishedSpans(); Assert.Equal(2, finishedSpans.Count); Assert.Equal(finishedSpans[0].Context.TraceId, finishedSpans[1].Context.TraceId); Assert.Equal(finishedSpans[0].Context.SpanId, finishedSpans[1].ParentId); }
public void FinishSuccess() { if (_configuration.Verbose) { _span.Log("Call completed"); } _span.Finish(); }
public void TestChildOfWithNullParentDoesNotThrowException() { MockTracer tracer = new MockTracer(); ISpan parent = null; ISpan span = tracer.BuildSpan("foo").AsChildOf(parent).Start(); span.Finish(); }
public void SayHello(string helloTo) { ISpan span = _tracer.BuildSpan("say-hello").Start(); var msg = FormatHello(span, helloTo); PrintHello(span, msg); span.Finish(); }
public static void AddException(this ISpan span, Exception e) { Tags.Error.Set(span, true); span.SetTag("event.error_code", 2); // exception span.SetTag("error.message", e.Message); span.SetTag("error.stack_trace", e.StackTrace); span.SetTag("error.type", e.GetType().Name); span.SetTag("error.time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0); span.Finish(); }
public void Finish_EndTimeInThePast_DurationIs0() { var startTime = DateTimeOffset.UtcNow; var endTime = startTime.AddMilliseconds(-10); ISpan span = GetScope("Op1", startTime).Span; span.Finish(endTime); Assert.Equal(TimeSpan.Zero, ((OpenTracingSpan)span).Duration); }
private void Finish() { if (_isFinished) { return; } EndScope(); _span.Finish(); _isFinished = true; }
public void Finish_EndTimeProvided_SpanWritenWithCorrectDuration() { var startTime = DateTimeOffset.UtcNow; var endTime = startTime.AddMilliseconds(10); ISpan span = GetScope("Op1", startTime).Span; span.Finish(endTime); Assert.Equal(endTime - startTime, ((OpenTracingSpan)span).Duration); }
public void Finish_StartTimeInThePastWithNoEndTime_DurationProperlyComputed() { TimeSpan expectedDuration = TimeSpan.FromMinutes(1); var startTime = DateTimeOffset.UtcNow - expectedDuration; ISpan span = GetScope("Op1", startTime).Span; span.Finish(); double durationDifference = Math.Abs((((OpenTracingSpan)span).Duration - expectedDuration).TotalMilliseconds); Assert.True(durationDifference < 100); }
private static void SetTracingBefore(ClientActionExecutingContext context) { if (context.Stream == null || GlobalTracer.Instance.ActiveSpan == null) { return; } var spanBuilder = GlobalTracer.Instance.BuildSpan( $"{ConstValue.ClientStream} {NetRpc.Helper.SizeSuffix(context.Stream.Length)} {ConstValue.SendStr}").AsChildOf(GlobalTracer.Instance.ActiveSpan); ISpan?span = null; context.OnceCall.SendRequestStreamStarted += (s, e) => span = spanBuilder.Start(); context.OnceCall.SendRequestStreamFinished += (s, e) => span?.Finish(); }
protected override void OnNext(string eventName, object arg) { switch (eventName) { case "System.Net.Http.Desktop.HttpRequestOut.Start": { var request = (HttpWebRequest)_activityStart_RequestFetcher.Fetch(arg); string operationName = _options.OperationNameResolver(request); ISpan span = Tracer.BuildSpan(operationName) .WithTag(Tags.SpanKind, Tags.SpanKindClient) .WithTag(Tags.Component, _options.ComponentName) .WithTag(Tags.HttpMethod, request.Method.ToString()) .WithTag(Tags.HttpUrl, request.RequestUri.ToString()) .WithTag(Tags.PeerHostname, request.RequestUri.Host) .WithTag(Tags.PeerPort, request.RequestUri.Port) .Start(); _options.OnRequest?.Invoke(span, request); if (_options.InjectEnabled?.Invoke(request) ?? true) { Tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new HttpHeadersInjectAdapter(request.Headers)); } spanContainer.TryAdd(request.Headers["uber-trace-id"], span); } break; case "System.Net.Http.Exception": break; case "System.Net.Http.Desktop.HttpRequestOut.Stop": { var request = (HttpWebRequest)_activityStop_RequestFetcher.Fetch(arg); if (spanContainer.TryRemove(request.Headers["uber-trace-id"], out var span)) { var response = (HttpWebResponse)_activityStop_ResponseFetcher.Fetch(arg); if (response != null) { span.SetTag(Tags.HttpStatus, (int)response.StatusCode); } span.Finish(); } } break; } }
public void OnAfterExecuteCommand(IDbCommand command, string executeMethod, bool isAsync) { Execute(() => { ISpan span = _span.Value; if (span == null) { Logger.LogError("Span not found"); return; } span.Finish(); }); }
private static void SetTracingBefore(ActionExecutingContext context) { if (context.Stream == null || context.Stream.Length == 0 || GlobalTracer.Instance.ActiveSpan == null) { return; } var spanBuilder = GlobalTracer.Instance.BuildSpan( $"{ConstValue.ServiceStream} {NetRpc.Helper.SizeSuffix(context.Stream.Length)} {ConstValue.ReceiveStr}").AsChildOf(GlobalTracer.Instance.ActiveSpan); ISpan span = null; context.Stream.Started += (s, e) => span = spanBuilder.Start(); context.Stream.Finished += (s, e) => { span?.Finish(); }; }
public void OnCommandExecutionError(IDbCommand command, string executeMethod, bool isAsync, Exception exception) { Execute(() => { ISpan span = _span.Value; if (span == null) { Logger.LogError("Span not found"); return; } span.SetException(exception); span.Finish(); }); }
public void Dispose() { if (_scopeManager.Active != this) { // This shouldn't happen if users call methods in the expected order. Bail out. return; } if (_finishOnDispose) { _wrappedSpan.Finish(); } _scopeManager.Active = _scopeToRestore; }
private static void SetTracingAfter(ActionExecutingContext context) { if (GlobalTracer.Instance.ActiveSpan == null) { return; } if (context.Result.TryGetStream(out var outStream, out _)) { var spanBuilder = GlobalTracer.Instance.BuildSpan($"{ConstValue.ServiceStream} {NetRpc.Helper.SizeSuffix(outStream.Length)} {ConstValue.SendStr}") .AsChildOf(GlobalTracer.Instance.ActiveSpan); ISpan span = null; context.SendResultStreamStarted += (s, e) => span = spanBuilder.Start(); context.SendResultStreamFinished += (s, e) => span?.Finish(); } }
public void Finish() { /*[0] = Operationname *[1] = Starttime *[2] = TraceId *[3] = SpanId *[4] = Reference_type *[5] = Endtime */ //Configure needed to handle dispose and finish of spans //Cautions: Test run parallel -> Portusage needs to vary between tests string address = "localhost"; int agentport = 13341; int reporterport = 13342; string expectedOperationName = "operationname"; Tracer tracer = new Tracer(); tracer.Configure(address, agentport, reporterport); ISpan span = tracer.BuildSpan("operationname").Start(); span.Finish(); Assert.IsNull(tracer.ActiveSpan); using (var scope = tracer.BuildSpan("somename").StartActive()) { Assert.IsNotNull(tracer.ActiveSpan); } Assert.IsNull(tracer.ActiveSpan); Assert.AreNotEqual(DateTime.MinValue, DateTime.Parse(span.ToString().Split(";")[5])); string[] actualSpanFields = span.ToString().Split(";"); string actualOperationName = actualSpanFields[0]; string startTimeSet = actualSpanFields[1]; string actualSpanContextTraceId = actualSpanFields[2]; string actualSpanContextSpanId = actualSpanFields[3]; string actualSpanContextReferenceTyp = actualSpanFields[4]; string endTimeSet = actualSpanFields[5]; Assert.AreEqual(expectedOperationName, actualOperationName); // toDO: Method for IDValidation Assert.IsNotNull(actualSpanContextTraceId); Assert.IsNotNull(actualSpanContextSpanId); Assert.AreEqual(References.ChildOf, actualSpanContextReferenceTyp); Assert.IsNotNull(startTimeSet); Assert.IsNotNull(endTimeSet); Assert.IsNotNull(DateTime.Parse(startTimeSet)); Assert.IsNotNull(DateTime.Parse(endTimeSet)); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { ISpan span = _tracer.BuildSpan("HttpRequest") .WithTag(Tags.SpanKind, Tags.SpanKindClient) .WithTag(Tags.Component, "LibWebAPI.Http") .WithTag(Tags.HttpMethod, request.Method.ToString()) .WithTag(Tags.HttpUrl, request.RequestUri.ToString()) .WithTag(Tags.PeerHostname, request.RequestUri.Host) .WithTag(Tags.PeerPort, request.RequestUri.Port) .Start(); _tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new HttpHeadersInjectAdapter(request.Headers)); HttpResponseMessage? response = null; Task <HttpResponseMessage>?requestTask = null; try { requestTask = base.SendAsync(request, cancellationToken); response = await requestTask; } catch (System.Net.Http.HttpRequestException e) { span.SetException(e); throw; } finally { if (response != null) { span.SetTag(Tags.HttpStatus, (int)response.StatusCode); } if (requestTask != null) { TaskStatus?requestTaskStatus = requestTask?.Status; if (requestTaskStatus == TaskStatus.Canceled || requestTaskStatus == TaskStatus.Faulted) { span.SetTag(Tags.Error, true); } } span.Finish(); } return(response); }
public static void Finish(this ISpan span, Exception e) { var status = e switch { ThreadAbortException _ => SpanStatus.Aborted, TaskCanceledException _ => SpanStatus.Cancelled, OperationCanceledException _ => SpanStatus.Cancelled, NotImplementedException _ => SpanStatus.Unimplemented, ArgumentOutOfRangeException _ => SpanStatus.OutOfRange, IndexOutOfRangeException _ => SpanStatus.OutOfRange, _ => SpanStatus.InternalError // _ => SpanStatus.UnknownError }; // TODO: Weak ref to Exception so that CaptureException later can find the span span.Finish(status); } }
private void PrintHello(ISpan rootSpan, string helloTo) { // 자식 Span 만들기 ISpan span = _tracer.BuildSpan("print-string") .AsChildOf(rootSpan) .Start(); try { _logger.LogInformation(helloTo); // Span 로그 span.Log(helloTo); } finally { span.Finish(); } }
internal static void AfterWrappedMethod <T>(ISpan span, Task <T> task) { if (AwsServiceHandler.UseDTWrapper) { if (span == null) { return; } var statusCode = GetHttpStatusCode(task); if (task.IsFaulted) { span.SetTag(Tags.Error, true); var ex = task.Exception; if (ex.InnerException != null) { if (ex.InnerException is AggregateException && ex.InnerException.InnerException != null) { span.SetException(ex.InnerException.InnerException); } else { span.SetException(ex.InnerException); } } else { span.SetException(ex); } } else if (task.IsCanceled) { span.SetTag(Tags.Error, true); } else if (statusCode != null && statusCode.HasValue) { span.SetTag(Tags.HttpStatus, statusCode.Value); } span.Finish(); } }