Class: Morpheus::Cli::MonitoringAlertsCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from MonitoringHelper

#available_severities, #check_type_for_id, #check_type_for_name, #check_type_for_name_or_id, #find_alert_by_id, #find_alert_by_name, #find_alert_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, #find_monitoring_app_by_id, #find_monitoring_app_by_name, #find_monitoring_app_by_name_or_id, #format_health_status, #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_recipient_method, #format_severity, #get_available_check_types, included, #monitoring_interface, #parse_recipient_method, #print_check_group_history_table, #print_check_groups_table, #print_check_history_table, #print_check_notifications_table, #print_checks_table, #print_incident_history_table, #print_incident_issues_table, #print_incident_notifications_table, #print_incidents_table, #print_monitor_app_history_table, #print_monitoring_apps_table, #prompt_for_check_groups, #prompt_for_checks, #prompt_for_monitor_apps, #prompt_for_recipients

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Constructor Details

#initializeMonitoringAlertsCommand

Returns a new instance of MonitoringAlertsCommand.



18
19
20
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 18

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

Instance Method Details

#_get(id, options) ⇒ Object



109
110
111
112
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
209
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
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 109

def _get(id, options)

  begin
    alert = find_alert_by_name_or_id(id)
    @monitoring_alerts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @monitoring_alerts_interface.dry.get(alert['id'])
      return
    end
    # get by ID to sideload associated checks,groups,apps
    json_response = @monitoring_alerts_interface.get(alert['id'])
    alert = json_response['alert']
    if options[:json]
      puts as_json(json_response, options, "alert")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "alert")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['alert']], options)
      return 0
    end

    print_h1 "Alert Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Min. Severity" => "minSeverity",
      "Min. Duration" => lambda {|alert| alert['minDuration'] && alert['minDuration'].to_i > 0 ? "#{alert['minDuration']} minutes" : "0 (immediate)" },
      "Checks" => lambda {|alert| 
        if alert['allChecks']
          "All"
        else
          checks = alert['checks'] || []
          # if checks.size > 3
          #   checks.first(3).collect {|r| r['name'] }.join(", ") + ", (#{checks.size - 3} more)"
          # else
          #   checks.collect {|r| r['name'] }.join(", ")
          # end
          checks.size.to_s
        end
      },
      "Groups" => lambda {|alert|
        if alert['allGroups']
          "All"
        else
          check_groups = alert['checkGroups'] || []
          # if check_groups.size > 3
          #   check_groups.first(3).collect {|r| r['name'] }.join(", ") + ", (#{check_groups.size - 3} more)"
          # else
          #   check_groups.collect {|r| r['name'] }.join(", ")
          # end
          check_groups.size.to_s
        end
      },
      "Apps" => lambda {|alert| 
        if alert['allApps']
          "All"
        else
          monitor_apps = alert['apps'] || []
          # if monitor_apps.size > 3
          #   monitor_apps.first(3).collect {|r| r['name'] }.join(", ") + ", (#{monitor_apps.size - 3} more)"
          # else
          #   monitor_apps.collect {|r| r['name'] }.join(", ")
          # end
          monitor_apps.size.to_s
        end
      },
      "Contacts" => lambda {|alert| 
        recipients = alert['contacts'] || alert['recipients'] || []
        # if recipients.size > 3
        #   recipients.first(3).collect {|r| r['name'] }.join(", ") + ", (#{recipients.size - 3} more)"
        # else
        #   recipients.collect {|r| r['name'] }.join(", ")
        # end
        recipients.size.to_s
      },
      "Created" => lambda {|alert| format_local_dt(alert['dateCreated']) },
      "Updated" => lambda {|alert| format_local_dt(alert['lastUpdated']) },
    }
    print as_description_list(alert, description_cols)
   


    ## Checks in this Alert
    #checks = alert["checks"]
    checks = json_response["checks"]
    if checks && !checks.empty?
      print_h2 "Checks"
      print_checks_table(checks, options)
    end

    ## Check Groups in this Alert
    # check_groups = alert["checkGroups"]
    check_groups = json_response["checkGroups"]
    if check_groups && !check_groups.empty?
      print_h2 "Check Groups"
      print_check_groups_table(check_groups, options)
    end

    ## Apps in this Alert
    monitor_apps = alert["apps"]
    monitor_apps = json_response["apps"]
    if monitor_apps && !monitor_apps.empty?
      print_h2 "Apps"
      print_monitoring_apps_table(monitor_apps, options)
    end

    ## Recipients in this Alert
    recipients = alert['contacts'] || alert['recipients'] || []
    if recipients && !recipients.empty?
      print_h2 "Contacts"
      columns = [
        {"CONTACT ID" => lambda {|recipient| recipient['id'] } },
        {"CONTACT NAME" => lambda {|recipient| recipient['name'] } },
        {"METHOD" => lambda {|recipient| format_recipient_method(recipient['method'] || recipient['addressTypes']) } },
        {"NOTIFY ON CHANGE" => lambda {|recipient| format_boolean(recipient['notify']) } },
        {"NOTIFY ON CLOSE" => lambda {|recipient| format_boolean(recipient['close']) } }
      ]
      print as_pretty_table(recipients, columns)
    end

    # show Notify events here...

    print reset, "\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#_remove(id, options) ⇒ Object



713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 713

def _remove(id, options)

  begin
    alert = find_alert_by_name_or_id(id)
    @monitoring_alerts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @monitoring_alerts_interface.dry.destroy(alert['id'])
      return
    end
    json_response = @monitoring_alerts_interface.destroy(alert['id'])
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success json_response["msg"] || "Alert (#{alert['id']}) #{alert['name']} deleted"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



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
274
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
321
322
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
377
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 242

def add(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on("--name STRING", String, "Alert name") do |val|
      params['name'] = val
    end
    opts.on('--min-severity VALUE', String, "Min. Severity. Trigger when severity level is reached. Default is critical") do |val|
      params['minSeverity'] = val.to_s.downcase
    end
    opts.on('--min-duration MINUTES', String, "Min. Duration. Trigger after a number of minutes. Default is 0 (immediate)") do |val|
      params['minDuration'] = val.to_i
    end
    opts.on('--all-checks [on|off]', String, "Toggle trigger for all checks.") do |val|
      params['allChecks'] = val.to_s == 'on' || val.to_s == 'true' || val == '' || val.nil?
    end
    opts.on('--checks LIST', Array, "Checks, comma separated list of names or IDs.") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['checks'] = []
      else
        params['checks'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--all-groups [on|off]', String, "Toggle trigger for all check groups.") do |val|
      params['allGroups'] = val.to_s == 'on' || val.to_s == 'true' || val == '' || val.nil?
    end
    opts.on('--groups LIST', Array, "Check Groups, comma separated list of names or IDs.") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['checkGroups'] = []
      else
        params['checkGroups'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--all-apps [on|off]', String, "Toggle trigger for all check groups.") do |val|
      params['allApps'] = val.to_s == 'on' || val.to_s == 'true' || val == '' || val.nil?
    end
    opts.on('--apps LIST', Array, "Monitor Apps, comma separated list of names or IDs.") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['apps'] = []
      else
        params['apps'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--contacts LIST', Array, "Contacts, comma separated list of Contact names or IDs. Additional recipient settings can be passed like Contact ID:method:notifyOnClose:notifyOnChange.") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['contacts'] = []
      else
        recipient_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
        params['contacts'] = recipient_list
      end
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
    opts.footer = "Create a monitoring alert rule." + "\n" +
                  "[name] is required. This is the name of the new alert rule."
  end
  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  if args[0]
    params['name'] = args[0]
  end
  connect(options)

  begin

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      if params['name'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Name', 'required' => true, 'description' => 'The name of this alert rule.'}], options[:options])
        params['name'] = v_prompt['name']
      end
      if params['minSeverity'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'minSeverity', 'type' => 'text', 'fieldLabel' => 'Min. Severity', 'required' => false, 'selectOptions' => available_severities, 'defaultValue' => 'critical', 'description' => 'Trigger when severity level is reached.'}], options[:options])
        params['minSeverity'] = v_prompt['minSeverity'].to_s unless v_prompt['minSeverity'].nil?
      end
      if params['minDuration'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'minDuration', 'type' => 'text', 'fieldLabel' => 'Min. Duration', 'required' => false, 'defaultValue' => '0', 'description' => 'Trigger after a number of minutes.'}], options[:options])
        params['minDuration'] = v_prompt['minDuration'].to_i unless v_prompt['minDuration'].nil?
      end
      # All Checks?
      if params['allChecks'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allChecks', 'type' => 'text', 'fieldLabel' => 'All Checks?', 'required' => false, 'defaultValue' => 'off', 'description' => 'Trigger for all checks.'}], options[:options])
        params['allChecks'] = (['on','true'].include?(v_prompt['allChecks'].to_s)) unless v_prompt['allChecks'].nil?
      end
      # Checks
      if params['allChecks'] == true
        params.delete('checks')
      else
        prompt_results = prompt_for_checks(params, options, @api_client)
        if prompt_results[:success]
          params['checks'] = prompt_results[:data] unless prompt_results[:data].nil?
        else
          return 1
        end
      end

      # All Check Groups?
      if params['allGroups'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allGroups', 'type' => 'text', 'fieldLabel' => 'All Groups?', 'required' => false, 'defaultValue' => 'off', 'description' => 'Trigger for all check groups.'}], options[:options])
        params['allGroups'] = (['on','true'].include?(v_prompt['allGroups'].to_s)) unless v_prompt['allGroups'].nil?
      end
      # Check Groups
      if params['allGroups'] == true
        params.delete('checkGroups')
      else
        prompt_results = prompt_for_check_groups(params, options, @api_client)
        if prompt_results[:success]
          params['checkGroups'] = prompt_results[:data] unless prompt_results[:data].nil?
        else
          return 1
        end
      end

      # All Apps?
      if params['allApps'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allApps', 'type' => 'text', 'fieldLabel' => 'All Apps?', 'required' => false, 'defaultValue' => 'off', 'description' => 'Trigger for all monitoring apps.'}], options[:options])
        params['allApps'] = (['on','true'].include?(v_prompt['allApps'].to_s)) unless v_prompt['allApps'].nil?
      end
      # Apps
      if params['allApps'] == true
        params.delete('apps')
      else
        prompt_results = prompt_for_monitor_apps(params, options, @api_client)
        if prompt_results[:success]
          params['apps'] = prompt_results[:data] unless prompt_results[:data].nil?
        else
          return 1
        end
      end

      # Recipients (Contacts)
      recipient_list = []
      contact_ids = []
        
      if params['contacts'].nil?
        still_prompting = true
        while still_prompting
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'contacts', 'type' => 'text', 'fieldLabel' => 'Contacts', 'required' => false, 'description' => "Contacts, comma separated list of contact names or IDs. Additional recipient settings can be passed like Contact ID:method:notifyOnClose:notifyOnChange"}], options[:options])
          unless v_prompt['contacts'].to_s.empty?
            recipient_list = v_prompt['contacts'].split(",").collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
          end
          bad_ids = []
          if recipient_list && recipient_list.size > 0
            recipient_list.each do |it|
              found_contact = nil
              begin
                parts = it.split(":").collect { |part| part.strip }
                found_contact = find_contact_by_name_or_id(parts[0])
              rescue SystemExit => cmdexit
              end
              if found_contact
                contact_ids << found_contact['id']
              else
                bad_ids << it
              end
            end
          end
          still_prompting = bad_ids.empty? ? false : true
        end
      else
        recipient_list = params['contacts']
        bad_ids = []
        if recipient_list && recipient_list.size > 0
          recipient_list.each do |it|
            found_contact = nil
            begin
              parts = it.split(":").collect { |part| part.strip }
              found_contact = find_contact_by_name_or_id(parts[0])
            rescue SystemExit => cmdexit
            end
            if found_contact
              contact_ids << found_contact['id']
            else
              bad_ids << it
            end
          end
        end
        if !bad_ids.empty?
          return 1
        end
      end
      recipient_records = []
      # parse recipient string as Contact ID:method:notifyOnClose:notifyOnChange
      recipient_list.each_with_index do |it, index|
        parts = it.split(":").collect { |part| part.strip }
        #recipient_id = parts[0]
        recipient_id = contact_ids[index]

        recipient_method = parts[1] ? parts[1].to_s : "emailAddress"
        recipient_notify = parts[2] ? ['on','true'].include?(parts[2].to_s.downcase) : true
        recipient_close = parts[3] ? ['on','true'].include?(parts[3].to_s.downcase) : true
        recipient_record = {
          "id" => recipient_id, 
          "method" => parse_recipient_method(recipient_method), 
          "notify" => recipient_notify,
          "close" => recipient_close
        }
        recipient_records << recipient_record
      end
      params['contacts'] = recipient_records
      
      payload = {'alert' => params}
    end

    @monitoring_alerts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @monitoring_alerts_interface.dry.create(payload)
      return
    end

    json_response = @monitoring_alerts_interface.create(payload)
    alert = json_response['alert']
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Created alert (#{alert['id']}) #{alert['name']}"
      #_get(alert['id'], options)
    end

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

#connect(opts) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 22

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @monitoring_interface = @api_client.monitoring
  @monitoring_alerts_interface = @api_client.monitoring.alerts
  @monitoring_checks_interface = @api_client.monitoring.checks
  @monitoring_groups_interface = @api_client.monitoring.groups
  @monitoring_apps_interface = @api_client.monitoring.apps
  @monitoring_contacts_interface = @api_client.monitoring.contacts
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[alert]")
    # opts.on(nil,'--history', "Display History") do |val|
    #   options[:show_history] = true
    # end
    # opts.on(nil,'--notifications', "Display Notifications") do |val|
    #   options[:show_notifications] = true
    # end
    build_common_options(opts, options, [:json, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a monitoring alert rule." + "\n" +
                  "[alert] is required. This is the name or ID of the alert rule. Supports 1-N [alert] arguments."
  end
  optparse.parse!(args)
  if args.count < 1
    raise_command_error "wrong number of arguments, expected 1-N and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  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



32
33
34
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 32

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 36

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :last_updated, :query, :json, :csv, :yaml, :fields, :json, :dry_run, :remote])
    opts.footer = "List monitoring alert rules."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))
    # JD: lastUpdated 500ing, alerts don't have that property ? =o  Fix it!
    @monitoring_alerts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @monitoring_alerts_interface.dry.list(params)
      return
    end

    json_response = @monitoring_alerts_interface.list(params)
    if options[:json]
      puts as_json(json_response, options, "alerts")
      return 0
    elsif options[:yaml]
      puts as_json(json_response, options, "alerts")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['alerts'], options)
      return 0
    end
    alerts = json_response['alerts']
    title = "Morpheus Monitoring Alerts"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options
    if alerts.empty?
      print cyan,"No alerts found.",reset,"\n"
    else
      print_alerts_table(alerts, options)
      print_results_pagination(json_response, {:label => "alert", :n_label => "alerts"})
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 691

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[alert]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Delete a monitoring alert rule." + "\n" +
                  "[alert] is required. This is the name or ID of the alert rule. Supports 1-N [alert] arguments."
  end
  optparse.parse!(args)
  if args.count < 1
    raise_command_error "wrong number of arguments, expected 1-N and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  id_list = parse_id_list(args)
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to delete #{id_list.size == 1 ? 'alert' : 'alerts'} #{anded_list(id_list)}?", options)
    exit 1
  end
  return run_command_for_each_arg(id_list) do |arg|
    _remove(arg, options)
  end
end

#update(args) ⇒ Object



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'lib/morpheus/cli/monitoring_alerts_command.rb', line 473

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[alert]")
    opts.on("--name STRING", String, "Alert name") do |val|
      params['name'] = val
    end
    opts.on("--name STRING", String, "Alert name") do |val|
      params['name'] = val
    end
    opts.on('--min-severity VALUE', String, "Min. Severity. Trigger when severity level is reached. Default is critical") do |val|
      params['minSeverity'] = val.to_s.downcase
    end
    opts.on('--min-duration MINUTES', String, "Min. Duration. Trigger after a number of minutes. Default is 0 (immediate)") do |val|
      params['minDuration'] = val.to_i
    end
    opts.on('--all-checks [on|off]', String, "Toggle trigger for all checks.") do |val|
      params['allChecks'] = val.to_s == 'on' || val.to_s == 'true' || val == '' || val.nil?
    end
    opts.on('--checks LIST', Array, "Checks, comma separated list of names or IDs.") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['checks'] = []
      else
        params['checks'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--all-groups [on|off]', String, "Toggle trigger for all check groups.") do |val|
      params['allGroups'] = val.to_s == 'on' || val.to_s == 'true' || val == '' || val.nil?
    end
    opts.on('--groups LIST', Array, "Check Groups, comma separated list of check group ID or names.") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['checkGroups'] = []
      else
        params['checkGroups'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--all-apps [on|off]', String, "Toggle trigger for all check groups.") do |val|
      params['allApps'] = val.to_s == 'on' || val.to_s == 'true' || val == '' || val.nil?
    end
    opts.on('--apps LIST', Array, "Monitor Apps, comma separated list of monitor app ID or names.") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['apps'] = []
      else
        params['apps'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--contacts LIST', Array, "Contacts, comma separated list of contact ID or names. Additional recipient settings can be passed like Contact ID:method:notifyOnClose:notifyOnChange") do |list|
      if list.size == 1 && ('[]' == list[0]) # clear array
        params['contacts'] = []
      else
        recipient_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
        params['contacts'] = recipient_list
      end
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
    opts.footer = "Update a monitoring alert rule." + "\n" +
                  "[alert] is required. This is the name or ID of the alert rule."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)

  begin
    alert = find_alert_by_name_or_id(args[0])

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      # if params['name'].nil?
      #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Name', 'required' => true, 'description' => 'The name of this alert rule.'}], options[:options])
      #   params['name'] = v_prompt['name']
      # end
      # if params['minSeverity'].nil?
      #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'minSeverity', 'type' => 'text', 'fieldLabel' => 'Min. Severity', 'required' => false, 'selectOptions' => available_severities, 'defaultValue' => 'critical', 'description' => 'Trigger when severity level is reached.'}], options[:options])
      #   params['minSeverity'] = v_prompt['minSeverity'].to_s unless v_prompt['minSeverity'].nil?
      # end
      # if params['minDuration'].nil?
      #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'minDuration', 'type' => 'text', 'fieldLabel' => 'Min. Duration', 'required' => false, 'defaultValue' => '0', 'description' => 'Trigger after a number of minutes.'}], options[:options])
      #   params['minDuration'] = v_prompt['minDuration'].to_i unless v_prompt['minDuration'].nil?
      # end
      # All Checks?
      # if params['allChecks'].nil?
      #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allChecks', 'type' => 'text', 'fieldLabel' => 'All Checks?', 'required' => false, 'defaultValue' => 'off', 'description' => 'Trigger for all checks.'}], options[:options])
      #   params['allChecks'] = (['on','true'].include?(v_prompt['allChecks'].to_s)) unless v_prompt['allChecks'].nil?
      # end
      # Checks
      if params['checks']
        prompt_results = prompt_for_checks(params, options, @api_client)
        if prompt_results[:success]
          params['checks'] = prompt_results[:data] unless prompt_results[:data].nil?
        else
          return 1
        end
      end

      # All Check Groups?
      # if params['allGroups'].nil?
      #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allGroups', 'type' => 'text', 'fieldLabel' => 'All Groups?', 'required' => false, 'defaultValue' => 'off', 'description' => 'Trigger for all check groups.'}], options[:options])
      #   params['allGroups'] = (['on','true'].include?(v_prompt['allGroups'].to_s)) unless v_prompt['allGroups'].nil?
      # end
      # Check Groups
      if params['checkGroups']
        prompt_results = prompt_for_check_groups(params, options, @api_client)
        if prompt_results[:success]
          params['checkGroups'] = prompt_results[:data] unless prompt_results[:data].nil?
        else
          return 1
        end
      end

      # All Apps?
      # if params['allApps'].nil?
      #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allApps', 'type' => 'text', 'fieldLabel' => 'All Apps?', 'required' => false, 'defaultValue' => 'off', 'description' => 'Trigger for all monitoring apps.'}], options[:options])
      #   params['allApps'] = (['on','true'].include?(v_prompt['allApps'].to_s)) unless v_prompt['allApps'].nil?
      # end
      # Apps
      if params['apps']
        prompt_results = prompt_for_monitor_apps(params, options, @api_client)
        if prompt_results[:success]
          params['apps'] = prompt_results[:data] unless prompt_results[:data].nil?
        else
          return 1
        end
      end

      # Recipients (Contacts)
      if params['contacts']
        
        recipient_list = params['contacts']
        contact_ids = []
        bad_ids = []
        if recipient_list && recipient_list.size > 0
          recipient_list.each do |it|
            found_contact = nil
            begin
              parts = it.split(":").collect { |part| part.strip }
              found_contact = find_contact_by_name_or_id(parts[0])
            rescue SystemExit => cmdexit
            end
            if found_contact
              contact_ids << found_contact['id']
            else
              bad_ids << it
            end
          end
        end
        if !bad_ids.empty?
          return 1
        end
        recipient_records = []
        # parse recipient string as Contact ID:method:notifyOnClose:notifyOnChange
        existing_recipients = alert['contacts'] || []
        recipient_list.each_with_index do |it, index|
          parts = it.split(":").collect { |part| part.strip }
          #recipient_id = parts[0]
          recipient_id = contact_ids[index]
          recipient_record = {
            "id" => recipient_id
          }
          # preserve existing values for these settings
          existing_recipient = existing_recipients.find {|rec| rec['id'] == recipient_id.to_i }
          if parts[1]
            recipient_record["method"] = parse_recipient_method(parts[1].to_s)
          elsif existing_recipient
            recipient_record["method"] = existing_recipient["method"]
          end
          if parts[2]
            recipient_record["notify"] = ['on','true'].include?(parts[2].to_s.downcase)
          elsif existing_recipient
            recipient_record["notify"] = existing_recipient["notify"]
          end
          if parts[3]
            recipient_record["close"] = ['on','true'].include?(parts[3].to_s.downcase)
          elsif existing_recipient
            recipient_record["close"] = existing_recipient["close"]
          end
          recipient_records << recipient_record
        end
        params['contacts'] = recipient_records
      end
      
      payload = {'alert' => params}
    end

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

    @monitoring_alerts_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @monitoring_alerts_interface.dry.update(alert["id"], payload)
      return
    end

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

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