Exemplo n.º 1
0
        public void RegisterMetrics(ICollectorRegistry registry)
        {
            MetricFactory metricFactory = Prometheus.Metrics.WithCustomRegistry(registry);
            var           counter       = metricFactory.CreateCounter("gc_collect_count", "GC collection count",
                                                                      _lableNames.Union(new[] { "generation" }).ToArray());

            for (var number = 0; number <= GC.MaxGeneration; number++)
            {
                _collectionCounts.Add(counter.Labels(_labelValues.Union(new[] { number.ToString() }).ToArray()));
            }

            _startTime = metricFactory
                         .CreateGauge("start_time", "Start time of the process since unix epoch in seconds", _lableNames)
                         .Labels(_labelValues);
            _cpuTotal = metricFactory.CreateCounter("cpu_seconds_total",
                                                    "Total user and system CPU time spent in seconds", _lableNames).Labels(_labelValues);
            _virtualMemorySize = metricFactory.CreateGauge("virtual_bytes", "Process virtual memory size", _lableNames).Labels(_labelValues);
            _workingSet        = metricFactory.CreateGauge("working_set", "Process working set", _lableNames).Labels(_labelValues);
            _privateMemorySize = metricFactory.CreateGauge("private_bytes", "Process private memory size", _lableNames).Labels(_labelValues);
            _openHandles       = metricFactory.CreateGauge("open_handles", "Number of open handles", _lableNames).Labels(_labelValues);
            _numThreads        = metricFactory.CreateGauge("num_threads", "Total number of threads", _lableNames).Labels(_labelValues);
            _pid         = metricFactory.CreateGauge("processid", "Process ID", _lableNames).Labels(_labelValues);
            _totalMemory = metricFactory.CreateGauge("totalmemory", "Total known allocated memory", _lableNames).Labels(_labelValues);
            _startTime.Set((_process.StartTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                           .TotalSeconds);
            _pid.Set(_process.Id);
        }
Exemplo n.º 2
0
 public void RegisterMetrics(ICollectorRegistry registry)
 {
     registry.GetOrAdd(txBytes);
     registry.GetOrAdd(rxBytes);
     signal = Metrics.WithCustomRegistry(registry)
              .CreateGauge("CAPsMAN_Clients_Signal", "CAPsMAN Client's signal", "MAC", "IP", "Hostname");
 }
Exemplo n.º 3
0
 public static async Task ProcessAsync(ICollectorRegistry registry, Stream outputStream)
 {
     using (var metricsWriter = new MetricsTextWriter(outputStream))
     {
         await registry.CollectToAsync(metricsWriter).ConfigureAwait(false);
     }
 }
Exemplo n.º 4
0
        public void RegisterMetrics(ICollectorRegistry registry)
        {
            var metrics = Metrics.WithCustomRegistry(registry);

            var collectionCountsParent = metrics.CreateCounter("dotnet_collection_count_total", "GC collection count", new[] { "generation" });

            for (var gen = 0; gen <= GC.MaxGeneration; gen++)
            {
                _collectionCounts.Add(collectionCountsParent.Labels(gen.ToString()));
            }

            // Metrics that make sense to compare between all operating systems
            // Keep the help text synchronized with the Go implementation to avoid pushgateway conflicts.
            // See https://github.com/prometheus/pushgateway/issues/194
            // and https://github.com/prometheus-net/prometheus-net/issues/89
            _startTime = metrics.CreateGauge("process_start_time_seconds", "Start time of the process since unix epoch in seconds.");
            _cpuTotal  = metrics.CreateCounter("process_cpu_seconds_total", "Total user and system CPU time spent in seconds.");

            _virtualMemorySize = metrics.CreateGauge("process_windows_virtual_bytes", "Process virtual memory size");
            _workingSet        = metrics.CreateGauge("process_windows_working_set", "Process working set");
            _privateMemorySize = metrics.CreateGauge("process_windows_private_bytes", "Process private memory size");
            _openHandles       = metrics.CreateGauge("process_windows_open_handles", "Number of open handles");
            _numThreads        = metrics.CreateGauge("process_windows_num_threads", "Total number of threads");
            _pid = metrics.CreateGauge("process_windows_processid", "Process ID");

            // .net specific metrics
            _totalMemory = metrics.CreateGauge("dotnet_totalmemory", "Total known allocated memory");
            _perfErrors  = metrics.CreateCounter("dotnet_collection_errors_total", "Total number of errors that occured during collections");

            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            _startTime.Set((_process.StartTime.ToUniversalTime() - epoch).TotalSeconds);
            _pid.Set(_process.Id);
        }
    public MotorMetricsFactory(
        IOptions <PrometheusOptions> options,
        IApplicationNameService nameService
        )
    {
        var prometheusConfig = options.Value ?? throw new ArgumentNullException(nameof(options), "Prometheus config doesn't exist.");

        _collectorRegistry = prometheusConfig.CollectorRegistryInstance ?? Prometheus.Client.Metrics.DefaultCollectorRegistry;

        _collectorRegistry.GetOrAdd(
            ThreadPoolGauge.ThreadPoolGaugeConfig,
            _ => new ThreadPoolGauge()
            );
        _metricFactory = new MetricFactory(_collectorRegistry);

        var counter = _metricFactory.CreateCounter(
            "motor_extensions_hosting_build_info",
            "A metric with a constant '1' value labeled by version, libversion, and framework from which the service was built.",
            "version", "libversion", "framework"
            );

        counter.WithLabels(
            nameService.GetVersion(),
            nameService.GetLibVersion(),
            RuntimeInformation.FrameworkDescription
            ).Inc();
    }
 public static void Process(ICollectorRegistry registry, Stream outputStream)
 {
     using (var metricsWriter = new MetricsTextWriter(outputStream))
     {
         registry.CollectTo(metricsWriter);
     }
 }
        public static ICollectorRegistry UseDotNetStats(this ICollectorRegistry registry, string prefixName)
        {
            registry.Add(new GCCollectionCountCollector(prefixName));
            registry.Add(new GCTotalMemoryCollector(prefixName));

            return(registry);
        }
Exemplo n.º 8
0
        public static ICollectorRegistry UseDefaultCollectors(this ICollectorRegistry registry, string prefixName)
        {
            registry.UseDotNetStats(prefixName);
            registry.UseProcessStats(prefixName);

            return(registry);
        }
Exemplo n.º 9
0
        public static ICollectorRegistry UseDefaultCollectors(this ICollectorRegistry registry)
        {
            registry.UseDotNetStats();
            registry.UseProcessStats();

            return(registry);
        }
        public static ICollectorRegistry UseDotNetStats(this ICollectorRegistry registry)
        {
            registry.Add(nameof(GCCollectionCountCollector), new GCCollectionCountCollector());
            registry.Add(nameof(GCTotalMemoryCollector), new GCTotalMemoryCollector());

            return(registry);
        }
        public MetricPusher(ICollectorRegistry collectorRegistry, string endpoint, string job, string instance, IEnumerable <KeyValuePair <string, string> > labels)
        {
            if (string.IsNullOrEmpty(job))
            {
                throw new ArgumentNullException(nameof(job));
            }

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            var stringBuilder = new StringBuilder(endpoint.TrimEnd('/') + "/metrics/job/" + job);

            if (!string.IsNullOrEmpty(instance))
            {
                stringBuilder.Append("/instance/" + instance);
            }

            if (labels != null)
            {
                foreach (var pair in labels.Where(l => !string.IsNullOrEmpty(l.Key) && !string.IsNullOrEmpty(l.Value)))
                {
                    stringBuilder.Append("/" + pair.Key + "/" + pair.Value);
                }
            }

            if (!Uri.TryCreate(stringBuilder.ToString(), UriKind.Absolute, out _targetUri))
            {
                throw new ArgumentException("Endpoint must be a valid url", nameof(endpoint));
            }

            _collectorRegistry = collectorRegistry ?? CollectorRegistry.Instance;
            _httpClient        = new HttpClient();
        }
Exemplo n.º 12
0
            public Startup(ICollectorRegistry _registry)
            {
                this._registry = _registry;
                var builder = new ConfigurationBuilder();

                Configuration = builder.Build();
            }
Exemplo n.º 13
0
        public MetricPusher(ICollectorRegistry collectorRegistry, string endpoint, string job, Dictionary <string, string> additionalHeaders, string instance,
                            IEnumerable <KeyValuePair <string, string> > labels)
        {
            if (string.IsNullOrEmpty(job))
            {
                throw new ArgumentNullException(nameof(job));
            }

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException(nameof(endpoint));
            }

            var stringBuilder = new StringBuilder(endpoint);

            if (!endpoint.EndsWith("/"))
            {
                stringBuilder.Append("/");
            }

            stringBuilder
            .Append("metrics/job/")
            .Append(job);

            if (!string.IsNullOrEmpty(instance))
            {
                stringBuilder
                .Append("/instance/")
                .Append(instance);
            }

            if (labels != null)
            {
                foreach (var pair in labels.Where(l => !string.IsNullOrEmpty(l.Key) && !string.IsNullOrEmpty(l.Value)))
                {
                    stringBuilder
                    .Append("/")
                    .Append(pair.Key)
                    .Append("/")
                    .Append(pair.Value);
                }
            }

            if (!Uri.TryCreate(stringBuilder.ToString(), UriKind.Absolute, out _targetUri))
            {
                throw new ArgumentException("Endpoint must be a valid url", nameof(endpoint));
            }

            _collectorRegistry = collectorRegistry ?? CollectorRegistry.Instance;
            _httpClient        = new HttpClient();
            foreach (KeyValuePair <string, string> header in additionalHeaders)
            {
                _httpClient.DefaultRequestHeaders.Add(
                    header.Key,
                    header.Value
                    );
            }
        }
Exemplo n.º 14
0
 public MetricServer(string hostname, int port, string url = "metrics/", ICollectorRegistry registry = null)
 {
     _registry = registry ?? DefaultCollectorRegistry.Instance;
     _httpListener.Prefixes.Add(string.Format("http://{0}:{1}/{2}", hostname, port, url));
     if (_registry == DefaultCollectorRegistry.Instance)
     {
         DefaultCollectorRegistry.Instance.RegisterStandardPerfCounters();
     }
 }
Exemplo n.º 15
0
        public static MemoryStream Process(ICollectorRegistry registry)
        {
            // leave open
            var stream = new MemoryStream();

            Process(registry, stream);
            stream.Position = 0;
            return(stream);
        }
            public Startup(ICollectorRegistry registry, string url)
            {
                _registry = registry;
                _url      = url;

                var builder = new ConfigurationBuilder();

                Configuration = builder.Build();
            }
Exemplo n.º 17
0
            public Startup(ICollectorRegistry registry, string mapPath)
            {
                _registry = registry;
                _mapPath  = mapPath;

                var builder = new ConfigurationBuilder();

                Configuration = builder.Build();
            }
Exemplo n.º 18
0
 public static void Process(ICollectorRegistry registry, Stream outputStream)
 {
     using (var metricsWriter = new MetricsTextWriter(outputStream))
     {
         foreach (var collector in registry.Enumerate())
         {
             collector.Collect(metricsWriter);
         }
     }
 }
        protected static Stream CollectionToStreamWriter(ICollectorRegistry registry)
        {
            var metrics = registry.CollectAll();
            var stream  = new MemoryStream();

            ScrapeHandler.ProcessScrapeRequest(metrics, ContentType, stream);

            stream.Position = 0;
            return(stream);
        }
Exemplo n.º 20
0
        public static MemoryStream Process(ICollectorRegistry registry)
        {
            // leave open
            var stream    = new MemoryStream();
            var collected = registry.CollectAll();

            TextFormatter.Format(stream, collected.ToArray());
            stream.Position = 0;
            return(stream);
        }
Exemplo n.º 21
0
        protected void ResetFactories()
        {
            _registry = new CollectorRegistry();
            _factory  = new MetricFactory(_registry);

            _theirRegistry      = Their.Prometheus.Metrics.NewCustomRegistry();
            _theirMetricFactory = Their.Prometheus.Metrics.WithCustomRegistry(_theirRegistry);

            GC.Collect();
        }
Exemplo n.º 22
0
 public MetricServer(string hostname,
                     int port,
                     string pathBase,
                     IEnumerable <IOnDemandCollector> standardCollectors = null,
                     ICollectorRegistry registry = null)
     : this(standardCollectors, registry)
 {
     _pathBase    = pathBase;
     _hostAddress = $"http://{hostname}:{port}/";
 }
Exemplo n.º 23
0
        public static async Task <MemoryStream> ProcessAsync(ICollectorRegistry registry)
        {
            // leave open
            var stream = new MemoryStream();

            await ProcessAsync(registry, stream);

            stream.Position = 0;
            return(stream);
        }
        /// <inheritdoc />
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="host">Host</param>
        /// <param name="port">Port</param>
        /// <param name="mapPath">Map Path: should start with '/'</param>
        /// <param name="registry">Collector registry</param>
        /// <param name="collectors">IOnDemandCollectors</param>
        /// <param name="useHttps">use Https</param>
        /// <param name="useDefaultCollectors">Use default collectors</param>
        public MetricServer(string host, int port, string mapPath, ICollectorRegistry registry, List <IOnDemandCollector> collectors, bool useHttps,
                            bool useDefaultCollectors)
            : base(registry, collectors, useDefaultCollectors)
        {
            if (!mapPath.StartsWith("/"))
            {
                throw new ArgumentException($"mapPath '{mapPath}' should start with '/'");
            }

            _httpListener.Prefixes.Add($"http{(useHttps ? "s" : "")}://{host}:{port}{mapPath.TrimEnd('/')}/");
        }
Exemplo n.º 25
0
        /// <summary>
        /// Custom metrics server without basic auth
        /// </summary>
        public MetricsCustomServer(int port, string hostname = "localhost", string url = "metrics/", ICollectorRegistry registry = null, bool useHttps = false)
        {
            this.hostname = hostname;
            this.port     = port;
            this.url      = url;
            this.registry = registry;
            this.useHttps = useHttps;
            var s = useHttps ? "s" : "";

            _httpListener.Prefixes.Add($"http{s}://{hostname}:{port}/{url}/");
            _registry = registry ?? DefaultCollectorRegistry.Instance;
        }
Exemplo n.º 26
0
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="registry">Collector registry</param>
        /// <param name="collectors">IOnDemandCollectors</param>
        /// <param name="useDefaultCollectors">Use default collectors</param>
        protected BaseMetricServer(ICollectorRegistry registry, List <IOnDemandCollector> collectors, bool useDefaultCollectors)
        {
            Registry = registry ?? CollectorRegistry.Instance;
            if (useDefaultCollectors)
            {
                var metricFactory = Registry == CollectorRegistry.Instance
                    ? Metrics.DefaultFactory
                    : new MetricFactory(Registry);

                collectors.AddRange(DefaultCollectors.Get(metricFactory));
            }

            Registry.RegisterOnDemandCollectors(collectors);
        }
        public static void CopyTo(this ICollectorRegistry registry, string collectorName, ICollectorRegistry destination)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if (!registry.TryGet(collectorName, out var collector))
            {
                throw new ArgumentOutOfRangeException(nameof(collectorName), collectorName, "Collector does not exist in the source registry");
            }

            destination.Add(collector);
        }
Exemplo n.º 28
0
        public MetricServer(string hostname, int port, IEnumerable<IOnDemandCollector> standardCollectors = null, string url = "metrics/", ICollectorRegistry registry = null)
        {
            _registry = registry ?? DefaultCollectorRegistry.Instance;
            _httpListener.Prefixes.Add(string.Format("http://{0}:{1}/{2}", hostname, port, url));
            if (_registry == DefaultCollectorRegistry.Instance)
            {
                // Default to DotNetStatsCollector if none speified
                // For no collectors, pass an empty collection
                if (standardCollectors == null)
                    standardCollectors = new[] {new DotNetStatsCollector()};

                DefaultCollectorRegistry.Instance.RegisterOnDemandCollectors(standardCollectors);
            }
        }
Exemplo n.º 29
0
        /// <inheritdoc />
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="host">Host</param>
        /// <param name="port">Port</param>
        /// <param name="mapPath">Map Path: Should strar with '/'</param>
        /// <param name="registry">Collector registry</param>
        /// <param name="collectors">IOnDemandCollectors</param>
        /// <param name="certificate">Certificate for Https</param>
        /// <param name="useDefaultCollectors">Use default collectors</param>
        public MetricServer(string host, int port, string mapPath, ICollectorRegistry registry, List <IOnDemandCollector> collectors, X509Certificate2 certificate,
                            bool useDefaultCollectors)
            : base(registry, collectors, useDefaultCollectors)
        {
            if (!mapPath.StartsWith("/"))
            {
                throw new ArgumentException($"mapPath '{mapPath}' should start with '/'");
            }

            _certificate = certificate;
            _port        = port;
            _hostName    = host;
            _mapPath     = mapPath;
        }
Exemplo n.º 30
0
        private MetricServer(IEnumerable <IOnDemandCollector> standardCollectors = null, ICollectorRegistry registry = null)
        {
            _registry = registry ?? CollectorRegistry.Instance;
            if (_registry != CollectorRegistry.Instance)
            {
                return;
            }

            if (standardCollectors == null)
            {
                standardCollectors = new[] { new DotNetStatsCollector() };
            }

            CollectorRegistry.Instance.RegisterOnDemandCollectors(standardCollectors);
        }
        /// <summary>
        ///     Constructor
        /// </summary>
        protected BaseMetricServer(IEnumerable <IOnDemandCollector> standardCollectors, ICollectorRegistry registry)
        {
            Registry = registry ?? CollectorRegistry.Instance;

            if (Registry != CollectorRegistry.Instance)
            {
                return;
            }

            if (standardCollectors != null)
            {
                _standardCollectors = standardCollectors;
            }

            CollectorRegistry.Instance.RegisterOnDemandCollectors(_standardCollectors);
        }
        public static void MoveTo(this ICollectorRegistry registry, string collectorName, ICollectorRegistry destination)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            var collector = registry.Remove(collectorName);

            if (collector == null)
            {
                throw new ArgumentOutOfRangeException(nameof(collectorName), collectorName, "Collector does not exist in the source registry");
            }

            destination.Add(collector);
        }
Exemplo n.º 33
0
 public MetricServer(int port, IEnumerable<IOnDemandCollector> standardCollectors = null, string url = "metrics/", ICollectorRegistry registry = null)
     : this("+", port, standardCollectors, url, registry)
 {
 }
Exemplo n.º 34
0
 public MetricFactory(ICollectorRegistry registry)
 {
     _registry = registry;
 }
Exemplo n.º 35
0
 public static MetricFactory WithCustomRegistry(ICollectorRegistry registry)
 {
     return new MetricFactory(registry);
 }
Exemplo n.º 36
0
 public MetricServer(int port, string url = "metrics/", ICollectorRegistry registry = null)
     : this("+", port, url, registry)
 {
 }