Skip to content

Commit

Permalink
Handle / in job name in Prometheus::Client::Push
Browse files Browse the repository at this point in the history
This a subtlety I missed when overhauling the Pushgateway client.

While the job name can't be empty like other grouping key labels can, it
can contain `/`, which means we need to base64 encode the value in that
case.

Signed-off-by: Chris Sinjakli <chris@sinjakli.co.uk>
  • Loading branch information
Sinjo committed Aug 3, 2023
1 parent 77e6b7b commit 6f7b6cf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/prometheus/client/push.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class HttpClientError < HttpError; end
class HttpServerError < HttpError; end

DEFAULT_GATEWAY = 'http://localhost:9091'.freeze
PATH = '/metrics/job/%s'.freeze
PATH = '/metrics'.freeze
SUPPORTED_SCHEMES = %w(http https).freeze

attr_reader :job, :gateway, :path
Expand Down Expand Up @@ -87,7 +87,14 @@ def parse(url)
end

def build_path(job, grouping_key)
path = format(PATH, ERB::Util::url_encode(job))
# Job can't be empty, but it can contain `/`, so we need to base64
# encode it in that case
if job.include?('/')
encoded_job = Base64.urlsafe_encode64(job)
path = "#{PATH}/job@base64/#{encoded_job}"
else
path = "#{PATH}/job/#{ERB::Util::url_encode(job)}"
end

grouping_key.each do |label, value|
if value.include?('/')
Expand Down
8 changes: 8 additions & 0 deletions spec/prometheus/client/push_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@
expect(push.path).to eql('/metrics/job/test-job/foo/bar/baz/qux')
end

it 'encodes the job name in url-safe base64 if it contains `/`' do
push = Prometheus::Client::Push.new(
job: 'foo/test-job',
)

expect(push.path).to eql('/metrics/job@base64/Zm9vL3Rlc3Qtam9i')
end

it 'encodes grouping key label values containing `/` in url-safe base64' do
push = Prometheus::Client::Push.new(
job: 'test-job',
Expand Down

0 comments on commit 6f7b6cf

Please sign in to comment.