Module: Sensu::Plugin::Utils

Included in:
Handler, Mutator
Defined in:
lib/sensu-plugin/utils.rb

Overview

rubocop:disable Metrics/ModuleLength

Instance Method Summary collapse

Instance Method Details

#api_request(method, path) {|req| ... } ⇒ Object

Yields:

  • (req)


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/sensu-plugin/utils.rb', line 82

def api_request(method, path, &_blk)
  if api_settings.nil?
    raise 'api.json settings not found.'
  end
  use_ssl = api_settings['ssl'].is_a?(Hash) ||
            api_settings['host'].start_with?('https')
  hostname = api_settings['host'].gsub(/https?:\/\//, '')
  req = net_http_req_class(method).new(path)
  if api_settings['user'] && api_settings['password']
    req.basic_auth(api_settings['user'], api_settings['password'])
  end
  yield(req) if block_given?
  res = Net::HTTP.start(hostname, api_settings['port'], use_ssl: use_ssl) do |http|
    http.request(req)
  end
  res
end

#api_settingsHash

Return a hash of API settings derived first from ENV if set, then Sensu config ‘api` scope if configured, and finally falling back to to ipv4 localhost address on default API port.

Returns:

  • (Hash)


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/sensu-plugin/utils.rb', line 62

def api_settings
  return @api_settings if @api_settings
  if ENV['SENSU_API_URL']
    uri = URI(ENV['SENSU_API_URL'])
    ssl = uri.scheme == 'https' ? {} : nil
    @api_settings = {
      'ssl' => ssl,
      'host' => uri.host,
      'port' => uri.port,
      'user' => uri.user,
      'password' => uri.password
    }
  else
    @api_settings = settings['api'] || {}
    @api_settings['host'] ||= '127.0.0.1'
    @api_settings['port'] ||= 4567
  end
  @api_settings
end

#api_settings=(api_settings) ⇒ Hash

Override API settings (for testing purposes)

Parameters:

  • api_settings (Hash)

Returns:

  • (Hash)


53
54
55
# File 'lib/sensu-plugin/utils.rb', line 53

def api_settings=(api_settings)
  @api_settings = api_settings
end

#cast_bool_values_int(value) ⇒ Object



139
140
141
142
143
144
145
146
147
148
# File 'lib/sensu-plugin/utils.rb', line 139

def cast_bool_values_int(value)
  case value
  when 'true', true
    1
  when 'false', false
    0
  else
    value
  end
end

#config_filesObject



6
7
8
9
10
11
12
13
14
# File 'lib/sensu-plugin/utils.rb', line 6

def config_files
  if ENV['SENSU_LOADED_TEMPFILE'] && File.file?(ENV['SENSU_LOADED_TEMPFILE'])
    IO.read(ENV['SENSU_LOADED_TEMPFILE']).split(':')
  elsif ENV['SENSU_CONFIG_FILES']
    ENV['SENSU_CONFIG_FILES'].split(':')
  else
    ['/etc/sensu/config.json'] + Dir['/etc/sensu/conf.d/**/*.json']
  end
end

#deep_merge(hash_one, hash_two) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/sensu-plugin/utils.rb', line 125

def deep_merge(hash_one, hash_two)
  merged = hash_one.dup
  hash_two.each do |key, value|
    merged[key] = if hash_one[key].is_a?(Hash) && value.is_a?(Hash)
                    deep_merge(hash_one[key], value)
                  elsif hash_one[key].is_a?(Array) && value.is_a?(Array)
                    hash_one[key].concat(value).uniq
                  else
                    value
                  end
  end
  merged
end

#load_config(filename) ⇒ Object



16
17
18
19
20
# File 'lib/sensu-plugin/utils.rb', line 16

def load_config(filename)
  JSON.parse(File.open(filename, 'r').read)
rescue
  {}
end

#net_http_req_class(method) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/sensu-plugin/utils.rb', line 36

def net_http_req_class(method)
  case method.to_s.upcase
  when 'GET'
    Net::HTTP::Get
  when 'POST'
    Net::HTTP::Post
  when 'DELETE'
    Net::HTTP::Delete
  when 'PUT'
    Net::HTTP::Put
  end
end

#paginated_get(path, options = {}) ⇒ Array

Use API query parameters to paginate HTTP GET requests, iterating over the results until an empty set is returned.

Parameters:

  • path (String)
  • options (Hash) (defaults to: {})

Returns:

  • (Array)


107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/sensu-plugin/utils.rb', line 107

def paginated_get(path, options = {})
  limit = options.fetch('limit', 500)
  offset = 0
  results = []
  loop do
    query_path = "#{path}?limit=#{limit}&offset=#{offset}"
    response = api_request(:GET, query_path)
    unless response.is_a?(Net::HTTPOK)
      unknown("Non-OK response from API query: #{get_uri(query_path)}")
    end
    data = JSON.parse(response.body)
    break if data.empty?
    results << data
    offset += limit
  end
  results.flatten
end

#read_event(file) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/sensu-plugin/utils.rb', line 26

def read_event(file)
  @event = ::JSON.parse(file.read)
  @event['occurrences'] ||= 1
  @event['check']       ||= {}
  @event['client']      ||= {}
rescue => e
  puts 'error reading event: ' + e.message
  exit 0
end

#settingsObject



22
23
24
# File 'lib/sensu-plugin/utils.rb', line 22

def settings
  @settings ||= config_files.map { |f| load_config(f) }.reduce { |a, b| deep_merge(a, b) }
end