Class: Morpheus::Cli::Hosts

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProvisioningHelper

#api_client, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #get_available_clouds, #get_available_environments, #get_available_groups, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_types_interface, #instances_interface, #options_interface, #prompt_evars, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_resize_volumes, #prompt_security_groups, #prompt_volumes, #reject_networking_option_types, #reject_service_plan_option_types, #reject_volume_option_types

Methods included from AccountsHelper

#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_role_type, #format_user_role_names, #get_access_string, included, #print_accounts_table, #print_roles_table, #print_users_table, #roles_interface, #user_groups_interface, #users_interface

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_refresh_interval, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #render_with_format, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeHosts

Returns a new instance of Hosts.



24
25
26
# File 'lib/morpheus/cli/hosts.rb', line 24

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

Instance Method Details

#_get(arg, options) ⇒ Object



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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/morpheus/cli/hosts.rb', line 408

def _get(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
    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 options[:json]
      json_response.delete('stats') if options[:include_fields]
      puts as_json(json_response, options, "server")
      return 0
    elsif options[:yaml]
      json_response.delete('stats') if options[:include_fields]
      puts as_yaml(json_response, options, "server")
      return 0
    end
    if options[:csv]
      puts records_as_csv([json_response['server']], options)
      return 0
    end
    server = json_response['server']
    #stats = server['stats'] || json_response['stats'] || {}
    stats = json_response['stats'] || {}
    title = "Host Details"
    print_h1 title, [], options
    print cyan
    print_description_list({
      "ID" => 'id',
      "Name" => 'name',
      "Description" => 'description',
      "Account" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      #"Group" => lambda {|it| it['group'] ? it['group']['name'] : '' },
      "Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
      "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'] : '' },
      "Agent" => lambda {|it| it['agentInstalled'] ? "#{server['agentVersion'] || ''} updated at #{format_local_dt(server['lastAgentUpdate'])}" : '(not installed)' },
      "Status" => lambda {|it| format_server_status(it) },
      "Nodes" => lambda {|it| it['containers'] ? it['containers'].size : 0 },
      "Power" => lambda {|it| format_server_power_state(it) },
    }, 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)
    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

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

#_stats(arg, options) ⇒ Object



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

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



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

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

    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

#add(args) ⇒ Object



630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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
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
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
# File 'lib/morpheus/cli/hosts.rb', line 630

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 sepearated 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 }.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 volume options if volumes were configured
      if !payload['volumes'].empty?
        option_type_list = reject_volume_option_types(option_type_list)
      end
      # remove networkId option if networks were configured above
      if !payload['networkInterfaces'].empty?
        option_type_list = reject_networking_option_types(option_type_list)
      end

      # 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



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

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).options
  @tasks_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).tasks
  @task_sets_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).task_sets
  @servers_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).servers
  @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_group
  @execution_request_interface = @api_client.execution_request
  @clusters_interface = @api_client.clusters
end

#count(args) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/morpheus/cli/hosts.rb', line 270

def count(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[options]")
    opts.on( '-a', '--account ACCOUNT', "Account 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
    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



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
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
# File 'lib/morpheus/cli/hosts.rb', line 1335

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"])
    else
      Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_request['uniqueId']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    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_common_options(opts, options, [:json, :csv, :yaml, :fields, :dry_run, :remote])
  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



45
46
47
# File 'lib/morpheus/cli/hosts.rb', line 45

def handle(args)
  handle_subcommand(args)
end

#install_agent(args) ⇒ Object



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
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
# File 'lib/morpheus/cli/hosts.rb', line 1168

def install_agent(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_option_type_options(opts, options, install_agent_option_types(false))
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    host = find_host_by_name_or_id(args[0])
    if host['agentInstalled']
      print_red_alert "Agent already installed on host '#{host['name']}'"
      return false
    end
    payload = {
      'server' => {}
    }
    params = Morpheus::Cli::OptionTypes.prompt(install_agent_option_types, options[:options], @api_client, options[:params])
    server_os = params.delete('serverOs')
    if server_os
      payload['server']['serverOs'] = {id: server_os}
    end
     = params.delete('account') # not yet implemented
    if 
      payload['server']['account'] = {id: }
    end
    payload['server'].merge!(params)
    @servers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @servers_interface.dry.install_agent(host['id'], payload)
      return
    end
    json_response = @servers_interface.install_agent(host['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Host #{host['name']} is being converted to managed."
      puts "Public Key:\n#{json_response['publicKey']}\n(copy to your authorized_keys file)"
    end
    return true
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list(args) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
# File 'lib/morpheus/cli/hosts.rb', line 49

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '-a', '--account ACCOUNT', "Account 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( '--cluster CLUSTER', '--cluster CLUSTER', "Filter by Cluster Name or ID" ) do |val|
      # params[:clusterId] = val
      options[:cluster] = 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
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List 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
    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

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

    if options[:json]
      json_response.delete('stats') if options[:include_fields]
      puts as_json(json_response, options, "servers")
      return 0
    elsif options[:yaml]
      json_response.delete('stats') if options[:include_fields]
      puts as_yaml(json_response, options, "servers")
      return 0
    elsif options[: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'], options)
      return 0
    else
      servers = json_response['servers']
      multi_tenant = json_response['multiTenant'] == true
      title = "Morpheus Hosts"
      subtitles = []
      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 yellow,"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]
            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'],
            tenant: server['account'] ? server['account']['name'] : server['accountId'],
            name: server['name'],
            platform: server['serverOs'] ? server['serverOs']['name'].upcase : 'N/A',
            cloud: server['zone'] ? server['zone']['name'] : '',
            type: server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged',
            nodes: server['containers'] ? server['containers'].size : '',
            status: format_server_status(server, cyan),
            power: format_server_power_state(server, cyan),
            cpu: cpu_usage_str + cyan,
            memory: memory_usage_str + cyan,
            storage: storage_usage_str + cyan
          }
          row
        }
        columns = [:id, :name, :type, :cloud, :nodes, :status, :power]
        if multi_tenant
          columns.insert(4, :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, options)
        print reset
        print_results_pagination(json_response)
      end
      print reset,"\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_types(args) ⇒ Object



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

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



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

def logs(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    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 = {}
    params.merge!(parse_list_options(options))
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    @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 = render_with_format(json_response, options, 'data')
    return 0 if render_result
    
    logs = json_response
    title = "Host Logs: #{server['name']} (#{server['computeServerType'] ? server['computeServerType']['name'] : 'unmanaged'})"
    subtitles = parse_list_subtitles(options)
    if params[:query]
      subtitles << "Search: #{params[:query]}".strip
    end
    # todo: startMs, endMs, sorts insteaad of sort..etc
    print_h1 title, subtitles, options
    if logs['data'].empty?
      puts "#{cyan}No logs found.#{reset}"
    else
      if logs['data'].empty?
        puts "#{cyan}No logs found.#{reset}"
      else
        logs['data'].reverse.each do |log_entry|
          log_level = ''
          case log_entry['level']
          when 'INFO'
            log_level = "#{blue}#{bold}INFO#{reset}"
          when 'DEBUG'
            log_level = "#{white}#{bold}DEBUG#{reset}"
          when 'WARN'
            log_level = "#{yellow}#{bold}WARN#{reset}"
          when 'ERROR'
            log_level = "#{red}#{bold}ERROR#{reset}"
          when 'FATAL'
            log_level = "#{red}#{bold}FATAL#{reset}"
          end
          puts "[#{log_entry['ts']}] #{log_level} - #{log_entry['message'].to_s.strip}"
        end
        print_results_pagination({'meta'=>{'total'=>json_response['total'],'size'=>json_response['data'].size,'max'=>(json_response['max'] || options[:max]),'offset'=>(json_response['offset'] || options[:offset] || 0)}})
      end
      print reset, "\n"
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



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

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



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
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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
# File 'lib/morpheus/cli/hosts.rb', line 1074

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



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
1328
1329
1330
1331
1332
1333
# File 'lib/morpheus/cli/hosts.rb', line 1253

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.task_types()
    editable_options = []
    workflow['taskSetTasks'].sort{|a,b| a['taskOrder'] <=> b['taskOrder']}.each do |task_set_task|
      task_type_id = task_set_task['task']['taskType']['id']
      task_type = task_types['taskTypes'].find{ |current_task_type| current_task_type['id'] == task_type_id}
      task_opts = task_type['optionTypes'].select { |otype| otype['editable']}
      if !task_opts.nil? && !task_opts.empty?
        editable_options += task_opts.collect do |task_opt|
          new_task_opt = task_opt.clone
          new_task_opt['fieldContext'] = "#{task_set_task['id']}.#{new_task_opt['fieldContext']}"
        end
      end
    end
    # 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



1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
# File 'lib/morpheus/cli/hosts.rb', line 1418

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 yellow,"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

#start(args) ⇒ Object



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

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



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/morpheus/cli/hosts.rb', line 502

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



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

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



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

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('--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?
    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



1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
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
# File 'lib/morpheus/cli/hosts.rb', line 1684

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



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

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



1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'lib/morpheus/cli/hosts.rb', line 1505

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



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

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



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

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