Class: Morpheus::Cli::CloudResourcePoolsCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, InfrastructureHelper, OptionSourceHelper
Defined in:
lib/morpheus/cli/commands/cloud_resource_pools_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from OptionSourceHelper

#find_available_user_option, #find_cloud_option, #find_group_option, #find_tenant_option, #get_available_user_options, #get_cloud_options, #get_group_options, #get_tenant_options, included, #load_option_source_data, #options_interface, #parse_cloud_id_list, #parse_group_id_list, #parse_option_source_id_list, #parse_project_id_list, #parse_tenant_id_list, #parse_user_id_list

Methods included from InfrastructureHelper

#cloud_type_for_id, #cloud_type_for_name, #cloud_type_for_name_or_id, #clouds_interface, #find_cloud_by_id, #find_cloud_by_name, #find_cloud_by_name_or_id, #find_group_by_id, #find_group_by_name, #find_group_by_name_or_id, #find_network_by_id, #find_network_by_name, #find_network_by_name_or_id, #find_network_group_by_id, #find_network_group_by_name, #find_network_group_by_name_or_id, #find_network_server_type_by_id, #find_network_server_type_by_name, #find_network_server_type_by_name_or_code, #find_network_server_type_by_name_or_id, #find_network_type_by_id, #find_network_type_by_name, #find_network_type_by_name_or_id, #find_resource_pool_group_by_id, #find_resource_pool_group_by_name, #find_resource_pool_group_by_name_or_id, #find_subnet_by_id, #find_subnet_by_name, #find_subnet_by_name_or_id, #find_subnet_type_by_id, #find_subnet_type_by_name, #find_subnet_type_by_name_or_id, #format_network_pool_server_status, #get_available_cloud_types, #groups_interface, included, #network_groups_interface, #network_pool_server_column_definitions, #network_pool_server_list_column_definitions, #network_pool_server_type_column_definitions, #network_pool_server_type_list_column_definitions, #network_server_type_column_definitions, #network_server_type_list_column_definitions, #network_types_interface, #networks_interface, #prompt_for_network, #prompt_for_networks, #prompt_for_pools, #prompt_for_subnets, #resource_pool_groups_interface, #resource_pools_interface, #subnet_types_interface, #subnets_interface

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Constructor Details

#initializeCloudResourcePoolsCommand

Returns a new instance of CloudResourcePoolsCommand.



13
14
15
# File 'lib/morpheus/cli/commands/cloud_resource_pools_command.rb', line 13

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

Instance Method Details

#add(args) ⇒ Object



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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
# File 'lib/morpheus/cli/commands/cloud_resource_pools_command.rb', line 272

def add(args)
  options = {}
  cloud_id = nil
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  plan_access_all = nil
  plan_access_list = nil
  plan_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud] [pool] [options]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    opts.add_hidden_option('-c') # prefer args[0] for [cloud]
    opts.on( '--name VALUE', String, "Name" ) do |val|
      options['name'] = val
    end
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true'  || val.to_s == ''
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--group-defaults LIST', Array, "Group Default Selection, comma separated list of group IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_defaults_list = []
      else
        group_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--plan-access-all [on|off]', String, "Toggle Access for all plans.") do |val|
      plan_access_all = val.to_s == 'on' || val.to_s == 'true'  || val.to_s == ''
    end
    opts.on('--plan-access LIST', Array, "Plan Access, comma separated list of plan IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        plan_access_list = []
      else
        plan_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--plan-defaults LIST', Array, "Plan Default Selection, comma separated list of plan IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        plan_defaults_list = []
      else
        plan_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on('--active [on|off]', String, "Can be used to disable a resource pool") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--inventory [on|off]', String, "Enable or disable inventory sync for resource pool during cloud refresh") do |val|
      options['inventory'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--default-pool [on|off]', String, "Set resource pool as the default") do |val|
      options['defaultPool'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      options['description'] = val.to_s
    end
    opts.on( '--role ROLE', String, "Role Name or ID (applicable to select resource pools)" ) do |val|
      options[:role] = val
    end
    build_standard_add_options(opts, options)
    opts.footer = "Add a resource pool." + "\n" +
                  "[cloud] is required. This is the name or id of the cloud."
  end
  optparse.parse!(args)
  if args.count == 2
    cloud_id = args[0]
    options['name'] = args[1]
  elsif args.count == 1 # && cloud_id
    if cloud_id
      options['name'] = args[0]
    else
      cloud_id = args[0]
    end
  else
    raise_command_error "wrong number of arguments, expected 1-2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end

  connect(options)

  # load cloud
  if cloud_id.nil?
    puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
    return 1
  end
  cloud = find_cloud_by_name_or_id(cloud_id)
  return 1 if cloud.nil?

  # merge -O options into normally parsed options
  options.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

  # construct payload
  payload = nil
  if options[:payload]
    payload = options[:payload]
  else
    # prompt for resource pool options
    payload = {
      'resourcePool' => {
      }
    }

    # allow arbitrary -O options
    payload['resourcePool'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    # Name
    if options['name']
      payload['resourcePool']['name'] = options['name']
    else
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Name'}], options)
      payload['resourcePool']['name'] = v_prompt['name']
    end

    # Group Access
    if group_access_all != nil
      payload['resourcePermissions'] ||= {}
      payload['resourcePermissions']['all'] = group_access_all
    else
      # default to all
      if payload['resourcePermissions'].nil? || payload['resourcePermissions']['all'].nil?
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['all'] = true
      end
    end
    if group_access_list != nil
      payload['resourcePermissions'] ||= {}
      payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
        site = {"id" => site_id.to_i}
        if group_defaults_list && group_defaults_list.include?(site_id)
          site["default"] = true
        end
        site
      end
    end

    # Service Plan Access
    if plan_access_all != nil
      payload['resourcePermissions'] ||= {}
      payload['resourcePermissions']['allPlans'] = plan_access_all
    else
      # default to all
      if payload['resourcePermissions'].nil? || payload['resourcePermissions']['allPlans'].nil?
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['allPlans'] = true
      end
    end
    if plan_access_list != nil
      payload['resourcePermissions'] ||= {}
      payload['resourcePermissions']['plans'] = plan_access_list.collect do |site_id|
        site = {"id" => site_id.to_i}
        if plan_defaults_list && plan_defaults_list.include?(site_id)
          site["default"] = true
        end
        site
      end
    end

    # Tenants
    if options['tenants']
      payload['tenantPermissions'] = {}
      payload['tenantPermissions']['accounts'] = options['tenants']
    end

    # Active
    if options['active'] != nil
      payload['resourcePool']['active'] = options['active']
    else
      payload['resourcePool']['active'] = true
    end
    
    #inventory
    if options['inventory'] != nil
      payload['resourcePool']['inventory'] = options['inventory']
    end

    # Default
    if options['defaultPool'] != nil
      payload['resourcePool']['defaultPool'] = options['defaultPool']
    end

    # Visibility
    if options['visibility'] != nil
      payload['resourcePool']['visibility'] = options['visibility']
    else
      payload['resourcePool']['visibility'] = 'private'
    end


    # Config options depend on type (until api returns these as optionTypes)
    zone_type = cloud['zoneType'] ? cloud['zoneType']['code'] : ''
    if zone_type == 'amazon'
      payload['resourcePool']['config'] ||= {}
      # CIDR
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => 'config', 'fieldName' => 'cidrBlock', 'fieldLabel' => 'CIDR', 'type' => 'text', 'required' => true, 'description' => 'Provide the base CIDR Block to use for this VPC (must be between a /16 and /28 Block)'}], options)
      payload['resourcePool']['config']['cidrBlock'] = v_prompt['config']['cidrBlock']
      # Tenancy
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => 'config', 'fieldName' => 'tenancy', 'fieldLabel' => 'Tenancy', 'type' => 'select', 'selectOptions' => [{'name' => 'Default', 'value' => 'default'}, {'name' => 'Dedicated', 'value' => 'dedicated'}], 'defaultValue' => 'default'}], options)
      payload['resourcePool']['config']['tenancy'] = v_prompt['config']['tenancy']

    elsif zone_type == 'azure'
      # no options
    elsif zone_type == 'cloudFoundry' || zone_type == 'bluemixCloudFoundry'

    elsif zone_type == 'openstack'
      payload['resourcePool']['config'] ||= {}
      # Description
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text'}], options)
      payload['resourcePool']['description'] = v_prompt['description']
      # Role
      role_options = load_option_source_data('openstackRoles', {zoneId: cloud['id']})
      if role = options[:role] ? role_options.find {|it| [it['name'], it['value']].include?(options[:role])} : nil
        payload['resourcePool']['config']['roleId'] = role['value']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => 'config', 'fieldName' => 'roleId', 'fieldLabel' => 'Role', 'type' => 'select', 'selectOptions' => role_options, 'required' => true}], options, @api_client,{zoneId: cloud['id']})
        payload['resourcePool']['config']['roleId'] = v_prompt['config']['roleId']
      end
    elsif zone_type == 'standard'
      # no options
    else
      #raise_command_error "Cloud type '#{zone_type}' does not allow creating resource pools"
    end
  end

  @cloud_resource_pools_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @cloud_resource_pools_interface.dry.create(cloud['id'], payload)
    return
  end
  json_response = @cloud_resource_pools_interface.create(cloud['id'], payload)
  render_response(json_response, options, 'resourcePool') do
    resource_pool = json_response['resourcePool']
    print_green_success "Created resource pool #{resource_pool['name']}"
    get([cloud['id'].to_s, resource_pool['id'].to_s])
  end
  return 0, nil
end

#connect(opts) ⇒ Object



17
18
19
20
21
22
# File 'lib/morpheus/cli/commands/cloud_resource_pools_command.rb', line 17

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @cloud_resource_pools_interface = @api_client.cloud_resource_pools
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
end

#get(args) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/morpheus/cli/commands/cloud_resource_pools_command.rb', line 123

def get(args)
  resource_pool_id = nil
  cloud_id = nil
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud] [pool]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    opts.add_hidden_option('-c') # prefer args[0] for [cloud]
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a resource pool." + "\n" +
                  "[cloud] is required. This is the name or id of the cloud." + "\n"
                  "[pool] is required. This is the name or id of a resource pool."
  end
  optparse.parse!(args)
  if args.count == 2
    cloud_id = args[0]
    resource_pool_id = args[1]
  elsif args.count == 1 && cloud_id
    resource_pool_id = args[0]
  else
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?
    @cloud_resource_pools_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @cloud_resource_pools_interface.dry.get(cloud['id'], resource_pool_id.to_i)
      else
        print_dry_run @cloud_resource_pools_interface.dry.list(cloud['id'], {name:resource_pool_id})
      end
      return
    end
    resource_pool = find_resource_pool_by_name_or_id(cloud['id'], resource_pool_id)
    return 1 if resource_pool.nil?
    json_response = {'resourcePool' => resource_pool}  # skip redundant request
    # json_response = @resource_pools_interface.get(resource_pool['id'])
    resource_pool = json_response['resourcePool']
    if options[:json]
      puts as_json(json_response, options, "resourcePool")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "resourcePool")
      return 0
    elsif options[:csv]
      puts records_as_csv([resource_pool], options)
      return 0
    end

    print_h1 "Resource Pool Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Display Name" => 'displayName',
      "Description" => 'description',
      #"Type" => lambda {|it| it['type'].to_s.capitalize },
      "Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
      "Active" => lambda {|it| format_boolean(it['active']) },
      "Inventory" => lambda {|it| format_boolean(it['inventory']) },
      "Default" => lambda {|it| format_boolean(it['defaultPool']) },
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Status" => lambda {|it| it['status'].to_s.capitalize },
      "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' }
    }

    if cloud['zoneType']['code'] == 'openstack'
      role = resource_pool['config']['roleId'] ? load_option_source_data('openstackRoles', {zoneId: cloud['id']}).find {|it| it['value'] == resource_pool['config']['roleId']} : nil
      description_cols['Role'] = lambda {|it| role ? role['name'] : ''}
    end

    print_description_list(description_cols, resource_pool)

    if resource_pool['resourcePermission'].nil?
      #print "\n", "No group access found", "\n"
    else
      print_h2 "Group Access"
      rows = []
      if resource_pool['resourcePermission']['all']
        rows.push({"name" => 'All'})
      end
      if resource_pool['resourcePermission']['sites']
        resource_pool['resourcePermission']['sites'].each do |site|
          rows.push(site)
        end
      end
      group_columns = {
        "GROUP" => 'name',
        "DEFAULT" => lambda {|it| it['default'].nil? ? '' : format_boolean(it['default']) }
      }
      print cyan
      print as_pretty_table(rows, group_columns)
    end

    if resource_pool['resourcePermission'] && resource_pool['resourcePermission']['plans'] && resource_pool['resourcePermission']['plans'].size > 0
      print_h2 "Service Plan Access"
      rows = []
      if resource_pool['resourcePermission']['allPlans']
        rows.push({"name" => 'All'})
      end
      if resource_pool['resourcePermission']['plans']
        resource_pool['resourcePermission']['plans'].each do |plan|
          rows.push(plan)
        end
      end
      # rows = rows.collect do |site|
      #   {plan: site['name'], default: site['default'] ? 'Yes' : ''}
      #   #{group: site['name']}
      # end
      plan_columns = {
        "PLAN" => 'name',
        "DEFAULT" => lambda {|it| it['default'].nil? ? '' : format_boolean(it['default']) }
      }
      print cyan
      print as_pretty_table(rows, plan_columns)
    end

    if resource_pool['tenants'].nil? || resource_pool['tenants'].empty?
      #print "\n", "No tenant permissions found", "\n"
    else
      print_h2 "Tenant Permissions"
      rows = []
      rows = resource_pool['tenants'] || []
      tenant_columns = {
        "TENANT" => 'name',
        "DEFAULT" => lambda {|it| format_boolean(it['defaultTarget']) },
        "IMAGE TARGET" => lambda {|it| format_boolean(it['defaultStore']) }
      }
      print cyan
      print as_pretty_table(rows, tenant_columns)
    end

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

#handle(args) ⇒ Object



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

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



28
29
30
31
32
33
34
35
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
# File 'lib/morpheus/cli/commands/cloud_resource_pools_command.rb', line 28

def list(args)
  cloud_id = nil
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    opts.add_hidden_option('-c') # prefer args[0] for [cloud]
    opts.on( '-s', '--search PHRASE', "Search by Name and/or Display Name" ) do |phrase|
      options[:phrase] = phrase
    end
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :dry_run, :remote], ['search'])
    opts.footer = "List resource pools for a cloud." + "\n" +
                  "[cloud] is required. This is the name or id of the cloud."
  end
  optparse.parse!(args)
  if args.count == 1
    cloud_id = args[0]
  elsif args.count == 0 && cloud_id
    # support -c
  else
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?

    params.merge!(parse_list_options(options))
    @cloud_resource_pools_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @cloud_resource_pools_interface.dry.list(cloud['id'], params)
      return
    end
    json_response = @cloud_resource_pools_interface.list(cloud['id'], params)
    resource_pools = json_response["resourcePools"]
    if options[:json]
      puts as_json(json_response, options, "resourcePools")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "resourcePools")
      return 0
    elsif options[:csv]
      puts records_as_csv(resource_pools, options)
      return 0
    end
    title = "Morpheus Resource Pools - Cloud: #{cloud['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if resource_pools.empty?
      print cyan,"No resource pools found.",reset,"\n"
    else
      rows = resource_pools.collect {|resource_pool| 
        formatted_name = (resource_pool['depth'] && resource_pool['depth'] > 0) ? (('  ' * resource_pool['depth'].to_i) + resource_pool['name'].to_s) : resource_pool['name'].to_s
        row = {
          id: resource_pool['id'],
          # name: resource_pool['name'],
          name: formatted_name,
          type: resource_pool['type'].to_s.capitalize,
          description: resource_pool['description'],
          active: format_boolean(resource_pool['active']),
          inventory: format_boolean(resource_pool['inventory']),
          status: resource_pool['status'].to_s.upcase,
          visibility: resource_pool['visibility'].to_s.capitalize,
          default: format_boolean(resource_pool['defaultPool']),
          tenants: resource_pool['tenants'] ? resource_pool['tenants'].collect {|it| it['name'] }.uniq.join(', ') : ''
          # owner: resource_pool['owner'] ? resource_pool['owner']['name'] : ''
        }
        row
      }
      columns = [:id, :name, :description, :active,:inventory, :default, :visibility, :tenants]
      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"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



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/commands/cloud_resource_pools_command.rb', line 754

def remove(args)
  cloud_id = nil
  resource_pool_id = nil
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud] [pool]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a resource pool." + "\n" +
                  "[cloud] is required. This is the name or id of the cloud." + "\n"
                  "[pool] is required. This is the name or id of a resource pool."
  end
  optparse.parse!(args)

  if args.count == 2
    cloud_id = args[0]
    resource_pool_id = args[1]
  elsif args.count == 1 && cloud_id
    resource_pool_id = args[0]
  else
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end

  connect(options)
  begin
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?

    resource_pool = find_resource_pool_by_name_or_id(cloud['id'], resource_pool_id)
    return 1 if resource_pool.nil?

    zone_type = cloud['zoneType'] ? cloud['zoneType']['code'] : ''
    if zone_type == ['amazon','azure','cloudFoundry','bluemixCloudFoundry','standard'].include?(zone_type)
    else
      #raise_command_error "Cloud type '#{zone_type}' does not allow deleting resource pools"
    end

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the resource pool: #{resource_pool['name']}?")
      return 9, "aborted command"
    end
    @cloud_resource_pools_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @cloud_resource_pools_interface.dry.destroy(cloud['id'], resource_pool["id"], params)
      return
    end
    json_response = @cloud_resource_pools_interface.destroy(cloud['id'], resource_pool["id"], params)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Removed resource pool #{resource_pool['name']}"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#update(args) ⇒ Object



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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
# File 'lib/morpheus/cli/commands/cloud_resource_pools_command.rb', line 527

def update(args)
  options = {}
  cloud_id = nil
  resource_pool_id = nil
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  plan_access_all = nil
  plan_access_list = nil
  plan_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud] [pool] [options]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    opts.add_hidden_option('-c') # prefer args[0] for [cloud]
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--group-defaults LIST', Array, "Group Default Selection, comma separated list of group IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_defaults_list = []
      else
        group_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--plan-access-all [on|off]', String, "Toggle Access for all plans.") do |val|
      plan_access_all = val.to_s == 'on' || val.to_s == 'true'  || val.to_s == ''
    end
    opts.on('--plan-access LIST', Array, "Plan Access, comma separated list of plan IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        plan_access_list = []
      else
        plan_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--plan-defaults LIST', Array, "Plan Default Selection, comma separated list of plan IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        plan_defaults_list = []
      else
        plan_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on('--active [on|off]', String, "Can be used to disable a resource pool") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--inventory [on|off]', String, "Enable or disable inventory sync for resource pool during cloud refresh") do |val|
      options['inventory'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--default-pool [on|off]', String, "Set resource pool as the default") do |val|
      options['defaultPool'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on("--description [TEXT]", String, "Description") do |val|
      options['description'] = val.to_s
    end
    opts.on("--display-name [TEXT]", String, "Display Name") do |val|
      options['displayName'] = val.to_s
    end
    opts.on( '--role ROLE', String, "Role Name or ID (applicable to select resource pools)" ) do |val|
      options['role'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a resource pool." + "\n" +
                  "[cloud] is required. This is the name or id of the cloud." + "\n"
                  "[pool] is required. This is the name or id of a resource pool."
  end
  optparse.parse!(args)
  if args.count == 2
    cloud_id = args[0]
    resource_pool_id = args[1]
  elsif args.count == 1 && cloud_id
    resource_pool_id = args[0]
  else
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end

  connect(options)
  puts "options #{options}"

  begin
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?

    resource_pool = find_resource_pool_by_name_or_id(cloud['id'], resource_pool_id)
    return 1 if resource_pool.nil?

    # merge -O options into normally parsed options
    options.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # prompt for resource pool options
      payload = {
        'resourcePool' => {
        }
      }

      # allow arbitrary -O options
      payload['resourcePool'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]


      # Group Access
      if group_access_all != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['all'] = group_access_all
      end
      if group_access_list != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
          site = {"id" => site_id.to_i}
          if group_defaults_list && group_defaults_list.include?(site_id)
            site["default"] = true
          end
          site
        end
      end

      # Service Plan Access
      if plan_access_all != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['allPlans'] = plan_access_all
      end
      if plan_access_list != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['plans'] = plan_access_list.collect do |site_id|
          site = {"id" => site_id.to_i}
          if plan_defaults_list && plan_defaults_list.include?(site_id)
            site["default"] = true
          end
          site
        end
      end

      # Tenants
      if options['tenants']
        payload['tenantPermissions'] = {}
        payload['tenantPermissions']['accounts'] = options['tenants']
      end

      # Active
      if options['active'] != nil
        payload['resourcePool']['active'] = options['active']
      end
      
      #inventory
      if options['inventory'] != nil
        payload['resourcePool']['inventory'] = options['inventory']
      end

      # Default
      if options['defaultPool'] != nil
        payload['resourcePool']['defaultPool'] = options['defaultPool']
      end

      # Visibility
      if options['visibility'] != nil
        payload['resourcePool']['visibility'] = options['visibility']
      end

      # Description
      if options['description'] != nil
        payload['resourcePool']['description'] = options['description']
      end

      # Display Name
      if options['displayName'] != nil
        payload['resourcePool']['displayName'] = options['displayName']
      end

      # Role
      if options['role'] != nil
        role_options = load_option_source_data('openstackRoles', {zoneId: cloud['id']})
        if role = role_options.find {|it| [it['name'], it['value']].include?(options['role'])}
          payload['resourcePool']['config'] ||= {}
          payload['resourcePool']['config']['roleId'] = role['value']
        end
      end

      if payload['resourcePool'].empty? && payload['resourcePermissions'].nil? && payload['tenantPermissions'].nil?
        raise_command_error "Specify at least one option to update.\n#{optparse}"
      end

    end
    @cloud_resource_pools_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @cloud_resource_pools_interface.dry.update(cloud['id'], resource_pool["id"], payload)
      return
    end
    json_response = @cloud_resource_pools_interface.update(cloud['id'], resource_pool["id"], payload)
    render_response(json_response, options, 'resourcePool') do
      resource_pool = json_response['resourcePool']
      print_green_success "Updated resource pool #{resource_pool['name']}"
      get([cloud['id'].to_s, resource_pool['id'].to_s])
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end