Skip to content

Commit 26a6e47

Browse files
authored
Merge pull request #1 from nohwnd/restrict-access-to-metrics-by-port
Add optional port restriction for /metrics endpoint
2 parents 4233ece + df6fd87 commit 26a6e47

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

src/Prometheus.Client.AspNetCore/PrometheusExtensions.cs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
using System;
1+
using System;
2+
using System.Net;
23
using System.Threading.Tasks;
34
using Prometheus.Client.Collectors;
45
using Microsoft.AspNetCore.Builder;
6+
using Microsoft.AspNetCore.Http;
57

68
namespace Prometheus.Client.AspNetCore
79
{
@@ -36,8 +38,8 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a
3638
throw new ArgumentException($"MapPath '{options.MapPath}' should start with '/'");
3739

3840
RegisterCollectors(options);
39-
40-
app.Map(options.MapPath, coreapp =>
41+
42+
Action<IApplicationBuilder> addMetricsHandler = coreapp =>
4143
{
4244
coreapp.Run(async context =>
4345
{
@@ -51,18 +53,24 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a
5153

5254
await Task.FromResult(0).ConfigureAwait(false);
5355
});
54-
});
56+
};
57+
58+
if (options.Port == null)
59+
{
60+
return app.Map(options.MapPath, addMetricsHandler);
61+
}
5562

56-
return app;
63+
Func<HttpContext, bool> portMatches = context => context.Connection.LocalPort == options.Port;
64+
return app.Map(options.MapPath, cfg => cfg.MapWhen(portMatches, addMetricsHandler));
5765
}
5866

5967

6068
private static void RegisterCollectors(PrometheusOptions options)
6169
{
6270
if (options.UseDefaultCollectors)
6371
{
64-
var metricFactory = options.CollectorRegistryInstance == CollectorRegistry.Instance
65-
? Metrics.DefaultFactory
72+
var metricFactory = options.CollectorRegistryInstance == CollectorRegistry.Instance
73+
? Metrics.DefaultFactory
6674
: new MetricFactory(options.CollectorRegistryInstance);
6775

6876
options.Collectors.AddRange(DefaultCollectors.Get(metricFactory));

src/Prometheus.Client.AspNetCore/PrometheusOptions.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ public class PrometheusOptions
1414
/// </summary>
1515
public string MapPath { get; set; } = "/metrics";
1616

17+
/// <summary>
18+
/// When specified only allow access to metrics on this port, otherwise return 404, default = null.
19+
/// </summary>
20+
public int? Port { get; set; }
21+
1722
/// <summary>
1823
/// CollectorRegistry intance
1924
/// </summary>
@@ -29,4 +34,4 @@ public class PrometheusOptions
2934
/// </summary>
3035
public bool UseDefaultCollectors { get; set; } = true;
3136
}
32-
}
37+
}

0 commit comments

Comments
 (0)