Class: Morpheus::Cli::Clouds

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #determine_ip_requirements, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_host_by_id, #find_host_by_name, #find_host_by_name_or_id, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, #get_volume_size, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #load_service_plan_datastores, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_cluster_load_balancer, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_permissions_v2, #prompt_resize_volumes, #prompt_security_groups, #prompt_service_plan_options, #prompt_virtual_interfaces, #prompt_volume_controller_mount_point, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

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_by_id, #find_resource_pool_by_name, #find_resource_pool_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

#initializeClouds

Returns a new instance of Clouds.



19
20
21
# File 'lib/morpheus/cli/commands/clouds.rb', line 19

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

Instance Method Details

#_get(id, params, options = {}) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 157

def _get(id, params, options={})
  cloud = nil
  if id.to_s !~ /\A\d{1,}\Z/
    cloud = find_cloud_by_name_or_id(id)
    id = cloud['id']
  end
  @clouds_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @clouds_interface.dry.get(id.to_i, params)
    return
  end
  json_response = @clouds_interface.get(id, params)
  render_response(json_response, options, 'zone') do
    cloud = json_response['zone']
    cloud_stats = cloud['stats']
    # serverCounts moved to zone.stats.serverCounts
    server_counts = nil
    if cloud_stats
      server_counts = cloud_stats['serverCounts']
    else
      server_counts = json_response['serverCounts'] # legacy
    end
    #cloud_type = cloud_type_for_id(cloud['zoneTypeId'])
    print_h1 "Cloud Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      # "Type" => lambda {|it| cloud_type ? cloud_type['name'] : '' },
      "Type" => lambda {|it| it['zoneType'] ? it['zoneType']['name'] : '' },
      "Code" => 'code',
      "Location" => 'location',
      "Labels" => lambda {|it| format_list(it['labels'], '') rescue '' },
      "Region Code" => 'regionCode',
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Groups" => lambda {|it| it['groups'].collect {|g| g.instance_of?(Hash) ? g['name'] : g.to_s }.join(', ') },
      #"Owner" => lambda {|it| it['owner'].instance_of?(Hash) ? it['owner']['name'] : it['ownerId'] },
      "Tenant" => lambda {|it| it['account'].instance_of?(Hash) ? it['account']['name'] : it['accountId'] },
      "Enabled" => lambda {|it| format_boolean(it['enabled']) },
      "Last Sync" => lambda {|it| format_local_dt(it['lastSync']) },
      "Sync Duration" => lambda {|it| format_duration_milliseconds(it['lastSyncDuration']).to_s },
      "Status" => lambda {|it| format_cloud_status(it) },
    }
    print_description_list(description_cols, cloud)

    print_h2 "Cloud Servers"
    print cyan
    if server_counts
      print "Container Hosts: #{server_counts['containerHost']}".center(20)
      print "Hypervisors: #{server_counts['hypervisor']}".center(20)
      print "Bare Metal: #{server_counts['baremetal']}".center(20)
      print "Virtual Machines: #{server_counts['vm']}".center(20)
      print "Unmanaged: #{server_counts['unmanaged']}".center(20)
      print "\n"
    end
    print reset,"\n"
  end
  return 0, nil
end

#add(args) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/morpheus/cli/commands/clouds.rb', line 217

def add(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] --group GROUP --type TYPE")
    opts.on( '-g', '--group GROUP', "Group Name" ) do |val|
      params[:group] = val
    end
    opts.on( '-t', '--type TYPE', "Cloud Type" ) do |val|
      params[:zone_type] = val
    end
    opts.on( '-d', '--description DESCRIPTION', "Description (optional)" ) do |desc|
      params[:description] = desc
    end
    opts.on( '--certificate-provider CODE', String, "Certificate Provider. Default is 'internal'" ) do |val|
      params[:certificate_provider] = val
    end
    opts.on('--costing-mode VALUE', String, "Costing Mode can be off,costing,full, Default is off." ) do |val|
      options[:options]['costingMode'] = val
    end
    opts.on('--credential VALUE', String, "Credential ID or \"local\"" ) do |val|
      options[:options]['credential'] = val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end

    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, max:1)
  connect(options)

  begin
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'zone' => parse_passed_options(options)})
    else
      cloud_payload = {name: args[0], description: params[:description]}
      cloud_payload.deep_merge!(parse_passed_options(options))
      # Group
      # use active group by default
      params[:group] ||= @active_group_id
      if options[:options]['group']
        params[:group] = options[:options]['group']
      end
      group_id = nil
      group = params[:group] ? find_group_by_name_or_id_for_provisioning(params[:group]) : nil
      if group
        group_id = group["id"]
      else
        # print_red_alert "Group not found or specified!"
        # exit 1
        #groups_dropdown = @groups_interface.list({})['groups'].collect {|it| {'name' => it["name"], 'value' => it["id"]} }
        group_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'type' => 'select', 'fieldLabel' => 'Group', 'optionSource' => 'groups', 'required' => true, 'description' => 'Select Group.'}],options[:options],@api_client,{})
        group_id = group_prompt['group']
      end
      cloud_payload['groupId'] = group_id
      cloud_payload.delete('group')
      # todo: pass groups as an array instead

      # Cloud Name
      if args[0]
        cloud_payload['name'] = args[0]
        options[:options]['name'] = args[0] # to skip prompt
      end
      # name_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true}], options[:options])
      # cloud_payload['name'] = name_prompt['name']

      # Cloud Type
      cloud_type = nil
      if params[:zone_type]
        cloud_type = cloud_type_for_name(params[:zone_type])
      else
        # print_red_alert "Cloud Type not found or specified!"
        # exit 1
        cloud_types_dropdown = cloud_types_for_dropdown
        cloud_type_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'type' => 'select', 'fieldLabel' => 'Cloud Type', 'selectOptions' => cloud_types_dropdown, 'required' => true, 'description' => 'Select Cloud Type.'}],options[:options],@api_client,{})
        cloud_type_code = cloud_type_prompt['type']
        cloud_type = cloud_type_for_name(cloud_type_code) # this does work
      end
      if !cloud_type
        print_red_alert "A cloud type is required."
        exit 1
      end
      cloud_payload.delete('type')
      cloud_payload['zoneType'] = {'code' => cloud_type['code']}

      cloud_payload['config'] ||= {}
      if params[:certificate_provider]
        cloud_payload['config']['certificateProvider'] = params[:certificate_provider]
      else
        cloud_payload['config']['certificateProvider'] = 'internal'
      end

      all_option_types = add_cloud_option_types(cloud_type)

      params = Morpheus::Cli::OptionTypes.prompt(all_option_types, options[:options], @api_client, {zoneTypeId: cloud_type['id']})
      # some optionTypes have fieldContext='zone', so move those to the root level of the zone payload
      if params['zone'].is_a?(Hash)
        cloud_payload.deep_merge!(params.delete('zone'))
      end
      cloud_payload.deep_merge!(params)
      payload = {zone: cloud_payload}
    end
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.create(payload)
      return
    end
    json_response = @clouds_interface.create(payload)
    cloud = json_response['zone']
    if options[:json]
      puts as_json(json_response, options)
    else
      get([cloud['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_affinity_group(args) ⇒ Object



1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
# File 'lib/morpheus/cli/commands/clouds.rb', line 1248

def add_affinity_group(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cloud] [name] [options]")
    build_option_type_options(opts, options, add_cloud_affinity_group_option_types)
    # opts.on('--refresh [SECONDS]', String, "Refresh until execution is complete. Default interval is #{default_refresh_interval} seconds.") do |val|
    #   options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
    # end
    # opts.on(nil, '--no-refresh', "Do not refresh" ) do
    #   options[:no_refresh] = true
    # end
    build_standard_add_options(opts, options)
    opts.footer = "Add affinity group to a cloud.\n" +
      "[cloud] is required. This is the name or id of an existing cloud.\n" +
      "[name] is required. This is the name of the new affinity group."
  end

  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1, max:2)
  connect(options)

  begin
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?
    if args[1]
      options[:options]['name']  = args[1]
    end
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload ||= {}
        payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end
    else
      options[:params] ||= {}
      options[:params].merge!({:cloudId => cloud['id'],:zoneId => cloud['id']})
      option_types = add_cloud_affinity_group_option_types
      affinity_group = Morpheus::Cli::OptionTypes.prompt(option_types, options[:options], @api_client, options[:params])

      # affinity_group_type = find_affinity_group_type_by_code(affinity_group['affinityGroupType'])
      # affinity_group['affinityGroupType'] = {id:affinity_group_type['id']}

      # # affinity_group type options
      # unless affinity_group_type['optionTypes'].empty?
      #   affinity_group.merge!(Morpheus::Cli::OptionTypes.prompt(affinity_group_type['optionTypes'], options[:options].deep_merge({:context_map => {'domain' => ''}, :checkbox_as_boolean => true}), @api_client, options[:params]))
      # end

      # perms
      perms = prompt_permissions(options.merge({:for_affinity_group => true}), ['plans', 'groupDefaults'])

      affinity_group['resourcePermissions'] = perms['resourcePermissions'] unless perms['resourcePermissions'].nil?
      affinity_group['tenants'] = perms['tenantPermissions'] unless perms['tenantPermissions'].nil?
      affinity_group['visibility'] = perms['resourcePool']['visibility'] if !perms['resourcePool'].nil? && !perms['resourcePool']['visibility'].nil?

      payload = {'affinityGroup' => affinity_group}
    end

    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.create_affinity_group(cloud['id'], payload)
      return
    end
    json_response = @clouds_interface.create_affinity_group(cloud['id'], payload)
    if options[:json]
      puts as_json(json_response)
    else
      if json_response['success']
        if json_response['msg'] == nil
          print_green_success "Adding affinity group to cloud #{cloud['name']}"
        else
          print_green_success json_response['msg']
        end
        execution_id = json_response['executionId']
        if !options[:no_refresh] && execution_id
          wait_for_execution_request(json_response['executionId'], options.merge({waiting_status:['new', 'pending', 'executing']}))
        end
      else
        print_red_alert "Failed to create cloud affinity group #{json_response['msg']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#apply_security_groups(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 706

def apply_security_groups(args)
  options = {}
  clear_or_secgroups_specified = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [-s] [--clear]")
    opts.on( '-c', '--clear', "Clear all security groups" ) do
      options[:securityGroupIds] = []
      clear_or_secgroups_specified = true
    end
    opts.on( '-s', '--secgroups SECGROUPS', "Apply the specified comma separated security group ids" ) do |secgroups|
      options[:securityGroupIds] = secgroups.split(",")
      clear_or_secgroups_specified = true
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if !clear_or_secgroups_specified
    puts optparse
    exit
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.apply_security_groups(cloud['id'])
      return
    end
    json_response = @clouds_interface.apply_security_groups(cloud['id'], options)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    security_groups([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



23
24
25
26
27
28
# File 'lib/morpheus/cli/commands/clouds.rb', line 23

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @clouds_interface = @api_client.clouds
  @groups_interface = @api_client.groups
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
end

#count(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 108

def count(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[options]")
    build_common_options(opts, options, [:query, :remote, :dry_run])
    opts.footer = "Get the number of clouds."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.list(params)
      return
    end
    json_response = @clouds_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
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#firewall_disable(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 593

def firewall_disable(args)
  options = {}
  clear_or_secgroups_specified = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.firewall_disable(cloud['id'])
      return
    end
    json_response = @clouds_interface.firewall_disable(cloud['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    security_groups([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#firewall_enable(args) ⇒ Object



626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/morpheus/cli/commands/clouds.rb', line 626

def firewall_enable(args)
  options = {}
  clear_or_secgroups_specified = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.firewall_enable(cloud['id'])
      return
    end
    json_response = @clouds_interface.firewall_enable(cloud['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    security_groups([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/morpheus/cli/commands/clouds.rb', line 138

def get(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_standard_list_options(opts, options)
    opts.footer = "Get details about a cloud.\n" +
                  "[name] is required. This is the name or id of a cloud."
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  connect(options)
  params.merge!(parse_query_options(options))
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, params, options)
  end
end

#get_affinity_group(args) ⇒ Object



1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'lib/morpheus/cli/commands/clouds.rb', line 1194

def get_affinity_group(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cloud] [affinity group]")
    build_standard_get_options(opts, options)
    opts.footer = "Get details about a cloud affinity group.\n" +
        "[cloud] is required. This is the name or id of an existing cloud.\n" +
        "[affinity group] is required. This is the name or id of an existing affinity group."
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)

  cloud = find_cloud_by_name_or_id(args[0])
  return 1 if cloud.nil?
  # this finds the affinity group in the cloud api response, then fetches it by ID
  affinity_group = find_cloud_affinity_group_by_name_or_id(cloud['id'], args[1])
  if affinity_group.nil?
    print_red_alert "Affinity Group not found for '#{args[1]}'"
    exit 1
  end

  params = {}
  params.merge!(parse_query_options(options))
  @clouds_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @clouds_interface.dry.get_affinity_group(cloud['id'], affinity_group['id'], params)
    return
  end
  json_response = @clouds_interface.get_affinity_group(cloud['id'], affinity_group['id'], params)
  render_response(json_response, options, 'affinityGroup') do
    affinity_group = json_response['affinityGroup']
    print_h1 "Affinity Group Details", [], options
    columns = {
      "ID" => 'id',
      "Name" => 'name',
      "Type" => lambda {|it| format_affinity_type(it['affinityType']) },
      "Resource Pool" => lambda {|it| it['pool'] ? (it['pool']['name'] || it['pool']['id']) : '' },
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Servers" => lambda {|it| it['servers'].size() },
      "Source" => lambda {|it| it['source'] },
      "Active" => lambda {|it| format_boolean(it['active']) },
    }
    print_description_list(columns, affinity_group)
    if affinity_group['servers'].size > 0
      print_h2 "Servers", options
      print as_pretty_table(affinity_group['servers'], [:id, :name], options)
    end
    print reset,"\n"
  end
  return 0, nil
    
end

#handle(args) ⇒ Object



30
31
32
# File 'lib/morpheus/cli/commands/clouds.rb', line 30

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 34

def list(args)
  options={}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '-g', '--group GROUP', "Group Name" ) do |group|
      options[:group] = group
    end
    opts.on( '-t', '--type TYPE', "Cloud Type" ) do |val|
      options[:zone_type] = val
    end
    opts.on('-l', '--labels LABEL', String, "Filter by labels, can match any of the values") do |val|
      add_query_parameter(params, 'labels', parse_labels(val))
    end
    opts.on('--all-labels LABEL', String, "Filter by labels, must match all of the values") do |val|
      add_query_parameter(params, 'allLabels', parse_labels(val))
    end
    build_standard_list_options(opts, options)
    opts.footer = "List clouds."
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  begin
    if options[:zone_type]
      cloud_type = cloud_type_for_name(options[:zone_type])
      params[:type] = cloud_type['code']
    end
    if !options[:group].nil?
      group = find_group_by_name(options[:group])
      if !group.nil?
        params['groupId'] = group['id']
      end
    end

    params.merge!(parse_list_options(options))
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.list(params)
      return 0
    end

    json_response = @clouds_interface.list(params)
    render_response(json_response, options, 'zones') do
      clouds = json_response['zones']
      title = "Morpheus Clouds"
      subtitles = []
      if group
        subtitles << "Group: #{group['name']}".strip
      end
      if cloud_type
        subtitles << "Type: #{cloud_type['name']}".strip
      end
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      if clouds.empty?
        print cyan,"No clouds found.",reset,"\n"
      else          
        columns = cloud_list_column_definitions(options).upcase_keys!
        print as_pretty_table(clouds, columns, options)
        print_results_pagination(json_response)
      end
      print reset,"\n"
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_affinity_groups(args) ⇒ Object



1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/morpheus/cli/commands/clouds.rb', line 1153

def list_affinity_groups(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cloud]")
    build_standard_list_options(opts, options)
    opts.footer = "List affinity groups for a cloud.\n" +
        "[cloud] is required. This is the name or id of an existing cloud."
  end

  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  
  cloud = find_cloud_by_name_or_id(args[0])
  return 1 if cloud.nil?
  params = {}
  params.merge!(parse_list_options(options))
  json_response = @clouds_interface.list_affinity_groups(cloud['id'], params)
  render_response(json_response, options, 'affinityGroups') do
    affinity_groups = json_response['affinityGroups']
    print_h1 "Morpheus Cloud Affinity Groups: #{cloud['name']}", parse_list_subtitles(options)
    if affinity_groups.empty?
      print cyan,"No affinity groups found.",reset,"\n"
    else          
      columns = {
        "ID" => 'id',
        "Name" => 'name',
        "Type" => lambda {|it| format_affinity_type(it['affinityType']) },
        "Resource Pool" => lambda {|it| it['pool'] ? (it['pool']['name'] || it['pool']['id']) : '' },
        "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
        # "Servers" => lambda {|it| it['serverCount'] },
        # "Source" => lambda {|it| it['source'] },
      }.upcase_keys!
      print as_pretty_table(affinity_groups, columns, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
end

#refresh(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 485

def refresh(args)
  options = {}
  query_params = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud] [options]")
    opts.on( '-m', '--mode [daily|costing]', "Refresh Mode. Use this to run the daily or costing jobs instead of the default hourly refresh." ) do |val|
      query_params[:mode] = val
    end
    opts.on( '--rebuild [on|off]', "Rebuild invoices for period. Only applies to mode=costing." ) do |val|
      query_params[:rebuild] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on( '--period PERIOD', "Period in the format YYYYMM to process invoices for. Default is the current period. Only applies to mode=costing." ) do |val|
      query_params[:period] = val.to_s
    end
    opts.on( '-f', '--force', "Force refresh. Useful if the cloud is disabled." ) do
      query_params[:force] = 'true'
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Refresh a cloud." + "\n" +
                  "[cloud] is required. This is the name or id of a cloud."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!(passed_options) unless passed_options.empty?
    else
      payload = {}
      payload.deep_merge!(passed_options) unless passed_options.empty?
    end
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.refresh(cloud['id'], query_params, payload)
      return
    end
    json_response = @clouds_interface.refresh(cloud['id'], query_params, payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Refreshing cloud #{cloud['name']}..."
      #get([cloud['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 441

def remove(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--remove-resources [on|off]', ['on','off'], "Remove Associated Resources. Default is off.") do |val|
      query_params[:removeResources] = val.nil? ? 'on' : val
    end
    opts.on( '-f', '--force', "Force Remove" ) do
      query_params[:force] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the cloud #{cloud['name']}?")
      exit
    end
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.destroy(cloud['id'], query_params)
      return 0
    end
    json_response = @clouds_interface.destroy(cloud['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Removed cloud #{cloud['name']}"
      #list([])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_affinity_group(args) ⇒ Object



1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
# File 'lib/morpheus/cli/commands/clouds.rb', line 1414

def remove_affinity_group(args)
  default_refresh_interval = 5
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud] [affinity group]")
    # opts.on( '-f', '--force', "Force Delete" ) do
    #   params[:force] = 'on'
    # end
    # opts.on('--refresh [SECONDS]', String, "Refresh until execution is complete. Default interval is #{default_refresh_interval} seconds.") do |val|
    #   options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
    # end
    # opts.on(nil, '--no-refresh', "Do not refresh" ) do
    #   options[:no_refresh] = true
    # end
    build_standard_remove_options(opts, options)
    opts.footer = "Delete an affinity group from a cloud.\n" +
      "[cloud] is required. This is the name or id of an existing cloud.\n" +
      "[affinity group] is required. This is the name or id of an existing affinity group."
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  params.merge!(parse_query_options(options))

  cloud = find_cloud_by_name_or_id(args[0])
  return 1 if cloud.nil?

  affinity_group_id = args[1]
  if affinity_group_id.empty?
    raise_command_error "missing required worker parameter"
  end

  affinity_group = find_cloud_affinity_group_by_name_or_id(cloud['id'], affinity_group_id)
  if affinity_group.nil?
    print_red_alert "Affinity Group not found for '#{affinity_group_id}'"
    return 1
  end
  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the cloud affinity group '#{affinity_group['name'] || affinity_group['id']}'?", options)
    return 9, "aborted command"
  end

  @clouds_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @clouds_interface.dry.destroy_affinity_group(cloud['id'], affinity_group['id'], params)
    return
  end
  json_response = @clouds_interface.destroy_affinity_group(cloud['id'], affinity_group['id'], params)
  if options[:json]
    puts as_json(json_response)
  else
    if json_response['success']
      print_green_success "Removed affinity group #{affinity_group['name']}"
      execution_id = json_response['executionId']
      if !options[:no_refresh] && execution_id
        wait_for_execution_request(execution_id, options.merge({waiting_status:['new', 'pending', 'executing']}))
      end
    else
      print_red_alert "Failed to remove cloud affinity group #{json_response['msg']}"
    end
  end
  return 0, nil
end

#security_groups(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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# File 'lib/morpheus/cli/commands/clouds.rb', line 659

def security_groups(args)
  options = {}
  clear_or_secgroups_specified = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    zone_id = cloud['id']
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.security_groups(zone_id)
      return
    end
    json_response = @clouds_interface.security_groups(zone_id)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    securityGroups = json_response['securityGroups']
    print_h1 "Morpheus Security Groups for Cloud: #{cloud['name']}"
    print cyan
    print_description_list({"Firewall Enabled" => lambda {|it| format_boolean it['firewallEnabled'] } }, json_response)
    if securityGroups.empty?
      print yellow,"\n","No security groups currently applied.",reset,"\n"
    else
      print "\n"
      securityGroups.each do |securityGroup|
        print cyan, "=  #{securityGroup['id']} (#{securityGroup['name']}) - (#{securityGroup['description']})\n"
      end
    end
    print reset,"\n"

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

#sync(args) ⇒ Object

not exposed yet, refresh should be all that’s needed.



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 544

def sync(args)
  options = {}
  query_params = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'true'
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Sync a cloud." + "\n" +
                  "[cloud] is required. This is the name or id of a cloud."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!(passed_options) unless passed_options.empty?
    else
      payload = {}
      payload.deep_merge!(passed_options) unless passed_options.empty?
    end
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.sync(cloud['id'], query_params, payload)
      return
    end
    json_response = @clouds_interface.sync(cloud['id'], query_params, payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      print_green_success "Syncing cloud #{cloud['name']}..."
      #get([cloud['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#type(args) ⇒ Object



794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
# File 'lib/morpheus/cli/commands/clouds.rb', line 794

def type(args)
  options={}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[type]")
    build_standard_get_options(opts, options)
          opts.footer = "Get details about a cloud type.\n[type] is required. This is the name or id of cloud type.\n"
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  # construct request
  params.merge!(parse_query_options(options))
  id = args[0]
  cloud_type = nil
  if id.to_s !~ /\A\d{1,}\Z/
    cloud_type = cloud_type_for_name_or_id(id)
    if cloud_type.nil?
      raise_command_error "cloud type not found for name or code '#{id}'"
    end
    id = cloud_type['id']
  end
  # execute request
  @clouds_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @clouds_interface.dry.cloud_type(id.to_i)
    return 0
  end
  json_response = @clouds_interface.cloud_type(id.to_i)
  # render response
  render_response(json_response, options, 'zoneType') do
    cloud_type = json_response['zoneType']
    print_h1 "Cloud Type", [], options
    print cyan
    #columns = rest_type_column_definitions(options)
    columns = {
      "ID" => 'id',
      "Name" => 'name',
      "Code" => 'code',
      "Enabled" => lambda {|it| format_boolean it['enabled'] },
      "Provision" => lambda {|it| format_boolean it['provision'] },
      "Auto Capacity" => lambda {|it| format_boolean it['autoCapacity'] },
      # "Migration Target" => lambda {|it| format_boolean it['migrationTarget'] },
      "Datastores" => lambda {|it| format_boolean it['hasDatastores'] },
      "Networks" => lambda {|it| format_boolean it['hasNetworks'] },
      "Resource Pools" => lambda {|it| format_boolean it['hasResourcePools'] },
      "Security Groups" => lambda {|it| format_boolean it['hasSecurityGroups'] },
      "Containers" => lambda {|it| format_boolean it['hasContainers'] },
      "Bare Metal" => lambda {|it| format_boolean it['hasBareMetal'] },
      "Services" => lambda {|it| format_boolean it['hasServices'] },
      "Functions" => lambda {|it| format_boolean it['hasFunctions'] },
      "Jobs" => lambda {|it| format_boolean it['hasJobs'] },
      "Discovery" => lambda {|it| format_boolean it['hasDiscovery'] },
      "Cloud Init" => lambda {|it| format_boolean it['hasCloudInit'] },
      "Folders" => lambda {|it| format_boolean it['hasFolders'] },
      # "Marketplace" => lambda {|it| format_boolean it['hasMarketplace'] },
      "Public Cloud" => lambda {|it| format_boolean(it['cloud'] == 'public') },
    }
    print_description_list(columns, cloud_type, options)
    # Option Types
    option_types = cloud_type['optionTypes']
    if option_types && option_types.size > 0
      print_h2 "Option Types", options
      print format_option_types_table(option_types, options, "zone")
    end
    print reset,"\n"
  end
end

#types(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 747

def types(args)
  options={}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search]")
    build_standard_list_options(opts, options)
    opts.footer = "List cloud types.\n"
  end
  optparse.parse!(args)
  connect(options)

  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  @clouds_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @clouds_interface.dry.cloud_types({})
    return 0
  end
  json_response = @clouds_interface.cloud_types(params)
    
  render_response(json_response, options, 'zoneTypes') do
    cloud_types = json_response['zoneTypes']
    subtitles = []        
    subtitles += parse_list_subtitles(options)
    print_h1 "Morpheus Cloud Types", subtitles, options
    if cloud_types.empty?
      print cyan,"No cloud types found.",reset,"\n"
    else
      print cyan
      cloud_types = cloud_types.select {|it| it['enabled'] }
      rows = cloud_types.collect do |cloud_type|
        {id: cloud_type['id'], name: cloud_type['name'], code: cloud_type['code']}
      end
      #print "\n"
      columns = [:id, :name, :code]
      columns = options[:include_fields] if options[:include_fields]
      print as_pretty_table(rows, columns, options)
      print_results_pagination(json_response)
      print reset,"\n"
    end
  end
end

#update(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 342

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    # opts.on( '-g', '--group GROUP', "Group Name" ) do |val|
    #   params[:group] = val
    # end
    # opts.on( '-t', '--type TYPE', "Cloud Type" ) do |val|
    #   params[:zone_type] = val
    # end
    # opts.on( '-d', '--description DESCRIPTION', "Description (optional)" ) do |desc|
    #   params[:description] = desc
    # end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    opts.on('--costing-mode VALUE', String, "Costing Mode can be off, costing, or full. Default is off." ) do |val|
      options[:options]['costingMode'] = val
    end
    opts.on('--credential VALUE', String, "Credential ID or \"local\"" ) do |val|
      options[:options]['credential'] = val
    end
    opts.on('--default-cloud-logos', "Reset logos to default cloud logos, removing any custom logo and dark logo" ) do
      options[:options]['defaultCloudLogos'] = true
    end
    
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload['zone'] ||= {}
        payload['zone'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end
    else
      cloud_type = cloud_type_for_id(cloud['zoneTypeId'])
      cloud_payload = {}
      all_option_types = update_cloud_option_types(cloud_type)
      #params = Morpheus::Cli::OptionTypes.no_prompt(all_option_types, options[:options], @api_client, {zoneId: cloud['id'], zoneTypeId: cloud_type['id']})
      params = options[:options] || {}

      # Credentials (ideally only if value passed in and name can be parsed)
      if options[:options]['credential']
        credential_code = "credential"
        credential_option_type = {'code' => credential_code, 'fieldName' => credential_code, 'fieldLabel' => 'Credentials', 'type' => 'select', 'optionSource' => 'credentials', 'description' => 'Enter an existing credential ID or choose "local"', 'defaultValue' => "local", 'required' => true}
        # supported_credential_types = ['username-keypair', 'username-password', 'username-password-keypair'].compact.flatten.join(",").split(",").collect {|it| it.strip }
        credential_params = {"new" => false, "zoneId" => cloud['id']}
        credential_value = Morpheus::Cli::OptionTypes.select_prompt(credential_option_type, @api_client, credential_params, true, options[:options][credential_code])
        if !credential_value.to_s.empty?
          if credential_value == "local"
            params[credential_code] = {"type" => credential_value}
          elsif credential_value.to_s =~ /\A\d{1,}\Z/
            params[credential_code] = {"id" => credential_value.to_i}
          end
        end
      end
      if params.empty?
        raise_command_error "Specify at least one option to update.\n#{optparse}"
      end
      # some optionTypes have fieldContext='zone', so move those to the root level of the zone payload
      if params['zone'].is_a?(Hash)
        cloud_payload.merge!(params.delete('zone'))
      end
      if params.key?('labels')
        params['labels'] = parse_labels(params['labels'])
      end
      cloud_payload.merge!(params)
      payload = {zone: cloud_payload}
    end
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.update(cloud['id'], payload)
      return
    end
    json_response = @clouds_interface.update(cloud['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    else
      get([cloud['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_affinity_group(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 1336

def update_affinity_group(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[cloud] [affinity group] [options]")
    opts.on('--active [on|off]', String, "Enable affinity group") do |val|
      options[:active] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    add_perms_options(opts, options, ['groupDefaults'])
    build_standard_update_options(opts, options)
    opts.footer = "Update a cloud affinity group.\n" +
        "[cloud] is required. This is the name or id of an existing cloud.\n" +
        "[affinity group] is required. This is the name or id of an existing affinity group."
  end

  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?
    affinity_group = find_cloud_affinity_group_by_name_or_id(cloud['id'], args[1])
    if affinity_group.nil?
      print_red_alert "Affinity Group not found by '#{args[1]}'"
      exit 1
    end
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of everything
      if options[:options]
        payload.deep_merge!({'affinityGroup' => options[:options].reject {|k,v| k.is_a?(Symbol) }})
      end
    else
      payload = {'affinityGroup' => {}}
      payload['affinityGroup']['active'] = options[:active].nil? ? (Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'active', 'fieldLabel' => 'Active', 'type' => 'checkbox', 'description' => 'Active', 'defaultValue' => true}], options[:options], @api_client))['active'] == 'on' : options[:active]

      perms = prompt_permissions(options.merge({:available_plans => namespace_service_plans}), affinity_group['owner']['id'] == current_user['accountId'] ? ['plans', 'groupDefaults'] : ['plans', 'groupDefaults', 'visibility', 'tenants'])
      perms_payload = {}
      perms_payload['resourcePermissions'] = perms['resourcePermissions'] if !perms['resourcePermissions'].nil?
      perms_payload['tenantPermissions'] = perms['tenantPermissions'] if !perms['tenantPermissions'].nil?

      payload['affinityGroup']['permissions'] = perms_payload
      payload['affinityGroup']['visibility'] = perms['resourcePool']['visibility'] if !perms['resourcePool'].nil? && !perms['resourcePool']['visibility'].nil?

      # support -O OPTION switch on top of everything
      if options[:options]
        payload.deep_merge!({'affinityGroup' => options[:options].reject {|k,v| k.is_a?(Symbol) }})
      end

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

    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.update_affinity_group(cloud['id'], affinity_group['id'], payload)
      return
    end
    json_response = @clouds_interface.update_affinity_group(cloud['id'], affinity_group['id'], payload)
    if options[:json]
      puts as_json(json_response)
    elsif !options[:quiet]
      affinity_group = json_response['affinityGroup']
      print_green_success "Updated affinity group #{affinity_group['name']}"
      #get_args = [cloud["id"], affinity_group["id"]] + (options[:remote] ? ["-r",options[:remote]] : [])
      #get_namespace(get_args)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_dark_logo(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 1103

def (args)
  options = {}
  params = {}
  filename = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [file]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Update the logo for a cloud.\n[name] is required. This is the name or id of a cloud.\n[file] is required. This is the path of the dark logo file\n"
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  layout_id = args[0]
  filename = args[1]
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?
    dark_logo_file = nil
    if filename == 'null'
      dark_logo_file = 'null' # clear it
    else
      filename = File.expand_path(filename)
      if !File.exist?(filename)
        print_red_alert "File not found: #{filename}"
        exit 1
      end
      dark_logo_file = File.new(filename, 'rb')
    end
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.(cloud['id'], nil, dark_logo_file)
      return
    end
    json_response = @clouds_interface.(cloud['id'], nil, dark_logo_file)
    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return 0
    end
    print_green_success "Updated cloud #{cloud['name']} dark logo"
    _get(cloud['id'], params, options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#update_logo(args) ⇒ Object



1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
# File 'lib/morpheus/cli/commands/clouds.rb', line 1053

def (args)
  options = {}
  params = {}
  filename = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [file]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Update the logo for a cloud.\n[name] is required. This is the name or id of a cloud.\n[file] is required. This is the path of the logo file\n"
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:2)
  connect(options)
  layout_id = args[0]
  filename = args[1]
  begin
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?
    logo_file = nil
    if filename == 'null'
      logo_file = 'null' # clear it
    else
      filename = File.expand_path(filename)
      if !File.exist?(filename)
        print_red_alert "File not found: #{filename}"
        exit 1
      end
      logo_file = File.new(filename, 'rb')
    end
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.(cloud['id'], logo_file)
      return
    end
    json_response = @clouds_interface.(cloud['id'], logo_file)
    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return 0
    end
    print_green_success "Updated cloud #{cloud['name']} logo"
    _get(cloud['id'], params, options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#update_wiki(args) ⇒ Object



975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
# File 'lib/morpheus/cli/commands/clouds.rb', line 975

def update_wiki(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud] [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.exist?(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
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.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
    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.update_wiki(cloud["id"], payload)
      return
    end
    json_response = @clouds_interface.update_wiki(cloud["id"], payload)

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

#view_wiki(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/clouds.rb', line 944

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 cloud wiki page in a web browser" + "\n" +
                  "[cloud] is required. This is the name or id of a cloud."
  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
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?

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

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

#wiki(args) ⇒ Object



866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
# File 'lib/morpheus/cli/commands/clouds.rb', line 866

def wiki(args)
  options = {}
  params = {}
  open_wiki_link = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[cloud]")
    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 cloud." + "\n" +
                  "[cloud] is required. This is the name or id of a cloud."
  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
    cloud = find_cloud_by_name_or_id(args[0])
    return 1 if cloud.nil?


    @clouds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @clouds_interface.dry.wiki(cloud["id"], params)
      return
    end
    json_response = @clouds_interface.wiki(cloud["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 "Cloud Wiki Page: #{cloud['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