Skip to content

Commit

Permalink
Add optional port restriction for /metrics endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
nohwnd committed Feb 25, 2019
1 parent 4233ece commit e6ac027
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
23 changes: 18 additions & 5 deletions src/Prometheus.Client.AspNetCore/PrometheusExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System;
using System.Net;
using System.Threading.Tasks;
using Prometheus.Client.Collectors;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace Prometheus.Client.AspNetCore
{
Expand Down Expand Up @@ -37,6 +39,19 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a

RegisterCollectors(options);

if (options.Port == null)
{
MapToRoute(app, options);
return app;
}

Func<HttpContext, bool> portMatches = context => context.Connection.LocalPort == options.Port;
app.MapWhen(portMatches, coreapp => MapToRoute(coreapp, options));
return app;
}

private static void MapToRoute(IApplicationBuilder app, PrometheusOptions options)
{
app.Map(options.MapPath, coreapp =>
{
coreapp.Run(async context =>
Expand All @@ -52,17 +67,15 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a
await Task.FromResult(0).ConfigureAwait(false);
});
});

return app;
}


private static void RegisterCollectors(PrometheusOptions options)
{
if (options.UseDefaultCollectors)
{
var metricFactory = options.CollectorRegistryInstance == CollectorRegistry.Instance
? Metrics.DefaultFactory
var metricFactory = options.CollectorRegistryInstance == CollectorRegistry.Instance
? Metrics.DefaultFactory
: new MetricFactory(options.CollectorRegistryInstance);

options.Collectors.AddRange(DefaultCollectors.Get(metricFactory));
Expand Down
7 changes: 6 additions & 1 deletion src/Prometheus.Client.AspNetCore/PrometheusOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ public class PrometheusOptions
/// </summary>
public string MapPath { get; set; } = "/metrics";

/// <summary>
/// When specified only allow access to metrics on this port, otherwise return 404, default = null.
/// </summary>
public int? Port { get; set; }

/// <summary>
/// CollectorRegistry intance
/// </summary>
Expand All @@ -29,4 +34,4 @@ public class PrometheusOptions
/// </summary>
public bool UseDefaultCollectors { get; set; } = true;
}
}
}

0 comments on commit e6ac027

Please sign in to comment.