Class: Morpheus::Cli::GuidanceCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand
Defined in:
lib/morpheus/cli/commands/guidance_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_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, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #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

Instance Method Details

#_get(id, options) ⇒ Object



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
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
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 240

def _get(id, options)
  params = {}
  begin
    @guidance_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @guidance_interface.dry.get(id, params)
      return
    end
    json_response = @guidance_interface.get(id, params)
    discovery = json_response['discovery']
    render_result = render_with_format(json_response, options, 'discovery')
    return 0 if render_result

    print_h1 "Discovery Info"
    print cyan

    description_cols = {
        "ID" => lambda {|it| it['id']},
        #"Ref ID" => lambda {|it| it['refId'] },
        "Resource" => lambda {|it| it['refName'] },
        "Action" => lambda {|it| action_title(it['type'])},
        "Date" => lambda {|it| format_local_date(it['dateCreated'], {:format => DEFAULT_TIME_FORMAT})},
        "State" => lambda {|it| (it['state'] == 'processed' ? green : (it['state'] == 'ignored' ? white : cyan)) + it['state'].capitalize + cyan}
    }
    description_cols['Cloud'] = lambda {|it| it['zone']['name']} if discovery['refType'] == 'computeServer'
    description_cols.merge!({
        "Action Category" => lambda {|it| it['actionCategory'].capitalize},
        "Action Type" => lambda {|it| it['actionType'].capitalize},
        "Savings" => lambda {|it| format_money(it['savings']['amount'], it['savings']['currency']) + '/month'}
    })
    print_description_list(description_cols, discovery)

    if discovery['resource']
      print_h2 "Resource Info"

      if discovery['refType'] == 'computeServer'
        cols = [
            {"Power State" => lambda {|it| format_status(it['resource']['powerState'])}},
            {"Status" => lambda {|it| (format_status(it['resource']['status']))}},
            {"Type" => lambda {|it| it['resource']['computeServerType']['name']}},
            {"Platform" => lambda {|it| ((it['resource']['serverOs'] ? it['resource']['serverOs']['platform'] : it['resource']['osType']) || 'unknown').capitalize}},
            {"Cloud Type" => lambda {|it| it['zone']['zoneType']['name']}}
        ]
      elsif discovery['refType'] == 'computeZone'
        cols = [
            {"Status" => lambda {|it| format_status(it['resource']['status'])}},
            {"Cloud Type" => lambda {|it| it['zone']['zoneType']['name']}}
        ]
      end
      print as_pretty_table(discovery, cols, options)
    end

    max_bars = 20

    if discovery['type']['code'] == 'size'
      print_h2 "Usage"
      cols = [
          {"Plan" => lambda {|it| it['planBeforeAction'] ? it['planBeforeAction']['name'] : '--'}},
          {"Compute Usage" => lambda {|it|
            usage = (it['config'] ? it['config']['cpuUsageAvg'] || 0 : 0)
            "#{format_percent(usage)} of 100%".ljust(25, ' ') + generate_usage_bar(usage.round(2), 100, {:max_bars => max_bars}) + cyan
          }},
          {"Memory Usage" => lambda {|it|
            max = (it['resource'] || {})['maxMemory'] || (it['planBeforeAction'] || {})['maxMemory']
            usage = max > 0 ? (it['config']['usedMemoryAvg'] || 0).to_f / max * 100.0 : 0
            usage = 200.0 if usage > 200
            "#{format_bytes((it['config'] || {})['usedMemoryAvg'] || 0, 'auto', 1)} of #{format_bytes(max, 'auto', 1)}".ljust(25, ' ') + generate_usage_bar(usage, 100, {:max_bars => max_bars}) + cyan
          }}
      ]
      print_description_list(cols, discovery, options.merge({:wrap => false}))
      print_h2 "After Resize"

      if discovery['planAfterAction'] && discovery['planAfterAction']['id'] != (discovery['planBeforeAction'] || {})['id']
        cols = [
            {"Plan" => lambda {|it| it['planAfterAction'] ? it['planAfterAction']['name'] : '--'}},
            {"Compute Usage" => lambda {|it|
              usage = ((it['planAfterAction'] || {})['maxCores'] || 0) > 0 ? (((it['resource'] || {})['maxCores'] || (it['planBeforeAction'] || {})['maxCores']) || 0).to_f / it['planAfterAction']['maxCores'] * (it['config']['cpuUsageAvg'] || 0) : 0
              "#{format_percent(usage)} of 100%".ljust(25, ' ') + generate_usage_bar(usage.round(2), 100, {:max_bars => max_bars}) + cyan
            }},
            {"Memory Usage" => lambda {|it|
              max = (it['planAfterAction'] || {})['maxMemory'] || 0
              usage = max > 0 ? ((it['config'] || {})['usedMemoryAvg'] || 0).to_f / it['planAfterAction']['maxMemory'] * 100.0 : 0
              usage = 200.0 if usage > 200
              "#{format_bytes((it['config'] || {})['usedMemoryAvg'] || 0, 'auto', 1)} of #{format_bytes(max, 'auto', 1)}".ljust(25, ' ') + generate_usage_bar(usage, 100, {:max_bars => max_bars}) + cyan
            }}
        ]
      else
        if discovery['actionValueType'] == 'memory'
          cols = [
              {"Memory" => lambda {|it| format_bytes(it['actionValue'].to_i, 'auto')}},
              {"Compute Usage" => lambda {|it|
                usage = (it['config'] ? it['config']['cpuUsageAvg'] || 0 : 0).round(2)
                "#{format_percent(usage)} of 100%".ljust(25, ' ') + generate_usage_bar(usage, 100, {:max_bars => max_bars}) + cyan
              }},
              {"Memory Usage" => lambda {|it|
                max = (it['actionValue'] || 0).to_f
                usage = max > 0 ? ((it['config'] || {})['usedMemoryAvg'] || 0) / max * 100.0 : 0
                usage = 200.0 if usage > 200
                "#{format_bytes((it['config'] || {})['usedMemoryAvg'] || 0, 'auto', 1)} of #{format_bytes(max, 'auto', 1)}".ljust(25, ' ') + generate_usage_bar(usage, 100, {:max_bars => max_bars}) + cyan
              }}
          ]
        elsif discovery['actionValueType'] == 'cpu'
          cols = [
              {"Cores" => lambda {|it| it['actionValue']}},
              {"Compute Usage" => lambda {|it|
                cores_before = it['beforeValue'] || (it['resource'] || {})['maxCores'] || (it['planBeforeAction'] || {})['maxCores'] || 0
                usage = (it['actionValue'] || 0).to_f > 0 ? cores_before / it['actionValue'].to_f * ((it['config'] || {})['cpuUsageAvg'] || 0) : 0
                "#{format_percent(usage)} of 100%".ljust(25, ' ') + generate_usage_bar(usage.round(2), 100, {:max_bars => max_bars}) + cyan
              }},
              {"Memory Usage" => lambda {|it|
                max = (it['resource'] || {})['maxMemory'] || (it['planAfterAction'] || {})['maxMemory']
                usage = max > 0 ? ((it['config'] || {})['usedMemoryAvg'] || 0) / max.to_f * 100.0 : 0
                usage = 200.0 if usage > 200
                "#{format_bytes((it['config'] || {})['usedMemoryAvg'] || 0, 'auto', 1)} of #{format_bytes(max, 'auto', 1)}".ljust(25, ' ') + generate_usage_bar(usage, 100, {:max_bars => max_bars}) + cyan
              }}
          ]
        end
      end
      print_description_list(cols, discovery, options.merge({:wrap => false}))
    elsif discovery['type']['code'] == 'shutdown'
      print_h2 "Usage"
      cols = [
          {"Plan" => lambda {|it| it['planBeforeAction'] ? it['planBeforeAction']['name'] : '--'}},
          {"Compute Usage" => lambda {|it|
            usage = (it['config'] ? it['config']['cpuUsageAvg'] || 0 : 0).round(2).to_s
            "#{format_percent(usage)} of 100%".ljust(25, ' ') + generate_usage_bar(usage, 100, {:max_bars => max_bars}) + cyan
          }},
          {"Network Usage" => lambda {|it|
            max = 1024 * 1024 * 1024
            usage = (it['config']['networkBandwidthAvg'] || 0) > 0 ? ((it['config']['networkBandwidthAvg'] || 0) / max.to_f) * 100 : 0
            "#{format_bytes((it['config']['networkBandwidthAvg'] || 0), 'auto', 1)} of #{format_bytes(max, 'auto', 1)}".ljust(25, ' ') + generate_usage_bar( usage, 100, {:max_bars => max_bars}) + cyan
          }}
      ]

      print_description_list(cols, discovery, options.merge({:wrap => false}))

      print_h2 "After Shutdown"
      cols = [
          {"Plan" => lambda {|it| it['planAfterAction'] ? it['planAfterAction']['name'] : '--'}},
          {"Monthly Savings" => lambda {|it| format_money(it['savings']['amount'], it['savings']['currency'], {:minus_color => red})}}
      ]
      print_description_list(cols, discovery, options)
    elsif discovery['type']['code'] == 'reservations'
      print_h2 "Current Cost"
      cols = [
          {"Current Cost" => lambda {|it| format_money((it['onDemandCost'] || 0) + (it['reservedCost'] || 0), discovery['savings']['currency'], {:minus_color => red})}},
          {"On-Demand Cost" => lambda {|it| format_money((it['onDemandCost'] || 0), discovery['savings']['currency'], {:minus_color => red})}},
          #{"Proposed Cost" => lambda {|it| format_money((it['recommendedCost'] || 0), discovery['savings']['currency'], {:minus_color => red})}}
      ]

      print_description_list(cols, discovery['config']['summary'], options)

      print_h2 "After Reservations"
      cols = [
          {"Proposed Cost" => lambda {|it| format_money((it['recommendedCost'] || 0), discovery['savings']['currency'], {:minus_color => red})}},
          {"Monthly Savings" => lambda {|it| format_money(discovery['savings']['amount'], discovery['savings']['currency'], {:minus_color => red})}},
          {"Savings Percent" => lambda {|it| format_percent(it['totalSavingsPercent'] * 100.0)}}
      ]
      print_description_list(cols, discovery['config']['summary'], options)

      cols = [
          {"Name" => lambda {|it| it['name']}},
          {"Region" => lambda {|it| it['region']}},
          {"Term" => lambda {|it| it['term']}},
          {"Current Cost" => lambda {|it| format_money(it['onDemandCost'], discovery['savings']['currency'], {:minus_color => red})}},
          {"Quantity" => lambda {|it| it['recommendedCount']}},
          {"Proposed Cost" => lambda {|it| format_money(it['recommendedCost'], discovery['savings']['currency'], {:minus_color => red})}},
          {"Savings" => lambda {|it| format_money(it['totalSavings'], discovery['savings']['currency'], {:minus_color => red})}}
      ]
      print_h2 "Details"
      print as_pretty_table(discovery['config']['detailList'], cols, options)
    end

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

#connect(opts) ⇒ Object



11
12
13
14
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 11

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @guidance_interface = @api_client.guidance
end

#execute(args) ⇒ Object



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 421

def execute(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_standard_remove_options(opts, options)
    opts.footer = "Get details about a specific discovery."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 1
  end
  connect(options)
  _resolve_action(args[0], options)
end

#get(args) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 221

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_standard_get_options(opts, options)
    opts.footer = "Get details about a specific discovery."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 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



16
17
18
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 16

def handle(args)
  handle_subcommand(args)
end

#ignore(args) ⇒ Object



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 437

def ignore(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_standard_remove_options(opts, options)
    opts.footer = "Ignore discovery."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 1
  end
  connect(options)
  _resolve_action(args[0], options, false)
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 137

def list(args)
  options = {}
  params = {}
  ref_ids = []
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('-l', '--severity LEVEL', String, "Filter by Severity Level: info, low, warning, critical" ) do |val|
      params['severity'] = val
    end
    opts.on('-t', '--type TYPE', String, "Filter by Type") do |val|
      options[:type] = val
    end
    opts.on('-i', '--ignored', String, "Include Ignored Discoveries") do |val|
      params['state'] = 'ignored'
    end
    opts.on('-p', '--processed', String, "Include Processed Discoveries") do |val|
      params['state'] = 'processed'
    end
    opts.on('-a', '--any', String, "Include Processed and Ignored Discoveries") do |val|
      params['state'] = 'any'
    end
    build_standard_list_options(opts, options)
    opts.footer = "List discoveries"
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 0
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0 and got (#{args.count}) #{args.join(', ')}\n#{optparse}"
    return 1
  end
  begin
    if options[:type]
      type = find_discovery_type(options[:type])

      if !type
        print_red_alert "Type #{options[:type]} not found"
        exit 1
      end
      params['code'] = type['code']
    end

    params.merge!(parse_list_options(options))
    @guidance_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @guidance_interface.dry.list(params)
      return
    end
    json_response = @guidance_interface.list(params)
    render_result = render_with_format(json_response, options, 'discoveries')
    return 0 if render_result

    discoveries = json_response['discoveries']

    subtitles = params['state'] ? ["state: #{params['state']}"] : []
    subtitles += parse_list_subtitles(options)
    print_h1 "Morpheus Discoveries", subtitles

    if discoveries.empty?
      print cyan,"No discoveries found.",reset,"\n"
    else
      cols = [
          {"ID" => lambda {|it| it['id']}},
          {"SEVERITY" => lambda {|it| (it['severity'] || '').capitalize}},
          {"TYPE/METRIC" => lambda {|it| it['type'] ? "#{it['type']['name']}: #{it['actionCategory'].capitalize || ''}" : ''}},
          {"ACTION" => lambda {|it| it['actionType'].capitalize}},
          {"CLOUD" => lambda {|it| it['zone'] ? it['zone']['name'] : ''}},
          {"RESOURCE" => lambda {|it| it['refName']}},
          {"SAVINGS" => lambda {|it| format_money(it['savings']['amount'], it['savings']['currency'], {:minus_color => red})}},
          {"DATE" => lambda {|it| format_local_date(it['dateCreated'], {:format => DEFAULT_TIME_FORMAT})}}
      ];
      if params['state'] == 'any'
        cols << {"STATE" => lambda {|it| (it['state'] == 'processed' ? green : (it['state'] == 'ignored' ? white : '')) + it['state'].capitalize + cyan}}
      end
      print as_pretty_table(discoveries, cols, options)
      print_results_pagination(json_response, {:label => "discovery", :n_label => "discoveries"})
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#stats(args) ⇒ Object



20
21
22
23
24
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
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 20

def stats(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_standard_get_options(opts, options)
    opts.footer = "Get guidance stats."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    @guidance_interface.setopts(options)

    if options[:dry_run]
      print_dry_run @guidance_interface.dry.stats()
      return
    end
    json_response = @guidance_interface.stats()
    if options[:json]
      puts as_json(json_response, options, "stats")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "stats")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['stats']], options)
      return 0
    end

    stats = json_response['stats']

    print_h1 "Guidance Stats"
    print cyan
    description_cols = {
        "Total Actions" => lambda {|it| it['total'] },
        "Savings Available" => lambda {|it| format_money(it['savings']['amount'], it['savings']['currency'], {:minus_color => red}) }
    }
    print_description_list(description_cols, stats)

    print_h2 "Severity Totals"
    {'info'=>white, 'low'=>yellow, 'warning'=>bright_yellow, 'critical'=>red}.each do |level, color|
      print "#{cyan}#{level.capitalize}".rjust(14, ' ') + ": " + stats['severity'][level].to_s.ljust(10, ' ')
      # print "#{cyan} #{guidance['stats']['severity'][level]} of #{guidance['stats']['severity'].collect{|k, v| v}.reduce(:+)}".ljust(20, ' ')
      println generate_usage_bar(stats['severity'][level], stats['severity'].collect{|k, v| v}.reduce(:+), {:max_bars => 20, :bar_color => color})
    end

    # "size": 13, "shutdown": 15, "move": 0, "schedule"
    print_h2 "Action Totals"
    {'size'=>green, 'move'=>magenta, 'shutdown'=>red, 'schedule'=>bright_yellow}.each do |level, color|
      print "#{cyan}#{level.capitalize}".rjust(14, ' ') + ": " + stats['type'][level].to_s.ljust(10, ' ')
      println generate_usage_bar(stats['type'][level], stats['type'].collect{|k, v| v}.reduce(:+), {:max_bars => 20, :bar_color => color})
    end
    print reset, "\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#types(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
108
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
# File 'lib/morpheus/cli/commands/guidance_command.rb', line 84

def types(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_standard_get_options(opts, options)
    opts.footer = "List discovery types."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    @guidance_interface.setopts(options)

    if options[:dry_run]
      print_dry_run @guidance_interface.dry.types()
      return
    end
    json_response = @guidance_interface.types()
    if options[:json]
      puts as_json(json_response, options, "types")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "types")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['types']], options)
      return 0
    end

    types = json_response['types']

    print_h1 "Discovery Types"
    print cyan

    cols = [
        {"ID" => lambda {|it| it['id']}},
        {"NAME" => lambda {|it| it['name']}},
        {"TITLE" => lambda {|it| it['title']}},
        {"CODE" => lambda {|it| it['code']}}
    ];
    print as_pretty_table(types, cols, options)
    print reset, "\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end