Skip to content

Commit

Permalink
FIX: avoid shelling to get hostname
Browse files Browse the repository at this point in the history
Previously we were using `hostname` to get hostname, this is slow
and risks orphan processes.

This swaps it with Socket.gethostname which is both faster and more
reliable.

We also now cache it on the PrometheusExporter instance
  • Loading branch information
SamSaffron committed Feb 14, 2020
1 parent f83b4f4 commit 45ff653
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 25 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG
@@ -1,6 +1,7 @@
0.5.0 - pending
0.5.0 - 14-02-2019

- Breaking change: listen only to localhost by default to prevent unintended insecure configuration
- FIX: Avoid calling `hostname` aggressively, instead cache it on the exporter instance

0.4.17 - 13-01-2019

Expand Down
11 changes: 11 additions & 0 deletions lib/prometheus_exporter.rb
Expand Up @@ -20,6 +20,17 @@ def self.dump(obj)
end
end

def self.hostname
@hostname ||=
begin
require 'socket'
Socket.gethostname
rescue => e
STDERR.puts "Unable to lookup hostname #{e}"
"unknown-host"
end
end

def self.detect_json_serializer(preferred)
if preferred.nil?
preferred = :oj if has_oj?
Expand Down
13 changes: 1 addition & 12 deletions lib/prometheus_exporter/instrumentation/active_record.rb
Expand Up @@ -51,17 +51,6 @@ def self.stop
def initialize(metric_labels, config_labels)
@metric_labels = metric_labels
@config_labels = config_labels
@hostname = nil
end

def hostname
@hostname ||=
begin
`hostname`.strip
rescue => e
STDERR.puts "Unable to lookup hostname #{e}"
"unknown-host"
end
end

def collect
Expand All @@ -87,7 +76,7 @@ def collect_active_record_pool_stats(metrics)
metric = {
pid: pid,
type: "active_record",
hostname: hostname,
hostname: ::PrometheusExporter.hostname,
metric_labels: labels
}
metric.merge!(pool.stat)
Expand Down
13 changes: 1 addition & 12 deletions lib/prometheus_exporter/instrumentation/process.rb
Expand Up @@ -42,24 +42,13 @@ def self.stop

def initialize(metric_labels)
@metric_labels = metric_labels
@hostname = nil
end

def hostname
@hostname ||=
begin
`hostname`.strip
rescue => e
STDERR.puts "Unable to lookup hostname #{e}"
"unknown-host"
end
end

def collect
metric = {}
metric[:type] = "process"
metric[:metric_labels] = @metric_labels
metric[:hostname] = hostname
metric[:hostname] = ::PrometheusExporter.hostname
collect_gc_stats(metric)
collect_v8_stats(metric)
collect_process_stats(metric)
Expand Down
4 changes: 4 additions & 0 deletions test/prometheus_exporter_test.rb
Expand Up @@ -6,4 +6,8 @@ class PrometheusExporterTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::PrometheusExporter::VERSION
end

def test_it_can_get_hostname
assert_equal `hostname`.strip, ::PrometheusExporter.hostname
end
end

0 comments on commit 45ff653

Please sign in to comment.