Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add port option to exporter middleware #199

Merged
merged 1 commit into from
Feb 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/prometheus/middleware/exporter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ def initialize(app, options = {})
@app = app
@registry = options[:registry] || Client.registry
@path = options[:path] || '/metrics'
@port = options[:port]
@acceptable = build_dictionary(FORMATS, FALLBACK)
end

def call(env)
if env['PATH_INFO'] == @path
if metrics_port?(env['SERVER_PORT']) && env['PATH_INFO'] == @path
format = negotiate(env, @acceptable)
format ? respond_with(format) : not_acceptable(FORMATS)
else
Expand Down Expand Up @@ -86,6 +87,10 @@ def build_dictionary(formats, fallback)
memo[format::MEDIA_TYPE] = format
end
end

def metrics_port?(request_port)
@port.nil? || @port.to_s == request_port
end
end
end
end
28 changes: 27 additions & 1 deletion spec/prometheus/middleware/exporter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
describe Prometheus::Middleware::Exporter do
include Rack::Test::Methods

let(:options) { { registry: registry } }
let(:registry) do
Prometheus::Client::Registry.new
end

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

context 'when requesting app endpoints' do
Expand Down Expand Up @@ -96,5 +97,30 @@

include_examples 'ok', { 'HTTP_ACCEPT' => accept }, text
end

context 'when a port is specified' do
let(:options) { { registry: registry, port: 9999 } }

context 'when a request is on the specified port' do
it 'responds with 200 OK' do
registry.counter(:foo, docstring: 'foo counter').increment(by: 9)

get 'http://example.org:9999/metrics', nil, {}

expect(last_response.status).to eql(200)
expect(last_response.header['Content-Type']).to eql(text::CONTENT_TYPE)
expect(last_response.body).to eql(text.marshal(registry))
end
end

context 'when a request is not on the specified port' do
it 'returns the app response' do
get 'http://example.org:8888/metrics', nil, {}

expect(last_response).to be_ok
expect(last_response.body).to eql('OK')
end
end
end
end
end