/// <summary>
        /// Initializes a new instance of the <see cref="PerformanceCollectorModule"/> class.
        /// </summary>
        public PerformanceCollectorModule()
        {
            this.Counters = new List <PerformanceCounterCollectionRequest>();

            this.collector = this.collector ?? (PerformanceCounterUtility.IsWebAppRunningInAzure() ?
                                                (IPerformanceCollector) new WebAppPerformanceCollector() : (IPerformanceCollector) new StandardPerformanceCollector());
        }
        internal void PerformanceCollectorBadStateTest(IPerformanceCollector collector)
        {
            var counters = new PerformanceCounter[]
            {
                new PerformanceCounter("Processor", "% Processor Time", "_Total123blabla"),
                new PerformanceCounter("Processor", "% Processor Time", "_Total")
            };

            foreach (var pc in counters)
            {
                try
                {
                    string error = null;
                    collector.RegisterCounter(
                        PerformanceCounterUtility.FormatPerformanceCounter(pc),
                        null,
                        true,
                        out error,
                        false);
                }
                catch (Exception)
                {
                }
            }

            Assert.IsTrue(collector.PerformanceCounters.First().IsInBadState);
            Assert.IsFalse(collector.PerformanceCounters.Last().IsInBadState);
        }
        private PerformanceCounter CreateCounter(
            string perfCounterName,
            IEnumerable <string> win32Instances,
            IEnumerable <string> clrInstances,
            out bool usesInstanceNamePlaceholder,
            out string error)
        {
            error = null;

            try
            {
                return(PerformanceCounterUtility.ParsePerformanceCounter(
                           perfCounterName,
                           win32Instances,
                           clrInstances,
                           out usesInstanceNamePlaceholder));
            }
            catch (Exception e)
            {
                usesInstanceNamePlaceholder = false;
                PerformanceCollectorEventSource.Log.CounterParsingFailedEvent(e.Message, perfCounterName);
                error = e.Message;

                return(null);
            }
        }
        private void RefreshCounter(
            PerformanceCounterData pcd,
            IEnumerable <string> win32Instances,
            IEnumerable <string> clrInstances)
        {
            string dummy;

            bool usesInstanceNamePlaceholder;
            var  pc = this.CreateCounter(
                pcd.OriginalString,
                win32Instances,
                clrInstances,
                out usesInstanceNamePlaceholder,
                out dummy);

            try
            {
                this.collector.RefreshPerformanceCounter(pcd, pc);

                PerformanceCollectorEventSource.Log.CounterRegisteredEvent(
                    PerformanceCounterUtility.FormatPerformanceCounter(pc));
            }
            catch (InvalidOperationException e)
            {
                PerformanceCollectorEventSource.Log.CounterRegistrationFailedEvent(
                    e.Message,
                    PerformanceCounterUtility.FormatPerformanceCounter(pc));
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Performs collection for all registered counters.
        /// </summary>
        /// <param name="onReadingFailure">Invoked when an individual counter fails to be read.</param>
        public IEnumerable <Tuple <PerformanceCounterData, double> > Collect(
            Action <string, Exception> onReadingFailure = null)
        {
            return(this.performanceCounters.Where(pc => !pc.Item1.IsInBadState).SelectMany(
                       pc =>
            {
                double value;

                try
                {
                    value = CollectCounter(pc.Item2);
                }
                catch (InvalidOperationException e)
                {
                    if (onReadingFailure != null)
                    {
                        onReadingFailure(
                            PerformanceCounterUtility.FormatPerformanceCounter(pc.Item2),
                            e);
                    }

                    return new Tuple <PerformanceCounterData, double>[] { };
                }

                return new[] { Tuple.Create(pc.Item1, value) };
            }));
        }
Exemplo n.º 6
0
        public PerformanceCounterStructure CreateCounter(
            string perfCounterName,
            bool supportInstanceNames,
            out bool usesInstanceNamePlaceholder,
            out string error)
        {
            error = null;

            try
            {
                return(PerformanceCounterUtility.ParsePerformanceCounter(
                           perfCounterName,
                           new string[] { },
                           new string[] { },
                           supportInstanceNames,
                           out usesInstanceNamePlaceholder));
            }
            catch (Exception e)
            {
                usesInstanceNamePlaceholder = false;
                PerformanceCollectorEventSource.Log.CounterParsingFailedEvent(e.Message, perfCounterName);
                error = e.Message;

                return(null);
            }
        }
Exemplo n.º 7
0
        private void RegisterCounter(
            string originalString,
            string reportAs,
            PerformanceCounterStructure pc,
            bool isCustomCounter,
            bool usesInstanceNamePlaceholder,
            out string error)
        {
            error = null;

            try
            {
                this.RegisterPerformanceCounter(
                    originalString,
                    reportAs,
                    pc.CategoryName,
                    pc.CounterName,
                    pc.InstanceName,
                    usesInstanceNamePlaceholder,
                    isCustomCounter);

                PerformanceCollectorEventSource.Log.CounterRegisteredEvent(
                    PerformanceCounterUtility.FormatPerformanceCounter(pc));
            }
            catch (InvalidOperationException e)
            {
                PerformanceCollectorEventSource.Log.CounterRegistrationFailedEvent(
                    e.Message,
                    PerformanceCounterUtility.FormatPerformanceCounter(pc));
                error = e.Message;
            }
        }
        internal void PerformanceCollectorAddRemoveCountersTest(StandardPerformanceCollector collector)
        {
            var counters = new[]
            {
                new PerformanceCounter("Processor", "% Processor Time", "_Total"),
                new PerformanceCounter("Memory", "Available Bytes", string.Empty)
            };

            foreach (var pc in counters)
            {
                string error;
                collector.RegisterCounter(
                    PerformanceCounterUtility.FormatPerformanceCounter(pc),
                    pc.GetHashCode().ToString(CultureInfo.InvariantCulture),
                    true,
                    out error,
                    false);
            }

            var twoCounters = collector.PerformanceCounters.ToArray();

            collector.RemoveCounter(@"\PROCESSOR(_Total)\% Processor Time", counters[0].GetHashCode().ToString(CultureInfo.InvariantCulture));

            var oneCounter = collector.PerformanceCounters.ToArray();

            Assert.AreEqual(2, twoCounters.Count());
            Assert.AreEqual(@"\Processor(_Total)\% Processor Time", twoCounters[0].OriginalString);
            Assert.AreEqual(@"\Memory\Available Bytes", twoCounters[1].OriginalString);

            Assert.AreEqual(@"\Memory\Available Bytes", oneCounter.Single().OriginalString);
        }
        internal void PerformanceCollectorAddRemoveCountersForWebAppTest(WebAppPerformanceCollector collector)
        {
            var counters = new[]
            {
                new PerformanceCounter("ASP.NET Applications", "Request Execution Time", "??APP_W3SVC_PROC??"),
                new PerformanceCounter("ASP.NET Applications", "Requests In Application Queue", "??APP_W3SVC_PROC??")
            };

            foreach (var pc in counters)
            {
                string error;
                collector.RegisterCounter(
                    PerformanceCounterUtility.FormatPerformanceCounter(pc),
                    pc.GetHashCode().ToString(CultureInfo.InvariantCulture),
                    true,
                    out error,
                    false);
            }

            var twoCounters = collector.PerformanceCounters.ToArray();

            collector.RemoveCounter(
                @"\ASP.NET APPLICATIONS(??APP_W3SVC_PROC??)\Request Execution Time",
                counters[0].GetHashCode().ToString(CultureInfo.InvariantCulture));

            var oneCounter = collector.PerformanceCounters.ToArray();

            Assert.AreEqual(2, twoCounters.Count());
            Assert.AreEqual(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time", twoCounters[0].OriginalString);
            Assert.AreEqual(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue", twoCounters[1].OriginalString);

            Assert.AreEqual(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue", oneCounter.Single().OriginalString);
        }
        /// <summary>
        /// Rebinds performance counters to Windows resources.
        /// </summary>
        public void RefreshPerformanceCounter(PerformanceCounterData pcd)
        {
            Tuple <PerformanceCounterData, ICounterValue> tupleToRemove = this.performanceCounters.FirstOrDefault(t => t.Item1 == pcd);

            if (tupleToRemove != null)
            {
                this.performanceCounters.Remove(tupleToRemove);
            }

            try
            {
                this.RegisterPerformanceCounter(
                    pcd.OriginalString,
                    pcd.ReportAs,
                    pcd.PerformanceCounter.CategoryName,
                    pcd.PerformanceCounter.CounterName,
                    pcd.PerformanceCounter.InstanceName,
                    pcd.UsesInstanceNamePlaceholder);
            }
            catch (InvalidOperationException e)
            {
                PerformanceCollectorEventSource.Log.CounterRegistrationFailedEvent(
                    e.Message,
                    PerformanceCounterUtility.FormatPerformanceCounter(pcd.PerformanceCounter));
            }
        }
        public void PerformanceCollectorBadStateTest()
        {
            var counters = new PerformanceCounter[]
            {
                new PerformanceCounter("Processor", "% Processor Time", "_Total123blabla"),
                new PerformanceCounter("Processor", "% Processor Time", "_Total")
            };

            IPerformanceCollector collector = new PerformanceCollector();

            foreach (var pc in counters)
            {
                try
                {
                    collector.RegisterPerformanceCounter(
                        PerformanceCounterUtility.FormatPerformanceCounter(pc),
                        null,
                        pc.CategoryName,
                        pc.CounterName,
                        pc.InstanceName,
                        false,
                        true);
                }
                catch (Exception)
                {
                }
            }

            Assert.IsTrue(collector.PerformanceCounters.First().IsInBadState);
            Assert.IsFalse(collector.PerformanceCounters.Last().IsInBadState);
        }
        public void PerformanceCollectorRefreshTest()
        {
            var counters = new PerformanceCounter[]
            {
                new PerformanceCounter("Processor", "% Processor Time", "_Total"),
                new PerformanceCounter("Processor", "% Processor Time", "_Total")
            };

            var newCounter = new PerformanceCounter("Memory", "Available Bytes", string.Empty);

            IPerformanceCollector collector = new PerformanceCollector();

            foreach (var pc in counters)
            {
                collector.RegisterPerformanceCounter(
                    PerformanceCounterUtility.FormatPerformanceCounter(pc),
                    null,
                    pc.CategoryName,
                    pc.CounterName,
                    pc.InstanceName,
                    false,
                    true);
            }

            collector.RefreshPerformanceCounter(collector.PerformanceCounters.Last(), newCounter);

            Assert.IsTrue(collector.PerformanceCounters.Last().PerformanceCounter.CategoryName == newCounter.CategoryName);
            Assert.IsTrue(collector.PerformanceCounters.Last().PerformanceCounter.CounterName == newCounter.CounterName);
            Assert.IsTrue(collector.PerformanceCounters.Last().PerformanceCounter.InstanceName == newCounter.InstanceName);
        }
        internal void PerformanceCollectorRefreshCountersTest(IPerformanceCollector collector)
        {
            var counters = new PerformanceCounter[]
            {
                new PerformanceCounter("Processor", "% Processor Time", "_Total123blabla"),
                new PerformanceCounter("Processor", "% Processor Time", "_Total"),
                new PerformanceCounter("Processor", "% Processor Time", "_Total123afadfdsdf"),
            };

            foreach (var pc in counters)
            {
                try
                {
                    string error = null;
                    collector.RegisterCounter(
                        PerformanceCounterUtility.FormatPerformanceCounter(pc),
                        null,
                        true,
                        out error,
                        false);
                }
                catch (Exception)
                {
                }
            }

            collector.RefreshCounters();

            // All bad state counters are removed and added later through register counter, and as a result, the order of the performance coutners is changed.
            Assert.AreEqual(collector.PerformanceCounters.First().PerformanceCounter.InstanceName, "_Total");
            Assert.AreEqual(collector.PerformanceCounters.Last().PerformanceCounter.InstanceName, "_Total123afadfdsdf");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Registers a counter using the counter name and reportAs value to the total list of counters.
        /// </summary>
        /// <param name="perfCounter">Name of the performance counter.</param>
        /// <param name="reportAs">Report as name for the performance counter.</param>
        /// <param name="isCustomCounter">Boolean to check if the performance counter is custom defined.</param>
        /// <param name="error">Captures the error logged.</param>
        /// <param name="blockCounterWithInstancePlaceHolder">Boolean that controls the registry of the counter based on the availability of instance place holder.</param>
        public void RegisterCounter(
            string perfCounter,
            string reportAs,
            bool isCustomCounter,
            out string error,
            bool blockCounterWithInstancePlaceHolder)
        {
            try
            {
                bool useInstancePlaceHolder = false;
                var  pc = PerformanceCounterUtility.CreateAndValidateCounter(perfCounter, null, null, out useInstancePlaceHolder, out error);

                if (pc != null)
                {
                    this.RegisterPerformanceCounter(perfCounter, this.GetCounterReportAsName(perfCounter, reportAs), pc.CategoryName, pc.CounterName, pc.InstanceName, useInstancePlaceHolder, false);
                }
                else
                {
                    // Even if validation failed, we might still be able to collect perf counter in WebApp.
                    this.RegisterPerformanceCounter(perfCounter, this.GetCounterReportAsName(perfCounter, reportAs), string.Empty, perfCounter, string.Empty, useInstancePlaceHolder, false);
                }
            }
            catch (Exception e)
            {
                PerformanceCollectorEventSource.Log.WebAppCounterRegistrationFailedEvent(
                    e.Message,
                    perfCounter);
                error = e.Message;
            }
        }
        /// <summary>
        /// Registers a counter using the counter name and reportAs value to the total list of counters.
        /// </summary>
        /// <param name="perfCounterName">Name of the performance counter.</param>
        /// <param name="reportAs">Report as name for the performance counter.</param>
        /// <param name="isCustomCounter">Boolean to check if the performance counter is custom defined.</param>
        /// <param name="error">Captures the error logged.</param>
        /// <param name="blockCounterWithInstancePlaceHolder">Boolean that controls the registry of the counter based on the availability of instance place holder.</param>
        public void RegisterCounter(
            string perfCounterName,
            string reportAs,
            bool isCustomCounter,
            out string error,
            bool blockCounterWithInstancePlaceHolder = false)
        {
            bool usesInstanceNamePlaceholder;

            if (!this.dependendentInstancesLoaded)
            {
                this.LoadDependentInstances();
                this.dependendentInstancesLoaded = true;
            }

            var pc = PerformanceCounterUtility.CreateAndValidateCounter(
                perfCounterName,
                this.win32Instances,
                this.clrInstances,
                out usesInstanceNamePlaceholder,
                out error);

            // If blockCounterWithInstancePlaceHolder is true, then we register the counter only if usesInstanceNamePlaceHolder is true.
            if (pc != null && !(blockCounterWithInstancePlaceHolder && usesInstanceNamePlaceholder))
            {
                this.RegisterCounter(perfCounterName, reportAs, pc, isCustomCounter, usesInstanceNamePlaceholder, out error);
            }
        }
Exemplo n.º 16
0
        private void InitializeServiceClient(TelemetryConfiguration configuration)
        {
            if (this.serviceClient != null)
            {
                // service client has been passed through a constructor, we don't need to do anything
                return;
            }

            Uri serviceEndpointUri;

            if (string.IsNullOrWhiteSpace(this.QuickPulseServiceEndpoint))
            {
                // endpoint is not specified in configuration, use the default one
                serviceEndpointUri = QuickPulseDefaults.ServiceEndpoint;
            }
            else
            {
                // endpoint appears to have been specified in configuration, try using it
                try
                {
                    serviceEndpointUri = new Uri(this.QuickPulseServiceEndpoint);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  "Error initializing QuickPulse module. QPS endpoint is not a correct URI: '{0}'",
                                  this.QuickPulseServiceEndpoint),
                              e);
                }
            }

            // create the default production implementation of the service client with the best service endpoint we could get
            string instanceName    = GetInstanceName(configuration);
            string streamId        = GetStreamId();
            string machineName     = Environment.MachineName;
            var    assemblyVersion = SdkVersionUtils.GetSdkVersion(null);
            bool   isWebApp        = PerformanceCounterUtility.IsWebAppRunningInAzure();
            int?   processorCount  = PerformanceCounterUtility.GetProcessorCount(isWebApp);

            this.serviceClient = new QuickPulseServiceClient(
                serviceEndpointUri,
                instanceName,
                streamId,
                machineName,
                assemblyVersion,
                this.timeProvider,
                isWebApp,
                processorCount ?? 0);

            QuickPulseEventSource.Log.TroubleshootingMessageEvent(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Service client initialized. Endpoint: '{0}', instance name: '{1}', assembly version: '{2}'",
                    serviceEndpointUri,
                    instanceName,
                    assemblyVersion));
        }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.isInitialized)
            {
                lock (this.lockObject)
                {
                    if (!this.isInitialized)
                    {
                        PerformanceCollectorEventSource.Log.ModuleIsBeingInitializedEvent(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Custom counters count: '{0}'",
                                Counters?.Count ?? 0));

                        if (configuration == null)
                        {
                            throw new ArgumentNullException(nameof(configuration));
                        }

                        if (!this.defaultCountersInitialized)
                        {
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time", @"\Process(??APP_WIN32_PROC??)\% Processor Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized", @"\Process(??APP_WIN32_PROC??)\% Processor Time Normalized"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Memory\Available Bytes", @"\Memory\Available Bytes"));
#if !NETSTANDARD2_0 // Exclude those counters which don't exist for .netcore
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests/Sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec", @"\.NET CLR Exceptions(??APP_CLR_PROC??)\# of Exceps Thrown / sec"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Request Execution Time"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue", @"\ASP.NET Applications(??APP_W3SVC_PROC??)\Requests In Application Queue"));
#endif
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\Private Bytes", @"\Process(??APP_WIN32_PROC??)\Private Bytes"));
                            this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec", @"\Process(??APP_WIN32_PROC??)\IO Data Bytes/sec"));
                            if (!PerformanceCounterUtility.IsWebAppRunningInAzure())
                            {
                                this.DefaultCounters.Add(new PerformanceCounterCollectionRequest(@"\Processor(_Total)\% Processor Time", @"\Processor(_Total)\% Processor Time"));
                            }
                        }

                        if (!this.EnableIISExpressPerformanceCounters && IsRunningUnderIisExpress())
                        {
                            PerformanceCollectorEventSource.Log.RunningUnderIisExpress();
                            return;
                        }

                        this.telemetryConfiguration = configuration;
                        this.client = new TelemetryClient(configuration);
                        this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion(PerformanceCounterUtility.SDKVersionPrefix());

                        this.lastRefreshTimestamp = DateTime.MinValue;

                        this.timer = new Timer(this.TimerCallback);

                        // schedule the first tick
                        this.timer.ScheduleNextTick(this.collectionPeriod);
                        this.isInitialized = true;
                    }
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        /// <param name="configuration">TelemetryConfiguration passed to the module.</param>
        public void Initialize(TelemetryConfiguration configuration)
        {
            if (!this.IsInitialized)
            {
                lock (this.moduleInitializationLock)
                {
                    if (!this.IsInitialized)
                    {
                        QuickPulseEventSource.Log.ModuleIsBeingInitializedEvent(
                            this.QuickPulseServiceEndpoint,
                            this.DisableFullTelemetryItems,
                            this.DisableTopCpuProcesses,
                            this.AuthenticationApiKey);

                        QuickPulseEventSource.Log.TroubleshootingMessageEvent("Validating configuration...");
                        ValidateConfiguration(configuration);
                        this.config = configuration;

                        QuickPulseEventSource.Log.TroubleshootingMessageEvent("Initializing members...");
                        this.collectionTimeSlotManager = this.collectionTimeSlotManager ?? new QuickPulseCollectionTimeSlotManager();

                        this.performanceCollector = this.performanceCollector ?? PerformanceCounterUtility.GetPerformanceCollector();

                        this.timeProvider    = this.timeProvider ?? new Clock();
                        this.topCpuCollector = this.topCpuCollector
                                               ?? new QuickPulseTopCpuCollector(this.timeProvider, new QuickPulseProcessProvider(PerfLib.GetPerfLib()));
                        this.timings = this.timings ?? QuickPulseTimings.Default;

                        CollectionConfigurationError[] errors;
                        this.collectionConfiguration = new CollectionConfiguration(
                            new CollectionConfigurationInfo()
                        {
                            ETag = string.Empty
                        },
                            out errors,
                            this.timeProvider);
                        this.dataAccumulatorManager = this.dataAccumulatorManager ?? new QuickPulseDataAccumulatorManager(this.collectionConfiguration);

                        this.InitializeServiceClient(configuration);

                        this.stateManager = new QuickPulseCollectionStateManager(
                            this.ServiceClient,
                            this.timeProvider,
                            this.timings,
                            this.OnStartCollection,
                            this.OnStopCollection,
                            this.OnSubmitSamples,
                            this.OnReturnFailedSamples,
                            this.OnUpdatedConfiguration,
                            this.OnUpdatedServiceEndpoint);

                        this.CreateStateThread();

                        this.IsInitialized = true;
                    }
                }
            }
        }
        /// <summary>
        /// Binds processes to performance counters instance names and adds performance counters to the collection.
        /// </summary>
        /// <remarks>This operation is expensive, but must be done periodically to account for IIS changing instance names
        /// of the counters it reports Web Sites on as worker processes start and terminate.</remarks>
        private void EnsurePerformanceCountersRegistered()
        {
            if (DateTime.Now - this.lastRefreshTimestamp < this.registrationPeriod)
            {
                // re-registration period hasn't elapsed yet, do nothing
                return;
            }

            PerformanceCounterUtility.InvalidatePlaceholderCache();

            if (this.lastRefreshTimestamp == DateTime.MinValue)
            {
                // this is the initial registration, register everything
                this.ProcessCustomCounters();

                string error;
                var    errors = new List <string>();

                foreach (PerformanceCounterCollectionRequest req in this.DefaultCounters.Union(this.Counters))
                {
                    this.collector.RegisterCounter(
                        req.PerformanceCounter,
                        req.ReportAs,
                        true,
                        out error,
                        false);

                    if (!string.IsNullOrWhiteSpace(error))
                    {
                        errors.Add(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Counter {0}: {1}",
                                req.PerformanceCounter,
                                error));
                    }
                }

                if (errors.Any())
                {
                    // send out the unified error message
                    PerformanceCollectorEventSource.Log.CounterCheckConfigurationEvent(
                        errors.Count.ToString(CultureInfo.InvariantCulture),
                        string.Join(Environment.NewLine, errors));
                }
            }
            else
            {
                // this is a periodic refresh
                this.collector.RefreshCounters();
            }

            // as per MSDN, we need to wait at least 1s before proceeding with counter collection
            Thread.Sleep(TimeSpan.FromSeconds(1));

            this.lastRefreshTimestamp = DateTime.Now;
        }
        /// <summary>
        ///  Initializes a new instance of the <see cref="XPlatProcessCPUPerformanceCounterNormalized" /> class.
        /// </summary>
        internal XPlatProcessCPUPerformanceCounterNormalized() : base()
        {
            int?count = PerformanceCounterUtility.GetProcessorCount();

            if (count.HasValue)
            {
                this.processorsCount = count.Value;
                this.isInitialized   = true;
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NormalizedCPUPercentageGauge"/> class.
        /// </summary>
        /// <param name="name"> Name of the SumUpCountersGauge.</param>
        /// <param name="value"> Gauges to sum.</param>
        public NormalizedCPUPercentageGauge(string name, ICounterValue value) : base(name, value)
        {
            int?count = PerformanceCounterUtility.GetProcessorCount();

            if (count.HasValue)
            {
                this.processorsCount = count.Value;
                this.isInitialized   = true;
            }
        }
Exemplo n.º 22
0
        public void PerformanceCounterUtilitySanityTest()
        {
            var win32Instances = PerformanceCounterUtility.GetWin32ProcessInstances();
            var clrInstances   = PerformanceCounterUtility.GetClrProcessInstances();

            var win32Instance = PerformanceCounterUtility.GetInstanceForWin32Process(win32Instances);
            var clrInstance   = PerformanceCounterUtility.GetInstanceForClrProcess(clrInstances);

            PerformanceCounterUtility.GetInstanceForCurrentW3SvcWorker();
        }
        private void WriteSamples(IEnumerable <QuickPulseDataSample> samples, string instrumentationKey, Stream stream, CollectionConfigurationError[] errors)
        {
            var monitoringPoints = new List <MonitoringDataPoint>();

            foreach (var sample in samples)
            {
                var metricPoints = new List <MetricPoint>();

                metricPoints.AddRange(CreateDefaultMetrics(sample));

                metricPoints.AddRange(
                    sample.PerfCountersLookup.Select(counter => new MetricPoint {
                    Name = counter.Key, Value = Round(counter.Value), Weight = 1,
                }));

                metricPoints.AddRange(CreateCalculatedMetrics(sample));

                ITelemetryDocument[] documents = sample.TelemetryDocuments.ToArray();
                Array.Reverse(documents);

                ProcessCpuData[] topCpuProcesses =
                    sample.TopCpuData.Select(p => new ProcessCpuData()
                {
                    ProcessName = p.Item1, CpuPercentage = p.Item2,
                }).ToArray();

                var dataPoint = new MonitoringDataPoint
                {
                    Version                        = this.version,
                    InvariantVersion               = MonitoringDataPoint.CurrentInvariantVersion,
                    InstrumentationKey             = instrumentationKey,
                    Instance                       = this.instanceName,
                    RoleName                       = this.roleName,
                    StreamId                       = this.streamId,
                    MachineName                    = this.machineName,
                    Timestamp                      = sample.EndTimestamp.UtcDateTime,
                    IsWebApp                       = this.isWebApp,
                    PerformanceCollectionSupported = PerformanceCounterUtility.IsPerfCounterSupported(),
                    ProcessorCount                 = this.processorCount,
                    Metrics                        = metricPoints.ToArray(),
                    Documents                      = documents,
                    GlobalDocumentQuotaReached     = sample.GlobalDocumentQuotaReached,
                    TopCpuProcesses                = topCpuProcesses.Length > 0 ? topCpuProcesses : null,
                    TopCpuDataAccessDenied         = sample.TopCpuDataAccessDenied,
                    CollectionConfigurationErrors  = errors,
                };

                monitoringPoints.Add(dataPoint);
            }

            this.serializerDataPointArray.WriteObject(stream, monitoringPoints.ToArray());
        }
Exemplo n.º 24
0
        /// <summary>
        ///  Initializes a new instance of the <see cref="NormalizedProcessCPUPerformanceCounter" /> class.
        /// </summary>
        /// <param name="categoryName">The counter category name.</param>
        /// <param name="counterName">The counter name.</param>
        /// <param name="instanceName">The instance name.</param>
        internal NormalizedProcessCPUPerformanceCounter(string categoryName, string counterName, string instanceName)
        {
            int?count = PerformanceCounterUtility.GetProcessorCount(false);

            if (count.HasValue)
            {
                this.processorsCount = count.Value;

                this.performanceCounter = new PerformanceCounter("Process", "% Processor Time", instanceName, true);

                this.isInitialized = true;
            }
        }
        public void ParsePerformanceCounterTest()
        {
            PerformanceCounter pc;

            pc = PerformanceCounterUtility.ParsePerformanceCounter(@"\Processor(_Total)\% Processor Time", null, null);
            Assert.AreEqual("Processor", pc.CategoryName);
            Assert.AreEqual("% Processor Time", pc.CounterName);
            Assert.AreEqual("_Total", pc.InstanceName);

            pc = PerformanceCounterUtility.ParsePerformanceCounter(@"\Memory\Available Memory", null, null);
            Assert.AreEqual("Memory", pc.CategoryName);
            Assert.AreEqual("Available Memory", pc.CounterName);
            Assert.AreEqual(string.Empty, pc.InstanceName);
        }
Exemplo n.º 26
0
 public void GetCollectorReturnsWebAppCollector()
 {
     try
     {
         Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", "something");
         var actual = PerformanceCounterUtility.GetPerformanceCollector();
         Assert.AreEqual("WebAppPerformanceCollector", actual.GetType().Name);
     }
     finally
     {
         PerformanceCounterUtility.isAzureWebApp = null;
         Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", string.Empty);
         Task.Delay(1000).Wait();
     }
 }
Exemplo n.º 27
0
        public void ParsePerformanceCounterTest()
        {
            PerformanceCounterStructure pc;

            bool usesInstanceNamePlaceholder;

            pc = PerformanceCounterUtility.ParsePerformanceCounter(@"\Processor(_Total)\% Processor Time", null, null, true, out usesInstanceNamePlaceholder);
            Assert.AreEqual("Processor", pc.CategoryName);
            Assert.AreEqual("% Processor Time", pc.CounterName);
            Assert.AreEqual("_Total", pc.InstanceName);

            pc = PerformanceCounterUtility.ParsePerformanceCounter(@"\Memory\Available Memory", null, null, true, out usesInstanceNamePlaceholder);
            Assert.AreEqual("Memory", pc.CategoryName);
            Assert.AreEqual("Available Memory", pc.CounterName);
            Assert.AreEqual(string.Empty, pc.InstanceName);
        }
Exemplo n.º 28
0
        public void GetCollectorReturnsCorrectCollector()
        {
            try
            {
                var actual = PerformanceCounterUtility.GetPerformanceCollector();
#if NETCOREAPP2_0
                Assert.AreEqual("StandardPerformanceCollector", actual.GetType().Name);
#else // NET452
                Assert.AreEqual("StandardPerformanceCollector", actual.GetType().Name);
#endif
            }
            finally
            {
                PerformanceCounterUtility.isAzureWebApp = null;
            }
        }
 /// <summary>
 /// Returns the current value of the counter as a <c ref="MetricTelemetry"/>.
 /// </summary>
 /// <returns>Value of the counter.</returns>
 public double Collect()
 {
     try
     {
         return(this.performanceCounter.NextValue());
     }
     catch (Exception e)
     {
         throw new InvalidOperationException(
                   string.Format(
                       CultureInfo.CurrentCulture,
                       Resources.PerformanceCounterReadFailed,
                       PerformanceCounterUtility.FormatPerformanceCounter(this.performanceCounter)),
                   e);
     }
 }
        public void GetCollectorReturnsXPlatformCollectorForNonWindows()
        {
#if NETCOREAPP2_0
            var original = PerformanceCounterUtility.IsWindows;
            try
            {
                PerformanceCounterUtility.IsWindows = false;
                var actual = PerformanceCounterUtility.GetPerformanceCollector();
                Assert.AreEqual("PerformanceCollectorXPlatform", actual.GetType().Name);
            }
            finally
            {
                PerformanceCounterUtility.IsWindows     = original;
                PerformanceCounterUtility.isAzureWebApp = null;
            }
#endif
        }