bin/metric-postgres-connections.rb in sensu-plugins-postgres-0.1.1 vs bin/metric-postgres-connections.rb in sensu-plugins-postgres-1.0.0

- old
+ new

@@ -53,30 +53,49 @@ description: 'Database port', short: '-P PORT', long: '--port PORT', default: 5432 - option :db, + option :database, description: 'Database name', short: '-d DB', long: '--db DB', default: 'postgres' option :scheme, description: 'Metric naming scheme, text to prepend to $queue_name.$metric', long: '--scheme SCHEME', default: "#{Socket.gethostname}.postgresql" + option :timeout, + description: 'Connection timeout (seconds)', + short: '-T TIMEOUT', + long: '--timeout TIMEOUT', + default: nil + def run timestamp = Time.now.to_i - con = PG::Connection.new(config[:hostname], config[:port], nil, nil, 'postgres', config[:user], config[:password]) + con = PG.connect(host: config[:hostname], + dbname: config[:database], + user: config[:user], + password: config[:password], + connect_timeout: config[:timeout]) request = [ - 'select count(*), waiting from pg_stat_activity', - "where datname = '#{config[:db]}' group by waiting" + "select case when count(*) = 1 then 'waiting' else", + "'case when wait_event_type is null then false else true end' end as wait_col", + 'from information_schema.columns', + "where table_name = 'pg_stat_activity' and table_schema = 'pg_catalog'", + "and column_name = 'waiting'" ] + wait_col = con.exec(request.join(' ')).first['wait_col'] + request = [ + "select count(*), #{wait_col} as waiting from pg_stat_activity", + "where datname = '#{config[:database]}' group by #{wait_col}" + ] + metrics = { active: 0, waiting: 0, total: 0 } @@ -91,10 +110,10 @@ end metrics[:total] = (metrics[:waiting].to_i + metrics[:active].to_i) metrics.each do |metric, value| - output "#{config[:scheme]}.connections.#{config[:db]}.#{metric}", value, timestamp + output "#{config[:scheme]}.connections.#{config[:database]}.#{metric}", value, timestamp end ok end end