Skip to content

Commit 1c8e407

Browse files
author
Chris Sinjakli
authored
Merge pull request #199 from gocardless/exporter-port
Add port option to exporter middleware
2 parents 0064da3 + 42860ce commit 1c8e407

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

lib/prometheus/middleware/exporter.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@ def initialize(app, options = {})
2121
@app = app
2222
@registry = options[:registry] || Client.registry
2323
@path = options[:path] || '/metrics'
24+
@port = options[:port]
2425
@acceptable = build_dictionary(FORMATS, FALLBACK)
2526
end
2627

2728
def call(env)
28-
if env['PATH_INFO'] == @path
29+
if metrics_port?(env['SERVER_PORT']) && env['PATH_INFO'] == @path
2930
format = negotiate(env, @acceptable)
3031
format ? respond_with(format) : not_acceptable(FORMATS)
3132
else
@@ -86,6 +87,10 @@ def build_dictionary(formats, fallback)
8687
memo[format::MEDIA_TYPE] = format
8788
end
8889
end
90+
91+
def metrics_port?(request_port)
92+
@port.nil? || @port.to_s == request_port
93+
end
8994
end
9095
end
9196
end

spec/prometheus/middleware/exporter_spec.rb

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@
66
describe Prometheus::Middleware::Exporter do
77
include Rack::Test::Methods
88

9+
let(:options) { { registry: registry } }
910
let(:registry) do
1011
Prometheus::Client::Registry.new
1112
end
1213

1314
let(:app) do
1415
app = ->(_) { [200, { 'Content-Type' => 'text/html' }, ['OK']] }
15-
described_class.new(app, registry: registry)
16+
described_class.new(app, **options)
1617
end
1718

1819
context 'when requesting app endpoints' do
@@ -96,5 +97,30 @@
9697

9798
include_examples 'ok', { 'HTTP_ACCEPT' => accept }, text
9899
end
100+
101+
context 'when a port is specified' do
102+
let(:options) { { registry: registry, port: 9999 } }
103+
104+
context 'when a request is on the specified port' do
105+
it 'responds with 200 OK' do
106+
registry.counter(:foo, docstring: 'foo counter').increment(by: 9)
107+
108+
get 'http://example.org:9999/metrics', nil, {}
109+
110+
expect(last_response.status).to eql(200)
111+
expect(last_response.header['Content-Type']).to eql(text::CONTENT_TYPE)
112+
expect(last_response.body).to eql(text.marshal(registry))
113+
end
114+
end
115+
116+
context 'when a request is not on the specified port' do
117+
it 'returns the app response' do
118+
get 'http://example.org:8888/metrics', nil, {}
119+
120+
expect(last_response).to be_ok
121+
expect(last_response.body).to eql('OK')
122+
end
123+
end
124+
end
99125
end
100126
end

0 commit comments

Comments
 (0)