Class: Morpheus::Cli::MonitoringChecksCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, MonitoringHelper
Defined in:
lib/morpheus/cli/monitoring_checks_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from MonitoringHelper

#check_type_for_id, #check_type_for_name, #check_type_for_name_or_id, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_check_by_id, #find_check_by_name, #find_check_by_name_or_id, #find_check_group_by_id, #find_check_group_by_name, #find_check_group_by_name_or_id, #find_contact_by_id, #find_contact_by_name, #find_contact_by_name_or_id, #find_incident_by_id, #format_monitoring_check_last_metric, #format_monitoring_check_status, #format_monitoring_check_type, #format_monitoring_incident_status, #format_monitoring_issue_attachment_type, #format_monitoring_issue_status, #format_severity, #get_available_check_types, included, #monitoring_interface, #print_check_history_table, #print_check_notifications_table, #print_checks_table, #print_incident_history_table, #print_incident_notifications_table, #print_incidents_table

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeMonitoringChecksCommand

Returns a new instance of MonitoringChecksCommand.



12
13
14
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 12

def initialize()
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#_get(id, options) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 113

def _get(id, options)

  begin
    check = find_check_by_name_or_id(id)

    if options[:dry_run]
      print_dry_run @monitoring_interface.checks.dry.get(check['id'])
      return
    end
    json_response = @monitoring_interface.checks.get(check['id'])
    check = json_response['check']
    
    if options[:json]
      if options[:include_fields]
        json_response = {"check" => filter_data(json_response["check"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['check']], options)
      return 0
    end

    print_h1 "Check Details"
    print cyan
    description_cols = {
      "ID" => lambda {|it| it['id'] },
      "Status" => lambda {|it| format_monitoring_check_status(it) },
      "Name" => lambda {|it| it['name'] },
      "Time" => lambda {|it| format_local_dt(it['lastRunDate']) },
      "Availability" => lambda {|it| it['availability'] ? "#{it['availability'].to_f.round(3).to_s}%" : "N/A"},
      "Response Time" => lambda {|it| it['lastTimer'] ? "#{it['lastTimer']}ms" : "N/A" },
      "Last Metric" => lambda {|it| it['lastMetric'] ? "#{it['lastMetric']}" : "N/A" },
      "Type" => 'checkType.name'
    }
    print_description_list(description_cols, check)

    ## Chart Stats


    ## Activity

    ## Groups
    
    check_groups = json_response["groups"]
    if check_groups && !check_groups.empty?
      print_h2 "Check Groups"
      print as_pretty_table(check_groups, [:id, {"Check Group" => :name}], options)
    else
      # print "\n"
      # puts "This check is not in any check groups."
    end

    ## Open Incidents

    open_incidents = json_response["openIncidents"]
    if open_incidents && !open_incidents.empty?
      print_h2 "Open Incidents"
      # puts "\n(table coming soon...)\n"
      puts print JSON.pretty_generate(open_incidents)
      # todo: move this to MonitoringHelper ?
      # print_incidents_table(issues, options)
    else
      print "\n"
      puts "No open incidents for this check"
    end

    ## History (plain old Hash)
    if options[:show_history]
      # history_items = json_response["history"]
      # gotta go get it
      history_json_response = @monitoring_interface.checks.history(check["id"], {})
      history_items = history_json_response["history"] || history_json_response["events"]  || history_json_response["issues"]
      issues = history_items
      if history_items && !history_items.empty?
        print_h2 "History"
        print_check_history_table(history_items, options)
        print_results_pagination(history_json_response, {:label => "event", :n_label => "events"})
      else
        print "\n"
        puts "No history found for this check"
      end
    end

    ## Statistics (Hash)
    if options[:show_statistics]
      # todo....
    end

    print reset,"\n"

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



16
17
18
19
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 16

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @monitoring_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).monitoring
end

#get(args) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 89

def get(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id list]")
    opts.on(nil,'--history', "Display Check History") do |val|
      options[:show_history] = true
    end
    # opts.on(nil,'--statistics', "Display Statistics") do |val|
    #   options[:show_statistics] = true
    # end
    build_common_options(opts, options, [:json, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end

#handle(args) ⇒ Object



21
22
23
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 21

def handle(args)
  handle_subcommand(args)
end

#history(args) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 210

def history(args)
  options = {}
  params = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id] [options]")
    # opts.on('--status LIST', Array, "Filter by status. open, closed") do |list|
    #   params['status'] = list
    # end
    opts.on('--severity LIST', Array, "Filter by severity. critical, warning, info") do |list|
      params['severity'] = list
    end
    build_common_options(opts, options, [:list, :last_updated, :json, :csv, :fields, :json, :dry_run])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    check = find_check_by_name_or_id(args[0])
    # return false if check.nil?
    
    [:phrase, :offset, :max, :sort, :direction, :lastUpdated].each do |k|
      params[k] = options[k] unless options[k].nil?
    end
    # JD: lastUpdated 500ing, checks don't have that property ? =o  Fix it!

    if options[:dry_run]
      print_dry_run @monitoring_interface.checks.dry.history(check['id'], params)
      return
    end

    json_response = @monitoring_interface.checks.history(check['id'], params)
    if options[:json]
      if options[:include_fields]
        json_response = {"history" => filter_data(json_response["history"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    end
    if options[:csv]
      puts records_as_csv(json_response['history'], options)
      return 0
    end
    history_items = json_response['history']
    title = "Check History: #{check['id']}: #{check['displayName'] || check['name']}"
    subtitles = []
    if params[:phrase]
      subtitles << "Search: #{params[:phrase]}".strip
    end
    print_h1 title, subtitles
    if history_items.empty?
      print cyan,"No history found.",reset,"\n"
    else
      print_check_history_table(history_items, options)
      print_results_pagination(json_response, {:label => "event", :n_label => "events"})
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list(args) ⇒ Object



25
26
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 25

def list(args)
  options = {}
  params = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    opts.on('--status LIST', Array, "Filter by status. open, closed") do |list|
      params['status'] = list
    end
    opts.on('--severity LIST', Array, "Filter by severity. critical, warning, info") do |list|
      params['severity'] = list
    end
    build_common_options(opts, options, [:list, :last_updated, :json, :csv, :fields, :json, :dry_run])
  end
  optparse.parse!(args)
  connect(options)
  begin
    [:phrase, :offset, :max, :sort, :direction, :lastUpdated].each do |k|
      params[k] = options[k] unless options[k].nil?
    end
    # JD: lastUpdated 500ing, checks don't have that property ? =o  Fix it!

    if options[:dry_run]
      print_dry_run @monitoring_interface.checks.dry.list(params)
      return
    end

    json_response = @monitoring_interface.checks.list(params)
    if options[:json]
      if options[:include_fields]
        json_response = {"checks" => filter_data(json_response["checks"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    end
    if options[:csv]
      puts records_as_csv(json_response['checks'], options)
      return 0
    end
    checks = json_response['checks']
    title = "Morpheus Checks"
    subtitles = []
    # if group
    #   subtitles << "Group: #{group['name']}".strip
    # end
    # if cloud
    #   subtitles << "Cloud: #{cloud['name']}".strip
    # end
    if params[:phrase]
      subtitles << "Search: #{params[:phrase]}".strip
    end
    print_h1 title, subtitles
    if checks.empty?
      print cyan,"No checks found.",reset,"\n"
    else
      print_checks_table(checks, options)
      print_results_pagination(json_response, {:label => "check", :n_label => "checks"})
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#quarantine(args) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 323

def quarantine(args)
  options = {}
  params = {'enabled' => true}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id list]")
    # this one is a bit weird.. it's a way to toggle incident.inUptime
    # opts.on("--enabled BOOL", String, "Quarantine can be removed with --enabled false") do |val|
    #   params['enabled'] = ['on','true'].include?(val.to_s.downcase)
    # end
    opts.on("-d", "--disabled", "Disable Quarantine instead") do
      params['enabled'] = false
    end
    build_common_options(opts, options, [:json, :dry_run, :quiet])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)

  begin
    check = find_check_by_name_or_id(args[0])

    if params.empty?
      print_red_alert "Specify atleast one option to update"
      puts optparse
      exit 1
    end

    # payload = {
    #   'check' => {id: check["id"]}
    # }
    # payload['check'].merge!(check)
    payload = params

    if options[:dry_run]
      print_dry_run @monitoring_interface.checks.dry.update(check["id"], payload)
      return
    end

    json_response = @monitoring_interface.checks.update(check["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Quarantined check #{check['id']}"
      _get(check['id'], {})
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 378

def remove(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:json, :dry_run, :quiet])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 127
  end
  connect(options)

  begin
    check = find_check_by_name_or_id(args[0])

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to delete check '#{check['name']}'?", options)
      return false
    end

    # payload = {
    #   'check' => {id: check["id"]}
    # }
    # payload['check'].merge!(check)
    payload = params

    if options[:dry_run]
      print_dry_run @monitoring_interface.checks.dry.destroy(check["id"])
      return
    end

    json_response = @monitoring_interface.checks.destroy(check["id"])
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Deleted check #{check['id']}"
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#update(args) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/morpheus/cli/monitoring_checks_command.rb', line 275

def update(args)
  options = {}
  params = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:json, :dry_run, :quiet])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)

  begin
    check = find_check_by_name_or_id(args[0])

    if params.empty?
      print_red_alert "Specify atleast one option to update"
      puts optparse
      exit 1
    end

    payload = {
      'check' => {id: check["id"]}
    }
    payload['check'].merge!(params)

    if options[:dry_run]
      print_dry_run @monitoring_interface.checks.dry.update(check["id"], payload)
      return
    end

    json_response = @monitoring_interface.checks.update(check["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Updated check #{check['id']}"
      _get(check['id'], {})
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end