Class: Morpheus::Cli::Hosts

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProvisioningHelper

#api_client, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_name, #get_available_clouds, #get_available_groups, included, #instance_context_options, #instance_types_interface, #instances_interface, #options_interface, #prompt_evars, #prompt_network_interfaces, #prompt_new_instance, #prompt_resize_volumes, #prompt_volumes, #reject_networking_option_types, #reject_service_plan_option_types, #reject_volume_option_types

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #handle_subcommand, included, #interactive?, #noninteractive, #print_usage, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeHosts

Returns a new instance of Hosts.



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

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

Instance Method Details

#add(args) ⇒ Object



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
472
473
# File 'lib/morpheus/cli/hosts.rb', line 320

def add(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[cloud]", "[name]")
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    opts.on( '-t', '--type TYPE', "Server Type Code" ) do |val|
      options[:server_type_code] = val
    end
    build_common_options(opts, options, [:options, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  connect(options)

  # support old format of `hosts add CLOUD NAME`
  if args[0]
    options[:cloud] = args[0]
  end
  if args[1]
    options[:host_name] = args[1]
  end
  # use active group by default
  options[:group] ||= @active_group_id

  params = {}

  # Group
  group_id = nil
  group = options[:group] ? find_group_by_name_or_id_for_provisioning(options[:group]) : nil
  if group
    group_id = group["id"]
  else
    # print_red_alert "Group not found or specified!"
    # exit 1
    group_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'type' => 'select', 'fieldLabel' => 'Group', 'selectOptions' => get_available_groups(), 'required' => true, 'description' => 'Select Group.'}],options[:options],@api_client,{})
    group_id = group_prompt['group']
  end

  # Cloud
  cloud_id = nil
  cloud = options[:cloud] ? find_cloud_by_name_or_id_for_provisioning(group_id, options[:cloud]) : nil
  if cloud
    cloud_id = cloud["id"]
  else
    available_clouds = get_available_clouds(group_id)
    if available_clouds.empty?
      print_red_alert "Group #{group['name']} has no available clouds"
      exit 1
    end
    cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'selectOptions' => available_clouds, 'required' => true, 'description' => 'Select Cloud.'}],options[:options],@api_client,{groupId: group_id})
    cloud_id = cloud_prompt['cloud']
    cloud = find_cloud_by_id_for_provisioning(group_id, cloud_id)
  end

  # Zone Type
  cloud_type = cloud_type_for_id(cloud['zoneTypeId'])

  # Server Type
  cloud_server_types = cloud_type['serverTypes'].select{|b| b['creatable'] == true }.sort { |x,y| x['displayOrder'] <=> y['displayOrder'] }
  if options[:server_type_code]
    server_type_code = options[:server_type_code]
  else
    server_type_options = cloud_server_types.collect {|it| {'name' => it['name'], 'value' => it['code']} }
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'type' => 'select', 'fieldLabel' => "Server Type", 'selectOptions' => server_type_options, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a server type.'}], options[:options])
    server_type_code = v_prompt['type']
  end
  server_type = cloud_server_types.find {|it| it['code'] == server_type_code }
  if server_type.nil?
    print_red_alert "Server Type #{server_type_code} not found cloud #{cloud['name']}"
    exit 1
  end

  # Server Name
  host_name = nil
  if options[:host_name]
    host_name = options[:host_name]
  else
    name_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Server Name', 'type' => 'text', 'required' => true}], options[:options])
    host_name = name_prompt['name'] || ''
  end

  payload = {}
  # prompt for service plan
  service_plans_json = @servers_interface.service_plans({zoneId: cloud['id'], serverTypeId: server_type["id"]})
  service_plans = service_plans_json["plans"]
  service_plans_dropdown = service_plans.collect {|sp| {'name' => sp["name"], 'value' => sp["id"]} } # already sorted
  plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'plan', 'type' => 'select', 'fieldLabel' => 'Plan', 'selectOptions' => service_plans_dropdown, 'required' => true, 'description' => 'Choose the appropriately sized plan for this server'}],options[:options])
  service_plan = service_plans.find {|sp| sp["id"] == plan_prompt['plan'].to_i }

  # prompt for volumes
  volumes = prompt_volumes(service_plan, options, @api_client, {})
  if !volumes.empty?
    payload[:volumes] = volumes
  end

  # prompt for network interfaces (if supported)
  if server_type["provisionType"] && server_type["provisionType"]["id"] && server_type["provisionType"]["hasNetworks"]
    begin
      network_interfaces = prompt_network_interfaces(cloud['id'], server_type["provisionType"]["id"], options)
      if !network_interfaces.empty?
        payload[:networkInterfaces] = network_interfaces
      end
    rescue RestClient::Exception => e
      print_yellow_warning "Unable to load network options. Proceeding..."
      print_rest_exception(e, options) if Morpheus::Logging.debug?
    end
  end

  server_type_option_types = server_type['optionTypes']
  # remove volume options if volumes were configured
  if !payload[:volumes].empty?
    server_type_option_types = reject_volume_option_types(server_type_option_types)
  end
  # remove networkId option if networks were configured above
  if !payload[:networkInterfaces].empty?
    server_type_option_types = reject_networking_option_types(server_type_option_types)
  end
  # remove cpu and memory option types, which now come from the plan
  server_type_option_types = reject_service_plan_option_types(server_type_option_types)

  params = Morpheus::Cli::OptionTypes.prompt(server_type_option_types,options[:options],@api_client, {zoneId: cloud['id']})
  begin
    params['server'] = params['server'] || {}
    payload = payload.merge({
                              server: {
                                name: host_name,
                                zone: {id: cloud['id']},
                                computeServerType: {id: server_type['id']},
                                plan: {id: service_plan["id"]}
                              }.merge(params['server'])
    })
    payload[:network] = params['network'] if params['network']
    payload[:config] = params['config'] if params['config']
    if options[:dry_run]
      print_dry_run @servers_interface.dry.create(payload)
      return
    end
    json_response = @servers_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Provisioning Server..." 
      list([])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



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

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @clouds_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).clouds
  @options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).options
  @tasks_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).tasks
  @task_sets_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).task_sets
  @servers_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).servers
  @logs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).logs
  @active_group_id = Morpheus::Cli::Groups.active_group
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @servers_interface.dry.get(args[0].to_i)
      else
        print_dry_run @servers_interface.dry.get({name: args[0]})
      end
      return
    end
    server = find_host_by_name_or_id(args[0])
    json_response = @servers_interface.get(server['id'])
    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    server = json_response['server']
    #stats = server['stats'] || json_response['stats'] || {}
    stats = json_response['stats'] || {}

    print "\n" ,cyan, bold, "Host Details\n","==================", reset, "\n\n"
    print cyan
    puts "ID: #{server['id']}"
    puts "Name: #{server['name']}"
    puts "Description: #{server['description']}"
    puts "Account: #{server['account'] ? server['account']['name'] : ''}"
    #puts "Group: #{server['group'] ? server['group']['name'] : ''}"
    #puts "Cloud: #{server['cloud'] ? server['cloud']['name'] : ''}"
    puts "Cloud: #{server['zone'] ? server['zone']['name'] : ''}"
    puts "Nodes: #{server['containers'] ? server['containers'].size : ''}"
    puts "Type: #{server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged'}"
    puts "Platform: #{server['serverOs'] ? server['serverOs']['name'].upcase : 'N/A'}"
    puts "Plan: #{server['plan'] ? server['plan']['name'] : ''}"
    if server['agentInstalled']
      puts "Agent: #{server['agentVersion'] || ''} updated at #{format_local_dt(server['lastAgentUpdate'])}"
    else
      puts "Agent: (not installed)"
    end
    puts "Status: #{format_host_status(server)}"
    puts "Power: #{format_server_power_state(server)}"
    if ((stats['maxMemory'].to_i != 0) || (stats['maxStorage'].to_i != 0))
      # stats_map = {}
      print "\n"
      #print "\n" ,cyan, bold, "Host Stats\n","==================", reset, "\n\n"
      # stats_map[:memory] = "#{Filesize.from("#{stats['usedMemory']} B").pretty} / #{Filesize.from("#{stats['maxMemory']} B").pretty}"
      # stats_map[:storage] = "#{Filesize.from("#{stats['usedStorage']} B").pretty} / #{Filesize.from("#{stats['maxStorage']} B").pretty}"
      # stats_map[:cpu] = "#{stats['cpuUsage'].to_f.round(2)}%"
      # tp [stats_map], :memory,:storage,:cpu
      print_stats_usage(stats)
    else
      #print yellow, "No stat data.", reset
    end

    print reset, "\n"

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

#handle(args) ⇒ Object



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

def handle(args)
  handle_subcommand(args)
end

#install_agent(args) ⇒ Object



676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
# File 'lib/morpheus/cli/hosts.rb', line 676

def install_agent(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_option_type_options(opts, options, install_agent_option_types(false))
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host = find_host_by_name_or_id(args[0])
    if host['agentInstalled']
      print_red_alert "Agent already installed on host '#{host['name']}'"
      return false
    end
    payload = {
      'server' => {}
    }
    params = Morpheus::Cli::OptionTypes.prompt(install_agent_option_types, options[:options], @api_client, options[:params])
    server_os = params.delete('serverOs')
    if server_os
      payload['server']['serverOs'] = {id: server_os}
    end
     = params.delete('account') # not yet implemented
    if 
      payload['server']['account'] = {id: }
    end
    payload['server'].merge!(params)

    if options[:dry_run]
      print_dry_run @servers_interface.dry.install_agent(host['id'], payload)
      return
    end
    json_response = @servers_interface.install_agent(host['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Host #{host['name']} is being converted to managed."
      puts "Public Key:\n#{json_response['publicKey']}\n(copy to your authorized_keys file)"
    end
    return true
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/morpheus/cli/hosts.rb', line 36

def list(args)
  options = {}
  params = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    build_common_options(opts, options, [:list, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  connect(options)
  begin
    group = options[:group] ? find_group_by_name_or_id_for_provisioning(options[:group]) : nil
    if group
      params['siteId'] = group['id']
    end

    # argh, this doesn't work because group_id is required for options/clouds
    # cloud = options[:cloud] ? find_cloud_by_name_or_id_for_provisioning(group_id, options[:cloud]) : nil
    cloud = options[:cloud] ? find_zone_by_name_or_id(nil, options[:cloud]) : nil
    if cloud
      params['zoneId'] = cloud['id']
    end

    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end

    if options[:dry_run]
      print_dry_run @servers_interface.dry.get(params)
      return
    end
    json_response = @servers_interface.get(params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      servers = json_response['servers']
      title = "Morpheus Hosts"
      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
      subtitle = subtitles.join(', ')
      print "\n" ,cyan, bold, title, (subtitle.empty? ? "" : " - #{subtitle}"), "\n", "==================", reset, "\n\n"
      if servers.empty?
        puts yellow,"No hosts found.",reset
      else
        print_servers_table(servers)
        print_results_pagination(json_response)
      end
      print reset,"\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#logs(args) ⇒ Object



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
274
275
276
277
278
279
280
281
282
283
# File 'lib/morpheus/cli/hosts.rb', line 233

def logs(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:list, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host = find_host_by_name_or_id(args[0])
    params = {}
    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    if options[:dry_run]
      print_dry_run @logs_interface.dry.server_logs([host['id']], params)
      return
    end
    logs = @logs_interface.server_logs([host['id']], params)
    output = ""
    if options[:json]
      output << JSON.pretty_generate(logs)
    else
      logs['data'].reverse.each do |log_entry|
        log_level = ''
        case log_entry['level']
        when 'INFO'
          log_level = "#{blue}#{bold}INFO#{reset}"
        when 'DEBUG'
          log_level = "#{white}#{bold}DEBUG#{reset}"
        when 'WARN'
          log_level = "#{yellow}#{bold}WARN#{reset}"
        when 'ERROR'
          log_level = "#{red}#{bold}ERROR#{reset}"
        when 'FATAL'
          log_level = "#{red}#{bold}FATAL#{reset}"
        end
        output << "[#{log_entry['ts']}] #{log_level} - #{log_entry['message']}\n"
      end
    end
    print output, reset, "\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



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

def remove(args)
  options = {}
  query_params = {removeResources: 'on', force: 'off'}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [-f] [-S]")
    opts.on( '-f', '--force', "Force Remove" ) do
      query_params[:force] = 'on'
    end
    opts.on( '-S', '--skip-remove-infrastructure', "Skip removal of underlying cloud infrastructure" ) do
      query_params[:removeResources] = 'off'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)

  begin
    server = find_host_by_name_or_id(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the server '#{server['name']}'?", options)
      exit 1
    end
    if options[:dry_run]
      print_dry_run @servers_interface.dry.destroy(server['id'], query_params)
      return
    end
    json_response = @servers_interface.destroy(server['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Host #{server['name']} is being removed..."
      #list([])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#resize(args) ⇒ Object



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

def resize(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:options, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    server = find_host_by_name_or_id(args[0])

    group_id = server["siteId"] || erver['group']['id']
    cloud_id = server["zoneId"] || server["zone"]["id"]
    server_type_id = server['computeServerType']['id']
    plan_id = server['plan']['id']
    payload = {
      :server => {:id => server["id"]}
    }

    # avoid 500 error
    # payload[:servicePlanOptions] = {}
    unless options[:no_prompt]
      puts "\nDue to limitations by most Guest Operating Systems, Disk sizes can only be expanded and not reduced.\nIf a smaller plan is selected, memory and CPU (if relevant) will be reduced but storage will not.\n\n"
      # unless hot_resize
      #   puts "\nWARNING: Resize actions for this server will cause instances to be restarted.\n\n"
      # end
    end

    # prompt for service plan
    service_plans_json = @servers_interface.service_plans({zoneId: cloud_id, serverTypeId: server_type_id})
    service_plans = service_plans_json["plans"]
    service_plans_dropdown = service_plans.collect {|sp| {'name' => sp["name"], 'value' => sp["id"]} } # already sorted
    service_plans_dropdown.each do |plan|
      if plan['value'] && plan['value'].to_i == plan_id.to_i
        plan['name'] = "#{plan['name']} (current)"
      end
    end
    plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'plan', 'type' => 'select', 'fieldLabel' => 'Plan', 'selectOptions' => service_plans_dropdown, 'required' => true, 'description' => 'Choose the appropriately sized plan for this server'}],options[:options])
    service_plan = service_plans.find {|sp| sp["id"] == plan_prompt['plan'].to_i }
    payload[:server][:plan] = {id: service_plan["id"]}

    # fetch volumes
    volumes_response = @servers_interface.volumes(server['id'])
    current_volumes = volumes_response['volumes'].sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }

    # prompt for volumes
    volumes = prompt_resize_volumes(current_volumes, service_plan, options)
    if !volumes.empty?
      payload[:volumes] = volumes
    end

    # todo: reconfigure networks
    #       need to get provision_type_id for network info
    # prompt for network interfaces (if supported)
    # if server_type["provisionType"] && server_type["provisionType"]["id"] && server_type["provisionType"]["hasNetworks"]
    #   begin
    #     network_interfaces = prompt_network_interfaces(cloud['id'], server_type["provisionType"]["id"], options)
    #     if !network_interfaces.empty?
    #       payload[:networkInterfaces] = network_interfaces
    #     end
    #   rescue RestClient::Exception => e
    #     print_yellow_warning "Unable to load network options. Proceeding..."
    #     print_rest_exception(e, options) if Morpheus::Logging.debug?
    #   end
    # end

    # only amazon supports this option
    # for now, always do this
    payload[:deleteOriginalVolumes] = true

    if options[:dry_run]
      print_dry_run @servers_interface.dry.resize(server['id'], payload)
      return
    end
    json_response = @servers_interface.resize(server['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      unless options[:quiet]
        puts "Host #{server['name']} resizing..."
        list([])
      end
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#run_workflow(args) ⇒ Object



760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
# File 'lib/morpheus/cli/hosts.rb', line 760

def run_workflow(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("run-workflow", "[name]", "[workflow]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    exit 1
  end
  connect(options)
  host = find_host_by_name_or_id(args[0])
  workflow = find_workflow_by_name(args[1])
  task_types = @tasks_interface.task_types()
  editable_options = []
  workflow['taskSetTasks'].sort{|a,b| a['taskOrder'] <=> b['taskOrder']}.each do |task_set_task|
    task_type_id = task_set_task['task']['taskType']['id']
    task_type = task_types['taskTypes'].find{ |current_task_type| current_task_type['id'] == task_type_id}
    task_opts = task_type['optionTypes'].select { |otype| otype['editable']}
    if !task_opts.nil? && !task_opts.empty?
      editable_options += task_opts.collect do |task_opt|
        new_task_opt = task_opt.clone
        new_task_opt['fieldContext'] = "#{task_set_task['id']}.#{new_task_opt['fieldContext']}"
      end
    end
  end
  params = options[:options] || {}

  if params.empty? && !editable_options.empty?
    puts optparse
    option_lines = editable_options.collect {|it| "\t-O #{it['fieldContext'] ? (it['fieldContext'] + '.') : ''}#{it['fieldName']}=\"value\"" }.join("\n")
    puts "\nAvailable Options:\n#{option_lines}\n\n"
    exit 1
  end

  workflow_payload = {taskSet: {"#{workflow['id']}" => params }}
  begin
    if options[:dry_run]
      print_dry_run @servers_interface.dry.workflow(host['id'],workflow['id'], workflow_payload)
      return
    end
    json_response = @servers_interface.workflow(host['id'],workflow['id'], workflow_payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      puts "Workflow #{workflow['name']} is running..."
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#server_types(args) ⇒ Object



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

def server_types(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[cloud]")
    build_common_options(opts, options, [:json, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  options[:zone] = args[0]
  connect(options)
  params = {}

  zone = find_zone_by_name_or_id(nil, options[:zone])
  cloud_type = cloud_type_for_id(zone['zoneTypeId'])
  cloud_server_types = cloud_type['serverTypes'].select{|b| b['creatable'] == true}
  cloud_server_types = cloud_server_types.sort { |x,y| x['displayOrder'] <=> y['displayOrder'] }
  if options[:json]
    print JSON.pretty_generate(cloud_server_types)
    print "\n"
  else
    print "\n" ,cyan, bold, "Morpheus Server Types - Cloud: #{zone['name']}\n","==================", reset, "\n\n"
    if cloud_server_types.nil? || cloud_server_types.empty?
      puts yellow,"No server types found for the selected cloud.",reset
    else
      cloud_server_types.each do |server_type|
        print cyan, "[#{server_type['code']}]".ljust(20), " - ", "#{server_type['name']}", "\n"
      end
    end
    print reset,"\n"
  end
end

#start(args) ⇒ Object



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

def start(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host = find_host_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @servers_interface.dry.start(host['id'])
      return
    end
    json_response = @servers_interface.start(host['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Host #{host['name']} started."
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#stats(args) ⇒ Object



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

def stats(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @servers_interface.dry.get(args[0].to_i)
      else
        print_dry_run @servers_interface.dry.get({name: args[0]})
      end
      return
    end
    server = find_host_by_name_or_id(args[0])
    json_response = @servers_interface.get(server['id'])
    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    server = json_response['server']
    #stats = server['stats'] || json_response['stats'] || {}
    stats = json_response['stats'] || {}

    print "\n" ,cyan, bold, "Host Stats: #{server['name']} (#{server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged'})\n","==================", "\n\n", reset, cyan
    puts "Status: #{format_host_status(server)}"
    puts "Power: #{format_server_power_state(server)}"
    if ((stats['maxMemory'].to_i != 0) || (stats['maxStorage'].to_i != 0))
      # stats_map = {}
      print "\n"
      #print "\n" ,cyan, bold, "Host Stats\n","==================", reset, "\n\n"
      # stats_map[:memory] = "#{Filesize.from("#{stats['usedMemory']} B").pretty} / #{Filesize.from("#{stats['maxMemory']} B").pretty}"
      # stats_map[:storage] = "#{Filesize.from("#{stats['usedStorage']} B").pretty} / #{Filesize.from("#{stats['maxStorage']} B").pretty}"
      # stats_map[:cpu] = "#{stats['cpuUsage'].to_f.round(2)}%"
      # tp [stats_map], :memory,:storage,:cpu
      print_stats_usage(stats)
    else
      #print yellow, "No stat data.", reset
    end

    print reset, "\n"

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

#stop(args) ⇒ Object



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

def stop(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host = find_host_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @servers_interface.dry.stop(host['id'])
      return
    end
    json_response = @servers_interface.stop(host['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      puts "Host #{host['name']} stopped."
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#upgrade_agent(args) ⇒ Object



728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/morpheus/cli/hosts.rb', line 728

def upgrade_agent(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host = find_host_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @servers_interface.dry.upgrade(host['id'])
      return
    end
    json_response = @servers_interface.upgrade(host['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      puts "Host #{host['name']} upgrading..." unless options[:quiet]
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end