Class: Morpheus::Cli::NetworksCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, InfrastructureHelper, ProvisioningHelper, WhoamiHelper
Defined in:
lib/morpheus/cli/commands/networks_command.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, #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_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #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_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_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 WhoamiHelper

#current_account, #current_user, #current_user_permissions, included, #is_master_account, #load_whoami

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

#initializeNetworksCommand

register_subcommands :list_subnets, # :get_subnet, :add_subnet, :update_subnet, :remove_subnet



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

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

Instance Method Details

#add(args) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# File 'lib/morpheus/cli/commands/networks_command.rb', line 298

def add(args)
  options = {}
  network_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("-t TYPE")
    opts.on( '-g', '--group GROUP', "Group Name or ID. Default is Shared." ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    opts.on('-t', '--type ID', "Network Type Name or ID") do |val|
      options['type'] = val
    end
    opts.on('-s', '--server ID', "Network Server Name or ID") do |val|
      options['server'] = val
    end
    opts.on('--name VALUE', String, "Name for this network") do |val|
      options['name'] = val
    end
    opts.on('--display-name VALUE', String, "Display name for this network") do |val|
      options['displayName'] = val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options['labels'] = parse_labels(val)
    end
    opts.on('--description VALUE', String, "Description of network") do |val|
      options['description'] = val
    end
    opts.on('--ipv4Enabled [on|off]', String, "ipv4Enabled") do |val|
      options['ipv4Enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--ipv6Enabled [on|off]', String, "ipv6Enabled") do |val|
      options['ipv6Enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--gateway VALUE', String, "Gateway") do |val|
      options['gateway'] = val
    end
    opts.on('--dns-primary VALUE', String, "DNS Primary") do |val|
      options['dnsPrimary'] = val
    end
    opts.on('--dns-secondary VALUE', String, "DNS Secondary") do |val|
      options['dnsSecondary'] = val
    end
    opts.on('--cidr VALUE', String, "CIDR") do |val|
      options['cidr'] = val
    end
    opts.on('--gateway-ipv6 VALUE', String, "IPv6 Gateway") do |val|
      options['gatewayIPv6'] = val
    end
    opts.on('--gatewayIPv6 VALUE', String, "IPv6 Gateway") do |val|
      options['gatewayIPv6'] = val
    end
    opts.add_hidden_option('--gatewayIPv6')
    opts.on('--dns-primary-ipv6 VALUE', String, "IPv6 DNS Primary") do |val|
      options['dnsPrimaryIPv6'] = val
    end
    opts.on('--dns-primaryIPv6 VALUE', String, "IPv6 DNS Primary") do |val|
      options['dnsPrimaryIPv6'] = val
    end
    opts.add_hidden_option('--dns-primaryIPv6')
    opts.on('--dns-secondary-ipv6 VALUE', String, "IPv6 DNS Secondary") do |val|
      options['dnsSecondaryIPv6'] = val
    end
    opts.on('--dns-secondaryIPv6 VALUE', String, "IPv6 DNS Secondary") do |val|
      options['dnsSecondaryIPv6'] = val
    end
    opts.add_hidden_option('--dns-secondaryIPv6')
    opts.on('--cidr-ipv6 VALUE', String, "IPv6 CIDR") do |val|
      options['cidrIPv6'] = val
    end
    opts.on('--cidrIPv6 VALUE', String, "IPv6 CIDR") do |val|
      options['cidrIPv6'] = val
    end
    opts.add_hidden_option('--cidrIPv6')
    opts.on('--vlan-id VALUE', String, "VLAN ID") do |val|
      options['vlanId'] = val.to_i
    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('--dhcp-serverIPv6 [on|off]', String, "IPv6 DHCP Server") do |val|
      options['dhcpServerIPv6'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--dhcp-server-ipv6 [on|off]', String, "IPv6 DHCP Server") do |val|
      options['dhcpServerIPv6'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--allow-ip-override [on|off]', String, "Allow IP Override") do |val|
      options['allowStaticOverride'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--domain [VALUE]', String, "Network Domain ID") do |val|
      options['domain'] = val
    end
    opts.on('--search-domains [VALUE]', String, "Search Domains") do |val|
      options['searchDomains'] = val
    end
    # opts.on('--scan [on|off]', String, "Scan Network") do |val|
    #   options['scanNetwork'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    # end
    opts.on('--proxy VALUE', String, "Network Proxy ID") do |val|
      options['proxy'] = val
    end
    opts.on('--proxy-bypass [on|off]', String, "Bypass Proxy for Appliance URL") do |val|
      options['applianceUrlProxyBypass'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--no-proxy LIST', String, "No Proxy Addresses") do |val|
      options['noProxy'] = 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 network") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true'
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
    opts.footer = "Create a new network." + "\n" +
                  "[name] is required and can be passed as --name instead."
  end
  optparse.parse!(args)
  if args.count > 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    # merge -O options into normally parsed options
    options.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    # support [name] as first argument
    if args[0]
      options['name'] = args[0]
    end

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]

      # backward compat
      if payload['resourcePermissions']
        payload['network'] ||= {}
        payload['network']['resourcePermission'] = payload['resourcePermissions']
        payload.delete('resourcePermissions')
      end
      if payload['network'] && payload['network']['resourcePermissions']
        payload['network']['resourcePermission'] = payload['network']['resourcePermissions']
        payload['network'].delete('resourcePermissions')
      end
    else
      # prompt for network options
      payload = {
        'network' => {
          # 'config' => {}
        }
      }
      
      # allow arbitrary -O options
      payload['network'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

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

      # Display Name
      if options['displayName']
        payload['network']['displayName'] = options['displayName']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'displayName', 'fieldLabel' => 'Display Name', 'type' => 'text', 'required' => false, 'description' => 'Display name for this network.'}], options)
        payload['network']['displayName'] = v_prompt['displayName']
      end

      # Labels
      if options['labels']
        payload['network']['labels'] = options['labels']
      end

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

      # Group
      # ok, networks list needs to know if they have full or groups permission
      group = nil
      groups_dropdown = nil
      group_is_required = true
      network_perm = (current_user_permissions || []).find {|perm| perm['code'] == 'infrastructure-networks'}
      if network_perm && ['full','read'].include?(network_perm['access'])
        group_is_required = false
        groups_dropdown = get_available_groups_with_shared
      else
        # they have group access, shared cannot be selected.
        groups_dropdown = get_available_groups
      end
      if options[:group]
        group_id = options[:group]
        group = groups_dropdown.find {|it| it["value"].to_s == group_id.to_s || it["name"].to_s == group_id}
        if group.nil?
          print_red_alert "Group not found by id #{group_id}"
          return 1
        end
        if group_id.to_s == 'shared'
          group_id = nil
          group = nil
        end
      else
        group_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'type' => 'select', 'fieldLabel' => 'Group', 'selectOptions' => groups_dropdown, 'required' => group_is_required, 'description' => 'Select Group.'}],options,@api_client,{})
        group_id = group_prompt['group']
        if group_id.to_s == '' || group_id.to_s == 'shared'
          group_id = nil
          group = nil
        else
          group = groups_dropdown.find {|it| it["value"].to_s == group_id.to_s || it["name"].to_s == group_id}
          if group.nil?
            print_red_alert "Group not found by id #{group_id}"
            return 1
          end
        end
      end
      if group
        payload['network']['site'] = {'id' => group['id']}
      else
        # shared
      end

      # Network Type
      network_type_id = nil
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Network Type', 'type' => 'select', 'optionSource' => 'creatableNetworkTypes', 'required' => true, 'description' => 'Choose a network type.'}], options, @api_client, {accountId: ()['id']})
      network_type_id = v_prompt['type']
      if network_type_id.nil? || network_type_id.to_s.empty?
        print_red_alert "Network Type not found by id '#{options['type']}'"
        return 1
      end
      payload['network']['type'] = {'id' => network_type_id.to_i }

      network_type = nil
      json_response = @network_types_interface.get(network_type_id)
      if json_response["networkType"]
        network_type = json_response["networkType"]
      else
        print_red_alert "Network Type not found by id '#{network_type_id}'"
        return 1
      end
      
      if network_type['hasNetworkServer']
        api_params = {networkType: {id: network_type['id']}}

        # Network Server
        if options['server']
          network_server = @options_interface.options_for_source('networkServer', api_params)['data'].find {|it|
            it['name'] == options['server'] || it['value'].to_s == options['server']
          }

          if network_server.nil?
            print_red_alert "Network Server not found by name or id '#{options['server']}' for network type '#{options['server']}'"
            return 1
          end
          network_server_id = network_server['value']
          payload['network']['networkServer'] = {'id' => network_server_id}
        else
          network_server_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'server', 'type' => 'select', 'fieldLabel' => 'Network Server', 'optionSource' => 'networkServer', 'required' => true, 'description' => 'Select Network Service.'}],options,@api_client,api_params)
          network_server_id = network_server_prompt['server']
          payload['network']['networkServer'] = {'id' => network_server_id}
        end
      else
        # Cloud
        cloud = nil
        if group
          if options[:cloud]
            cloud_id = options[:cloud]
            cloud = group["clouds"].find {|it| it["id"].to_s == cloud_id.to_s || it["name"].to_s == cloud_id}
            if cloud.nil?
              print_red_alert "Cloud not found by id #{cloud_id}"
              return 1
            end
          else
            api_params = {groupId:group['id']}
            cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'optionSource' => 'cloudsForNetworks', 'required' => true, 'description' => 'Select Cloud.'}],options,@api_client,api_params)
            cloud_id = cloud_prompt['cloud']
            cloud = find_cloud_by_name_or_id(cloud_id) if cloud_id
            return 1 if cloud.nil?
          end
        else
          if options[:cloud]
            cloud = find_cloud_by_name_or_id(options[:cloud])
            # meh, should validate cloud is in the cloudsForNetworks dropdown..
            return 1 if cloud.nil?
          else
            api_params = {}
            cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'optionSource' => 'cloudsForNetworks', 'required' => true, 'description' => 'Select Cloud.'}],options,@api_client,api_params)
            cloud_id = cloud_prompt['cloud']
            cloud = find_cloud_by_name_or_id(cloud_id) if cloud_id
            return 1 if cloud.nil?
          end
        end
        payload['network']['zone'] = {'id' => cloud['id']}
      end

      if options['ipv4Enabled'].nil? && payload['network']['ipv4Enabled'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'ipv4Enabled', 'fieldLabel' => 'IPv4 Enabled', 'type' => 'checkbox', 'required' => false, 'description' => '', 'defaultValue' => true}], options)
        val = v_prompt['ipv4Enabled']
        payload['network']['ipv4Enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
      else
        payload['network']['ipv4Enabled'] = options['ipv4Enabled']
      end

      if payload['network']['ipv4Enabled'] 
        # CIDR
        if network_type['hasCidr'] && network_type['cidrEditable']
          if options['cidr']
            payload['network']['cidr'] = options['cidr']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cidr', 'fieldLabel' => network_type['code'] == 'nsxtLogicalSwitch' ? 'Gateway CIDR' : 'CIDR', 'type' => 'text', 'required' => network_type['cidrRequired'], 'description' => ''}], options)
            payload['network']['cidr'] = v_prompt['cidr']
          end
        end

        # Gateway
        if network_type['gatewayEditable']
          if options['gateway']
            payload['network']['gateway'] = options['gateway']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'gateway', 'fieldLabel' => 'Gateway', 'type' => 'text', 'required' => false, 'description' => ''}], options)
            payload['network']['gateway'] = v_prompt['gateway']
          end
        end

        # DNS
        if network_type['dnsEditable']
          if options['dnsPrimary']
            payload['network']['dnsPrimary'] = options['dnsPrimary']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsPrimary', 'fieldLabel' => 'DNS Primary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
            payload['network']['dnsPrimary'] = v_prompt['dnsPrimary']
          end

          if options['dnsSecondary']
            payload['network']['dnsSecondary'] = options['dnsSecondary']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsSecondary', 'fieldLabel' => 'DNS Secondary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
            payload['network']['dnsSecondary'] = v_prompt['dnsSecondary']
          end
        end
      end

      if options['ipv6Enabled'].nil? && payload['network']['ipv6Enabled'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'ipv6Enabled', 'fieldLabel' => 'IPv6 Enabled', 'type' => 'checkbox', 'required' => false, 'description' => '', 'defaultValue' => false}], options)
        val = v_prompt['ipv6Enabled']
        payload['network']['ipv6Enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
      else
        payload['network']['ipv6Enabled'] = options['ipv6Enabled']
      end

      if payload['network']['ipv6Enabled'] 
        #IPv6 Options
        # CIDR
        if network_type['hasCidr'] && network_type['cidrEditable']
          if options['cidrIPv6']
            payload['network']['cidrIPv6'] = options['cidr']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cidrIPv6', 'fieldLabel' => 'IPv6 CIDR', 'type' => 'text', 'required' => false, 'description' => ''}], options)
            payload['network']['cidrIPv6'] = v_prompt['cidrIPv6']
          end
        end

        # Gateway
        if network_type['gatewayEditable']
          if options['gatewayIPv6']
            payload['network']['gatewayIPv6'] = options['gatewayIPv6']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'gatewayIPv6', 'fieldLabel' => 'IPv6 Gateway', 'type' => 'text', 'required' => false, 'description' => ''}], options)
            payload['network']['gatewayIPv6'] = v_prompt['gatewayIPv6']
          end
        end

        # DNS
        if network_type['dnsEditable']
          if options['dnsPrimaryIPv6']
            payload['network']['dnsPrimaryIPv6'] = options['dnsPrimaryIPv6']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsPrimaryIPv6', 'fieldLabel' => 'IPv6 DNS Primary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
            payload['network']['dnsPrimaryIPv6'] = v_prompt['dnsPrimaryIPv6']
          end

          if options['dnsSecondary']
            payload['network']['dnsSecondaryIPv6'] = options['dnsSecondaryIPv6']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dnsSecondaryIPv6', 'fieldLabel' => 'IPv6 DNS Secondary', 'type' => 'text', 'required' => false, 'description' => ''}], options)
            payload['network']['dnsSecondaryIPv6'] = v_prompt['dnsSecondaryIPv6']
          end
        end
                  # DHCP Server
        if network_type['dhcpServerEditable'] && payload['network']['dhcpServerIPv6'].nil?
          if options['dhcpServerIPv6'] != nil
            payload['network']['dhcpServerIPv6'] = options['dhcpServerIPv6']
          else
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dhcpServerIPv6', 'fieldLabel' => 'IPv6 DHCP Server', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
            payload['network']['dhcpServerIPv6'] = v_prompt['dhcpServerIPv6']
          end
        end
      end


      # VLAN ID
      if network_type['vlanIdEditable']
        if options['vlanId']
          payload['network']['vlanId'] = options['vlanId']
        else
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'vlanId', 'fieldLabel' => 'VLAN ID', 'type' => 'number', 'required' => false, 'description' => ''}], options)
          payload['network']['vlanId'] = v_prompt['vlanId']
        end
      end

      # prompt for option types
      network_type_option_types = network_type['optionTypes']
      if network_type_option_types && network_type_option_types.size > 0
        api_params = {}
        api_params['network.site.id'] = group ? group['id'] : 'shared'
        api_params['network.zone.id'] = cloud['id'] if !cloud.nil?
        api_params['network.type.id'] = network_type['id']
        api_params['network.networkServer.id'] = network_server_id if !network_server_id.nil?
        network_type_params = Morpheus::Cli::OptionTypes.prompt(network_type_option_types,(options[:options] || {}).merge(payload),@api_client, api_params)
        # network context options belong at network level and not network.network
        network_context_params = network_type_params.delete('network')
        payload['network'].deep_merge!(network_context_params) if network_context_params
        payload['network'].deep_merge!(network_type_params)
      end

      # Active
      if options['active'].nil? && payload['network']['active'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'active', 'fieldLabel' => 'Active', 'type' => 'checkbox', 'required' => false, 'description' => '', 'defaultValue' => true}], options)
        payload['network']['active'] = v_prompt['active']
      else
        payload['network']['active'] = options['active']
      end

      # DHCP Server
      if network_type['dhcpServerEditable'] && payload['network']['dhcpServer'].nil?
        if options['dhcpServer'] != nil
          payload['network']['dhcpServer'] = options['dhcpServer']
        else
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dhcpServer', 'fieldLabel' => 'DHCP Server', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
          payload['network']['dhcpServer'] = v_prompt['dhcpServer']
        end
      end

      # Allow IP Override
      if network_type['staticOverrideEditable'] && payload['network']['allowStaticOverride'].nil?
        if options['allowStaticOverride'] != nil
          payload['network']['allowStaticOverride'] = options['allowStaticOverride']
        else
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allowStaticOverride', 'fieldLabel' => 'Allow IP Override', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
          payload['network']['allowStaticOverride'] = v_prompt['allowStaticOverride']
        end
      end

      ## IPAM Options

      # Network Pool
      if network_type['canAssignPool'] && payload['network']['pool'].nil?
        if options['pool']
          payload['network']['pool'] = options['pool'].to_i
        else
          # todo: select dropdown
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'pool', 'fieldLabel' => 'Network Pool', 'type' => 'select', 'optionSource' => 'networkPools', 'required' => false, 'description' => ''}], options, @api_client, api_params)
          payload['network']['pool'] = v_prompt['pool'].to_i if v_prompt['pool']
        end
      end
      
      ## Advanced Options

      # Network Domain
      if network_type['networkDomainEditable'] && payload['network']['networkDomain'].nil?
        if options.key?('domain')
          if options['domain'].to_s.empty?  # clear it?
            payload['network']['networkDomain'] = {'id' => nil}
          else
            # always prompt to handle value as name instead of id...
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'domain', 'fieldLabel' => 'Network Domain', 'type' => 'select', 'optionSource' => 'networkDomains', 'required' => false, 'description' => ''}], options, @api_client)
            payload['network']['networkDomain'] = {'id' => v_prompt['domain'].to_i} unless v_prompt['domain'].to_s.empty?
          end
        end
      end

      # Search Domains
      if options.key?('searchDomains')
        payload['network']['searchDomains'] = options['searchDomains']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'searchDomains', 'fieldLabel' => 'Search Domains', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        payload['network']['searchDomains'] = v_prompt['searchDomains']
      end

      # Scan Network
      if options['scanNetwork'] != nil
        payload['network']['scanNetwork'] = options['scanNetwork']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'scanNetwork', 'fieldLabel' => 'Scan Network', 'type' => 'checkbox', 'required' => false, 'description' => '', 'defaultValue' => false}], options)
        payload['network']['scanNetwork'] = v_prompt['scanNetwork']
      end

      # Proxy
      if options['networkProxy']
        payload['network']['networkProxy'] = {'id' => options['networkProxy'].to_i}
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'networkProxy', 'fieldLabel' => 'Network Proxy', 'type' => 'select', 'optionSource' => 'networkProxies', 'required' => false, 'description' => ''}], options, @api_client)
        payload['network']['networkProxy'] = {'id' => v_prompt['networkProxy'].to_i} unless v_prompt['networkProxy'].to_s.empty?
      end

      # ByPass Proxy for Appliance URL 
      if options['applianceUrlProxyBypass'] != nil
        payload['network']['applianceUrlProxyBypass'] = options['applianceUrlProxyBypass']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'applianceUrlProxyBypass', 'fieldLabel' => 'Bypass Proxy for Appliance URL', 'type' => 'checkbox', 'required' => false, 'description' => '', 'defaultValue' => true}], options)
        payload['network']['applianceUrlProxyBypass'] = v_prompt['applianceUrlProxyBypass']
      end

      # No Proxy
      if options['noProxy']
        payload['network']['noProxy'] = options['noProxy']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'noProxy', 'fieldLabel' => 'No Proxy', 'type' => 'text', 'required' => false, 'description' => 'List of ip addresses or name servers to exclude proxy traversal for. Typically locally routable servers are excluded.'}], options)
        payload['network']['noProxy'] = v_prompt['noProxy']
      end

      # Group Access
      # Group Access (default is All)
      if !options[:no_prompt] && group_access_all.nil? && group_access_list.nil? && payload['resourcePermission'].nil? && payload['network']['resourcePermission'].nil?
        perm_excludes = ['plans']
        perm_excludes << 'tenants' if options['tenants'] || payload['tenantPermissions'] || payload['network']['tenants']
        perm_excludes << 'visibility' if options['visibility'] || payload['network']['visibility']
        perms = prompt_permissions(options, perm_excludes)

        payload['network']['resourcePermission'] = perms['resourcePermissions']
        payload['network']['tenants'] = perms['tenantPermissions']['accounts'].collect {|it| {'id': it}} if perms['tenantPermissions']
        payload['network']['visibility'] = perms['resourcePool']['visibility'] if perms['resourcePool']
      else
        if !group_access_list.nil?
          payload['network']['resourcePermission'] ||= {}
          payload['network']['resourcePermission']['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
        elsif !group_access_all.nil?
          payload['network']['resourcePermission'] ||= {}
          payload['network']['resourcePermission']['all'] = group_access_all
        else
          payload['network']['resourcePermission'] ||= {}
          payload['network']['resourcePermission']['all'] = true
        end
      end

      # Tenants
      if !options[:no_prompt] && options['tenants'].nil? && payload['tenantPermissions'].nil? && payload['network']['tenants'].nil?
        perm_excludes = ['plans', 'groups']
        perm_excludes << 'visibility' if options['visibility'] || payload['network']['visibility']
        perms = prompt_permissions(options, perm_excludes)

        payload['network']['tenants'] = perms['tenantPermissions']['accounts'].collect {|it| {'id': it}} if perms['tenantPermissions']
        payload['network']['visibility'] = perms['resourcePool']['visibility'] if perms['resourcePool']
      elsif options['tenants']
        payload['network']['tenants'] = options['tenants'].collect {|it| {'id': it}}
      end

      # Visibility
      if options['visibility'].nil? && payload['network']['visibility'].nil?
        perms = prompt_permissions(options, ['plans', 'groups', 'tenants'])
        payload['network']['visibility'] = perms['resourcePool'].nil? ? 'private' : perms['resourcePool']['visibility']
      else
        payload['network']['visibility'] = options['visibility'] || 'private'
      end
    end

    @networks_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @networks_interface.dry.create(payload)
      return
    end
    json_response = @networks_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      network = json_response['network']
      print_green_success "Added network #{network['name']}"
      get_args = [network['id']] + (options[:remote] ? ["-r",options[:remote]] : [])
      get(get_args)
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



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

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @networks_interface = @api_client.networks
  @network_types_interface = @api_client.network_types
  @network_services_interface = @api_client.network_services
  @subnets_interface = @api_client.subnets
  @subnet_types_interface = @api_client.subnet_types
  @groups_interface = @api_client.groups
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
end

#get(args) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
# File 'lib/morpheus/cli/commands/networks_command.rb', line 159

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[network]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a network." + "\n" +
                  "[network] is required. This is the name or id of a network."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [network]\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    @networks_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @networks_interface.dry.get(args[0].to_i)
      else
        print_dry_run @networks_interface.dry.list({name:args[0]})
      end
      return
    end
    network = find_network_by_name_or_id(args[0])
    return 1 if network.nil?
    json_response = {'network' => network}  # skip redundant request
    # json_response = @networks_interface.get(network['id'])
    network = json_response['network']
    if options[:json]
      puts as_json(json_response, options, "network")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "network")
      return 0
    elsif options[:csv]
      puts records_as_csv([network], options)
      return 0
    end
    print_h1 "Network Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => lambda {|it| it['displayName'] ? it['displayName'] : it['name'] },
      "Labels" => lambda {|it| format_list(it['labels']) rescue '' },
      "Description" => 'description',
      "Type" => lambda {|it| it['type'] ? it['type']['name'] : '' },
      "Group" => lambda {|it| it['group'] ? it['group']['name'] : 'Shared' },
      "Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
      "IPv4 Enabled" => 'ipv4Enabled',
      "IPv6 Enabled" => 'ipv6Enabled',
      "CIDR" => 'cidr',
      "Gateway" => 'gateway',
      "Netmask" => 'netmask',
      "Subnet" => 'subnetAddress',
      "Primary DNS" => 'dnsPrimary',
      "Secondary DNS" => 'dnsSecondary',
      "IPv6 CIDR" => 'cidrIPv6',
      "IPv6 Gateway" => 'gatewayIPv6',
      "IPv6 Netmask" => 'netmaskIPv6',
      "IPv6 Primary DNS" => 'dnsPrimaryIPv6',
      "IPv6 Secondary DNS" => 'dnsSecondaryIPv6',
      "Domain" => lambda {|it| it['networkDomain'] ? it['networkDomain']['name'] : '' },
      "Search Domains" => lambda {|it| it['searchDomains'] },
      "Pool" => lambda {|it| it['pool'] ? it['pool']['name'] : '' },
      "IPv6 Pool" => lambda {|it| it['poolIPv6'] ? it['poolIPv6']['name'] : '' },
      "VPC" => lambda {|it| it['zonePool'] ? it['zonePool']['name'] : '' },
      "DHCP" => lambda {|it| it['dhcpServer'] ? 'Yes' : 'No' },
      "IPv6 DHCP" => lambda {|it| it['dhcpServerIPv6'] ? 'Yes' : 'No' },
      "Active" => lambda {|it| format_boolean(it['active']) },
      "Allow IP Override" => lambda {|it| it['allowStaticOverride'] ? 'Yes' : 'No' },
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' },
    }
    description_cols.delete("Domain") if network['networkDomain'].nil?
    description_cols.delete("Search Domains") if network['searchDomains'].to_s.empty?
    print_description_list(description_cols, network)

    if network["group"]
      # Group Access is n/a unless network is_a? Shared (no group)
    elsif network['resourcePermission'].nil?
      print "\n", "No group access found", "\n"
    else
      print_h2 "Group Access"
      rows = []
      if network['resourcePermission']['all']
        rows.push({"name" => 'All'})
      end
      if network['resourcePermission']['sites']
        network['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

    # if options[:show_subnets]
    # subnets data is limited, use /networks/:id/subnets to fetch it all.
    subnets = network['subnets']
    if subnets and subnets.size > 0
      print_h2 "Subnets", options
      rows = []
      subnet_rows = subnets.collect { |subnet|
        {
          id: subnet['id'],
          name: "  #{subnet['displayName'] || subnet['name']}",
          labels: format_list(subnet['labels'], '', 3),
          # type: subnet['type'] ? subnet['type']['name'] : '',
          type: "Subnet",
          cloud: network['zone'] ? network['zone']['name'] : '',
          cidr: subnet['cidr'],
          cidrIPv6: subnet['cidrIPv6'],
          pool: subnet['pool'] ? subnet['pool']['name'] : '',
          dhcp: subnet['dhcpServer'] ? 'Yes' : 'No',
          visibility: subnet['visibility'].to_s.capitalize,
          active: format_boolean(subnet['active']),
          tenants: subnet['tenants'] ? subnet['tenants'].collect {|it| it['name'] }.uniq.join(', ') : ''
        }
      }
      columns = [:id, :name, :labels, :cidr, :cidrIPv6, :dhcp, :active, :visibility]
      print cyan
      print as_pretty_table(subnet_rows, columns, options)
      print reset
      print_results_pagination({'meta'=>{'total'=>subnet_rows.size,'size'=>subnet_rows.size}}, {:label => "subnet", :n_label => "subnets"})
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#get_type(args) ⇒ Object



1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
# File 'lib/morpheus/cli/commands/networks_command.rb', line 1505

def get_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 network type.\n" +
                  "[type] is required. This is the id or name of a network type."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    @network_types_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_types_interface.dry.get(args[0].to_i)
      else
        print_dry_run @network_types_interface.dry.list({name:args[0]})
      end
      return
    end

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

    network_type = json_response['networkType']

    title = "Morpheus Network Type"
    
    print_h1 "Morpheus Network Type", [], options
    
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Code" => 'code',
      "Description" => 'description',
      # lots more here
      "Createable" => lambda {|it| format_boolean(it['creatable']) },
      "Deletable" => lambda {|it| format_boolean(it['deleteable']) },
    }
    print_description_list(description_cols, network_type)


    option_types = network_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



33
34
35
# File 'lib/morpheus/cli/commands/networks_command.rb', line 33

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/morpheus/cli/commands/networks_command.rb', line 37

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '-c', '--cloud CLOUD', "Filter by Cloud" ) do |val|
      options[:cloud] = val
    end
    opts.on('--cidr VALUE', String, "Filter by cidr, matches beginning of value.") do |val|
      params['cidr'] = val
    end
    opts.on('-a', '--all', "Display all data, including subnets.") do
      options[:show_subnets] = true
    end
    opts.on('--subnets', '--subnets', "Display subnets as rows under each network found.") do
      options[:show_subnets] = true
    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_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :json, :dry_run, :remote])
    opts.footer = "List networks."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  begin
    params.merge!(parse_list_options(options))
    cloud = nil
    if options[:cloud]
      cloud = find_cloud_by_name_or_id(options[:cloud])
      return 1 if cloud.nil?
      params['zoneId'] = cloud['id']
    end
    @networks_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @networks_interface.dry.list(params)
      return
    end
    json_response = @networks_interface.list(params)
    networks = json_response["networks"]
    if options[:json]
      puts as_json(json_response, options, "networks")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networks")
      return 0
    elsif options[:csv]
      puts records_as_csv(networks, options)
      return 0
    end
    title = "Morpheus Networks"
    subtitles = []
    if cloud
      subtitles << "Cloud: #{cloud['id']}"
    end
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if networks.empty?
      print cyan,"No networks found.",reset,"\n"
    else
      rows = []
      networks.each do |network|
        row = {
          id: network['id'],
          name: network['displayName'] || network['name'],
          labels: format_list(network['labels'], '', 3),
          type: network['type'] ? network['type']['name'] : '',
          group: network['group'] ? network['group']['name'] : 'Shared',
          cloud: network['zone'] ? network['zone']['name'] : '',
          cidr: network['cidr'],
          pool: network['pool'] ? network['pool']['name'] : '',
          dhcp: network['dhcpServer'] ? 'Yes' : 'No',
          subnets: (network['subnets'].size rescue 'n/a'),
          visibility: network['visibility'].to_s.capitalize,
          active: format_boolean(network['active']),
          tenants: network['tenants'] ? network['tenants'].collect {|it| it['name'] }.uniq.join(', ') : ''
        }
        rows << row
        if network['subnets'] && network['subnets'].size() > 0 && options[:show_subnets]
          network['subnets'].each do |subnet|
            subnet_row = {
              id: subnet['id'],
              name: "  #{subnet['displayName'] || subnet['name']}",
              labels: format_list(subnet['labels'], '', 3),
              # type: subnet['type'] ? subnet['type']['name'] : '',
              type: "Subnet",
              group: network['group'] ? network['group']['name'] : 'Shared',
              cloud: network['zone'] ? network['zone']['name'] : '',
              cidr: subnet['cidr'],
              pool: subnet['pool'] ? subnet['pool']['name'] : '',
              dhcp: subnet['dhcpServer'] ? 'Yes' : 'No',
              visibility: subnet['visibility'].to_s.capitalize,
              active: format_boolean(subnet['active']),
              tenants: subnet['tenants'] ? subnet['tenants'].collect {|it| it['name'] }.uniq.join(', ') : ''
            }
            rows << subnet_row
          end
        end
      end
      columns = [:id, :name, :labels, :type, :group, :cloud, :cidr, :pool, :dhcp, :subnets, :active, :visibility, :tenants]
      if options[:include_fields]
        columns = options[:include_fields]
      end
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      print_results_pagination(json_response, {:label => "network", :n_label => "networks"})
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_subnets(args) ⇒ Object



1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
# File 'lib/morpheus/cli/commands/networks_command.rb', line 1575

def list_subnets(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[network]")
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List subnets under a network." + "\n" +
                  "[network] is required. This is the name or id of a network."
  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?
    params['networkId'] = network['id']
    params.merge!(parse_list_options(options))
    @subnets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @subnets_interface.dry.list(params)
      return
    end
    json_response = @subnets_interface.list(params)
    subnets = json_response["subnets"]
    if options[:json]
      puts as_json(json_response, options, "subnets")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "subnets")
      return 0
    elsif options[:csv]
      puts records_as_csv(subnets, options)
      return 0
    end
    title = "Morpheus Subnets"
    subtitles = []
    subtitles << "Network: #{network['name']}"
    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',
        #"Description" => 'description',
        "Type" => lambda {|it| it['type']['name'] rescue it['type'] },
        "CIDR" => lambda {|it| it['cidr'] },
        "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)
    end
    print reset,"\n"
    return 0
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#list_types(args) ⇒ Object



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
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
# File 'lib/morpheus/cli/commands/networks_command.rb', line 1439

def list_types(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List network 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
    @network_types_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_types_interface.dry.list(params)
      return
    end
    json_response = @network_types_interface.list(params)
    
    render_result = render_with_format(json_response, options, 'networkTypes')
    return 0 if render_result

    network_types = json_response['networkTypes']

    title = "Morpheus Network Types"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    if options[:cloud]
      subtitles << "Cloud: #{options[:cloud]}"
    end
    print_h1 title, subtitles
    if network_types.empty?
      print cyan,"No network types found.",reset,"\n"
    else
      rows = network_types.collect do |network_type|
        {
          id: network_type['id'],
          code: network_type['code'],
          name: network_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



1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
# File 'lib/morpheus/cli/commands/networks_command.rb', line 1391

def remove(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[network]")
    build_common_options(opts, options, [:account, :auto_confirm, :json, :dry_run, :remote])
    opts.on( '-f', '--force', "Force Delete" ) do
      params[:force] = 'true'
    end
    opts.footer = "Delete a network." + "\n" +
                  "[network] is required. This is the name or id of a network."
  end
  optparse.parse!(args)

  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [network]\n#{optparse}"
    return 1
  end

  connect(options)
  begin
    network = find_network_by_name_or_id(args[0])
    return 1 if network.nil?

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

#update(args) ⇒ Object



941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
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
1052
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
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
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
1247
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
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
# File 'lib/morpheus/cli/commands/networks_command.rb', line 941

def update(args)
  options = {}
  # network_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("[network] [options]")
    # opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
    #   options[:cloud] = val
    # end
    # opts.on('-t', '--type ID', "Network Type Name or ID") do |val|
    #   options['type'] = val
    # end
    opts.on('--name VALUE', String, "Name for this network") do |val|
      options['name'] = val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options['labels'] = parse_labels(val)
    end
    opts.on('--description VALUE', String, "Description of network") do |val|
      options['description'] = val
    end
    opts.on('--display-name VALUE', String, "Display name for this network") do |val|
      options['displayName'] = val
    end
    opts.on('--ipv4Enabled [on|off]', String, "ipv4Enabled") do |val|
      options['ipv4Enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--ipv6Enabled [on|off]', String, "ipv6Enabled") do |val|
      options['ipv6Enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--gateway VALUE', String, "Gateway") do |val|
      options['gateway'] = val
    end
    opts.on('--dns-primary VALUE', String, "DNS Primary") do |val|
      options['dnsPrimary'] = val
    end
    opts.on('--dns-secondary VALUE', String, "DNS Secondary") do |val|
      options['dnsSecondary'] = val
    end
    opts.on('--cidr VALUE', String, "CIDR") do |val|
      options['cidr'] = val
    end
    opts.on('--gateway-ipv6 VALUE', String, "IPv6 Gateway") do |val|
      options['gatewayIPv6'] = val
    end
    opts.on('--gatewayIPv6 VALUE', String, "IPv6 Gateway") do |val|
      options['gatewayIPv6'] = val
    end
    opts.add_hidden_option('--gatewayIPv6')
    opts.on('--dns-primary-ipv6 VALUE', String, "IPv6 DNS Primary") do |val|
      options['dnsPrimaryIPv6'] = val
    end
    opts.on('--dns-primaryIPv6 VALUE', String, "IPv6 DNS Primary") do |val|
      options['dnsPrimaryIPv6'] = val
    end
    opts.add_hidden_option('--dns-primaryIPv6')
    opts.on('--dns-secondary-ipv6 VALUE', String, "IPv6 DNS Secondary") do |val|
      options['dnsSecondaryIPv6'] = val
    end
    opts.on('--dns-secondaryIPv6 VALUE', String, "IPv6 DNS Secondary") do |val|
      options['dnsSecondaryIPv6'] = val
    end
    opts.add_hidden_option('--dns-secondaryIPv6')
    opts.on('--cidr-ipv6 VALUE', String, "IPv6 CIDR") do |val|
      options['cidrIPv6'] = val
    end
    opts.on('--cidrIPv6 VALUE', String, "IPv6 CIDR") do |val|
      options['cidrIPv6'] = val
    end
    opts.add_hidden_option('--cidrIPv6')
    opts.on('--vlan-id VALUE', String, "VLAN ID") do |val|
      options['vlanId'] = val.to_i
    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('--dhcp-serverIPv6 [on|off]', String, "IPv6 DHCP Server") do |val|
      options['dhcpServerIPv6'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--dhcp-server-ipv6 [on|off]', String, "IPv6 DHCP Server") do |val|
      options['dhcpServerIPv6'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--allow-ip-override [on|off]', String, "Allow IP Override") do |val|
      options['allowStaticOverride'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--domain [VALUE]', String, "Network Domain ID") do |val|
      options['domain'] = val
    end
    opts.on('--search-domains [VALUE]', String, "Search Domains") do |val|
      options['searchDomains'] = val
    end
    # opts.on('--scan [on|off]', String, "Scan Network") do |val|
    #   options['scanNetwork'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    # end
    opts.on('--proxy VALUE', String, "Network Proxy ID") do |val|
      options['proxy'] = val
    end
    opts.on('--proxy-bypass [on|off]', String, "Bypass Proxy for Appliance URL") do |val|
      options['applianceUrlProxyBypass'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--no-proxy LIST', String, "No Proxy Addresses") do |val|
      options['noProxy'] = 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 network") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true'
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network." + "\n" +
                  "[network] is required. This is the id of a network."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    network = find_network_by_name_or_id(args[0])
    return 1 if network.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]

      # backward compat
      if payload['resourcePermissions']
        payload['network'] ||= {}
        payload['network']['resourcePermission'] = payload['resourcePermissions']
        payload.delete('resourcePermissions')
      end
      if payload['network'] && payload['network']['resourcePermissions']
        payload['network']['resourcePermission'] = payload['network']['resourcePermissions']
        payload['network'].delete('resourcePermissions')
      end
    else
      # prompt for network options
      payload = {
        'network' => {
          # 'config' => {}
        }
      }
      
      # allow arbitrary -O options
      payload['network'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

      # # Cloud
      # cloud = nil
      # if options[:cloud]
      #   cloud = find_cloud_by_name_or_id(options[:cloud])
      #   # meh, should validate cloud is in the cloudsForNetworks dropdown..
      #   return 1 if cloud.nil?
      # else
      #   # print_red_alert "Cloud not specified!"
      #   # exit 1
      #   cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'optionSource' => 'cloudsForNetworks', 'required' => true, 'description' => 'Select Cloud.'}],options,@api_client,{})
      #   cloud_id = cloud_prompt['cloud']
      #   cloud = find_cloud_by_name_or_id(cloud_id) if cloud_id
      #   return 1 if cloud.nil?
      # end

      # # Network Type
      # network_type_id = nil
      # api_params = {"network.zone.id" => cloud['id']} #{network:{zone:{id: cloud['id']}}}
      # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Network Type', 'type' => 'select', 'optionSource' => 'networkTypesForCloud', 'required' => true, 'description' => 'Choose a network type.'}], options, @api_client, api_params)
      # network_type_id = v_prompt['type']
      # if network_type_id.nil? || network_type_id.to_s.empty?
      #   print_red_alert "Network Type not found by id '#{options['type']}'"
      #   return 1
      # end
      # payload['network']['type'] = {'id' => network_type_id.to_i }

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

      if options['displayName']
        payload['network']['displayName'] = options['displayName']
      end

      # Labels
      if options['labels']
        payload['network']['labels'] = options['labels']
      end

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

      # IP Types Enabled
      if options['ipv4Enabled'] != nil
        payload['network']['ipv4Enabled'] = options['ipv4Enabled']
      end

      if options['ipv6Enabled'] != nil
        payload['network']['ipv6Enabled'] = options['ipv6Enabled']
      end

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

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

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

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

      # IPv6 Gateway
      if options['gatewayIPv6']
        payload['network']['gatewayIPv6'] = options['gatewayIPv6']
      end

      # IPv6 DNS Primary
      if options['dnsPrimaryIPv6']
        payload['network']['dnsPrimarIPv6y'] = options['dnsPrimaryIPv6']
      end

      # IPv6 DNS Secondary
      if options['dnsSecondaryIPv6']
        payload['network']['dnsSecondaryIPv6'] = options['dnsSecondaryIPv6']
      end

      # IPv6 CIDR
      if options['cidrIPv6']
        payload['network']['cidrIPv6'] = options['cidrIPv6']
      end

      # VLAN ID
      if options['vlanId']
        payload['network']['vlanId'] = options['vlanId']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'vlanId', 'fieldLabel' => 'VLAN ID', 'type' => 'number', 'required' => false, 'description' => ''}], options)
        # payload['network']['vlanId'] = v_prompt['vlanId']
      end

      # Network Pool
      if options['pool']
        payload['network']['pool'] = options['pool'].to_i
      else
        # todo: select dropdown
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'pool', 'fieldLabel' => 'Network Pool', 'type' => 'select', 'optionSource' => 'networkPools', 'required' => false, 'description' => ''}], options, @api_client, {zoneId: cloud['id']})
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'pool', 'fieldLabel' => 'Network Pool', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        # payload['network']['pool'] = v_prompt['pool'].to_i if v_prompt['pool']
      end

      # DHCP Server
      if options['dhcpServer'] != nil
        payload['network']['dhcpServer'] = options['dhcpServer']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dhcpServer', 'fieldLabel' => 'DHCP Server', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
        # payload['network']['dhcpServer'] = v_prompt['dhcpServer']
      end

      # IPv6 DHCP Server
      if options['dhcpServerIPv6'] != nil
        payload['network']['dhcpServerIPv6'] = options['dhcpServerIPv6']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dhcpServerIPv6', 'fieldLabel' => 'IPv6 DHCP Server', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
        # payload['network']['dhcpServerIPv6'] = v_prompt['dhcpServerIPv6']
      end

      # Allow IP Override
      if options['allowStaticOverride'] != nil
        payload['network']['allowStaticOverride'] = options['allowStaticOverride']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allowStaticOverride', 'fieldLabel' => 'Allow IP Override', 'type' => 'checkbox', 'required' => false, 'description' => ''}], options)
        # payload['network']['allowStaticOverride'] = v_prompt['allowStaticOverride']
      end
      
      # Network Domain
      if options.key?('domain')
        if options['domain'].to_s.empty?  # clear it?
          payload['network']['networkDomain'] = {'id' => nil}
        else
          # always prompt to handle value as name instead of id...
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'domain', 'fieldLabel' => 'Network Domain', 'type' => 'select', 'optionSource' => 'networkDomains', 'required' => false, 'description' => ''}], options, @api_client)
          payload['network']['networkDomain'] = {'id' => v_prompt['domain'].to_i} unless v_prompt['domain'].to_s.empty?
        end
      end

      # Search Domains
      if options.key?('searchDomains')
        payload['network']['searchDomains'] = options['searchDomains']
      else
        # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'searchDomains', 'fieldLabel' => 'Search Domains', 'type' => 'text', 'required' => false, 'description' => ''}], options)
        # payload['network']['searchDomains'] = v_prompt['searchDomains']
      end

      # Scan Network
      if options['scanNetwork'] != nil
        payload['network']['scanNetwork'] = options['scanNetwork']
      else
        #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'scanNetwork', 'fieldLabel' => 'Scan Network', 'type' => 'checkbox', 'required' => false, 'description' => '', 'defaultValue' => false}], options)
        #payload['network']['scanNetwork'] = v_prompt['scanNetwork']
      end

      # Proxy
      if options['networkProxy']
        payload['network']['networkProxy'] = {'id' => options['networkProxy'].to_i}
      else
        #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'networkProxy', 'fieldLabel' => 'Network Proxy', 'type' => 'select', 'optionSource' => 'networkProxies', 'required' => false, 'description' => ''}], options, @api_client)
        #payload['network']['networkProxy'] = {'id' => v_prompt['networkProxy'].to_i} unless v_prompt['networkProxy'].to_s.empty?
      end

      # ByPass Proxy for Appliance URL 
      if options['applianceUrlProxyBypass'] != nil
        payload['network']['applianceUrlProxyBypass'] = options['applianceUrlProxyBypass']
      else
        #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'applianceUrlProxyBypass', 'fieldLabel' => 'Bypass Proxy for Appliance URL', 'type' => 'checkbox', 'required' => false, 'description' => '', 'defaultValue' => true}], options)
        #payload['network']['applianceUrlProxyBypass'] = v_prompt['applianceUrlProxyBypass']
      end

      # No Proxy
      if options['noProxy']
        payload['network']['noProxy'] = options['noProxy']
      else
        #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'noProxy', 'fieldLabel' => 'No Proxy', 'type' => 'text', 'required' => false, 'description' => 'List of ip addresses or name servers to exclude proxy traversal for. Typically locally routable servers are excluded.'}], options)
        #payload['network']['noProxy'] = v_prompt['noProxy']
      end

      # Group Access
      if group_access_all != nil
        payload['network']['resourcePermission'] ||= {}
        payload['network']['resourcePermission']['all'] = group_access_all
      end
      if group_access_list != nil
        payload['network']['resourcePermission'] ||= {}
        payload['network']['resourcePermission']['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['network']['tenants'] = {}
        payload['network']['tenants'] = options['tenants'].collect {|it| {'id': it}}
      end

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

    end
    @networks_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @networks_interface.dry.update(network["id"], payload)
      return
    end
    json_response = @networks_interface.update(network["id"], payload)
    if options[:json]
      puts as_json(json_response)
    else
      network = json_response['network']
      print_green_success "Updated network #{network['name']}"
      get_args = [network['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