Class: Morpheus::Cli::SubnetsCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

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

#initializeSubnetsCommand

set_default_subcommand :list



16
17
18
# File 'lib/morpheus/cli/commands/subnets_command.rb', line 16

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

Instance Method Details

#add(args) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
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
# File 'lib/morpheus/cli/commands/subnets_command.rb', line 229

def add(args)
  options = {}
  network_id = nil
  subnet_type_id = nil
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] --network NETWORK")
    opts.on('--network NETWORK', String, "Network name or ID that this subnet will be a part of.") do |val|
      network_id = val
    end
    opts.on('-t', '--type ID', "Subnet Type Name or ID") do |val|
      subnet_type_id = val
    end
    opts.on('--name VALUE', String, "Name for this subnet") do |val|
      options[:options]['name'] = val
      # fill in silly names that vary by type
      options[:options].deep_merge!({'config' => {'subnetName' => val}})
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    opts.on('--cidr VALUE', String, "Name for this subnet") do |val|
      options[:options]['cidr'] = val
      # fill in silly names that vary by type
      options[:options].deep_merge!({'config' => {'subnetCidr' => 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('--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('--accounts LIST', Array, "alias for --tenants") 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 subnet") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--pool ID', String, "Network Pool") do |val|
      options['pool'] = val.to_i
    end
    opts.on('--dhcp-server [on|off]', String, "DHCP Server") do |val|
      options['dhcpServer'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--can-assign-pool [on|off]', String, "DHCP Server") do |val|
      options['canAssignPool'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a new subnet." + "\n" +
                  "--network is required. This is the name or id of a network." #+ "\n" +
                  #"[name] is required and can be passed as --name instead."
  end
  optparse.parse!(args)
  # if args.count < 1 || args.count > 2
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  if args[0]
    options[:options]['name'] = args[1]
    options[:options].deep_merge!({'config' => {'subnetName' => args[0]}})
  end
  connect(options)
  begin
    passed_options = (options[:options] || {}).reject {|k,v| k.is_a?(Symbol) }
    payload = nil

    # Network
    prompt_results = prompt_for_network(network_id, options)
    if prompt_results[:success]
      network = prompt_results[:network]
    else
      return 1, "Network prompt failed."
    end

    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'subnet' => passed_options}) unless passed_options.empty?
      
    else
      payload = {'subnet' => {}}
      payload.deep_merge!({'subnet' => passed_options}) unless passed_options.empty?

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

      # Subnet Type
      if !subnet_type_id
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Subnet Type', 'type' => 'select', 'optionSource' => 'subnetTypes', 'required' => true, 'description' => 'Choose a subnet type.'}], options[:options], @api_client, {networkId: network['id']})
        subnet_type_id = v_prompt['type']
      end
      subnet_type = find_subnet_type_by_name_or_id(subnet_type_id)
      return 1 if subnet_type.nil?
      if subnet_type['creatable'] == false
        raise_command_error "Subnet Type cannot be created: #{subnet_type['name']}"
      end
      payload['subnet']['type'] = {'id' => subnet_type['id'] }
      #payload['subnet']['type'] = {'code' => subnet_type['code'] }

      subnet_type_option_types = subnet_type['optionTypes']
      if subnet_type_option_types && subnet_type_option_types.size > 0
        # prompt for option types
        subnet_type_params = Morpheus::Cli::OptionTypes.prompt(subnet_type_option_types,options[:options],@api_client, {networkId: network['id'], zoneId: network['zone']['id']})
        if subnet_type_params['subnet']
          payload['subnet'].deep_merge!(subnet_type_params['subnet'])
        end
        if subnet_type_params['config']
          payload['subnet']['config'] ||= {}
          payload['subnet']['config'].deep_merge!(subnet_type_params['config'])
        end
      else
        # DEFAULT INPUTS

        # CIDR
        # if options['cidr']
        #   payload['subnet']['cidr'] = options['cidr']
        # else
        #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cidr', 'fieldLabel' => 'CIDR', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        #   payload['subnet']['cidr'] = v_prompt['cidr']
        # end

      end

      # CIDR
      if options['cidr']
        payload['subnet']['cidr'] = options['cidr']
      elsif !subnet_type['code'].include? 'azure'
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cidr', 'fieldLabel' => 'CIDR', 'type' => 'text', 'required' => true, 'description' => ''}], options)
        payload['subnet']['cidr'] = v_prompt['cidr']
      end

      # DHCP
      if options['dhcpServer']
        payload['subnet']['dhcpServer'] = options['dhcpServer']
      elsif subnet_type['dhcpServerEditable'] && payload['subnet']['dhcpServer'].nil? && !options[:no_prompt]
        payload['subnet']['dhcpServer'] = Morpheus::Cli::OptionTypes.confirm("DHCP Server?", {:default=>false})
      end

      # Allow IP Override
      if options['allowStaticOverride']
        payload['subnet']['allowStaticOverride']
      elsif !options[:no_prompt]
        payload['subnet']['allowStaticOverride'] = Morpheus::Cli::OptionTypes.confirm("Allow IP Override?", {:default=>false})
      end

      # IP Pool
      if options['pool']
        payload['subnet']['pool'] = {'id' => options['pool']}
      elsif subnet_type['canAssignPool'] && !options[:no_prompt]
        network_pool_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => "pool", 'type' => 'select', 'fieldLabel' => "Network Pool", 'selectOptions' => list_network_pool_options(), 'required' => false, 'description' => 'Select Network Pool'}], options[:options], @api_client, {zoneId: network['zone']['id']}, options[:no_prompt])["pool"]
        payload['subnet']['pool'] = {'id' => network_pool_id} if network_pool_id
      end

      # Group Access
      # Group Access (default is All)
      if group_access_all.nil?
        if payload['resourcePermissions'].nil?
          payload['resourcePermissions'] ||= {}
          payload['resourcePermissions']['all'] = true
        end
      else
        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

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

      # Active
      if options['active'] != nil
        payload['subnet']['active'] = options['active']
      end
      
      # Visibility
      if options['visibility'] != nil
        payload['subnet']['visibility'] = options['visibility']
      end

    end

    @subnets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @subnets_interface.dry.create(network['id'], payload)
      return
    end

    json_response = @subnets_interface.create(network['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      subnet = json_response['subnet']
      print_green_success "Added subnet #{subnet['name']}"
      get_args = [subnet['id']] + (options[:remote] ? ["-r",options[:remote]] : [])
      get(get_args)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#connect(opts) ⇒ Object



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

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @networks_interface = @api_client.networks
  @network_pools_interface = @api_client.network_pools
  @network_types_interface = @api_client.network_types
  @subnets_interface = @api_client.subnets
  @subnet_types_interface = @api_client.subnet_types
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[subnet]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a subnet." + "\n" +
                  "[subnet] is required. This is the name or id of a subnet."
  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)
  exit_code, err = 0, nil
  begin
    subnet_id = nil
    if args[0].to_s =~ /\A\d{1,}\Z/
      subnet_id = args[0].to_i
    else
      subnet = find_subnet_by_name(args[0])
      return 1, "Security Group not found" if subnet.nil?
      subnet_id = subnet['id']
    end
    @subnets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @subnets_interface.dry.get(subnet_id)
      return exit_code, err
    end
    json_response = @subnets_interface.get(subnet_id)
    render_result = render_with_format(json_response, options, 'subnet')
    return exit_code, err if render_result

    subnet = json_response['subnet']
    if options[:json]
      puts as_json(json_response, options, "subnet")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "subnet")
      return 0
    elsif options[:csv]
      puts records_as_csv([subnet], options)
      return 0
    end
    print_h1 "Subnet Details", [], options
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Labels" => lambda {|it| format_list(it['labels']) },
      "Description" => 'description',
      "Type" => lambda {|it| it['type'] ? it['type']['name'] : '' },
      "Network" => lambda {|it| subnet['network']['name'] rescue subnet['network'] },
      "Cloud" => lambda {|it| subnet['zone']['name'] rescue subnet['zone'] },
      "CIDR" => 'cidr',
      "Gateway" => 'gateway',
      "Netmask" => 'netmask',
      "Subnet" => 'subnetAddress',
      "Primary DNS" => 'dnsPrimary',
      "Secondary DNS" => 'dnsSecondary',
      "Pool" => lambda {|it| it['pool'] ? it['pool']['name'] : '' },
      "DHCP" => lambda {|it| format_boolean it['dhcpServer'] },
      "Allow IP Override" => lambda {|it| it['allowStaticOverride'] ? 'Yes' : 'No' },
      "Active" => lambda {|it| format_boolean(it['active']) },
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' },
    }
    print_description_list(description_cols, subnet)

    if subnet['resourcePermission'].nil?
      print "\n", "No group access found", "\n"
    else
      print_h2 "Group Access"
      rows = []
      if subnet['resourcePermission']['all']
        rows.push({"name" => 'All'})
      end
      if subnet['resourcePermission']['sites']
        subnet['resourcePermission']['sites'].each do |site|
          rows.push(site)
        end
      end
      rows = rows.collect do |site|
        {group: site['name'], default: site['default'] ? 'Yes' : ''}
      end
      columns = [:group, :default]
      print cyan
      print as_pretty_table(rows, columns)
    end

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

#get_subnet_type(args) ⇒ Object



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

def get_subnet_type(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[type]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a subnet type.\n" +
                  "[type] is required. This is the id or name of a subnet type."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    @subnet_types_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @subnet_types_interface.dry.get(args[0].to_i)
      else
        print_dry_run @subnet_types_interface.dry.list({name:args[0]})
      end
      return
    end

    subnet_type = find_subnet_type_by_name_or_id(args[0])
    return 1 if subnet_type.nil?
    json_response = {'subnetType' => subnet_type}  # skip redundant request
    # json_response = @networks_interface.get(subnet_type['id'])
    
    render_result = render_with_format(json_response, options, 'subnetType')
    return 0 if render_result

    subnet_type = json_response['subnetType']

    title = "Morpheus Subnet Type"
    
    print_h1 "Morpheus Subnet Type", [], options
    
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Code" => 'name',
      "Description" => 'description',
      "Createable" => lambda {|it| format_boolean(it['creatable']) },
      "Deletable" => lambda {|it| format_boolean(it['deleteable']) },
    }
    print_description_list(description_cols, subnet_type)



    option_types = subnet_type['optionTypes'] || []
    option_types = option_types.sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }
    if !option_types.empty?
      print_h2 "Config Option Types", [], options
      option_type_cols = {
        "Name" => lambda {|it| it['fieldContext'].to_s != '' ? "#{it['fieldContext']}.#{it['fieldName']}" : it['fieldName'] },
        "Label" => lambda {|it| it['fieldLabel'] },
        "Type" => lambda {|it| it['type'] },
      }
      print cyan
      print as_pretty_table(option_types, option_type_cols)
    end
    
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#handle(args) ⇒ Object



31
32
33
# File 'lib/morpheus/cli/commands/subnets_command.rb', line 31

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
122
123
124
125
126
127
128
129
130
# File 'lib/morpheus/cli/commands/subnets_command.rb', line 35

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.on( '-c', '--cloud CLOUD', "Filter by Cloud" ) do |val|
      options[:cloud] = val
    end
    opts.on( '--network NETWORK', '--network NETWORK', "Filter by Network" ) do |val|
      options[:network] = 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
    opts.footer = "List subnets."
  end
  optparse.parse!(args)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  connect(options)
  
  params.merge!(parse_list_options(options))
  network = nil
  if options[:network]
    network = find_network_by_name_or_id(options[:network])
    if network
      params['networkId'] = network['id']
    else
      return 1, "Network not found"
    end
  end
  cloud = nil
  if options[:cloud]
    cloud = find_cloud_by_name_or_id(options[:cloud])
    if cloud
      params['zoneId'] = cloud['id']
    else
      return 1, "Cloud not found"
    end
  end
  

  exit_code, err = 0, nil

  @subnets_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @subnets_interface.dry.list(params)
    return exit_code, err
  end
  json_response = @subnets_interface.list(params)
  subnets = json_response["subnets"]

  render_result = render_with_format(json_response, options, 'subnets')
  return exit_code, err if render_result

  title = "Morpheus Subnets"
  subtitles = []
  if network
    subtitles << "Network: #{network['name']}"
  end
  if cloud
    subtitles << "Cloud: #{cloud['name']}"
  end
  subtitles += parse_list_subtitles(options)
  print_h1 title, subtitles
  
  if subnets.empty?
    print cyan,"No subnets found.",reset,"\n"
  else
    subnet_columns = {
      "ID" => 'id',
      "Name" => 'name',
      "Labels" => lambda {|it| format_list(it['labels'], '', 3) },
      #"Description" => 'description',
      "Network" => lambda {|it| it['network']['name'] rescue it['network'] },
      "Type" => lambda {|it| it['type']['name'] rescue it['type'] },
      "Cloud" => lambda {|it| it['zone']['name'] rescue it['zone'] },
      "CIDR" => lambda {|it| it['cidr'] },
      "DHCP" => lambda {|it| format_boolean(it['dhcpServer']) },
      "Active" => lambda {|it| format_boolean(it['active']) },
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' },
    }
    print cyan
    print as_pretty_table(subnets, subnet_columns)
    print_results_pagination(json_response, {:label => "subnet", :n_label => "subnets"})
  end
  print reset,"\n"
  return exit_code, err  
  
end

#list_subnet_types(args) ⇒ Object



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'lib/morpheus/cli/commands/subnets_command.rb', line 746

def list_subnet_types(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List subnet types."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
    if options[:cloud]
      #return network_types_for_cloud(options[:cloud], options)
      zone = find_zone_by_name_or_id(nil, options[:cloud])
      #params["zoneTypeId"] = zone['zoneTypeId']
      params["zoneId"] = zone['id']
      params["creatable"] = true
    end
    @subnet_types_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @subnet_types_interface.dry.list(params)
      return
    end
    json_response = @subnet_types_interface.list(params)
    
    render_result = render_with_format(json_response, options, 'subnetTypes')
    return 0 if render_result

    subnet_types = json_response['subnetTypes']

    title = "Morpheus Subnet Types"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    if options[:cloud]
      subtitles << "Cloud: #{options[:cloud]}"
    end
    print_h1 title, subtitles
    if subnet_types.empty?
      print cyan,"No subnet types found.",reset,"\n"
    else
      rows = subnet_types.collect do |subnet_type|
        {
          id: subnet_type['id'],
          code: subnet_type['code'],
          name: subnet_type['name']
        }
      end
      columns = [:id, :name, :code]
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      print_results_pagination(json_response)
    end
    print reset,"\n"
    return 0

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

#remove(args) ⇒ Object



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

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[subnet]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a subnet." + "\n" +
                  "[subnet] is required. This is the name or id of a subnet."
  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
    subnet = find_subnet_by_name_or_id(args[0])
    return 1 if subnet.nil?

    subnet_type = find_subnet_type_by_name_or_id(subnet['type']['id'])
    return 1 if subnet_type.nil?
    if subnet_type['deletable'] == false
      raise_command_error "Subnet Type cannot be deleted: #{subnet_type['name']}"
    end

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

#update(args) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# File 'lib/morpheus/cli/commands/subnets_command.rb', line 472

def update(args)
  options = {}
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[subnet]")
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(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('--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('--accounts LIST', Array, "alias for --tenants") 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 subnet") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--pool ID', String, "Network Pool") do |val|
      options['pool'] = val.to_i
    end
    opts.on('--dhcp-server [on|off]', String, "DHCP Server") do |val|
      options['dhcpServer'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--can-assign-pool [on|off]', String, "DHCP Server") do |val|
      options['canAssignPool'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a subnet." + "\n" +
                  "[subnet] is required. This is the name or id of a subnet."
  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
    # network = find_network_by_name_or_id(args[0])
    # return 1 if network.nil?

    subnet = find_subnet_by_name_or_id(args[0])
    return 1 if subnet.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 network options
      payload = {
        'subnet' => {
        }
      }
      
      # allow arbitrary -O options
      payload['subnet'].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

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

      # Active
      if options['active'] != nil
        payload['subnet']['active'] = options['active']
      end
      
      # Visibility
      if options['visibility'] != nil
        payload['subnet']['visibility'] = options['visibility']
      end

      # DHCP
      if options['dhcpServer'] != nil
        payload['subnet']['dhcpServer'] = options['dhcpServer']
      end

      # Allow IP Override
      if options['allowStaticOverride'] != nil
        payload['subnet']['allowStaticOverride']
      end

      # IP Pool
      if options['pool'] != nil
        payload['subnet']['pool'] = {'id' => options['pool']}
      end

    end

    @subnets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @subnets_interface.dry.update(subnet['id'], payload)
      return
    end
    json_response = @subnets_interface.update(subnet['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      subnet = json_response['subnet']
      print_green_success "Updated subnet #{subnet['name']}"
      get_args = [subnet['id']] + (options[:remote] ? ["-r",options[:remote]] : [])
      get(get_args)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end