bin/check-http-json.rb in sensu-plugins-http-1.0.0 vs bin/check-http-json.rb in sensu-plugins-http-2.0.0
- old
+ new
@@ -54,10 +54,11 @@
option :certkey, long: '--cert-key FILE'
option :cacert, short: '-C FILE', long: '--cacert FILE'
option :timeout, short: '-t SECS', proc: proc(&:to_i), default: 15
option :key, short: '-K KEY', long: '--key KEY'
option :value, short: '-v VALUE', long: '--value VALUE'
+ option :whole_response, short: '-w', long: '--whole-response', boolean: true, default: false
def run
if config[:url]
uri = URI.parse(config[:url])
config[:host] = uri.host
@@ -82,10 +83,44 @@
rescue => e
critical "Connection error: #{e.message}"
end
end
+ def deep_value(data, desired_key, parent = '')
+ case data
+ when Array
+ data.each_with_index do |value, index|
+ arr_key = parent + '[' + index.to_s + ']'
+
+ if arr_key == desired_key
+ return value
+ end
+
+ if desired_key.include? arr_key
+ search = deep_value(value, desired_key, arr_key)
+
+ return search unless search.nil?
+ end
+ end
+ when Hash
+ data.each do |key, value|
+ key_prefix = parent.empty? ? '' : '.'
+ hash_key = parent + key_prefix + key
+
+ if hash_key == desired_key
+ return value
+ end
+
+ if desired_key.include?(hash_key + '.') || desired_key.include?(hash_key + '[')
+ search = deep_value(value, desired_key, hash_key)
+
+ return search unless search.nil?
+ end
+ end
+ end
+ end
+
def json_valid?(str)
JSON.parse(str)
return true
rescue JSON::ParserError
return false
@@ -126,23 +161,22 @@
req[h] = v.strip
end
end
res = http.request(req)
- critical res.code unless res.code =~ /^2/
+ unless res.code =~ /^2/
+ critacal "http code: #{res.code}: body: #{res.body}" if config[:whole_response]
+ critical res.code
+ end
critical 'invalid JSON from request' unless json_valid?(res.body)
ok 'valid JSON returned' if config[:key].nil? && config[:value].nil?
json = JSON.parse(res.body)
begin
- keys = config[:key].scan(/(?:\\\.|[^.])+/).map { |key| key.gsub(/\\./, '.') }
+ leaf = deep_value(json, config[:key])
- leaf = keys.reduce(json) do |tree, key|
- raise "could not find key: #{config[:key]}" unless tree.key?(key)
- tree[key]
- end
-
+ raise "could not find key: #{config[:key]}" if leaf.nil?
raise "unexpected value for key: '#{config[:value]}' != '#{leaf}'" unless leaf.to_s == config[:value].to_s
ok "key has expected value: '#{config[:key]}' = '#{config[:value]}'"
rescue => e
critical "key check failed: #{e}"