From 839147e09932fbc0a9e9f75b8a76005a5a4704f8 Mon Sep 17 00:00:00 2001
From: Tim Rogers <rogers.timothy.john@gmail.com>
Date: Mon, 24 Jun 2024 09:41:04 -0500
Subject: [PATCH] Added check for STATSD_ADDR setting to emit a warning and
 proceed rather than crashing if the address is unreachable (#30691)

---
 config/initializers/statsd.rb | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/config/initializers/statsd.rb b/config/initializers/statsd.rb
index 93ea1d1e4a..d65d16aa58 100644
--- a/config/initializers/statsd.rb
+++ b/config/initializers/statsd.rb
@@ -3,13 +3,17 @@
 if ENV['STATSD_ADDR'].present?
   host, port = ENV['STATSD_ADDR'].split(':')
 
-  $statsd = ::Statsd.new(host, port)
-  $statsd.namespace = ENV.fetch('STATSD_NAMESPACE') { ['Mastodon', Rails.env].join('.') }
+  begin
+    statsd = Statsd.new(host, port)
+    statsd.namespace = ENV.fetch('STATSD_NAMESPACE') { ['Mastodon', Rails.env].join('.') }
 
-  ::NSA.inform_statsd($statsd) do |informant|
-    informant.collect(:action_controller, :web)
-    informant.collect(:active_record, :db)
-    informant.collect(:active_support_cache, :cache)
-    informant.collect(:sidekiq, :sidekiq)
+    NSA.inform_statsd(statsd) do |informant|
+      informant.collect(:action_controller, :web)
+      informant.collect(:active_record, :db)
+      informant.collect(:active_support_cache, :cache)
+      informant.collect(:sidekiq, :sidekiq)
+    end
+  rescue
+    Rails.logger.warn("statsd address #{ENV['STATSD_ADDR']} not reachable, proceeding without statsd")
   end
 end