Skip to content

Commit

Permalink
Merge pull request #1 from nohwnd/restrict-access-to-metrics-by-port
Browse files Browse the repository at this point in the history
Add optional port restriction for /metrics endpoint
  • Loading branch information
phnx47 authored Feb 25, 2019
2 parents 4233ece + df6fd87 commit 26a6e47
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
22 changes: 15 additions & 7 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 @@ -36,8 +38,8 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a
throw new ArgumentException($"MapPath '{options.MapPath}' should start with '/'");

RegisterCollectors(options);

app.Map(options.MapPath, coreapp =>
Action<IApplicationBuilder> addMetricsHandler = coreapp =>
{
coreapp.Run(async context =>
{
Expand All @@ -51,18 +53,24 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a

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

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

return app;
Func<HttpContext, bool> portMatches = context => context.Connection.LocalPort == options.Port;
return app.Map(options.MapPath, cfg => cfg.MapWhen(portMatches, addMetricsHandler));
}


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 26a6e47

Please sign in to comment.