Class: Morpheus::Cli::Hosts

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from LogsHelper

#clusters_interface, #containers_interface, #format_log_level, #format_log_records, #format_log_table, included, #instances_interface, #logs_interface, #servers_interface

Methods included from ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #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_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_resize_volumes, #prompt_security_groups, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from AccountsHelper

#account_column_definitions, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_interface, #users_interface

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

#initializeHosts

Returns a new instance of Hosts.



27
28
29
# File 'lib/morpheus/cli/hosts.rb', line 27

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

Instance Method Details

#_get(arg, options) ⇒ Object



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

def _get(arg, options)
  @servers_interface.setopts(options)
  if options[:dry_run]
    if arg.to_s =~ /\A\d{1,}\Z/
      print_dry_run @servers_interface.dry.get(arg.to_i)
    else
      print_dry_run @servers_interface.dry.list({name: arg})
    end
    return
  end
  json_response = nil
  if arg.to_s =~ /\A\d{1,}\Z/
    json_response = @servers_interface.get(arg.to_i)
  else
    server = find_host_by_name_or_id(arg)
    json_response = @servers_interface.get(server['id'])
    # json_response = {"server" => server} need stats
  end
  render_response(json_response, options, "server") do
    server = json_response['server'] || json_response['host'] || {}
    #stats = server['stats'] || json_response['stats'] || {}
    stats = json_response['stats'] || {}
    tags = server['tags'] || server['metadata']
    title = "Host Details"
    print_h1 title, [], options
    print cyan
    server_columns = {
      "ID" => 'id',
      "Name" => 'name',
      "Hostname" => 'hostname',
      "Description" => 'description',
      "Labels" => lambda {|it| it['labels'] ? it['labels'].join(',') : '' },
      "Tags" => lambda {|it| tags ? (tags) : '' },
      "Owner" => lambda {|it| it['owner'] ? it['owner']['username'] : '' },
      "Tenant" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      #"Group" => lambda {|it| it['group'] ? it['group']['name'] : '' },
      "Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
      "IP" => lambda {|it| it['externalIp'] },
      "Private IP" => lambda {|it| it['internalIp'] },
      "Type" => lambda {|it| it['computeServerType'] ? it['computeServerType']['name'] : 'unmanaged' },
      "Platform" => lambda {|it| it['serverOs'] ? it['serverOs']['name'].upcase : 'N/A' },
      "Plan" => lambda {|it| it['plan'] ? it['plan']['name'] : '' },
      "Cost" => lambda {|it| it['hourlyCost'] ? format_money(it['hourlyCost'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
      "Price" => lambda {|it| it['hourlyPrice'] ? format_money(it['hourlyPrice'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
      "Agent" => lambda {|it| it['agentInstalled'] ? "#{server['agentVersion'] || ''} updated at #{format_local_dt(server['lastAgentUpdate'])}" : '(not installed)' },
      "Nodes" => lambda {|it| it['containers'] ? it['containers'].size : 0 },
      # "Status" => lambda {|it| format_server_status(it) },
      # "Power" => lambda {|it| format_server_power_state(it) },
      "Status" => lambda {|it| format_server_status_friendly(it) }, # combo
    }
    server_columns.delete("Hostname") if server['hostname'].to_s.empty? || server['hostname'] == server['name']
    server_columns.delete("IP") if server['externalIp'].to_s.empty?
    server_columns.delete("Private IP") if server['internalIp'].to_s.empty?
    # server_columns.delete("Tenant") if multi_tenant != true
    server_columns.delete("Cost") if server['hourlyCost'].to_f == 0
    server_columns.delete("Price") if server['hourlyPrice'].to_f == 0 || server['hourlyPrice'] == server['hourlyCost']
    server_columns.delete("Labels") if server['labels'].nil? || server['labels'].empty?
    server_columns.delete("Tags") if tags.nil? || tags.empty?

    print_description_list(server_columns, server)

    if server['statusMessage']
      print_h2 "Status Message", options
      if server['status'] == 'failed'
        print red, server['statusMessage'], reset
      else
        print server['statusMessage']
      end
      print "\n"
    end
    if server['errorMessage']
      print_h2 "Error Message", options
      print red, server['errorMessage'], reset, "\n"
    end

    print_h2 "Host Usage", options
    print_stats_usage(stats)

    if options[:include_costs]
      print_h2 "Host Cost"
      cost_columns = {
        "Cost" => lambda {|it| it['hourlyCost'] ? format_money(it['hourlyCost'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
        "Price" => lambda {|it| it['hourlyPrice'] ? format_money(it['hourlyPrice'], (it['currency'] || 'USD'), {sigdig:15}).to_s + ' per hour' : '' },
      }
      print_description_list(cost_columns, server)
    end

    print reset, "\n"


    # refresh until a status is reached
    if options[:refresh_until_status]
      if options[:refresh_interval].nil? || options[:refresh_interval].to_f < 0
        options[:refresh_interval] = default_refresh_interval
      end
      statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
      if !statuses.include?(server['status'])
        print cyan
        print cyan, "Refreshing in #{options[:refresh_interval] > 1 ? options[:refresh_interval].to_i : options[:refresh_interval]} seconds"
        sleep_with_dots(options[:refresh_interval])
        print "\n"
        _get(arg, options)
      end
    end
  end
  return 0, nil
end

#_stats(arg, options) ⇒ Object



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

def _stats(arg, options)
  begin
    @servers_interface.setopts(options)
    if options[:dry_run]
      if arg.to_s =~ /\A\d{1,}\Z/
        print_dry_run @servers_interface.dry.get(arg.to_i)
      else
        print_dry_run @servers_interface.dry.list({name: arg})
      end
      return
    end
    server = find_host_by_name_or_id(arg)
    json_response = @servers_interface.get(server['id'])
    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
    server = json_response['server']
    #stats = server['stats'] || json_response['stats'] || {}
    stats = json_response['stats'] || {}
    title = "Host Stats: #{server['name']} (#{server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged'})"
    print_h1 title, [], options
    puts cyan + "Power: ".rjust(12) + format_server_power_state(server).to_s
    puts cyan + "Status: ".rjust(12) + format_server_status(server).to_s
    puts cyan + "Nodes: ".rjust(12) + (server['containers'] ? server['containers'].size : '').to_s
    #print_h2 "Host Usage", options
    print_stats_usage(stats, {label_width: 10})

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

#_view(arg, options = {}) ⇒ Object



1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
# File 'lib/morpheus/cli/hosts.rb', line 1687

def _view(arg, options={})
  begin
    host = find_host_by_name_or_id(arg)
    return 1 if host.nil?

    link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/infrastructure/servers/#{host['id']}"
    if options[:link_tab]
      link << "#!#{options[:link_tab]}"
    end

    if options[:dry_run]
      puts Morpheus::Util.open_url_command(link)
      return 0
    end
    return Morpheus::Util.open_url(link)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



746
747
748
749
750
751
752
753
754
755
756
757
758
759
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
# File 'lib/morpheus/cli/hosts.rb', line 746

def add(args)
  options = {}
  optparse = Morpheus::Cli::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
    opts.on("--security-groups LIST", Integer, "Security Groups, comma separated list of security group IDs") do |val|
      options[:security_groups] = val.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until status is running,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  connect(options)
  begin
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      #payload.deep_merge!({'server' => passed_options}) unless passed_options.empty?
      payload.deep_merge!(passed_options) unless passed_options.empty?
    else
      # 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 && b['containerHypervisor'] == false }.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 for 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 }

      # uh ok, this actually expects config at root level, sibling of server 
      # payload.deep_merge!({'server' => passed_options}) unless passed_options.empty?
      payload.deep_merge!(passed_options) unless passed_options.empty?
      payload.deep_merge!({'server' => {
        'name' => host_name,
        'zone' => {'id' => cloud['id']},
        'computeServerType' => {'id' => server_type['id']},
        'plan' => {'id' => service_plan["id"]}
        }
      })

      option_type_list = server_type['optionTypes']

      # remove cpu and memory option types, which now come from the plan
      option_type_list = reject_service_plan_option_types(option_type_list)

      # prompt for resource pool
      pool_id = nil
      has_zone_pools = server_type["provisionType"] && server_type["provisionType"]["hasZonePools"]
      if has_zone_pools
        # pluck out the resourcePoolId option type to prompt for..why the heck is this even needed? 
        resource_pool_option_type = option_type_list.find {|opt| ['resourcePool','resourcePoolId','azureResourceGroupId'].include?(opt['fieldName']) }
        option_type_list = option_type_list.reject {|opt| ['resourcePool','resourcePoolId','azureResourceGroupId'].include?(opt['fieldName']) }
        resource_pool_option_type ||= {'fieldContext' => 'config', 'fieldName' => 'resourcePool', 'type' => 'select', 'fieldLabel' => 'Resource Pool', 'optionSource' => 'zonePools', 'required' => true, 'skipSingleOption' => true, 'description' => 'Select resource pool.'}
        resource_pool_prompt = Morpheus::Cli::OptionTypes.prompt([resource_pool_option_type],options[:options],api_client,{groupId: group_id, siteId: group_id, zoneId: cloud_id, cloudId: cloud_id, planId: service_plan["id"], serverTypeId: server_type['id']})
        resource_pool_prompt.deep_compact!
        payload.deep_merge!(resource_pool_prompt)
        if resource_pool_option_type['fieldContext'] && resource_pool_prompt[resource_pool_option_type['fieldContext']]
          pool_id = resource_pool_prompt[resource_pool_option_type['fieldContext']][resource_pool_option_type['fieldName']]
        elsif resource_pool_prompt[resource_pool_option_type['fieldName']]
          pool_id = resource_pool_prompt[resource_pool_option_type['fieldName']]
        end
      end

      # prompt for volumes
      volumes = prompt_volumes(service_plan, options, @api_client, {zoneId: cloud_id, serverTypeId: server_type['id'], siteId: group_id})
      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"], pool_id, options)
          if !network_interfaces.empty?
            payload['networkInterfaces'] = network_interfaces
          end
        rescue RestClient::Exception => e
          print yellow,"Unable to load network options. Proceeding...",reset,"\n"
          print_rest_exception(e, options) if Morpheus::Logging.debug?
        end
      end

      # Security Groups
      # prompt for multiple security groups
      sg_option_type = option_type_list.find {|opt| ((opt['code'] == 'provisionType.amazon.securityId') || (opt['name'] == 'securityId')) }
      option_type_list = option_type_list.reject {|opt| ((opt['code'] == 'provisionType.amazon.securityId') || (opt['name'] == 'securityId')) }
      # ok.. seed data has changed and serverTypes do not have this optionType anymore...
      if sg_option_type.nil?
        if server_type["provisionType"] && (server_type["provisionType"]["code"] == 'amazon')
          sg_option_type = {'fieldContext' => 'config', 'fieldName' => 'securityId', 'type' => 'select', 'fieldLabel' => 'Security Group', 'optionSource' => 'amazonSecurityGroup', 'required' => true, 'description' => 'Select security group.'}
        end
      end
      has_security_groups = !!sg_option_type
      if options[:security_groups]
        payload['securityGroups'] = options[:security_groups].collect {|sg_id| {'id' => sg_id} }
      else
        if has_security_groups
          security_groups_array = prompt_security_groups(sg_option_type, {zoneId: cloud_id, poolId: pool_id}, options)
          if !security_groups_array.empty?
            payload['securityGroups'] = security_groups_array.collect {|sg_id| {'id' => sg_id} }
          end
        end
      end
  
      api_params = {}
      api_params['zoneId'] = cloud['id']
      api_params['poolId'] = payload['config']['resourcePool'] if (payload['config'] && payload['config']['resourcePool'])
      if payload['config']
        api_params.deep_merge!(payload['config'])
      end
      #api_params.deep_merge(payload)
      params = Morpheus::Cli::OptionTypes.prompt(option_type_list,options[:options],@api_client, api_params)
      payload.deep_merge!(params)
      
    end
    @servers_interface.setopts(options)
    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]
      server_id = json_response["server"]["id"]
      server_name = json_response["server"]["name"]
      print_green_success "Provisioning host [#{server_id}] #{server_name}"
      # print details
      get_args = [server_id] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
      get(get_args)
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/morpheus/cli/hosts.rb', line 31

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @accounts_interface = @api_client.accounts
  @users_interface = @api_client.users
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
  @tasks_interface = @api_client.tasks
  @task_sets_interface = @api_client.task_sets
  @servers_interface = @api_client.servers
  @server_types_interface = @api_client.server_types
  @logs_interface = @api_client.logs
  @accounts_interface = @api_client.accounts
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
  @execution_request_interface = @api_client.execution_request
  @clusters_interface = @api_client.clusters
end

#count(args) ⇒ Object



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

def count(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[options]")
    opts.on( '--tenant TENANT', "Tenant Name or ID" ) do |val|
      options[:account] = val
    end
    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( '-M', '--managed', "Show only Managed Servers" ) do |val|
      params[:managed] = true
    end
    opts.on( '-U', '--unmanaged', "Show only Unmanaged Servers" ) do |val|
      params[:managed] = false
    end
    opts.on( '-t', '--type TYPE', "Show only Certain Server Types" ) do |val|
      params[:serverType] = val
    end
    opts.on( '-p', '--power STATE', "Filter by Power Status" ) do |val|
      params[:powerState] = val
    end
    opts.on( '-i', '--ip IPADDRESS', "Filter by IP Address" ) do |val|
      params[:ip] = val
    end
    opts.on( '', '--vm', "Show only virtual machines" ) do |val|
      params[:vm] = true
    end
    opts.on( '', '--hypervisor', "Show only VM Hypervisors" ) do |val|
      params[:vmHypervisor] = true
    end
    opts.on( '', '--container', "Show only Container Hypervisors" ) do |val|
      params[:containerHypervisor] = true
    end
    opts.on( '', '--baremetal', "Show only Baremetal Servers" ) do |val|
      params[:bareMetalHost] = true
    end
    opts.on( '', '--status STATUS', "Filter by Status" ) do |val|
      params[:status] = val
    end
    opts.on( '', '--agent', "Show only Servers with the agent installed" ) do |val|
      params[:agentInstalled] = true
    end
    opts.on( '', '--noagent', "Show only Servers with No agent" ) do |val|
      params[:agentInstalled] = false
    end
    opts.on( '--created-by USER', "Created By User Username or ID" ) do |val|
      options[:created_by] = val
    end
    opts.on('--details', "Display more details: memory and storage usage used / max values." ) do
      options[:details] = true
    end
    opts.on( '-s', '--search PHRASE', "Search Phrase" ) do |phrase|
      options[:phrase] = phrase
    end
    build_common_options(opts, options, [:query, :remote, :dry_run])
    opts.footer = "Get the number of hosts."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))
     = nil
    if options[:account]
       = (options[:account])
      if .nil?
        return 1
      else
        params['accountId'] = ['id']
      end
    end
    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

    if options[:created_by]
      created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:created_by])
      return if created_by_ids.nil?
      params['createdBy'] = created_by_ids
      # params['ownerId'] = created_by_ids # 4.2.1+
    end
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.list(params)
      return
    end
    json_response = @servers_interface.list(params)
    # print number only
    if json_response['meta'] && json_response['meta']['total']
      print cyan, json_response['meta']['total'], reset, "\n"
    else
      print yellow, "unknown", reset, "\n"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#execution_request(args) ⇒ Object



1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
# File 'lib/morpheus/cli/hosts.rb', line 1492

def execution_request(args)
  options = {}
  params = {}
  script_content = nil
  do_refresh = true
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[id] [options]")
    opts.on('--script SCRIPT', "Script to be executed" ) do |val|
      script_content = val
    end
    opts.on('--file FILE', "File containing the script. This can be used instead of --script" ) do |filename|
      full_filename = File.expand_path(filename)
      if File.exists?(full_filename)
        script_content = File.read(full_filename)
      else
        print_red_alert "File not found: #{full_filename}"
        exit 1
      end
    end
    opts.on(nil, '--no-refresh', "Do not refresh until finished" ) do
      do_refresh = false
    end
    #build_option_type_options(opts, options, add_user_source_option_types())
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
    opts.footer = "Execute an arbitrary command or script on a host." + "\n" +
                  "[id] is required. This is the id a host." + "\n" +
                  "[script] is required. This is the script that is to be executed."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  
  
  begin
    host = find_host_by_name_or_id(args[0])
    return 1 if host.nil?
    params['serverId'] = host['id']
    # construct payload
    payload = {}
    if options[:payload]
      payload = options[:payload]
    else
      payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      # prompt for Script
      if script_content.nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'script', 'type' => 'code-editor', 'fieldLabel' => 'Script', 'required' => true, 'description' => 'The script content'}], options[:options])
        script_content = v_prompt['script']
      end
      payload['script'] = script_content
    end
    # dry run?
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execution_request_interface.dry.create(params, payload)
      return 0
    end
    # do it
    json_response = @execution_request_interface.create(params, payload)
    # print and return result
    if options[:quiet]
      return 0
    elsif options[:json]
      puts as_json(json_response, options)
      return 0
    end
    execution_request = json_response['executionRequest']
    print_green_success "Executing request #{execution_request['uniqueId']}"
    if do_refresh
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId'], "--refresh"]+ (options[:remote] ? ["-r",options[:remote]] : []))
    else
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId']]+ (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( nil, '--costs', "Display Cost and Price" ) do
      options[:include_costs] = true
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until status is provisioned,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_until_status] ||= "provisioned,failed"
      if !val.to_s.empty?
        options[:refresh_interval] = val.to_f
      end
    end
    opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
      options[:refresh_until_status] = val.to_s.downcase
    end
    build_standard_get_options(opts, options)
  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



48
49
50
# File 'lib/morpheus/cli/hosts.rb', line 48

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::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
    opts.on( '-M', '--managed', "Show only Managed Servers" ) do |val|
      params[:managed] = true
    end
    opts.on( '-U', '--unmanaged', "Show only Unmanaged Servers" ) do |val|
      params[:managed] = false
    end
    opts.on( '-t', '--type TYPE', "Show only Certain Server Types" ) do |val|
      params[:serverType] = val
    end
    opts.on( '-p', '--power STATE', "Filter by Power Status" ) do |val|
      params[:powerState] = val
    end
    opts.on( '-i', '--ip IPADDRESS', "Filter by IP Address" ) do |val|
      params[:ip] = val
    end
    opts.on( '--cluster CLUSTER', '--cluster CLUSTER', "Filter by Cluster Name or ID" ) do |val|
      # params[:clusterId] = val
      options[:cluster] = val
    end
    opts.on( '--plan NAME', String, "Filter by Plan name(s)" ) do |val|
      # commas used in names a lot so use --plan one --plan two
      params['plan'] ||= []
      params['plan'] << val
    end
    opts.on( '--plan-id ID', String, "Filter by Plan id(s)" ) do |val|
      params['planId'] = parse_id_list(val)
    end
    opts.on( '--plan-code CODE', String, "Filter by Plan code(s)" ) do |val|
      params['planCode'] = parse_id_list(val)
    end
    opts.on( '', '--vm', "Show only virtual machines" ) do |val|
      params[:vm] = true
    end
    opts.on( '', '--hypervisor', "Show only VM Hypervisors" ) do |val|
      params[:vmHypervisor] = true
    end
    opts.on( '', '--container', "Show only Container Hypervisors" ) do |val|
      params[:containerHypervisor] = true
    end
    opts.on( '', '--baremetal', "Show only Baremetal Servers" ) do |val|
      params[:bareMetalHost] = true
    end
    opts.on( '', '--status STATUS', "Filter by Status" ) do |val|
      params[:status] = val
    end
    opts.on( '', '--agent', "Show only Servers with the agent installed" ) do |val|
      params[:agentInstalled] = true
    end
    opts.on( '', '--noagent', "Show only Servers with No agent" ) do |val|
      params[:agentInstalled] = false
    end
    opts.on( '--created-by USER', "Created By User Username or ID" ) do |val|
      options[:created_by] = val
    end
    opts.on( '--tenant TENANT', "Tenant Name or ID" ) do |val|
      options[:account] = val
    end
    opts.on('--labels label',String, "Filter by labels (keywords).") do |val|
      val.split(",").each do |k|
        options[:labels] ||= []
        options[:labels] << k.strip
      end
    end
    opts.on('--tags Name=Value',String, "Filter by tags.") do |val|
      val.split(",").each do |value_pair|
        k,v = value_pair.strip.split("=")
        options[:tags] ||= {}
        options[:tags][k] ||= []
        options[:tags][k] << (v || '')
      end
    end
    opts.on('--tag-compliant', "Displays only servers that are valid according to applied tag policies. Does not show servers that do not have tag policies." ) do
      params[:tagCompliant] = true
    end
    opts.on('--non-tag-compliant', "Displays only servers with tag compliance warnings." ) do
      params[:tagCompliant] = false
    end
    opts.on('--stats', "Display values for memory and storage usage used / max values." ) do
      options[:stats] = true
    end
    opts.on('-a', '--details', "Display all details: hostname, private ip, plan, stats, etc." ) do
      options[:details] = true
    end
    build_standard_list_options(opts, options)
    opts.footer = "List hosts."
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  
  params.merge!(parse_list_options(options))
   = nil
  if options[:account]
     = (options[:account])
    if .nil?
      return 1
    else
      params['accountId'] = ['id']
    end
  end
  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

  if options[:created_by]
    created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:created_by])
    return if created_by_ids.nil?
    params['createdBy'] = created_by_ids
    # params['ownerId'] = created_by_ids # 4.2.1+
  end
  
  cluster = nil
  if options[:cluster]
    if options[:cluster].to_s =~ /\A\d{1,}\Z/
      params['clusterId'] = options[:cluster]
    else
      cluster = find_cluster_by_name_or_id(options[:cluster])
      return 1 if cluster.nil?
      params['clusterId'] = cluster['id']
    end
  end
  params['labels'] = options[:labels] if options[:labels]
  if options[:tags] && !options[:tags].empty?
    options[:tags].each do |k,v|
      params['tags.' + k] = v
    end
  end

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

  # merge stats to be nice here..
  all_stats = json_response['stats']
  if options[:include_fields] || options[:all_fields]
    if json_response['servers']
      if all_stats
        json_response['servers'].each do |it|
          it['stats'] ||= all_stats[it['id'].to_s] || all_stats[it['id']]
        end
      end
    end
  end
  render_response(json_response, options, "servers") do
    
    servers = json_response['servers']
    multi_tenant = json_response['multiTenant'] == true
    title = "Morpheus Hosts"
    subtitles = []
    if 
      subtitles << "Tenant: #{['name']}".strip
    end
    if group
      subtitles << "Group: #{group['name']}".strip
    end
    if cloud
      subtitles << "Cloud: #{cloud['name']}".strip
    end
    if cluster
      subtitles << "Cluster: #{cluster['name']}".strip
    elsif params['clusterId']
      subtitles << "Cluster: #{params['clusterId']}".strip
    end
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options
    if servers.empty?
      print cyan,"No hosts found.",reset,"\n"
    else
      # print_servers_table(servers)
      # server returns stats in a separate key stats => {"id" => {} }
      # the id is a string right now..for some reason..
      all_stats = json_response['stats'] || {} 
      servers.each do |it|
        found_stats = all_stats[it['id'].to_s] || all_stats[it['id']]
        if found_stats
          if !it['stats']
            it['stats'] = found_stats # || {}
          else
            it['stats'] = found_stats.merge!(it['stats'])
          end
        end
      end

      rows = servers.collect {|server| 
        stats = server['stats']
        
        if !stats['maxMemory']
          stats['maxMemory'] = stats['usedMemory'] + stats['freeMemory']
        end
        cpu_usage_str = !stats ? "" : generate_usage_bar((stats['usedCpu'] || stats['cpuUsage']).to_f, 100, {max_bars: 10})
        memory_usage_str = !stats ? "" : generate_usage_bar(stats['usedMemory'], stats['maxMemory'], {max_bars: 10})
        storage_usage_str = !stats ? "" : generate_usage_bar(stats['usedStorage'], stats['maxStorage'], {max_bars: 10})
        if options[:details] || options[:stats]
          if stats['maxMemory'] && stats['maxMemory'].to_i != 0
            memory_usage_str = memory_usage_str + cyan + format_bytes_short(stats['usedMemory']).strip.rjust(8, ' ')  + " / " + format_bytes_short(stats['maxMemory']).strip
          end
          if stats['maxStorage'] && stats['maxStorage'].to_i != 0
            storage_usage_str = storage_usage_str + cyan + format_bytes_short(stats['usedStorage']).strip.rjust(8, ' ') + " / " + format_bytes_short(stats['maxStorage']).strip
          end
        end
        row = {
          id: server['id'],
          name: server['name'],
          external_name: server['externalName'],
          hostname: server['hostname'],
          platform: server['serverOs'] ? server['serverOs']['name'].upcase : 'N/A',
          type: server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged',
          tenant: server['account'] ? server['account']['name'] : server['accountId'],
          owner: server['owner'] ? server['owner']['username'] : server['owner'],
          cloud: server['zone'] ? server['zone']['name'] : '',
          plan: server['plan'] ? server['plan']['name'] : '',
          ip: server['externalIp'],
          internal_ip: server['internalIp'],
          nodes: server['containers'] ? server['containers'].size : '',
          # status: format_server_status(server, cyan),
          status: (options[:details]||options[:all_fields]) ? format_server_status(server, cyan) : format_server_status_friendly(server, cyan),
          power: format_server_power_state(server, cyan),
          cpu: cpu_usage_str + cyan,
          memory: memory_usage_str + cyan,
          storage: storage_usage_str + cyan,
          created: format_local_dt(server['dateCreated']),
          updated: format_local_dt(server['lastUpdated']),
        }
        row
      }
      # columns = [:id, :name, :type, :cloud, :ip, :internal_ip, :nodes, :status, :power]
      columns = {
        "ID" => :id,
        "Name" => :name,
        "External Name" => :external_name,
        "Hostname" => :hostname,
        "Type" => :type,
        "Owner" => :owner,
        "Tenant" => :tenant,
        "Cloud" => :cloud,
        "Plan" => :plan,
        "IP" => :ip,
        "Private IP" => :internal_ip,
        "Nodes" => :nodes,
        "Status" => :status,
        "Power" => :power,
        "CPU" => :cpu,
        "Memory" => :memory,
        "Storage" => :storage,
        "Created" => :created,
        "Updated" => :updated,
      }
      if options[:details] != true
        columns.delete("External Name")
        columns.delete("Hostname")
        columns.delete("Plan")
        columns.delete("Private IP")
        columns.delete("Owner")
        columns.delete("Tenant")
        columns.delete("Power")
        columns.delete("Created")
        columns.delete("Updated")
      end
      # hide External Name if there are none
      if !servers.find {|it| it['externalName'] && it['externalName'] != it['name']}
        columns.delete("External Name")
      end
      if !multi_tenant
        columns.delete("Tenant")
      end
      # columns += [:cpu, :memory, :storage]
      # # custom pretty table columns ...
      # if options[:include_fields]
      #   columns = options[:include_fields]
      # end
      print cyan
      print as_pretty_table(rows, columns.upcase_keys!, options)
      print reset
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
end

#list_types(args) ⇒ Object



1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
# File 'lib/morpheus/cli/hosts.rb', line 1597

def list_types(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List host types."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
    if options[:cloud]
      #return server_types_for_cloud(options[:cloud], options)
      zone = find_zone_by_name_or_id(nil, options[:cloud])
      params["zoneTypeId"] = zone['zoneTypeId']
      params["creatable"] = true
    end
    @server_types_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @server_types_interface.dry.list(params)
      return
    end
    json_response = @server_types_interface.list(params)
    
    render_result = render_with_format(json_response, options, 'serverTypes')
    return 0 if render_result

    server_types = json_response['serverTypes']

    title = "Morpheus Server Types"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    if options[:cloud]
      subtitles << "Cloud: #{options[:cloud]}"
    end
    print_h1 title, subtitles
    if server_types.empty?
      print cyan,"No server types found.",reset,"\n"
    else
      rows = server_types.collect do |server_type|
        {
          id: server_type['id'],
          code: server_type['code'],
          name: server_type['name']
        }
      end
      columns = [:id, :name, :code]
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      print_results_pagination(json_response)
    end
    print reset,"\n"
    return 0

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

#logs(args) ⇒ Object



668
669
670
671
672
673
674
675
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/morpheus/cli/hosts.rb', line 668

def logs(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--start TIMESTAMP','--start TIMESTAMP', "Start timestamp. Default is 30 days ago.") do |val|
      options[:start] = parse_time(val) #.utc.iso8601
    end
    opts.on('--end TIMESTAMP','--end TIMESTAMP', "End timestamp. Default is now.") do |val|
      options[:end] = parse_time(val) #.utc.iso8601
    end
    opts.on('--level VALUE', String, "Log Level. DEBUG,INFO,WARN,ERROR") do |val|
      params['level'] = params['level'] ? [params['level'], val].flatten : [val]
    end
    opts.on('--table', '--table', "Format ouput as a table.") do
      options[:table] = true
    end
    opts.on('-a', '--all', "Display all details: entire message." ) do
      options[:details] = true
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :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])
    params['level'] = params['level'].collect {|it| it.to_s.upcase }.join('|') if params['level'] # api works with INFO|WARN
    params.merge!(parse_list_options(options))
    params['query'] = params.delete('phrase') if params['phrase']
    params['order'] = params['direction'] unless params['direction'].nil? # old api version expects order instead of direction
    params['startMs'] = (options[:start].to_i * 1000) if options[:start]
    params['endMs'] = (options[:end].to_i * 1000) if options[:end]
    @logs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @logs_interface.dry.server_logs([server['id']], params)
      return
    end
    json_response = @logs_interface.server_logs([server['id']], params)
    render_result = json_response['logs'] ? render_with_format(json_response, options, 'logs') : render_with_format(json_response, options, 'data')
    return 0 if render_result
    
    title = "Host Logs: #{server['name']} (#{server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged'})"
    subtitles = parse_list_subtitles(options)
    if options[:start]
      subtitles << "Start: #{options[:start]}".strip
    end
    if options[:end]
      subtitles << "End: #{options[:end]}".strip
    end
    if params[:query]
      subtitles << "Search: #{params[:query]}".strip
    end
    # if params['containers']
    #   subtitles << "Containers: #{params['containers']}".strip
    # end
    if params['level']
      subtitles << "Level: #{params['level']}"
    end
    print_h1 title, subtitles, options
    logs = json_response['data'] || json_response['logs']
    if logs.empty?
      print "#{cyan}No logs found.#{reset}\n"
    else
      print format_log_records(logs, options)
      print_results_pagination({'meta'=>{'total'=>(json_response['total']['value'] rescue json_response['total']),'size'=>logs.size,'max'=>(json_response['max'] || options[:max]),'offset'=>(json_response['offset'] || options[:offset] || 0)}})
    end
    print reset, "\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#make_managed(args) ⇒ Object



1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
# File 'lib/morpheus/cli/hosts.rb', line 1304

def make_managed(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_option_type_options(opts, options, make_managed_option_types(false))
    opts.on('--install-agent [on|off]', String, "Install Agent? Pass false to manually install agent. Default is true.") do |val|
      options['installAgent'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('-g', '--group GROUP', String, "Group to assign to new instance.") do |val|
      options[:group] = val
    end
    # opts.on('--instance-type-id ID', String, "Instance Type ID for the new instance.") do |val|
    #   options['instanceTypeId'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    # end
    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
    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' => {}
    }
    passed_options = (options[:options] || {}).reject {|k,v| k.is_a?(Symbol) }
    payload.deep_merge!(passed_options)
    params = Morpheus::Cli::OptionTypes.prompt(make_managed_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
    if options[:group]
      group = options[:group] ? find_group_by_name_or_id_for_provisioning(options[:group]) : nil
      return 1 if group.nil?
      params['provisionSiteId'] = group['id']
    end
    payload['server'].merge!(params)
    ['installAgent','instanceTypeId'].each do |k|
      if options[k] != nil
        payload[k] = options[k]
      end
    end
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run(@servers_interface.dry.make_managed(host['id'], payload), options)
      return 0
    end
    json_response = @servers_interface.make_managed(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 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
# File 'lib/morpheus/cli/hosts.rb', line 1064

def remove(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    # opts.on( '-S', '--skip-remove-infrastructure', "Skip removal of underlying cloud infrastructure. Same as --remove-resources off" ) do
    #   query_params[:removeResources] = 'off'
    # end
    opts.on('--remove-resources [on|off]', ['on','off'], "Remove Infrastructure. Default is on if server is managed.") do |val|
      query_params[:removeResources] = val.nil? ? 'on' : val
    end
    opts.on('--preserve-volumes [on|off]', ['on','off'], "Preserve Volumes. Default is off.") do |val|
      query_params[:preserveVolumes] = val.nil? ? 'on' : val
    end
    opts.on('--remove-instances [on|off]', ['on','off'], "Remove Associated Instances. Default is off.") do |val|
      query_params[:removeInstances] = val.nil? ? 'on' : val
    end
    opts.on('--release-eips [on|off]', ['on','off'], "Release EIPs, default is on. Amazon only.") do |val|
      params[:releaseEIPs] = val.nil? ? 'on' : val
    end
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'on'
    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
    @servers_interface.setopts(options)
    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



1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
# File 'lib/morpheus/cli/hosts.rb', line 1210

def resize(args)
  options = {}
  optparse = Morpheus::Cli::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"], null, options)
    #     if !network_interfaces.empty?
    #       payload[:networkInterfaces] = network_interfaces
    #     end
    #   rescue RestClient::Exception => e
    #     print yellow,"Unable to load network options. Proceeding...",reset,"\n"
    #     print_rest_exception(e, options) if Morpheus::Logging.debug?
    #   end
    # end

    # only amazon supports this option
    # for now, always do this
    payload[:deleteOriginalVolumes] = true
    @servers_interface.setopts(options)
    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



1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
# File 'lib/morpheus/cli/hosts.rb', line 1410

def run_workflow(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [workflow] [options]")
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count != 2
    puts_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 2 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)

  host = find_host_by_name_or_id(args[0])
  return 1 if host.nil?
  workflow = find_workflow_by_name_or_id(args[1])
  return 1 if workflow.nil?

  # support -O options as arbitrary params
  old_option_options = (options[:options] || {}).reject {|k,v| k.is_a?(Symbol) }
  params.deep_merge!(old_option_options) unless old_option_options.empty?

  # the payload format is unusual
  # payload example: {"taskSet": {taskSetId": {"taskSetTaskId": {"customOptions": {"dbVersion":"5.6"}}}}}
  payload = nil
  if options[:payload]
    payload = options[:payload]
  else
    payload = {}
    # i guess you must pass an option if there are editable options
    # any option, heh
    task_types = @tasks_interface.list_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
    # 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"
    #   return 1
    # end

  end

  if !params.empty?
    payload['taskSet'] ||= {}
    payload['taskSet']["#{workflow['id']}"] ||= {}
    payload['taskSet']["#{workflow['id']}"].deep_merge!(params)
  end

  begin
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.workflow(host['id'],workflow['id'], payload)
      return
    end
    json_response = @servers_interface.workflow(host['id'],workflow['id'], payload)
    if options[:json]
      print as_json(json_response, options), "\n"
      return
    elsif options[:quiet]
      return 0
    else
      print_green_success "Running workflow #{workflow['name']} on host #{host['name']} ..."
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#server_types_for_cloud(cloud_id, options) ⇒ Object



1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
# File 'lib/morpheus/cli/hosts.rb', line 1575

def server_types_for_cloud(cloud_id, options)
  connect(options)
  zone = find_zone_by_name_or_id(nil, cloud_id)
  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_h1 "Morpheus Server Types - Cloud: #{zone['name']}", [], options
    if cloud_server_types.nil? || cloud_server_types.empty?
      print cyan,"No server types found for the selected cloud",reset,"\n"
    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

#snapshots(args) ⇒ Object



1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
# File 'lib/morpheus/cli/hosts.rb', line 1907

def snapshots(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[host]")
    # no pagination yet
    # build_standard_list_options(opts, options)
    build_standard_get_options(opts, options)
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  begin
    server = find_host_by_name_or_id(args[0])
    return 1 if server.nil?
    params = {}
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.snapshots(server['id'], params)
      return
    end
    json_response = @servers_interface.snapshots(server['id'], params)
    snapshots = json_response['snapshots']      
    render_response(json_response, options, 'snapshots') do
      print_h1 "Snapshots: #{server['name']}", [], options
      if snapshots.empty?
        print cyan,"No snapshots found",reset,"\n"
      else
        snapshot_column_definitions = {
          "ID" => lambda {|it| it['id'] },
          "Name" => lambda {|it| it['name'] },
          "Description" => lambda {|it| it['description'] },
          # "Type" => lambda {|it| it['snapshotType'] },
          "Date Created" => lambda {|it| format_local_dt(it['snapshotCreated']) },
          "Status" => lambda {|it| format_snapshot_status(it) }
        }
        print cyan
        print as_pretty_table(snapshots, snapshot_column_definitions.upcase_keys!, options)
        print_results_pagination({size: snapshots.size, total: snapshots.size})
      end
      print reset, "\n"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#software(args) ⇒ Object



1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
# File 'lib/morpheus/cli/hosts.rb', line 1955

def software(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[host]")
    build_standard_list_options(opts, options)
    opts.footer = <<-EOT
List installed software for a host.
[host] is required. This is the name or id of a host.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  begin
    server = find_host_by_name_or_id(args[0])
    return 1 if server.nil?
    params = {}
    params.merge!(parse_list_options(options))
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.software(server['id'], params)
      return
    end
    json_response = @servers_interface.software(server['id'], params)
    software = json_response['software']
    render_response(json_response, options, 'software') do
      print_h1 "Software: #{server['name']}", [], options
      if software.empty?
        print cyan,"No software found",reset,"\n"
      else
        software_column_definitions = {
          # "ID" => lambda {|it| it['id'] },
          "Name" => lambda {|it| it['name'] },
          "Version" => lambda {|it| it['packageVersion'] },
          "Publisher" => lambda {|it| it['packagePublisher'] },
          # "Release" => lambda {|it| it['packageRelease'] },
          # "Type" => lambda {|it| it['packageType'] },
          # "Architecture" => lambda {|it| it['architecture'] },
          # "Install Date" => lambda {|it| format_local_dt(it['installDate']) },
        }
        print cyan
        print as_pretty_table(software, software_column_definitions.upcase_keys!, options)
        print_results_pagination({size: software.size, total: software.size})
      end
      print reset, "\n"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#software_sync(args) ⇒ Object



2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
# File 'lib/morpheus/cli/hosts.rb', line 2008

def software_sync(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[host]")
    build_standard_update_options(opts, options)
    opts.footer = <<-EOT
Sync installed software for a host.
[host] is required. This is the name or id of a host.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  begin
    server = find_host_by_name_or_id(args[0])
    return 1 if server.nil?
    payload = {}
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!(parse_passed_options(options))
    else
      payload.deep_merge!(parse_passed_options(options))
    end
    params = {}
    params.merge!(parse_query_options(options))
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.software_sync(server['id'], payload, params)
      return
    end
    json_response = @servers_interface.software_sync(server['id'], payload, params)
    render_response(json_response, options) do
      print_green_success "Syncing software for host #{server['name']}"
      #get([server['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#start(args) ⇒ Object



1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
# File 'lib/morpheus/cli/hosts.rb', line 1120

def start(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Start a host.\n" +
                  "[name] is required. This is the name or id of a host. Supports 1-N [name] arguments."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host_ids = parse_id_list(args)
    hosts = []
    host_ids.each do |host_id|
      host = find_host_by_name_or_id(host_id)
      return 1 if host.nil?
      hosts << host
    end
    objects_label = "#{hosts.size == 1 ? 'host' : (hosts.size.to_s + ' hosts')} #{anded_list(hosts.collect {|it| it['name'] })}"
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to start #{objects_label}?", options)
      return 9, "aborted command"
    end
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.start(hosts.collect {|it| it['id'] })
      return
    end
    json_response = @servers_interface.start(hosts.collect {|it| it['id'] })
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Started #{objects_label}"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#stats(args) ⇒ Object



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# File 'lib/morpheus/cli/hosts.rb', line 607

def stats(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  ids = args
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _stats(arg, options)
  end
end

#stop(args) ⇒ Object



1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# File 'lib/morpheus/cli/hosts.rb', line 1165

def stop(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    opts.footer = "Stop a host.\n" +
                  "[name] is required. This is the name or id of a host. Supports 1-N [name] arguments."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host_ids = parse_id_list(args)
    hosts = []
    host_ids.each do |host_id|
      host = find_host_by_name_or_id(host_id)
      return 1 if host.nil?
      hosts << host
    end
    objects_label = "#{hosts.size == 1 ? 'host' : (hosts.size.to_s + ' hosts')} #{anded_list(hosts.collect {|it| it['name'] })}"
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop #{objects_label}?", options)
      return 9, "aborted command"
    end
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.stop(hosts.collect {|it| it['id'] })
      return
    end
    json_response = @servers_interface.stop(hosts.collect {|it| it['id'] })
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Stopped #{objects_label}"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
# File 'lib/morpheus/cli/hosts.rb', line 960

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name") do |val|
      params['name'] = val == "null" ? nil : val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val == "null" ? nil : val
    end
    opts.on('--ssh-username VALUE', String, "SSH Username") do |val|
      params['sshUsername'] = val == "null" ? nil : val
    end
    opts.on('--ssh-password VALUE', String, "SSH Password") do |val|
      params['sshPassword'] = val == "null" ? nil : val
    end
    opts.on('--power-schedule-type ID', String, "Power Schedule Type ID") do |val|
      params['powerScheduleType'] = val == "null" ? nil : val
    end
    opts.on('--labels [LIST]', String, "Labels (keywords) in the format 'foo, bar'") do |val|
      params['labels'] = val.to_s.split(',').collect {|it| it.to_s.strip }.compact.uniq.join(',')
    end
    opts.on('--tags LIST', String, "Tags in the format 'name:value, name:value'. This will add and remove tags.") do |val|
      options[:tags] = val
    end
    opts.on('--metadata LIST', String, "Alias for --tags.") do |val|
      options[:tags] = val
    end
    opts.add_hidden_option('--metadata')
    opts.on('--add-tags TAGS', String, "Add Tags in the format 'name:value, name:value'. This will only add/update tags.") do |val|
      options[:add_tags] = val
    end
    opts.on('--remove-tags TAGS', String, "Remove Tags in the format 'name, name:value'. This removes tags, the :value component is optional and must match if passed.") do |val|
      options[:remove_tags] = val
    end
    # opts.on('--created-by ID', String, "Created By User ID") do |val|
    #   params['createdById'] = val
    # end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count != 1
    puts optparse
    return 1
  end
  connect(options)

  begin
    server = find_host_by_name_or_id(args[0])
    return 1 if server.nil?
    new_group = nil
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    params.deep_merge!(passed_options) unless passed_options.empty?
    # metadata tags
    if options[:tags]
      params['tags'] = (options[:tags])
    else
      # params['tags'] = prompt_metadata(options)
    end
    if options[:add_tags]
      params['addTags'] = (options[:add_tags])
    end
    if options[:remove_tags]
      params['removeTags'] = (options[:remove_tags])
    end
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support args and option parameters on top of payload
      if !params.empty?
        payload['server'] ||= {}
        payload['server'].deep_merge!(params)
      end
    else
      if params.empty?
        print_red_alert "Specify at least one option to update"
        puts optparse
        return 1
      end
      payload = {}
      payload['server'] = params
    end

    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.update(server["id"], payload)
      return
    end
    json_response = @servers_interface.update(server["id"], payload)

    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Updated host #{server['name']}"
      get([server['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_wiki(args) ⇒ Object



1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
# File 'lib/morpheus/cli/hosts.rb', line 1829

def update_wiki(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[host] [options]")
    build_option_type_options(opts, options, update_wiki_page_option_types)
    opts.on('--file FILE', "File containing the wiki content. This can be used instead of --content") do |filename|
      full_filename = File.expand_path(filename)
      if File.exists?(full_filename)
        params['content'] = File.read(full_filename)
      else
        print_red_alert "File not found: #{full_filename}"
        return 1
      end
      # use the filename as the name by default.
      if !params['name']
        params['name'] = File.basename(full_filename)
      end
    end
    opts.on(nil, '--clear', "Clear current page content") do |val|
      params['content'] = ""
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count != 1
    puts_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 1 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    host = find_host_by_name_or_id(args[0])
    return 1 if host.nil?
    # construct payload
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'page' => passed_options}) unless passed_options.empty?
    else
      payload = {
        'page' => {
        }
      }
      # allow arbitrary -O options
      payload.deep_merge!({'page' => passed_options}) unless passed_options.empty?
      # prompt for options
      #params = Morpheus::Cli::OptionTypes.prompt(update_wiki_page_option_types, options[:options], @api_client, options[:params])
      #params = passed_options
      params.deep_merge!(passed_options)

      if params.empty?
        raise_command_error "Specify at least one option to update.\n#{optparse}"
      end

      payload.deep_merge!({'page' => params}) unless params.empty?
    end
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.update_wiki(host["id"], payload)
      return
    end
    json_response = @servers_interface.update_wiki(host["id"], payload)

    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Updated wiki page for host #{host['name']}"
      wiki([host['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#upgrade_agent(args) ⇒ Object



1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
# File 'lib/morpheus/cli/hosts.rb', line 1377

def upgrade_agent(args)
  options = {}
  optparse = Morpheus::Cli::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])
    @servers_interface.setopts(options)
    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

#view(args) ⇒ Object



1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
# File 'lib/morpheus/cli/hosts.rb', line 1662

def view(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[host]")
    opts.on('-w','--wiki', "Open the wiki tab for this host") do
      options[:link_tab] = "wiki"
    end
    opts.on('--tab VALUE', String, "Open a specific tab") do |val|
      options[:link_tab] = val.to_s
    end
    build_common_options(opts, options, [:dry_run, :remote])
    opts.footer = "View a host in a web browser" + "\n" +
                  "[host] is required. This is the name or id of a host. Supports 1-N [host] arguments."
  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)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _view(arg, options)
  end
end

#view_wiki(args) ⇒ Object



1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
# File 'lib/morpheus/cli/hosts.rb', line 1786

def view_wiki(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:dry_run, :remote])
    opts.footer = "View host wiki page in a web browser" + "\n" +
                  "[host] is required. This is the name or id of a host."
  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
    host = find_host_by_name_or_id(args[0])
    return 1 if host.nil?

    link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/infrastructure/servers/#{host['id']}#!wiki"

    open_command = nil
    if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
      open_command = "start #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /darwin/
      open_command = "open #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
      open_command = "xdg-open #{link}"
    end

    if options[:dry_run]
      puts "system: #{open_command}"
      return 0
    end

    system(open_command)
    
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#wiki(args) ⇒ Object



1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
# File 'lib/morpheus/cli/hosts.rb', line 1708

def wiki(args)
  options = {}
  params = {}
  open_wiki_link = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[host]")
    opts.on('--view', '--view', "View wiki page in web browser.") do
      open_wiki_link = true
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "View wiki page details for a host." + "\n" +
                  "[host] is required. This is the name or id of a host."
  end
  optparse.parse!(args)
  if args.count != 1
    puts_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 1 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    host = find_host_by_name_or_id(args[0])
    return 1 if host.nil?


    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.wiki(host["id"], params)
      return
    end
    json_response = @servers_interface.wiki(host["id"], params)
    page = json_response['page']

    render_result = render_with_format(json_response, options, 'page')
    return 0 if render_result

    if page

      # my_terminal.exec("wiki get #{page['id']}")

      print_h1 "Host Wiki Page: #{host['name']}"
      # print_h1 "Wiki Page Details"
      print cyan

      print_description_list({
        "Page ID" => 'id',
        "Name" => 'name',
        #"Category" => 'category',
        #"Ref Type" => 'refType',
        #"Ref ID" => 'refId',
        #"Owner" => lambda {|it| it['account'] ? it['account']['name'] : '' },
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Created By" => lambda {|it| it['createdBy'] ? it['createdBy']['username'] : '' },
        "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) },
        "Updated By" => lambda {|it| it['updatedBy'] ? it['updatedBy']['username'] : '' }
      }, page)
      print reset,"\n"

      print_h2 "Page Content"
      print cyan, page['content'], reset, "\n"

    else
      print "\n"
      print cyan, "No wiki page found.", reset, "\n"
    end
    print reset,"\n"

    if open_wiki_link
      return view_wiki([args[0]])
    end

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