FIX: Memory leaks in unicorn + puma collectors

FIX: Memory leaks in unicorn + puma collectors

Both collectors were storing objects in a local array but never removing them. This fix records a date and expires objects that are old.

Co-authored-by: Fivell fedoronchuk@gmail.com

diff --git a/lib/prometheus_exporter/server/puma_collector.rb b/lib/prometheus_exporter/server/puma_collector.rb
index 66582b4..25945f3 100644
--- a/lib/prometheus_exporter/server/puma_collector.rb
+++ b/lib/prometheus_exporter/server/puma_collector.rb
@@ -2,6 +2,7 @@
 
 module PrometheusExporter::Server
   class PumaCollector < TypeCollector
+    MAX_PUMA_METRIC_AGE = 30
     PUMA_GAUGES = {
       workers_total: "Number of puma workers.",
       booted_workers_total: "Number of puma workers booted.",
@@ -47,6 +48,10 @@ module PrometheusExporter::Server
     end
 
     def collect(obj)
+      now = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
+
+      obj["created_at"] = now
+      @puma_metrics.delete_if { |m| m["created_at"] + MAX_PUMA_METRIC_AGE < now }
       @puma_metrics << obj
     end
   end
diff --git a/lib/prometheus_exporter/server/unicorn_collector.rb b/lib/prometheus_exporter/server/unicorn_collector.rb
index e24177c..109b358 100644
--- a/lib/prometheus_exporter/server/unicorn_collector.rb
+++ b/lib/prometheus_exporter/server/unicorn_collector.rb
@@ -3,6 +3,8 @@
 # custom type collector for prometheus_exporter for handling the metrics sent from
 # PrometheusExporter::Instrumentation::Unicorn
 class PrometheusExporter::Server::UnicornCollector < PrometheusExporter::Server::TypeCollector
+  MAX_UNICORN_METRIC_AGE = 60
+
   UNICORN_GAUGES = {
     workers_total: 'Number of unicorn workers.',
     active_workers_total: 'Number of active unicorn workers',
@@ -36,6 +38,9 @@ class PrometheusExporter::Server::UnicornCollector < PrometheusExporter::Server:
   end
 
   def collect(obj)
+    now = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
+    obj["created_at"] = now
+    @unicorn_metrics.delete_if { |m| m['created_at'] + MAX_UNICORN_METRIC_AGE < now }
     @unicorn_metrics << obj
   end
 end

GitHub sha: e2d75a5a

1 Like