public void Configure(IApplicationBuilder app)
            {
                app.Run(context =>
                {
                    if (context.Request.Path == _url)
                    {
                        var response        = context.Response;
                        var request         = context.Request;
                        response.StatusCode = 200;

                        var acceptHeader     = request.Headers["Accept"];
                        var contentType      = ScrapeHandler.GetContentType(acceptHeader);
                        response.ContentType = contentType;

                        using (var outputStream = response.Body)
                        {
                            var collected = _registry.CollectAll();
                            ScrapeHandler.ProcessScrapeRequest(collected, contentType, outputStream);
                        }

                        return(Task.FromResult(true));
                    }

                    context.Response.StatusCode = 404;
                    return(Task.FromResult(true));
                });
            }
        public void Handle(IHttpRequest request, IHttpResponse response)
        {
            // Largely cribbed from https://github.com/prometheus-net/prometheus-net/blob/master/Prometheus.NetStandard/MetricServer.cs

            MetricFamily[] metrics;

            try
            {
                metrics = _registry.CollectAll().ToArray();

                _logger.Trace($"{nameof(MetricsActivityHandler)}.{nameof(Handle)}",
                              new LogItem("Event", "CollectAll result"),
                              new LogItem("MetricsCount", metrics.Length));

                var acceptHeader  = request.RequestHeader["Accept"];
                var acceptHeaders = acceptHeader?.Split(',');

                var contentType = ScrapeHandler.GetContentType(acceptHeaders);


                response.HttpStatusCode = HttpStatusCode.OK;

                response.HttpContent = new MetricsHttpContent(_logger, metrics, contentType);
            }
            catch (Exception ex)
            {
                _logger.Error($"{nameof(MetricsActivityHandler)}.{nameof(Handle)}",
                              new LogItem("Event", "ScrapeFailed"),
                              new LogItem("Exception", ex.Message),
                              new LogItem("StackTrace", ex.StackTrace));

                response.HttpStatusCode = HttpStatusCode.ServiceUnavailable;
                response.SetStringContent(ex.Message);
            }
        }
        private void StartListen()
        {
            _httpListener.Start();
            IsRunning = true;

            while (IsRunning)
            {
                try
                {
                    var context  = _httpListener.GetContext();
                    var response = context.Response;
                    response.ContentType = Defaults.ContentType;

                    using (var outputStream = response.OutputStream)
                    {
                        ScrapeHandler.Process(Registry, outputStream);
                    }
                }

                catch (HttpListenerException ex)
                {
                    Trace.WriteLine($"Error in MetricServer: {ex}");
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Enables an endpoint which exposes metrics that can be consumed by Prometheus server
        /// </summary>
        /// <param name="app"></param>
        /// <param name="endpoint">The endpoint where the metrics are exposed. /metrics by default</param>
        /// <param name="collectorRegistry"></param>
        public static void UsePrometheus(this IApplicationBuilder app, string endpoint = "/metrics", ICollectorRegistry collectorRegistry = null)
        {
            var registry = collectorRegistry ?? DefaultCollectorRegistry.Instance;

            if (registry == DefaultCollectorRegistry.Instance)
            {
                DefaultCollectorRegistry.Instance.RegisterOnDemandCollectors(new[] { new DotNetStatsCollector() });
            }

            app.Map(endpoint, builder =>
            {
                builder.Run(context =>
                {
                    var acceptHeaders = context.Request.Headers["Accept"];
                    var contentType   = ScrapeHandler.GetContentType(acceptHeaders);

                    context.Response.ContentType = contentType;

                    using (var stream = context.Response.Body)
                    {
                        var collected = registry.CollectAll();
                        ScrapeHandler.ProcessScrapeRequest(collected, contentType, stream);
                    }

                    return(Task.FromResult(0));
                });
            });
        }
 public void CollectAndSerialize()
 {
     using (var stream = new NullStream())
     {
         ScrapeHandler.Process(_registry, stream);
     }
 }
Ejemplo n.º 6
0
        public IActionResult Index()
        {
            try
            {
                var metrics = _registry.CollectAll().ToArray();

                _logger.Trace($"{nameof(MetricsController)}.{nameof(Handle)}",
                              new LogItem("Event", "CollectAll result"),
                              new LogItem("MetricsCount", metrics.Length));

                var acceptHeader  = Request.Headers["Accept"];
                var acceptHeaders = acceptHeader.ToArray();

                var contentType = ScrapeHandler.GetContentType(acceptHeaders);

                var metricsContent = new MetricsHttpContent(_logger, metrics, contentType);
                Response.StatusCode  = (int)HttpStatusCode.OK;
                Response.ContentType = contentType;
                metricsContent.WriteToStream(Response.Body);

                return(new EmptyResult());
            }
            catch (Exception ex)
            {
                _logger.Error($"{nameof(MetricsController)}.{nameof(Handle)}",
                              new LogItem("Event", "ScrapeFailed"),
                              new LogItem("Exception", ex.Message),
                              new LogItem("StackTrace", ex.StackTrace));


                return(StatusCode((int)HttpStatusCode.ServiceUnavailable, ex.Message));
            }
        }
Ejemplo n.º 7
0
 public void CollectAndSerialize()
 {
     using (var stream = Stream.Null)
     {
         ScrapeHandler.ProcessAsync(_registry, stream).GetAwaiter().GetResult();
     }
 }
Ejemplo n.º 8
0
 public async Task Get()
 {
     Response.StatusCode = 200;
     using (var outputStream = Response.Body)
     {
         await ScrapeHandler.ProcessAsync(_registry, outputStream);
     }
 }
Ejemplo n.º 9
0
 public void Get()
 {
     Response.StatusCode = 200;
     using (var outputStream = Response.Body)
     {
         ScrapeHandler.Process(CollectorRegistry.Instance, outputStream);
     }
 }
        /// <inheritdoc />
        public async Task PushAsync()
        {
            var memoryStream = ScrapeHandler.Process(_collectorRegistry);
            var response     = await _httpClient.PostAsync(_targetUri, new StreamContent(memoryStream));

            response.EnsureSuccessStatusCode();
            memoryStream.Dispose();
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     Add PrometheusServer request execution pipeline.
        /// </summary>
        public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder app, Action <PrometheusOptions> setupOptions)
        {
            var options = new PrometheusOptions
            {
                CollectorRegistryInstance = (ICollectorRegistry)app.ApplicationServices.GetService(typeof(ICollectorRegistry)) ?? Metrics.DefaultCollectorRegistry
            };

            setupOptions?.Invoke(options);

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

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

            if (!options.MapPath.StartsWith("/"))
            {
                throw new ArgumentException($"MapPath '{options.MapPath}' should start with '/'");
            }

            if (options.UseDefaultCollectors)
            {
                options.CollectorRegistryInstance.UseDefaultCollectors(options.MetricPrefixName);
            }

            var contentType = "text/plain; version=0.0.4";

            if (options.ResponseEncoding != null)
            {
                contentType += $"; charset={options.ResponseEncoding.BodyName}";
            }

            void AddMetricsHandler(IApplicationBuilder coreapp)
            {
                coreapp.Run(async context =>
                {
                    var response = context.Response;

                    response.ContentType = contentType;

                    using var outputStream = response.Body;
                    await ScrapeHandler.ProcessAsync(options.CollectorRegistryInstance, outputStream);
                });
            }

            if (options.Port == null)
            {
                return(app.Map(options.MapPath, AddMetricsHandler));
            }

            bool PortMatches(HttpContext context) => context.Connection.LocalPort == options.Port;

            return(app.Map(options.MapPath, cfg => cfg.MapWhen(PortMatches, AddMetricsHandler)));
        }
        public void should_send_metrics_and_get_success()
        {
            var memoryStream = new MemoryStream();

            ScrapeHandler.ProcessScrapeRequest(_metrics.CollectAll(), null, memoryStream);
            var expectedResult = Encoding.UTF8.GetString(memoryStream.ToArray());

            Assert.Equal(expectedResult, _result);
        }
Ejemplo n.º 13
0
 public static string GenerateOutput()
 {
     using (var outputStream = new MemoryStream())
     {
         var collected = DefaultCollectorRegistry.Instance.CollectAll();
         ScrapeHandler.ProcessScrapeRequest(collected, "text/plain", outputStream);
         return(Encoding.UTF8.GetString(outputStream.ToArray()));
     }
 }
Ejemplo n.º 14
0
        private static string ConfigureHeaders(HttpListenerContext httpListenerContext)
        {
            httpListenerContext.Response.StatusCode = 200;
            var acceptHeader  = httpListenerContext.Request.Headers.Get("Accept");
            var acceptHeaders = acceptHeader == null ? null : acceptHeader.Split(',');
            var contentType   = ScrapeHandler.GetContentType(acceptHeaders);

            httpListenerContext.Response.ContentType = contentType;
            return(contentType);
        }
        protected static Stream CollectionToStreamWriter(ICollectorRegistry registry)
        {
            var metrics = registry.CollectAll();
            var stream  = new MemoryStream();

            ScrapeHandler.ProcessScrapeRequest(metrics, ContentType, stream);

            stream.Position = 0;
            return(stream);
        }
Ejemplo n.º 16
0
 public void WriteMetrics(HttpListenerResponse response, string contentType, IEnumerable <MetricFamily> metricFamily)
 {
     using (var outputStream = response.OutputStream)
     {
         try
         {
             ScrapeHandler.ProcessScrapeRequest(metricFamily, contentType, outputStream);
         }
         catch (HttpListenerException) { }
     }
 }
        /// <summary>
        ///     Add PrometheusServer request execution pipeline.
        /// </summary>
        public static IAppBuilder UsePrometheusServer(this IAppBuilder app, Action <PrometheusOptions> setupOptions)
        {
            var options = new PrometheusOptions();

            setupOptions?.Invoke(options);

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

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

            if (!options.MapPath.StartsWith("/"))
            {
                throw new ArgumentException($"MapPath '{options.MapPath}' should start with '/'");
            }

            RegisterCollectors(options);

            app.Map(options.MapPath, coreapp =>
            {
                coreapp.Run(async context =>
                {
                    var req      = context.Request;
                    var response = context.Response;

                    var acceptHeader  = req.Headers.Get("Accept");
                    var acceptHeaders = acceptHeader?.Split(',');
                    var contentType   = ScrapeHandler.GetContentType(acceptHeaders);

                    response.ContentType = contentType;

                    using (var outputStream = response.Body)
                    {
                        var collected = options.CollectorRegistryInstance.CollectAll();
                        ScrapeHandler.ProcessScrapeRequest(collected, contentType, outputStream);
                    }

                    await Task.FromResult(0).ConfigureAwait(false);
                });
            });

            return(app);
        }
            public void Configure(IApplicationBuilder app)
            {
                app.Map(_mapPath, coreapp =>
                {
                    coreapp.Run(async context =>
                    {
                        var response         = context.Response;
                        response.ContentType = _contentType;

                        using (var outputStream = response.Body)
                        {
                            await ScrapeHandler.ProcessAsync(_registry, outputStream);
                        }
                    });
                });
            }
        public void WriteToStream(Stream stream)
        {
            _logger.Trace($"{nameof(MetricsHttpContent)}.{nameof(WriteToStream)}",
                          new LogItem("Event", "ProcessScrapeRequest"));

            try
            {
                ScrapeHandler.ProcessScrapeRequest(_metrics, _contentType, stream);
            }
            catch (Exception ex)
            {
                _logger.Error($"{nameof(MetricsHttpContent)}.{nameof(WriteToStream)}",
                              new LogItem("Event", "ProcessScrapeRequest failed"),
                              new LogItem("Exception", ex.Message),
                              new LogItem("StackTrace", ex.StackTrace));
            }
        }
        private void StartListen()
        {
            var cancel = _cancellation.Token;

            while (!_cancellation.IsCancellationRequested)
            {
                try
                {
                    var getContext = _httpListener.GetContextAsync();
                    getContext.Wait(cancel);
                    if (cancel.IsCancellationRequested)
                    {
                        return;
                    }

                    var context  = getContext.Result;
                    var request  = context.Request;
                    var response = context.Response;

                    var rawUrl = request.RawUrl.EndsWith("/") ? request.RawUrl : request.RawUrl + "/";

                    if (rawUrl == _mapPath)
                    {
                        response.StatusCode  = 200;
                        response.ContentType = _contentType;
                        using (var outputStream = response.OutputStream)
                        {
                            ScrapeHandler.ProcessAsync(_registry, outputStream).GetAwaiter().GetResult();
                        }
                    }
                    else
                    {
                        response.StatusCode = 404;
                        using (var outputStream = response.OutputStream)
                        {
                        }
                    }
                }

                catch (Exception ex)
                {
                    Trace.WriteLine($"Error in MetricServer: {ex}");
                }
            }
        }
Ejemplo n.º 21
0
            public void Configure(IApplicationBuilder app)
            {
                app.Map(_mapPath, coreapp =>
                {
                    coreapp.Run(async context =>
                    {
                        var response         = context.Response;
                        response.ContentType = Defaults.ContentType;

                        using (var outputStream = response.Body)
                        {
                            ScrapeHandler.Process(_registry, outputStream);
                        }

                        await Task.FromResult(0).ConfigureAwait(false);
                    });
                });
            }
Ejemplo n.º 22
0
        public IActionResult Get()
        {
            var registry      = CollectorRegistry.Instance;
            var acceptHeaders = Request.Headers["Accept"];
            var contentType   = ScrapeHandler.GetContentType(acceptHeaders);

            Response.ContentType = contentType;
            string content;

            using (var outputStream = new MemoryStream())
            {
                var collected = registry.CollectAll();
                ScrapeHandler.ProcessScrapeRequest(collected, contentType, outputStream);
                content = Encoding.UTF8.GetString(outputStream.ToArray());
            }

            return(Ok(content));
        }
Ejemplo n.º 23
0
        public void Index()
        {
            var response = HttpContext.Response;
            var request  = HttpContext.Request;

            response.StatusCode = 200;

            var acceptHeader = request.Headers["Accept"];
            var contentType  = ScrapeHandler.GetContentType(acceptHeader);

            response.ContentType = contentType;

            using (var outputStream = response.Body)
            {
                var collected = DefaultCollectorRegistry.Instance.CollectAll();
                ScrapeHandler.ProcessScrapeRequest(collected, contentType, outputStream);
            };
        }
Ejemplo n.º 24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            var collectorRegistry = DefaultCollectorRegistry.Instance;

            collectorRegistry.RegisterOnDemandCollectors(new [] {
                new DotNetStatsCollector()
            });

            app.Map("/metrics", appConfig => {
                appConfig.Run(async context =>
                {
                    var acceptHeader = context.Request.Headers["Accept"];
                    var contentType  = ScrapeHandler.GetContentType(acceptHeader);

                    context.Response.ContentType = contentType;

                    using (var outputStream = context.Response.Body)
                    {
                        ScrapeHandler.ProcessScrapeRequest(collectorRegistry.CollectAll(),
                                                           contentType, outputStream);
                    }

                    await Task.FromResult(0).ConfigureAwait(false);
                });
            });
        }
Ejemplo n.º 25
0
        private static Task Handle(HttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            if (request.Method == HttpMethods.Get)
            {
                _counter.Inc();

                var registry = CollectorRegistry.Instance;
                response.StatusCode = 200;
                ScrapeHandler.Process(registry, response.Body);
            }
            else
            {
                response.StatusCode = StatusCodes.Status405MethodNotAllowed;
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     Add PrometheusServer request execution pipeline.
        /// </summary>
        public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder app, Action <PrometheusOptions> setupOptions)
        {
            var options = new PrometheusOptions();

            setupOptions?.Invoke(options);

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

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

            if (!options.MapPath.StartsWith("/"))
            {
                throw new ArgumentException($"MapPath '{options.MapPath}' should start with '/'");
            }

            RegisterCollectors(options);

            app.Map(options.MapPath, coreapp =>
            {
                coreapp.Run(async context =>
                {
                    var response         = context.Response;
                    response.ContentType = "text/plain; version=0.0.4";

                    using (var outputStream = response.Body)
                    {
                        ScrapeHandler.Process(options.CollectorRegistryInstance, outputStream);
                    }

                    await Task.FromResult(0).ConfigureAwait(false);
                });
            });

            return(app);
        }
Ejemplo n.º 27
0
            public void Configure(IApplicationBuilder app)
            {
                app.Run(context =>
                {
                    if (context.Request.Path == _mapPath)
                    {
                        var response         = context.Response;
                        response.ContentType = Defaults.ContentType;

                        using (var outputStream = response.Body)
                        {
                            ScrapeHandler.Process(_registry, outputStream);
                        }

                        return(Task.FromResult(true));
                    }

                    context.Response.StatusCode = 404;
                    return(Task.FromResult(true));
                });
            }
        private void StartListen()
        {
            _httpListener.Start();
            IsRunning = true;

            while (IsRunning)
            {
                try
                {
                    var context  = _httpListener.GetContext();
                    var request  = context.Request;
                    var response = context.Response;

                    var rawUrl = request.RawUrl.EndsWith("/") ? request.RawUrl : request.RawUrl + "/";

                    if (rawUrl == _mapPath)
                    {
                        response.StatusCode  = 200;
                        response.ContentType = Defaults.ContentType;
                        using (var outputStream = response.OutputStream)
                        {
                            ScrapeHandler.Process(Registry, outputStream);
                        }
                    }
                    else
                    {
                        response.StatusCode = 404;
                        using (var outputStream = response.OutputStream)
                        {
                        }
                    }
                }

                catch (HttpListenerException ex)
                {
                    Trace.WriteLine($"Error in MetricServer: {ex}");
                }
            }
        }
        private static void GetMetrics(HttpContext httpContext)
        {
            var syncIoFeature = httpContext.Features.Get <IHttpBodyControlFeature>();

            if (syncIoFeature != null)
            {
                syncIoFeature.AllowSynchronousIO = true;
            }

            var request  = httpContext.Request;
            var response = httpContext.Response;

            var acceptHeaders = request.Headers["Accept"];

            response.ContentType = ScrapeHandler.GetContentType(acceptHeaders);
            response.StatusCode  = (int)HttpStatusCode.OK;

            using var outputStream = response.Body;
            var collected = DefaultCollectorRegistry.Instance.CollectAll();

            ScrapeHandler.ProcessScrapeRequest(collected, response.ContentType, outputStream);
        }
Ejemplo n.º 30
0
        private void StartListen()
        {
            _httpListener.Start();
            IsRunning = true;

            while (IsRunning)
            {
                try
                {
                    var context  = _httpListener.GetContext();
                    var request  = context.Request;
                    var response = context.Response;

                    var inputStream = request.InputStream;
                    var encoding    = request.ContentEncoding;
                    var reader      = new StreamReader(inputStream, encoding);
                    reader.ReadToEnd();
                    response.StatusCode = 200;

                    var acceptHeader  = request.Headers.Get("Accept");
                    var acceptHeaders = acceptHeader?.Split(',');
                    var contentType   = ScrapeHandler.GetContentType(acceptHeaders);
                    response.ContentType = contentType;

                    using (var outputStream = response.OutputStream)
                    {
                        var collected = Registry.CollectAll();
                        ScrapeHandler.ProcessScrapeRequest(collected, contentType, outputStream);
                    }
                }

                catch (HttpListenerException ex)
                {
                    Trace.WriteLine($"Error in MetricServer: {ex}");
                }
            }
        }