Class: Wavefront::Cli::Alerts

Inherits:
Wavefront::Cli show all
Includes:
Mixins
Defined in:
lib/wavefront/cli/alerts.rb

Instance Attribute Summary collapse

Attributes inherited from Wavefront::Cli

#noop

Instance Method Summary collapse

Methods included from Mixins

#call_delete, #call_get, #call_post, #hash_to_qs, #interpolate_schema, #load_file, #parse_time, #time_to_ms, #uri_concat

Methods inherited from Wavefront::Cli

#initialize, #validate_opts

Constructor Details

This class inherits a constructor from Wavefront::Cli

Instance Attribute Details

#argumentsObject

Returns the value of attribute arguments.



25
26
27
# File 'lib/wavefront/cli/alerts.rb', line 25

def arguments
  @arguments
end

#optionsObject

Returns the value of attribute options.



25
26
27
# File 'lib/wavefront/cli/alerts.rb', line 25

def options
  @options
end

#wfaObject

Returns the value of attribute wfa.



25
26
27
# File 'lib/wavefront/cli/alerts.rb', line 25

def wfa
  @wfa
end

Instance Method Details

#export_alert(id) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/wavefront/cli/alerts.rb', line 87

def export_alert(id)
  begin
    resp = wfa.get_alert(id)
  rescue => e
    puts e if @options[:debug]
    raise 'Unable to retrieve alert.'
  end

  return if options[:noop]

  case options[:alertformat].to_sym
  when :json
    puts JSON.pretty_generate(resp)
  when :yaml
    puts resp.to_yaml
  when :human
    puts humanize([resp])
  else
    puts 'unknown output format.'
  end
end

#format_result(result, format) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/wavefront/cli/alerts.rb', line 109

def format_result(result, format)
  #
  # Call a suitable method to display the output of the API call,
  # which is JSON.
  #
  return if noop

  case format
  when :ruby
    pp result
  when :json
    puts JSON.pretty_generate(JSON.parse(result))
  when :yaml
    puts JSON.parse(result).to_yaml
  when :human
    puts humanize(JSON.parse(result))
  else
    raise "Invalid output format '#{format}'. See --help for more detail."
  end
end

#human_line(k, v) ⇒ Object



185
186
187
# File 'lib/wavefront/cli/alerts.rb', line 185

def human_line(k, v)
  ('%-22s%s' % [k, v]).rstrip
end

#human_line_additionalInformation(k, v) ⇒ Object



219
220
221
# File 'lib/wavefront/cli/alerts.rb', line 219

def human_line_additionalInformation(k, v)
  human_line(k, indent_wrap(v))
end

#human_line_alertStates(k, v) ⇒ Object



215
216
217
# File 'lib/wavefront/cli/alerts.rb', line 215

def human_line_alertStates(k, v)
  human_line(k, v.join(','))
end

#human_line_created(k, v) ⇒ Object



189
190
191
192
193
194
195
# File 'lib/wavefront/cli/alerts.rb', line 189

def human_line_created(k, v)
  #
  # The 'created' and 'updated' timestamps are in epoch
  # milliseconds
  #
  human_line(k, "#{Time.at(v / 1000)} (#{v})")
end

#human_line_hostsUsed(k, v) ⇒ Object



201
202
203
204
205
206
207
208
209
# File 'lib/wavefront/cli/alerts.rb', line 201

def human_line_hostsUsed(k, v)
  #
  # Put each host on its own line, indented. Does this by
  # returning an array.
  #
  return k unless v && v.is_a?(Array) && ! v.empty?
  v.sort!
  [human_line(k, v.shift)] + v.map {|el| human_line('', el)}
end

#human_line_metricsUsed(k, v) ⇒ Object



211
212
213
# File 'lib/wavefront/cli/alerts.rb', line 211

def human_line_metricsUsed(k, v)
  human_line_hostsUsed(k, v)
end

#human_line_updated(k, v) ⇒ Object



197
198
199
# File 'lib/wavefront/cli/alerts.rb', line 197

def human_line_updated(k, v)
  human_line_created(k, v)
end

#humanize(alerts) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/wavefront/cli/alerts.rb', line 153

def humanize(alerts)
  #
  # Selectively display alert information in an easily
  # human-readable format. I have chosen not to display certain
  # fields which I don't think are useful in this context. I also
  # wish to put the fields in order. Here are the fields I want, in
  # the order I want them.
  #
  row_order = %w(name created severity condition displayExpression
                 minutes resolveAfterMinutes updated alertStates
                 metricsUsed hostsUsed additionalInformation)

  # build up an array of lines then turn it into a string and
  # return it
  #
  # Most things get printed with the human_line() method, but some
  # data needs special handling. To do that, just add a method
  # called human_line_key() where key is something in row_order,
  # and it will be found.
  #
  x = alerts.map do |alert|
    row_order.map do |key|
      lm = "human_line_#{key}"
      if self.respond_to?(lm)
        self.method(lm.to_sym).call(key, alert[key])
      else
        human_line(key, alert[key])
      end
    end.<< ''
  end
end

#import_alertObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/wavefront/cli/alerts.rb', line 69

def import_alert
  raw = load_file(options[:'<file>'])

  begin
    prepped = wfa.import_to_create(raw)
  rescue => e
    puts e if options[:debug]
    raise 'could not parse input.'
  end

  begin
    wfa.create_alert(prepped)
    puts 'Alert imported.' unless options[:noop]
  rescue RestClient::BadRequest
    raise '400 error: alert probably exists.'
  end
end

#indent_wrap(line, cols = 78, offset = 22) ⇒ Object



223
224
225
226
227
228
229
230
# File 'lib/wavefront/cli/alerts.rb', line 223

def indent_wrap(line, cols=78, offset=22)
  #
  # hanging indent long lines to fit in an 80-column terminal
  #
  return unless line
  line.gsub(/(.{1,#{cols - offset}})(\s+|\Z)/, "\\1\n#{' ' *
            offset}").rstrip
end

#runObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/wavefront/cli/alerts.rb', line 27

def run
  raise 'Missing token.' if ! @options[:token] || @options[:token].empty?
  raise 'Missing query.' if arguments.empty?
  valid_format?(@options[:alertformat].to_sym)

  @wfa = Wavefront::Alerting.new(@options[:token], @options[:endpoint],
                                @options[:debug], {
    noop: @options[:noop], verbose: @options[:verbose]})

  if options[:export]
    export_alert(options[:'<timestamp>'])
    return
  end

  if options[:import]
    import_alert
    return
  end

  query = arguments[0].to_sym
  valid_state?(wfa, query)
  options = { host: @options[:endpoint] }

  if @options[:shared]
    options[:shared_tags] = @options[:shared].delete(' ').split(',')
  end

  if @options[:private]
    options[:private_tags] = @options[:private].delete(' ').split(',')
  end

  begin
    result = wfa.send(query, options)
  rescue => e
    puts e if @options[:debug]
    raise 'Unable to execute query.'
  end

  format_result(result, @options[:alertformat].to_sym)
  exit
end

#valid_format?(fmt) ⇒ Boolean

Returns:

  • (Boolean)


130
131
132
133
134
135
136
137
138
# File 'lib/wavefront/cli/alerts.rb', line 130

def valid_format?(fmt)
  fmt = fmt.to_sym if fmt.is_a?(String)

  unless Wavefront::Client::ALERT_FORMATS.include?(fmt)
    raise 'Output format must be one of: ' +
      Wavefront::Client::ALERT_FORMATS.join(', ') + '.'
  end
  true
end

#valid_state?(wfa, state) ⇒ Boolean

Returns:

  • (Boolean)


140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/wavefront/cli/alerts.rb', line 140

def valid_state?(wfa, state)
  #
  # Check the alert type we've been given is valid. There needs to
  # be a public method in the 'alerting' class for every one.
  #
  states = %w(active affected_by_maintenance all invalid snoozed)

  unless states.include?(state.to_s)
    raise "State must be one of: #{states.join(', ')}."
  end
  true
end