Class: Morpheus::Cli::Hosts

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProvisioningHelper

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

Methods included from CliCommand

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

Constructor Details

#initializeHosts

Returns a new instance of Hosts.



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

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

Instance Method Details

#_get(arg, options) ⇒ Object



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

def _get(arg, options)
  begin
    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.get({name: arg})
      end
      return
    end
    server = find_host_by_name_or_id(arg)
    json_response = @servers_interface.get(server['id'])
    if options[:json]
      if options[:include_fields]
        json_response = {"server" => filter_data(json_response["server"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    elsif options[:yaml]
      if options[:include_fields]
        json_response = {"server" => filter_data(json_response["server"], options[:include_fields]) }
      end
      puts as_yaml(json_response, options)
      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
    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_host_status(it) },
      "Nodes" => lambda {|it| it['containers'] ? it['containers'].size : 0 },
      "Power" => lambda {|it| format_server_power_state(it) },
    }, server)
    
    print_h2 "Host Usage"
    print_stats_usage(stats)
    print reset, "\n"

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

#_stats(arg, options) ⇒ Object



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

def _stats(arg, options)
  begin
    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.get({name: arg})
      end
      return
    end
    server = find_host_by_name_or_id(arg)
    json_response = @servers_interface.get(server['id'])
    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return 0
    elsif options[:yaml]
      if options[:include_fields]
        json_response = {"stats" => filter_data(json_response["stats"], options[:include_fields]) }
      end
      puts as_yaml(json_response, options)
      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
    puts cyan + "Power: ".rjust(12) + format_server_power_state(server).to_s
    puts cyan + "Status: ".rjust(12) + format_host_status(server).to_s
    puts cyan + "Nodes: ".rjust(12) + (server['containers'] ? server['containers'].size : '').to_s
    #print_h2 "Host Usage"
    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

#add(args) ⇒ Object



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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/morpheus/cli/hosts.rb', line 449

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

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

  params = {}

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

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

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

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

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

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

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

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

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

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

#connect(opts) ⇒ Object



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

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

#get(args) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/morpheus/cli/hosts.rb', line 209

def get(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    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



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

def handle(args)
  handle_subcommand(args)
end

#install_agent(args) ⇒ Object



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

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

    if options[:dry_run]
      print_dry_run @servers_interface.dry.install_agent(host['id'], payload)
      return
    end
    json_response = @servers_interface.install_agent(host['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Host #{host['name']} is being converted to managed."
      puts "Public Key:\n#{json_response['publicKey']}\n(copy to your authorized_keys file)"
    end
    return true
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list(args) ⇒ Object



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

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

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

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

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

    if options[:json]
      if options[:include_fields]
        json_response = {"servers" => filter_data(json_response["servers"], options[:include_fields]) }
      end
      puts as_json(json_response, options)
      return 0
    elsif options[:yaml]
      if options[:include_fields]
        json_response = {"servers" => filter_data(json_response["servers"], options[:include_fields]) }
      end
      puts as_yaml(json_response, options)
      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']
      title = "Morpheus Hosts"
      subtitles = []
      if group
        subtitles << "Group: #{group['name']}".strip
      end
      if cloud
        subtitles << "Cloud: #{cloud['name']}".strip
      end
      if params[:phrase]
        subtitles << "Search: #{params[:phrase]}".strip
      end
      print_h1 title, subtitles
      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 !it['stats']
            it['stats'] = found_stats # || {}
          else
            it['stats'] = found_stats.merge!(it['stats'])
          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})
          row = {
            id: server['id'],
            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_host_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]
        term_width = current_terminal_width()
        if term_width > 170
          columns += [:cpu, :memory, :storage]
        end
        # 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

#logs(args) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/morpheus/cli/hosts.rb', line 351

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

#remove(args) ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/morpheus/cli/hosts.rb', line 604

def remove(args)
  options = {}
  query_params = {removeResources: 'on', force: 'off'}
  optparse = OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [-fS]")
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'on'
    end
    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
    end
    opts.on('--remove-volumes [on|off]', ['on','off'], "Remove Volumes. Default is on.") do |val|
      query_params[:removeVolumes] = val
    end
    opts.on('--remove-instances [on|off]', ['on','off'], "Remove Associated Instances.") do |val|
      query_params[:removeInstances] = val
    end
    opts.on('--release-eips [on|off]', ['on','off'], "Release EIPs, default is true. Amazon only.") do |val|
      params[:releaseEIPs] = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)

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

#resize(args) ⇒ Object



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

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

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

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

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

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

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

    # todo: reconfigure networks
    #       need to get provision_type_id for network info
    # prompt for network interfaces (if supported)
    # if server_type["provisionType"] && server_type["provisionType"]["id"] && server_type["provisionType"]["hasNetworks"]
    #   begin
    #     network_interfaces = prompt_network_interfaces(cloud['id'], server_type["provisionType"]["id"], options)
    #     if !network_interfaces.empty?
    #       payload[:networkInterfaces] = network_interfaces
    #     end
    #   rescue RestClient::Exception => e
    #     print yellow,"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

    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



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

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

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

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

#server_types(args) ⇒ Object



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

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

  zone = find_zone_by_name_or_id(nil, options[:zone])
  cloud_type = cloud_type_for_id(zone['zoneTypeId'])
  cloud_server_types = cloud_type['serverTypes'].select{|b| b['creatable'] == true}
  cloud_server_types = cloud_server_types.sort { |x,y| x['displayOrder'] <=> y['displayOrder'] }
  if options[:json]
    print JSON.pretty_generate(cloud_server_types)
    print "\n"
  else
    print_h1 "Morpheus Server Types - Cloud: #{zone['name']}"
    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



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

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

#stats(args) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/morpheus/cli/hosts.rb', line 288

def stats(args)
  options = {}
  optparse = 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



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

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

#upgrade_agent(args) ⇒ Object



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

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