Skip to content

Commit

Permalink
Merge pull request #3 from meetcleo/PLT-XXX-cleanse-names
Browse files Browse the repository at this point in the history
[PLT-XXX] Ensure metric names are valid Prometheus
  • Loading branch information
joshuafleck authored Oct 13, 2023
2 parents 5c08148 + 2cf6193 commit 146bed7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
9 changes: 8 additions & 1 deletion lib/statsd/instrument/prometheus/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module Prometheus
class Serializer
# Colon separated, but allows double-colon values, e.g. name:value, name.1:value.1, name:Module1::Module2::Class
LABEL_EXTRACTOR = /^(?<name>[^\:]+)\:(?<value>.+)$/
INVALID_NAME_CHARACTERS = /[^a-zA-Z0-9:_]/

def initialize(datagrams, application_name, subsystem)
@datagrams = datagrams
Expand All @@ -20,6 +21,12 @@ def run
::Prometheus::WriteRequest.encode(::Prometheus::WriteRequest.new(timeseries: timeseries, metadata: []))
end

class << self
def cleanse_name(name)
name.gsub(INVALID_NAME_CHARACTERS, "_")
end
end

private

attr_reader :datagrams, :current_time_ms, :pid, :hostname, :application_name, :subsystem
Expand Down Expand Up @@ -47,7 +54,7 @@ def default_prometheus_labels
# This will prevent dup labels
def labels_by_name(datagram)
labels = default_prometheus_labels.clone
labels["__name__"] = ::Prometheus::Label.new(name: "__name__", value: datagram.name)
labels["__name__"] = ::Prometheus::Label.new(name: "__name__", value: self.class.cleanse_name(datagram.name))
return labels unless datagram.tags

extracted_labels_from_tags = datagram.tags.map do |tag|
Expand Down
8 changes: 4 additions & 4 deletions test/prometheus/integration_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_mocked_request
{ name: "__meta_subsystem", value: "subsystem" },
{ name: "host", value: "" },
{ name: "pid", value: "" },
{ name: "__name__", value: "counter.total" },
{ name: "__name__", value: "counter_total" },
{ name: "source", value: "App::Main::Controller" },
{ name: "env", value: "test" },
],
Expand All @@ -64,9 +64,9 @@ def test_mocked_request
},
expected_metric("metrics_since_last_flush", 1.0),
expected_metric("pre_aggregation_number_of_metrics_since_last_flush", 2.0),
expected_metric("number_of_requests_attempted.total", 1.0),
expected_metric("number_of_requests_succeeded_upto_previous_flush.total", 0.0),
expected_metric("number_of_metrics_dropped_due_to_buffer_full.total", 0.0),
expected_metric("number_of_requests_attempted_total", 1.0),
expected_metric("number_of_requests_succeeded_upto_previous_flush_total", 0.0),
expected_metric("number_of_metrics_dropped_due_to_buffer_full_total", 0.0),
expected_metric("time_since_last_flush_initiated", -1),
],
metadata: [],
Expand Down

0 comments on commit 146bed7

Please sign in to comment.