private async Task <AzureInstanceComputeMetadata> MakeAzureMetadataRequestAsync(string metadataRequestUrl) { AzureInstanceComputeMetadata requestResult = null; SdkInternalOperationsMonitor.Enter(); try { if (this.azureIMSRequestor != null) { requestResult = await this.azureIMSRequestor(metadataRequestUrl).ConfigureAwait(false); } else { requestResult = await this.MakeWebRequestAsync(metadataRequestUrl).ConfigureAwait(false); } } catch (Exception ex) { WindowsServerEventSource.Log.AzureInstanceMetadataRequestFailure( metadataRequestUrl, ex.Message, ex.InnerException != null ? ex.InnerException.Message : string.Empty); } finally { SdkInternalOperationsMonitor.Exit(); } return(requestResult); }
/// <summary> /// Retrieves the app id given the instrumentation key. /// </summary> /// <param name="instrumentationKey">Instrumentation key for which app id is to be retrieved.</param> /// <returns>App id.</returns> private async Task <string> FetchAppIdFromService(string instrumentationKey) { try { #if !NETCORE SdkInternalOperationsMonitor.Enter(); #endif Uri appIdEndpoint = this.GetAppIdEndPointUri(instrumentationKey); #if !NETCORE WebRequest request = WebRequest.Create(appIdEndpoint); request.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync().ConfigureAwait(false)) using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return(await reader.ReadToEndAsync()); } #else using (HttpClient client = new HttpClient()) { return(await client.GetStringAsync(appIdEndpoint).ConfigureAwait(false)); } #endif } finally { #if !NETCORE SdkInternalOperationsMonitor.Exit(); #endif } }
/// <summary> /// Retrieves the app id given the instrumentation key. /// </summary> /// <param name="instrumentationKey">Instrumentation key for which app id is to be retrieved.</param> /// <returns>App id.</returns> private Task <string> FetchAppIdFromService(string instrumentationKey) { return(Task.Factory.StartNew(() => { try { SdkInternalOperationsMonitor.Enter(); Uri appIdEndpoint = this.GetAppIdEndPointUri(instrumentationKey); WebRequest request = WebRequest.Create(appIdEndpoint); request.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } catch (Exception ex) { AppMapCorrelationEventSource.Log.FetchAppIdFailed(this.GetExceptionDetailString(ex)); return null; } finally { SdkInternalOperationsMonitor.Exit(); } })); }
/// <summary> /// Flushes the in-memory buffer and sends the telemetry items in <see cref="sendingInterval"/> intervals or when /// <see cref="startRunnerEvent" /> is set. /// </summary> private void Runner() { #if !NETSTANDARD1_3 SdkInternalOperationsMonitor.Enter(); try { #endif using (this.startRunnerEvent = new AutoResetEvent(false)) { while (this.enabled) { // Pulling all items from the buffer and sending as one transmission. this.DequeueAndSend(timeout: default(TimeSpan)); // when default(TimeSpan) is provided, value is ignored and default timeout of 100 sec is used // Waiting for the flush delay to elapse this.startRunnerEvent.WaitOne(this.sendingInterval); } } #if !NETSTANDARD1_3 } finally { SdkInternalOperationsMonitor.Exit(); } #endif }
/// <summary> /// Retrieves the app id given the instrumentation key. /// </summary> /// <param name="instrumentationKey">Instrumentation key for which app id is to be retrieved.</param> /// <returns>App id.</returns> private Task <string> FetchAppIdFromService(string instrumentationKey) { return(Task.Factory.StartNew(() => { try { SdkInternalOperationsMonitor.Enter(); Uri appIdEndpoint = this.GetAppIdEndPointUri(instrumentationKey); WebRequest request = WebRequest.Create(appIdEndpoint); request.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } finally { SdkInternalOperationsMonitor.Exit(); } })); }
public virtual void Initialize(TelemetryConfiguration configuration, TelemetryModules modules, string serializedConfiguration) { try { SdkInternalOperationsMonitor.Enter(); if (modules != null && !modules.Modules.Any(module => module is DiagnosticsTelemetryModule)) { // Create diagnostics module so configuration loading errors are reported to the portal modules.Modules.Add(new DiagnosticsTelemetryModule()); } configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer()); // Load configuration from the specified configuration if (!string.IsNullOrEmpty(serializedConfiguration)) { try { XDocument xml = XDocument.Parse(serializedConfiguration); LoadFromXml(configuration, modules, xml); } catch (XmlException exp) { CoreEventSource.Log.ConfigurationFileCouldNotBeParsedError(exp.Message); } } // If an environment variable exists with an instrumentation key then use it (instead) for the "blackfield" scenario. string environmentInstrumentationKey = PlatformSingleton.Current.GetEnvironmentVariable(InstrumentationKeyWebSitesEnvironmentVariable); if (!string.IsNullOrEmpty(environmentInstrumentationKey)) { configuration.InstrumentationKey = environmentInstrumentationKey; } // Creating the processor chain with default processor (transmissionprocessor) if none configured if (configuration.TelemetryProcessors == null) { configuration.TelemetryProcessorChainBuilder.Build(); } foreach (var telemetrySink in configuration.TelemetrySinks) { telemetrySink.Initialize(configuration); if (telemetrySink.TelemetryProcessorChain == null) { telemetrySink.TelemetryProcessorChainBuilder.Build(); } } InitializeComponents(configuration, modules); } finally { SdkInternalOperationsMonitor.Exit(); } }
/// <summary> /// Retrieves the app id given the instrumentation key. /// </summary> /// <param name="instrumentationKey">Instrumentation key for which app id is to be retrieved.</param> /// <returns>App id.</returns> private async Task <string> FetchAppIdFromService(string instrumentationKey) { #if NETSTANDARD1_6 string result = null; Uri appIdEndpoint = this.GetAppIdEndPointUri(instrumentationKey); using (HttpClient client = new HttpClient()) { var resultMessage = await client.GetAsync(appIdEndpoint).ConfigureAwait(false); if (resultMessage.IsSuccessStatusCode) { result = await resultMessage.Content.ReadAsStringAsync().ConfigureAwait(false); } else { this.RegisterFetchFailure(instrumentationKey, resultMessage.StatusCode); } } return(result); #else try { SdkInternalOperationsMonitor.Enter(); string result = null; Uri appIdEndpoint = this.GetAppIdEndPointUri(instrumentationKey); WebRequest request = WebRequest.Create(appIdEndpoint); request.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync().ConfigureAwait(false)) { if (response.StatusCode == HttpStatusCode.OK) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { result = await reader.ReadToEndAsync(); } } else { this.RegisterFetchFailure(instrumentationKey, response.StatusCode); } } return(result); } finally { SdkInternalOperationsMonitor.Exit(); } #endif }
private void TimerCallback(object state) { try { SdkInternalOperationsMonitor.Enter(); PerformanceCollectorEventSource.Log.CounterCollectionAttemptEvent(); var stopwatch = new Stopwatch(); stopwatch.Start(); this.EnsurePerformanceCountersRegistered(); var results = this.collector.Collect( (counterName, e) => PerformanceCollectorEventSource.Log.CounterReadingFailedEvent(e.ToString(), counterName)) .ToList(); stopwatch.Stop(); PerformanceCollectorEventSource.Log.CounterCollectionSuccessEvent( #pragma warning disable CA1829 // Use Length/Count property instead of Count() when available results.LongCount(), #pragma warning restore CA1829 // Use Length/Count property instead of Count() when available stopwatch.ElapsedMilliseconds); foreach (var result in results) { var telemetry = CreateTelemetry(result.Item1, result.Item2); try { this.client.Track(telemetry); } catch (InvalidOperationException e) { PerformanceCollectorEventSource.Log.TelemetrySendFailedEvent(e.ToString()); } } } catch (Exception e) { PerformanceCollectorEventSource.Log.UnknownErrorEvent(e.ToString()); } finally { if (this.timer != null) { this.timer.ScheduleNextTick(this.collectionPeriod); } SdkInternalOperationsMonitor.Exit(); } }
/// <summary> /// Flushes the in-memory buffer and sends it. /// </summary> internal void Flush(TimeSpan timeout) { SdkInternalOperationsMonitor.Enter(); try { this.DequeueAndSend(timeout); } finally { SdkInternalOperationsMonitor.Exit(); } }
public virtual void Initialize(TelemetryConfiguration configuration, TelemetryModules modules, string serializedConfiguration) { try { SdkInternalOperationsMonitor.Enter(); if (modules != null && !modules.Modules.Any(module => module is DiagnosticsTelemetryModule)) { // Create diagnostics module so configuration loading errors are reported to the portal modules.Modules.Add(new DiagnosticsTelemetryModule()); } configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer()); // Load configuration from the specified configuration if (!string.IsNullOrEmpty(serializedConfiguration)) { try { XDocument xml = XDocument.Parse(serializedConfiguration); LoadFromXml(configuration, modules, xml); } catch (XmlException exp) { CoreEventSource.Log.ConfigurationFileCouldNotBeParsedError(exp.Message); } } // Creating the processor chain with default processor (transmissionprocessor) if none configured if (configuration.TelemetryProcessors == null) { configuration.TelemetryProcessorChainBuilder.Build(); } foreach (var telemetrySink in configuration.TelemetrySinks) { telemetrySink.Initialize(configuration); if (telemetrySink.TelemetryProcessorChain == null) { telemetrySink.TelemetryProcessorChainBuilder.Build(); } } this.SelectInstrumentationKey(configuration); InitializeComponents(configuration, modules); } finally { SdkInternalOperationsMonitor.Exit(); } }
private async Task StartSending(Transmission transmission) { SdkInternalOperationsMonitor.Enter(); try { Exception exception = null; HttpWebResponseWrapper responseContent = null; // Locally self-throttle this payload before we send it Transmission acceptedTransmission = this.Throttle(transmission); // Now that we've self-imposed a throttle, we can try to send the remaining data try { TelemetryChannelEventSource.Log.TransmissionSendStarted(acceptedTransmission.Id); responseContent = await acceptedTransmission.SendAsync().ConfigureAwait(false); } catch (Exception e) { exception = e; } finally { int currentCapacity = Interlocked.Decrement(ref this.transmissionCount); if (exception == null) { TelemetryChannelEventSource.Log.TransmissionSentSuccessfully(acceptedTransmission.Id, currentCapacity); } else { TelemetryChannelEventSource.Log.TransmissionSendingFailedWarning(acceptedTransmission.Id, exception.ToString()); } if (responseContent == null && exception is WebException) { HttpWebResponse response = (HttpWebResponse)((WebException)exception).Response; responseContent = new HttpWebResponseWrapper() { StatusCode = (int)response.StatusCode, StatusDescription = response.StatusDescription, RetryAfterHeader = response.Headers?.Get("Retry-After") }; } this.OnTransmissionSent(new TransmissionProcessedEventArgs(acceptedTransmission, exception, responseContent)); } } finally { SdkInternalOperationsMonitor.Exit(); } }
public void FirstChanceExceptionStatisticsTelemetryModuleUsesSetsInternalOperationName() { var metrics = new List <KeyValuePair <Metric, double> >(); StubMetricProcessor stub = new StubMetricProcessor() { OnTrack = (m, v) => { metrics.Add(new KeyValuePair <Metric, double>(m, v)); } }; this.configuration.TelemetryInitializers.Add(new StubTelemetryInitializer() { OnInitialize = (item) => { item.Context.Operation.Name = TestOperationName; } }); using (var module = new FirstChanceExceptionStatisticsTelemetryModule()) { module.Initialize(this.configuration); module.MetricManager.MetricProcessors.Add(stub); SdkInternalOperationsMonitor.Enter(); try { try { // FirstChanceExceptionStatisticsTelemetryModule will process this exception throw new Exception("test"); } catch (Exception exc) { // code to prevent profiler optimizations Assert.Equal("test", exc.Message); } } finally { SdkInternalOperationsMonitor.Exit(); } } Assert.Equal(1, metrics.Count); Assert.Equal("Exceptions thrown", metrics[0].Key.Name); var dims = metrics[0].Key.Dimensions; Assert.Equal(2, dims.Count); Assert.True(dims.Contains(new KeyValuePair <string, string>(FirstChanceExceptionStatisticsTelemetryModule.OperationNameTag, "AI (Internal)"))); }
private void StateThreadWorker(CancellationToken cancellationToken) { SdkInternalOperationsMonitor.Enter(); var stopwatch = new Stopwatch(); TimeSpan?timeToNextUpdate = null; while (true) { var currentCallbackStarted = this.timeProvider.UtcNow; try { if (cancellationToken.IsCancellationRequested) { SdkInternalOperationsMonitor.Exit(); return; } stopwatch.Restart(); timeToNextUpdate = this.stateManager.UpdateState(this.config.InstrumentationKey, this.AuthenticationApiKey); QuickPulseEventSource.Log.StateTimerTickFinishedEvent(stopwatch.ElapsedMilliseconds); } catch (Exception e) { QuickPulseEventSource.Log.UnknownErrorEvent(e.ToInvariantString()); } // the catastrophic fallback is for the case when we've catastrophically failed some place above timeToNextUpdate = timeToNextUpdate ?? this.timings.CatastrophicFailureTimeout; // try to factor in the time spend in this tick when scheduling the next one so that the average period is close to the intended TimeSpan timeSpentInThisTick = this.timeProvider.UtcNow - currentCallbackStarted; TimeSpan timeLeftUntilNextTick = timeToNextUpdate.Value - timeSpentInThisTick; timeLeftUntilNextTick = timeLeftUntilNextTick > TimeSpan.Zero ? timeLeftUntilNextTick : TimeSpan.Zero; try { Task.Delay(timeLeftUntilNextTick, cancellationToken).GetAwaiter().GetResult(); } catch (OperationCanceledException) { } } }
/// <summary> /// Flushes the in-memory buffer and sends it. /// </summary> internal void Flush(TimeSpan timeout) { #if !NETSTANDARD1_3 SdkInternalOperationsMonitor.Enter(); try { #endif this.DequeueAndSend(timeout); #if !NETSTANDARD1_3 } finally { SdkInternalOperationsMonitor.Exit(); } #endif }
/// <summary> /// Flushes the in-memory buffer and sends it. /// </summary> internal void Flush(TimeSpan timeout) { #if !CORE_PCL SdkInternalOperationsMonitor.Enter(); try { #endif this.DequeueAndSend(timeout); #if !CORE_PCL } finally { SdkInternalOperationsMonitor.Exit(); } #endif }
public void FirstChanceExceptionStatisticsTelemetryModuleMarksOperationAsInternal() { var metrics = new List <KeyValuePair <Metric, double> >(); StubMetricProcessor stub = new StubMetricProcessor() { OnTrack = (m, v) => { metrics.Add(new KeyValuePair <Metric, double>(m, v)); } }; using (var module = new FirstChanceExceptionStatisticsTelemetryModule()) { module.Initialize(this.configuration); module.MetricManager.MetricProcessors.Add(stub); try { SdkInternalOperationsMonitor.Enter(); // FirstChanceExceptionStatisticsTelemetryModule will process this exception throw new Exception("test"); } catch (Exception exc) { // code to prevent profiler optimizations Assert.Equal("test", exc.Message); } finally { SdkInternalOperationsMonitor.Exit(); } } Assert.Equal(1, metrics.Count); Assert.Equal("Exceptions thrown", metrics[0].Key.Name); var dims = metrics[0].Key.Dimensions; Assert.Equal(2, dims.Count); string operationName; Assert.True(dims.TryGetValue(FirstChanceExceptionStatisticsTelemetryModule.OperationNameTag, out operationName)); Assert.Equal("AI (Internal)", operationName); }
private void CollectionThreadWorker(CancellationToken cancellationToken) { SdkInternalOperationsMonitor.Enter(); var stopwatch = new Stopwatch(); this.InitializeCollectionThread(); while (true) { try { if (cancellationToken.IsCancellationRequested) { this.CloseCollectionThread(); SdkInternalOperationsMonitor.Exit(); return; } stopwatch.Restart(); this.CollectData(); QuickPulseEventSource.Log.CollectionTimerTickFinishedEvent(stopwatch.ElapsedMilliseconds); } catch (Exception e) { QuickPulseEventSource.Log.UnknownErrorEvent(e.ToInvariantString()); } DateTimeOffset nextTick = this.collectionTimeSlotManager.GetNextCollectionTimeSlot(this.timeProvider.UtcNow); TimeSpan timeLeftUntilNextTick = nextTick - this.timeProvider.UtcNow; timeLeftUntilNextTick = timeLeftUntilNextTick > TimeSpan.Zero ? timeLeftUntilNextTick : TimeSpan.Zero; try { Task.Delay(timeLeftUntilNextTick, cancellationToken).GetAwaiter().GetResult(); } catch (OperationCanceledException) { } } }
private void CollectionThreadWorker(object state) { SdkInternalOperationsMonitor.Enter(); var stopwatch = new Stopwatch(); var threadState = (QuickPulseThreadState)state; this.InitializeCollectionThread(); while (true) { try { if (threadState.IsStopRequested) { this.CloseCollectionThread(); SdkInternalOperationsMonitor.Exit(); return; } stopwatch.Restart(); this.CollectData(); QuickPulseEventSource.Log.CollectionTimerTickFinishedEvent(stopwatch.ElapsedMilliseconds); } catch (Exception e) { QuickPulseEventSource.Log.UnknownErrorEvent(e.ToInvariantString()); } DateTimeOffset nextTick = this.collectionTimeSlotManager.GetNextCollectionTimeSlot(this.timeProvider.UtcNow); TimeSpan timeLeftUntilNextTick = nextTick - this.timeProvider.UtcNow; Thread.Sleep(timeLeftUntilNextTick > TimeSpan.Zero ? timeLeftUntilNextTick : TimeSpan.Zero); } }
/// <summary> /// Retrieves the Application Id given the Instrumentation Key. /// </summary> /// <param name="instrumentationKey">Instrumentation key for which Application Id is to be retrieved.</param> /// <returns>Task to resolve Application Id.</returns> private async Task <string> SendRequestAsync(string instrumentationKey) { try { SdkInternalOperationsMonitor.Enter(); var resultMessage = await this.GetAsync(instrumentationKey).ConfigureAwait(false); if (resultMessage.IsSuccessStatusCode) { return(await resultMessage.Content.ReadAsStringAsync().ConfigureAwait(false)); } else { this.FailedRequestsManager.RegisterFetchFailure(instrumentationKey, resultMessage.StatusCode); return(null); } } finally { SdkInternalOperationsMonitor.Exit(); } }
private async Task StartSending(Transmission transmission) { SdkInternalOperationsMonitor.Enter(); try { Exception exception = null; HttpWebResponseWrapper responseContent = null; // Locally self-throttle this payload before we send it Transmission acceptedTransmission = this.Throttle(transmission); // Now that we've self-imposed a throttle, we can try to send the remaining data try { TelemetryChannelEventSource.Log.TransmissionSendStarted(acceptedTransmission.Id); responseContent = await acceptedTransmission.SendAsync().ConfigureAwait(false); } catch (Exception e) { exception = e; } finally { int currentCapacity = Interlocked.Decrement(ref this.transmissionCount); if (exception != null) { TelemetryChannelEventSource.Log.TransmissionSendingFailedWarning(acceptedTransmission.Id, exception.ToString()); } else { if (responseContent != null) { if (responseContent.StatusCode < 400) { TelemetryChannelEventSource.Log.TransmissionSentSuccessfully(acceptedTransmission.Id, currentCapacity); } else { TelemetryChannelEventSource.Log.TransmissionSendingFailedWarning( acceptedTransmission.Id, responseContent.StatusCode.ToString(CultureInfo.InvariantCulture)); } if (TelemetryChannelEventSource.IsVerboseEnabled) { TelemetryChannelEventSource.Log.RawResponseFromAIBackend(acceptedTransmission.Id, responseContent.Content); } } } if (responseContent == null && exception is HttpRequestException) { // HttpClient.SendAsync throws HttpRequestException on the following scenarios: // "The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout." // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.sendasync?view=netstandard-1.6 responseContent = new HttpWebResponseWrapper() { // Expectation is that RetryPolicy will attempt retry for this status. StatusCode = ResponseStatusCodes.UnknownNetworkError }; } this.OnTransmissionSent(new TransmissionProcessedEventArgs(acceptedTransmission, exception, responseContent)); } } finally { SdkInternalOperationsMonitor.Exit(); } }