Class: Morpheus::Cli::Hosts
- Inherits:
-
Object
- Object
- Morpheus::Cli::Hosts
- Includes:
- AccountsHelper, CliCommand, LogsHelper, ProvisioningHelper
- Defined in:
- lib/morpheus/cli/hosts.rb
Instance Attribute Summary
Attributes included from CliCommand
Instance Method Summary collapse
- #_get(arg, options) ⇒ Object
- #_stats(arg, options) ⇒ Object
- #_view(arg, options = {}) ⇒ Object
- #add(args) ⇒ Object
- #connect(opts) ⇒ Object
- #count(args) ⇒ Object
- #execution_request(args) ⇒ Object
- #get(args) ⇒ Object
- #handle(args) ⇒ Object
-
#initialize ⇒ Hosts
constructor
A new instance of Hosts.
- #list(args) ⇒ Object
- #list_types(args) ⇒ Object
- #logs(args) ⇒ Object
- #make_managed(args) ⇒ Object
- #remove(args) ⇒ Object
- #resize(args) ⇒ Object
- #run_workflow(args) ⇒ Object
- #server_types_for_cloud(cloud_id, options) ⇒ Object
- #snapshots(args) ⇒ Object
- #software(args) ⇒ Object
- #start(args) ⇒ Object
- #stats(args) ⇒ Object
- #stop(args) ⇒ Object
- #update(args) ⇒ Object
- #update_wiki(args) ⇒ Object
- #upgrade_agent(args) ⇒ Object
- #view(args) ⇒ Object
- #view_wiki(args) ⇒ Object
- #wiki(args) ⇒ Object
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
#initialize ⇒ Hosts
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
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 |
# File 'lib/morpheus/cli/hosts.rb', line 508 def _get(arg, ) begin @servers_interface.setopts() if [: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 if [:json] json_response.delete('stats') if [:include_fields] puts as_json(json_response, , "server") return 0 elsif [:yaml] json_response.delete('stats') if [:include_fields] puts as_yaml(json_response, , "server") return 0 end if [:csv] puts records_as_csv([json_response['server']], ) return 0 end server = json_response['server'] || json_response['host'] || {} #stats = server['stats'] || json_response['stats'] || {} stats = json_response['stats'] || {} = server['tags'] || server['metadata'] title = "Host Details" print_h1 title, [], print cyan server_columns = { "ID" => 'id', "Name" => 'name', "Hostname" => 'hostname', "Description" => 'description', "Labels" => lambda {|it| it['labels'] ? it['labels'].join(',') : '' }, "Tags" => lambda {|it| ? () : '' }, "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 .nil? || .empty? print_description_list(server_columns, server) if server['statusMessage'] print_h2 "Status Message", if server['status'] == 'failed' print red, server['statusMessage'], reset else print server['statusMessage'] end print "\n" end if server['errorMessage'] print_h2 "Error Message", print red, server['errorMessage'], reset, "\n" end print_h2 "Host Usage", print_stats_usage(stats) if [: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 [:refresh_until_status] if [:refresh_interval].nil? || [:refresh_interval].to_f < 0 [:refresh_interval] = default_refresh_interval end statuses = [: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 #{[:refresh_interval] > 1 ? [:refresh_interval].to_i : [:refresh_interval]} seconds" sleep_with_dots([:refresh_interval]) print "\n" _get(arg, ) end end rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#_stats(arg, options) ⇒ Object
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 |
# File 'lib/morpheus/cli/hosts.rb', line 651 def _stats(arg, ) begin @servers_interface.setopts() if [: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 [:json] puts as_json(json_response, , "stats") return 0 elsif [:yaml] puts as_yaml(json_response, , "stats") return 0 elsif [:csv] puts records_as_csv([json_response['stats']], ) 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, [], 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, ) exit 1 end end |
#_view(arg, options = {}) ⇒ Object
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 |
# File 'lib/morpheus/cli/hosts.rb', line 1712 def _view(arg, ={}) 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 [:link_tab] link << "#!#{[:link_tab]}" end if [: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, ) exit 1 end end |
#add(args) ⇒ Object
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 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 |
# File 'lib/morpheus/cli/hosts.rb', line 771 def add(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[cloud]", "[name]") opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val| [:group] = val end opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val| [:cloud] = val end opts.on( '-t', '--type TYPE', "Server Type Code" ) do |val| [:server_type_code] = val end opts.on("--security-groups LIST", Integer, "Security Groups, comma sepearated list of security group IDs") do |val| [: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| [:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f end (opts, , [:options, :payload, :json, :dry_run, :quiet, :remote]) end optparse.parse!(args) connect() begin = [:options] ? [:options].reject {|k,v| k.is_a?(Symbol) } : {} payload = nil if [:payload] payload = [:payload] #payload.deep_merge!({'server' => passed_options}) unless passed_options.empty? payload.deep_merge!() unless .empty? else # support old format of `hosts add CLOUD NAME` if args[0] [:cloud] = args[0] end if args[1] [:host_name] = args[1] end # use active group by default [:group] ||= @active_group_id params = {} # Group group_id = nil group = [:group] ? find_group_by_name_or_id_for_provisioning([: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],@api_client,{}) group_id = group_prompt['group'] end # Cloud cloud_id = nil cloud = [:cloud] ? find_cloud_by_name_or_id_for_provisioning(group_id, [: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],@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 [:server_type_code] server_type_code = [:server_type_code] else = 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' => , 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a server type.'}], [: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 [:host_name] host_name = [:host_name] else name_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Server Name', 'type' => 'text', 'required' => true}], [: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]) 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!() unless .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],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, , @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, ) 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, ) 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 [:security_groups] payload['securityGroups'] = [: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}, ) 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],@api_client, api_params) payload.deep_merge!(params) end @servers_interface.setopts() if [:dry_run] print_dry_run @servers_interface.dry.create(payload) return end json_response = @servers_interface.create(payload) if [:json] print JSON.pretty_generate(json_response) print "\n" elsif ![: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] + ([:remote] ? ["-r",[:remote]] : []) + ([:refresh_interval] ? ['--refresh', [:refresh_interval].to_s] : []) get(get_args) end rescue RestClient::Exception => e print_rest_exception(e, ) 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 = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).clouds @options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url). @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 @server_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).server_types @logs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).logs @accounts_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).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
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 474 475 476 |
# File 'lib/morpheus/cli/hosts.rb', line 366 def count(args) params = {} = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[options]") opts.on( '--tenant TENANT', "Tenant Name or ID" ) do |val| [:account] = val end opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val| [:group] = val end opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val| [: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| [:created_by] = val end opts.on('--details', "Display more details: memory and storage usage used / max values." ) do [:details] = true end opts.on( '-s', '--search PHRASE', "Search Phrase" ) do |phrase| [:phrase] = phrase end (opts, , [:query, :remote, :dry_run]) opts. = "Get the number of hosts." end optparse.parse!(args) connect() begin params.merge!(()) account = nil if [:account] account = find_account_by_name_or_id([:account]) if account.nil? return 1 else params['accountId'] = account['id'] end end group = [:group] ? find_group_by_name_or_id_for_provisioning([: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 = [:cloud] ? find_zone_by_name_or_id(nil, [:cloud]) : nil if cloud params['zoneId'] = cloud['id'] end if [:created_by] created_by_ids = find_all_user_ids(account ? account['id'] : nil, [: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() if [: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, ) exit 1 end end |
#execution_request(args) ⇒ Object
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 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 |
# File 'lib/morpheus/cli/hosts.rb', line 1517 def execution_request(args) = {} params = {} script_content = nil do_refresh = true optparse = Morpheus::Cli::OptionParser.new do|opts| opts. = 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.(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()) (opts, , [:options, :payload, :json, :dry_run, :quiet, :remote]) opts. = "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() 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 [:payload] payload = [:payload] else payload.deep_merge!([:options].reject {|k,v| k.is_a?(Symbol) }) if [: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]) script_content = v_prompt['script'] end payload['script'] = script_content end # dry run? @servers_interface.setopts() if [: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 [:quiet] return 0 elsif [:json] puts as_json(json_response, ) 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"]+ ([:remote] ? ["-r",[:remote]] : [])) else Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId']]+ ([:remote] ? ["-r",[:remote]] : [])) end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#get(args) ⇒ Object
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 |
# File 'lib/morpheus/cli/hosts.rb', line 478 def get(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") opts.on( nil, '--costs', "Display Cost and Price" ) do [:include_costs] = true end opts.on('--refresh [SECONDS]', String, "Refresh until status is provisioned,failed. Default interval is #{default_refresh_interval} seconds.") do |val| [:refresh_until_status] ||= "provisioned,failed" if !val.to_s.empty? [:refresh_interval] = val.to_f end end opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val| [:refresh_until_status] = val.to_s.downcase end (opts, , [:json, :csv, :yaml, :fields, :dry_run, :remote]) end optparse.parse!(args) if args.count < 1 puts optparse exit 1 end connect() id_list = parse_id_list(args) return run_command_for_each_arg(id_list) do |arg| _get(arg, ) 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 356 357 358 359 360 361 362 363 364 |
# File 'lib/morpheus/cli/hosts.rb', line 52 def list(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage() opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val| [:group] = val end opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val| [: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 [: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| [:created_by] = val end opts.on( '--tenant TENANT', "Tenant Name or ID" ) do |val| [:account] = val end opts.on('--labels label',String, "Filter by labels (keywords).") do |val| val.split(",").each do |k| [:labels] ||= [] [: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("=") [:tags] ||= {} [:tags][k] ||= [] [: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 [:stats] = true end opts.on('-a', '--details', "Display all details: hostname, private ip, plan, stats, etc." ) do [:details] = true end (opts, ) opts. = "List hosts." end optparse.parse!(args) connect() # verify_args!(args:args, optparse:optparse, count:0) if args.count > 0 [:phrase] = args.join(" ") end begin params.merge!(()) account = nil if [:account] account = find_account_by_name_or_id([:account]) if account.nil? return 1 else params['accountId'] = account['id'] end end group = [:group] ? find_group_by_name_or_id_for_provisioning([: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 = [:cloud] ? find_zone_by_name_or_id(nil, [:cloud]) : nil if cloud params['zoneId'] = cloud['id'] end if [:created_by] created_by_ids = find_all_user_ids(account ? account['id'] : nil, [: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 [:cluster] if [:cluster].to_s =~ /\A\d{1,}\Z/ params['clusterId'] = [:cluster] else cluster = find_cluster_by_name_or_id([:cluster]) return 1 if cluster.nil? params['clusterId'] = cluster['id'] end end params['labels'] = [:labels] if [:labels] if [:tags] && ![:tags].empty? [:tags].each do |k,v| params['tags.' + k] = v end end @servers_interface.setopts() if [:dry_run] print_dry_run @servers_interface.dry.list(params) return end json_response = @servers_interface.list(params) if [:json] json_response.delete('stats') if [:include_fields] puts as_json(json_response, , "servers") return 0 elsif [:yaml] json_response.delete('stats') if [:include_fields] puts as_yaml(json_response, , "servers") return 0 elsif [:csv] # merge stats to be nice here.. if json_response['servers'] all_stats = json_response['stats'] || {} json_response['servers'].each do |it| it['stats'] ||= all_stats[it['id'].to_s] || all_stats[it['id']] end end puts records_as_csv(json_response['servers'], ) return 0 else servers = json_response['servers'] multi_tenant = json_response['multiTenant'] == true title = "Morpheus Hosts" subtitles = [] if account subtitles << "Tenant: #{account['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() print_h1 title, subtitles, 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 ? "" : ((stats['usedCpu'] || stats['cpuUsage']).to_f, 100, {max_bars: 10}) memory_usage_str = !stats ? "" : (stats['usedMemory'], stats['maxMemory'], {max_bars: 10}) storage_usage_str = !stats ? "" : (stats['usedStorage'], stats['maxStorage'], {max_bars: 10}) if [:details] || [: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: ([:details]||[: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 [: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!, ) print reset print_results_pagination(json_response) end print reset,"\n" end rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#list_types(args) ⇒ Object
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 1661 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 1622 def list_types(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage() opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val| [:cloud] = val end (opts, , [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote]) opts. = "List host types." end optparse.parse!(args) connect() begin params = {} params.merge!(()) if [:cloud] #return server_types_for_cloud(options[:cloud], options) zone = find_zone_by_name_or_id(nil, [:cloud]) params["zoneTypeId"] = zone['zoneTypeId'] params["creatable"] = true end @server_types_interface.setopts() if [: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, , 'serverTypes') return 0 if render_result server_types = json_response['serverTypes'] title = "Morpheus Server Types" subtitles = [] subtitles += parse_list_subtitles() if [:cloud] subtitles << "Cloud: #{[: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, ) print reset print_results_pagination(json_response) end print reset,"\n" return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#logs(args) ⇒ Object
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 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 |
# File 'lib/morpheus/cli/hosts.rb', line 693 def logs(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") opts.on('--start TIMESTAMP','--start TIMESTAMP', "Start timestamp. Default is 30 days ago.") do |val| [:start] = parse_time(val) #.utc.iso8601 end opts.on('--end TIMESTAMP','--end TIMESTAMP', "End timestamp. Default is now.") do |val| [: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 [:table] = true end opts.on('-a', '--all', "Display all details: entire message." ) do [:details] = true end (opts, , [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote]) end optparse.parse!(args) if args.count < 1 puts optparse exit 1 end connect() 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!(()) 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'] = ([:start].to_i * 1000) if [:start] params['endMs'] = ([:end].to_i * 1000) if [:end] @logs_interface.setopts() if [: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, , 'logs') : render_with_format(json_response, , 'data') return 0 if render_result title = "Host Logs: #{server['name']} (#{server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged'})" subtitles = parse_list_subtitles() if [:start] subtitles << "Start: #{[:start]}".strip end if [:end] subtitles << "End: #{[: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, logs = json_response['data'] || json_response['logs'] if logs.empty? print "#{cyan}No logs found.#{reset}\n" else print format_log_records(logs, ) print_results_pagination({'meta'=>{'total'=>(json_response['total']['value'] rescue json_response['total']),'size'=>logs.size,'max'=>(json_response['max'] || [:max]),'offset'=>(json_response['offset'] || [:offset] || 0)}}) end print reset, "\n" return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#make_managed(args) ⇒ Object
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 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 |
# File 'lib/morpheus/cli/hosts.rb', line 1329 def make_managed(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") (opts, , 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| ['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| [: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 (opts, , [:options, :json, :dry_run, :quiet, :remote]) end optparse.parse!(args) if args.count < 1 puts optparse exit 1 end connect() 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' => {} } = ([:options] || {}).reject {|k,v| k.is_a?(Symbol) } payload.deep_merge!() params = Morpheus::Cli::OptionTypes.prompt(make_managed_option_types, [:options], @api_client, [:params]) server_os = params.delete('serverOs') if server_os payload['server']['serverOs'] = {id: server_os} end account_id = params.delete('account') # not yet implemented if account_id payload['server']['account'] = {id: account} end if [:group] group = [:group] ? find_group_by_name_or_id_for_provisioning([:group]) : nil return 1 if group.nil? params['provisionSiteId'] = group['id'] end payload['server'].merge!(params) ['installAgent','instanceTypeId'].each do |k| if [k] != nil payload[k] = [k] end end @servers_interface.setopts() if [:dry_run] print_dry_run(@servers_interface.dry.make_managed(host['id'], payload), ) return 0 end json_response = @servers_interface.make_managed(host['id'], payload) if [:json] print JSON.pretty_generate(json_response) print "\n" elsif ![: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, ) exit 1 end end |
#remove(args) ⇒ Object
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 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 |
# File 'lib/morpheus/cli/hosts.rb', line 1089 def remove(args) = {} query_params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = 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 (opts, , [:auto_confirm, :json, :dry_run, :quiet, :remote]) end optparse.parse!(args) if args.count < 1 puts optparse exit 1 end connect() begin server = find_host_by_name_or_id(args[0]) unless [:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the server '#{server['name']}'?", ) exit 1 end @servers_interface.setopts() if [: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 [:json] print JSON.pretty_generate(json_response) print "\n" elsif ![:quiet] print_green_success "Host #{server['name']} is being removed..." #list([]) end rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#resize(args) ⇒ Object
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 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 |
# File 'lib/morpheus/cli/hosts.rb', line 1235 def resize(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") (opts, , [:options, :json, :dry_run, :quiet, :remote]) end optparse.parse!(args) if args.count < 1 puts optparse exit 1 end connect() 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 [: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]) 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, ) 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() if [:dry_run] print_dry_run @servers_interface.dry.resize(server['id'], payload) return end json_response = @servers_interface.resize(server['id'], payload) if [:json] print JSON.pretty_generate(json_response) print "\n" else unless [:quiet] puts "Host #{server['name']} resizing..." list([]) end end rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#run_workflow(args) ⇒ Object
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 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 |
# File 'lib/morpheus/cli/hosts.rb', line 1435 def run_workflow(args) params = {} = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name] [workflow] [options]") (opts, , [: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() 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 = ([:options] || {}).reject {|k,v| k.is_a?(Symbol) } params.deep_merge!() unless .empty? # the payload format is unusual # payload example: {"taskSet": {taskSetId": {"taskSetTaskId": {"customOptions": {"dbVersion":"5.6"}}}}} payload = nil if [:payload] payload = [:payload] else payload = {} # i guess you must pass an option if there are editable options # any option, heh task_types = @tasks_interface.list_types() = [] 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? += 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() if [: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 [:json] print as_json(json_response, ), "\n" return elsif [: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, ) exit 1 end end |
#server_types_for_cloud(cloud_id, options) ⇒ Object
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 |
# File 'lib/morpheus/cli/hosts.rb', line 1600 def server_types_for_cloud(cloud_id, ) connect() 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 [:json] print JSON.pretty_generate(cloud_server_types) print "\n" else print_h1 "Morpheus Server Types - Cloud: #{zone['name']}", [], 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
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 |
# File 'lib/morpheus/cli/hosts.rb', line 1932 def snapshots(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[host]") # no pagination yet # build_standard_list_options(opts, options) (opts, ) end optparse.parse!(args) verify_args!(args:args, optparse:optparse, count:1) connect() begin server = find_host_by_name_or_id(args[0]) return 1 if server.nil? params = {} @servers_interface.setopts() if [: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, , 'snapshots') do print_h1 "Snapshots: #{server['name']}", [], 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!, ) print_results_pagination({size: snapshots.size, total: snapshots.size}) end print reset, "\n" end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#software(args) ⇒ Object
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 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 |
# File 'lib/morpheus/cli/hosts.rb', line 1980 def software(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[host]") (opts, ) end optparse.parse!(args) verify_args!(args:args, optparse:optparse, count:1) connect() begin server = find_host_by_name_or_id(args[0]) return 1 if server.nil? params = {} params.merge!(()) @servers_interface.setopts() if [: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, , 'software') do print_h1 "Software: #{server['name']}", [], 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!, ) print_results_pagination({size: software.size, total: software.size}) end print reset, "\n" end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#start(args) ⇒ Object
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 |
# File 'lib/morpheus/cli/hosts.rb', line 1145 def start(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") (opts, , [:auto_confirm, :quiet, :json, :dry_run, :remote]) opts. = "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() 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 [:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to start #{objects_label}?", ) return 9, "aborted command" end @servers_interface.setopts() if [: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 [:json] print JSON.pretty_generate(json_response) print "\n" elsif ![:quiet] print_green_success "Started #{objects_label}" end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#stats(args) ⇒ Object
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 |
# File 'lib/morpheus/cli/hosts.rb', line 632 def stats(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") (opts, , [:json, :yaml, :csv, :fields, :dry_run, :remote]) end optparse.parse!(args) if args.count < 1 puts optparse exit 1 end connect() ids = args id_list = parse_id_list(args) return run_command_for_each_arg(id_list) do |arg| _stats(arg, ) end end |
#stop(args) ⇒ Object
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 |
# File 'lib/morpheus/cli/hosts.rb', line 1190 def stop(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") (opts, , [:auto_confirm, :quiet, :json, :dry_run, :remote]) opts. = "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() 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 [:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop #{objects_label}?", ) return 9, "aborted command" end @servers_interface.setopts() if [: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 [:json] print JSON.pretty_generate(json_response) print "\n" elsif ![:quiet] print_green_success "Stopped #{objects_label}" end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#update(args) ⇒ Object
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 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 |
# File 'lib/morpheus/cli/hosts.rb', line 985 def update(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = 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| [:tags] = val end opts.on('--metadata LIST', String, "Alias for --tags.") do |val| [: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| [: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| [:remove_tags] = val end # opts.on('--created-by ID', String, "Created By User ID") do |val| # params['createdById'] = val # end (opts, , [:options, :payload, :json, :dry_run, :remote]) end optparse.parse!(args) if args.count != 1 puts optparse return 1 end connect() begin server = find_host_by_name_or_id(args[0]) return 1 if server.nil? new_group = nil = [:options] ? [:options].reject {|k,v| k.is_a?(Symbol) } : {} params.deep_merge!() unless .empty? # metadata tags if [:tags] params['tags'] = ([:tags]) else # params['tags'] = prompt_metadata(options) end if [:add_tags] params['addTags'] = ([:add_tags]) end if [:remove_tags] params['removeTags'] = ([:remove_tags]) end payload = nil if [:payload] payload = [: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() if [:dry_run] print_dry_run @servers_interface.dry.update(server["id"], payload) return end json_response = @servers_interface.update(server["id"], payload) if [:json] puts as_json(json_response, ) else print_green_success "Updated host #{server['name']}" get([server['id']]) end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#update_wiki(args) ⇒ Object
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 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 |
# File 'lib/morpheus/cli/hosts.rb', line 1854 def update_wiki(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[host] [options]") (opts, , 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.(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 (opts, , [: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() begin host = find_host_by_name_or_id(args[0]) return 1 if host.nil? # construct payload = [:options] ? [:options].reject {|k,v| k.is_a?(Symbol) } : {} payload = nil if [:payload] payload = [:payload] payload.deep_merge!({'page' => }) unless .empty? else payload = { 'page' => { } } # allow arbitrary -O options payload.deep_merge!({'page' => }) unless .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!() 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() if [: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 [:json] puts as_json(json_response, ) 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, ) exit 1 end end |
#upgrade_agent(args) ⇒ Object
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 |
# File 'lib/morpheus/cli/hosts.rb', line 1402 def upgrade_agent(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") (opts, , [:json, :dry_run, :quiet, :remote]) end optparse.parse!(args) if args.count < 1 puts optparse exit 1 end connect() begin host = find_host_by_name_or_id(args[0]) @servers_interface.setopts() if [:dry_run] print_dry_run @servers_interface.dry.upgrade(host['id']) return end json_response = @servers_interface.upgrade(host['id']) if [:json] print JSON.pretty_generate(json_response) print "\n" else puts "Host #{host['name']} upgrading..." unless [:quiet] end return rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#view(args) ⇒ Object
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 |
# File 'lib/morpheus/cli/hosts.rb', line 1687 def view(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[host]") opts.on('-w','--wiki', "Open the wiki tab for this host") do [:link_tab] = "wiki" end opts.on('--tab VALUE', String, "Open a specific tab") do |val| [:link_tab] = val.to_s end (opts, , [:dry_run, :remote]) opts. = "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() id_list = parse_id_list(args) return run_command_for_each_arg(id_list) do |arg| _view(arg, ) end end |
#view_wiki(args) ⇒ Object
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 |
# File 'lib/morpheus/cli/hosts.rb', line 1811 def view_wiki(args) params = {} = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[id]") (opts, , [:dry_run, :remote]) opts. = "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() 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 [:dry_run] puts "system: #{open_command}" return 0 end system(open_command) return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#wiki(args) ⇒ Object
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 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 |
# File 'lib/morpheus/cli/hosts.rb', line 1733 def wiki(args) = {} params = {} open_wiki_link = false optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[host]") opts.on('--view', '--view', "View wiki page in web browser.") do open_wiki_link = true end (opts, , [:json, :dry_run, :remote]) opts. = "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() begin host = find_host_by_name_or_id(args[0]) return 1 if host.nil? @servers_interface.setopts() if [: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, , '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, ) exit 1 end end |