From b8680c628c1b9b6ae5e09026f4d27b917ec2957f Mon Sep 17 00:00:00 2001 From: Julik Tarkhanov Date: Sun, 3 May 2020 02:27:31 +0200 Subject: [PATCH] Allow use of Hash-shaped stats Future puma versions will be outputting a Hash instead of a string of JSON, so the parsing step is no longer needed. Also update key use to always use symbols, since this allows better object reuse (and the builtin #stats method will be returning Symbol-keyed hashes natively) --- lib/puma/metrics/app.rb | 11 ++++++++++- lib/puma/metrics/parser.rb | 8 ++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/lib/puma/metrics/app.rb b/lib/puma/metrics/app.rb index 85d499a..f645175 100644 --- a/lib/puma/metrics/app.rb +++ b/lib/puma/metrics/app.rb @@ -14,13 +14,22 @@ def initialize(launcher) end def call(_env) - @parser.parse JSON.parse(@launcher.stats) + retrieve_and_parse_stats! [ 200, { 'Content-Type' => 'text/plain' }, [Prometheus::Client::Formats::Text.marshal(Prometheus::Client.registry)] ] end + + def retrieve_and_parse_stats! + puma_stats = @launcher.stats + if puma_stats.is_a?(Hash) # Modern Puma outputs stats as a Symbol-keyed Hash + @parser.parse(puma_stats) + else + @parser.parse(JSON.parse(puma_stats, symbolize_names: true)) + end + end end end end diff --git a/lib/puma/metrics/parser.rb b/lib/puma/metrics/parser.rb index 3b0db74..e783cf9 100644 --- a/lib/puma/metrics/parser.rb +++ b/lib/puma/metrics/parser.rb @@ -10,10 +10,10 @@ def initialize(clustered = false) register_clustered_metrics if clustered end - def parse(stats, labels = {}) - stats.each do |key, value| - value.each { |s| parse(s, labels.merge(index: s['index'])) } if key == 'worker_status' - parse(value, labels) if key == 'last_status' + def parse(symbol_keyed_stats, labels = {}) + symbol_keyed_stats.each do |key, value| + value.each { |s| parse(s, labels.merge(index: s[:index])) } if key == :worker_status + parse(value, labels) if key == :last_status update_metric(key, value, labels) end end