Class: Morpheus::Cli::NetworkRoutersCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from WhoamiHelper

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

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_groups, #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 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

#initializeNetworkRoutersCommand

Returns a new instance of NetworkRoutersCommand.



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

def initialize()
end

Instance Method Details

#_bgp_neighbors(router_id, options) ⇒ Object



1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1909

def _bgp_neighbors(router_id, options)
  @network_routers_interface.setopts(options)
  if options[:dry_run]
    if args[0].to_s =~ /\A\d{1,}\Z/
      print_dry_run @network_routers_interface.dry.get(router_id.to_i)
    else
      print_dry_run @network_routers_interface.dry.list({name:router_id})
    end
    return
  end
  router = find_router(router_id)
  if router.nil?
    return 1
  end

  if router['type']['hasBgp']
    json_response = {'networkRouterBgpNeighbors' => router['bgpNeighbors']}
    render_response(json_response, options, 'networkRouterBgpNeighbor') do
      print_h1 "Network Router BGP Neighbors For: #{router['name']}"
      print cyan
      print_bgp_neighbors(router)
    end
  else
    print_red_alert "BGP not supported for #{router['type']['name']}"
  end
  print reset
end

#_firewall_rule(router_id, rule_id, options) ⇒ Object



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

def _firewall_rule(router_id, rule_id, options)
  router = find_router(router_id)
  if router.nil?
    return 1
  end

  if router['type']['hasFirewall']
    rule = find_firewall_rule(router, rule_id)

    if rule
      json_response = {'rule' => rule}

      if options[:json]
        puts as_json(json_response, options, "rule")
        return 0
      elsif options[:yaml]
        puts as_yaml(json_response, options, "rule")
        return 0
      elsif options[:csv]
        puts records_as_csv([json_response['rule']], options)
        return 0
      end

      print_h1 "Firewall Rule Details"
      print cyan
      description_cols = {
        "ID" => lambda {|it| it['id'] },
        "Enabled" => lambda {|it| format_boolean(it['enabled'])},
        "Priority" => lambda {|it| it['priority']},
        "Name" => lambda {|it| it['name'] },
        "Type" => lambda {|it| it['ruleType'] },
        "Policy" => lambda {|it| it['policy'] },
        "Direction" => lambda {|it| it['direction'] || 'any' },
        "Source" => lambda {|it| it['source'].kind_of?(Array) && it['source'].count > 0 ? it['source'].join(', ') : (it['source'].nil? || it['source'].empty? ? 'any' : it['source']) },
        "Destination" => lambda {|it| it['destination'].kind_of?(Array) && it['destination'].count > 0 ? it['destination'].join(', ') : (it['destination'].nil? || it['destination'].empty? ? 'any' : it['destination'])},
        "Application" => lambda {|it| it['applications'].count > 0 ? it['applications'][0]['name'] : "#{(it['protocol'] || 'any')} #{it['portRange'] || ''}"}
      }
      print_description_list(description_cols, rule)
    else
      print_red_alert "Firewall rule #{rule_id} not found for router #{router['name']}"
    end
  else
    print_red_alert "Firewall not supported for #{router['type']['name']}"
  end
  println reset
end

#_firewall_rule_group(router_id, group_id, options) ⇒ Object



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

def _firewall_rule_group(router_id, group_id, options)
  @network_routers_interface.setopts(options)
  if options[:dry_run]
    if router_id.to_s =~ /\A\d{1,}\Z/
      print_dry_run @network_routers_interface.dry.list({name:router_id})
    else
      if group_id.to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get_firewall_rule_group(router_id.to_i, group_id)
      else
        print_dry_run @network_routers_interface.dry.list_firewall_rule_groups(router_id.to_i, {phrase:router_id})
      end
    end
    return
  end
  router = find_router(router_id)
  if router.nil?
    return 1
  end

  if router['type']['hasFirewallGroups']
    group = find_firewall_rule_group(router['id'], group_id)
    return 1 if group.nil?

    render_response({ruleGroup: group}, options, 'ruleGroup') do
      print_h1 "Firewall Rule Group Details"
      print cyan
      description_cols = {
        "ID" => lambda {|it| it['id'] },
        "Name" => lambda {|it| it['name'] },
        "Description" => lambda {|it| it['description']},
        "Priority" => lambda {|it| it['priority']},
        "Category" => lambda {|it| it['groupLayer']}
      }
      print_description_list(description_cols, group)

      if 
        description_cols["Visibility"] = lambda {|it| it['visibility']}
        description_cols["Tenants"] = lambda {|it| it['tenants'].collect {|tenant| tenant['name']}.join(', ')}
      end
      print_description_list(description_cols, group)
    end
  else
    print_red_alert "Firewall rule groups not supported for #{router['type']['name']}"
    return 1
  end
  println reset
end

#_firewall_rule_groups(router, options) ⇒ Object



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

def _firewall_rule_groups(router, options)
  if router['type']['hasFirewallGroups']
    json_response = {'ruleGroups' => router['firewall']['ruleGroups'] || []}

    if options[:json]
      puts as_json(json_response, options, "ruleGroups")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "ruleGroups")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['ruleGroups'], options)
      return 0
    end

    if (router['firewall']['ruleGroups'] || []).count > 0
      print_h1 "Firewall Rule Groups For: #{router['name']}"
      rows = router['firewall']['ruleGroups'].collect do |rule_group|
        {
          id: rule_group['id'],
          name: rule_group['name'],
          description: rule_group['description'],
          priority: rule_group['priority'],
          category: rule_group['groupLayer']
        }
      end
      rows = rows.reject {|it| it[:id].to_s != options[:rule_group_id].to_s} if options[:rule_group_id]
      puts as_pretty_table(rows, [:id, :name, :description, :priority, :category])
    else
      print_h1 "No Firewall Rule Groups"
    end
  else
    print_red_alert "Firewall rule groups not supported for #{router['type']['name']}"
  end
  println reset
end

#_firewall_rules(router, options) ⇒ Object



938
939
940
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
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 938

def _firewall_rules(router, options)
  if router['type']['hasFirewall']
    rules = router['type']['hasFirewallGroups'] ? (router['firewall']['ruleGroups'] || []).collect {|it| it['rules']}.flatten : router['firewall']['rules']

    json_response = {'rules' => rules}

    if options[:json]
      puts as_json(json_response, options, "rules")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "rules")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['rules'], options)
      return 0
    end

    if router['type']['hasFirewallGroups']
      rules = []
      (router['firewall']['ruleGroups'] || []).each do |rule_group|
        (rule_group['rules'] || []).each do |rule|
          rule['groupId'] = rule_group['id']
          rule['groupName'] ||= rule_group['name']
          rules << rule
        end
      end
    end

    if rules.count > 0
      print_h1 "Firewall Rules For: #{router['name']}"
      rows = rules.collect do |it|
        {
          id: it['id'],
          group_name: it['groupName'],
          name: it['name'],
          type: it['ruleType'],
          policy: it['policy'],
          direction: it['direction'] || 'any',
          source: it['source'].kind_of?(Array) && it['source'].count > 0 ? it['source'].join(', ') : (it['source'].nil? || it['source'].empty? ? 'any' : it['source']),
          destination: it['destination'].kind_of?(Array) && it['destination'].count > 0 ? it['destination'].join(', ') : (it['destination'].nil? || it['destination'].empty? ? 'any' : it['destination']),
          application: it['applications'].count > 0 ? it['applications'][0]['name'] : "#{(it['protocol'] || 'any')} #{it['portRange'] || ''}"
        }
      end

      if router['type']['hasFirewallGroups']
        puts as_pretty_table(rows, [:id, :group_name, :name, :type, :policy, :direction, :source, :destination, :application])
      else
        puts as_pretty_table(rows, [:id, :name, :type, :policy, :direction, :source, :destination, :application])
      end
    else
      print_h1 "No Firewall Rules"
    end
  else
    print_red_alert "Firewall not supported for #{router['type']['name']}"
  end
  println reset
end

#_get(id, options) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 128

def _get(id, options)
  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if arg.to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(arg.to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:arg})
      end
      return
    end
    router = find_router(id)
    if router.nil?
      return 1
    end

    json_response = {'networkRouter' => router}

    if options[:json]
      puts as_json(json_response, options, "networkRouter")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networkRouter")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['networkRouter']], options)
      return 0
    end

    print_h1 "Network Router Details"
    print cyan
    description_cols = {
        "ID" => lambda {|it| it['id'] },
        "Name" => lambda {|it| it['name'] },
        "Status" => lambda {|it| format_router_status(it)},
        "Type" => lambda {|it| it['type']['name']},
        "Service" => lambda {|it| it['networkServer'] ? it['networkServer']['name'] : nil},
        "Group" => lambda {|it| it['site'] ? it['site']['name'] : 'Shared'},
        # "Integration" => lambda {|it| router_integration_label(it)},
        "Provider ID" => lambda {|it| it['providerId'] || it['externalId']},
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
    }

    print_description_list(description_cols, router)

    if (router['interfaces'] || []).count > 0
      rows = router['interfaces'].sort_by{|it| it['networkPosition']}.collect do |it|
        {
            position: it['networkPosition'],
            name: it['name'],
            type: it['interfaceType'],
            network: (it['network'] || {})['name'],
            link: it['externalLink'],
            ip_address: it['ipAddress'],
            subnet: it['cidr'],
            enabled: format_boolean(it['enabled'])
        }
      end
      print_h2 "Interfaces"
      puts as_pretty_table(rows, [:position, :name, :type, :link, :network, :ip_address, :subnet, :enabled])
    end

    if router['type']['hasFirewall']
      print_h2 "Firewall"
      print cyan
      print_firewall(router, options)
    end
    if router['type']['hasDhcp']
      print_h2 "DHCP"
      print cyan
      print_dhcp(router, options[:details])
    end
    if router['type']['hasRouting'] && options[:details]
      print_h2 "Routes"
      print cyan
      print_routes(router)
    end
    if router['type']['hasNat'] && options[:details]
      print_h2 "NATs"
      print cyan
      print_nats(router)
    end
    if router['permissions'] && options[:details]
      print_h2 "Tenant Permissions"
      print cyan
      description_cols = {
          "Visibility" => lambda{|it| (it['permissions']['visibility'] || '').capitalize},
          "Tenants" => lambda{|it|
            accounts = (it['permissions']['tenantPermissions'] || {})['accounts'] || []
            accounts.count > 0 ? accounts.join(', ') : ''
          }
      }
      print_description_list(description_cols, router)
      println
    end
    print reset
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#_nats(router_id, options) ⇒ Object



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

def _nats(router_id, options)
  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(router_id.to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:router_id})
      end
      return
    end
    router = find_router(router_id)
    if router.nil?
      return 1
    end

    json_response = {'networkRouterNATs' => router['nats']}

    if options[:json]
      puts as_json(json_response, options, "networkRouterNATs")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networkRouterNATs")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['networkRouterNATs'], options)
      return 0
    end

    print_h1 "Network Router NATs For: #{router['name']}"
    print cyan

    if router['type']['hasNat']
      print_nats(router)
    else
      print_red_alert "NATs not supported for #{router['type']['name']}"
    end
    print reset
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#_routes(router_id, options) ⇒ Object



1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1377

def _routes(router_id, options)
  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(router_id.to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:router_id})
      end
      return
    end
    router = find_router(router_id)
    if router.nil?
      return 1
    end

    json_response = {'networkRoutes' => router['routes']}

    if options[:json]
      puts as_json(json_response, options, "networkRoutes")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networkRoutes")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['networkRoutes'], options)
      return 0
    end

    print_h1 "Network Router Routes For: #{router['name']}"
    print cyan

    if router['type']['hasRouting']
      print_routes(router)
    else
      print_red_alert "Routes not supported for #{router['type']['name']}"
    end
    print reset
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#add(args) ⇒ Object



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

def add(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[type] [name] [options]")
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options[:group] = val
    end
    opts.on('-t', '--type VALUE', String, "Name or ID of router type") do |val|
      options[:options]['routerType'] = val
    end
    opts.on('-n', '--name VALUE', String, "Name for this network router") do |val|
      options[:options]['name'] = val
    end
    opts.on('-D', '--description VALUE', String, "Description") do |val|
      options[:options]['description'] = val
    end
    opts.on('-s', '--server VALUE', String, "Network server") do |val|
      options[:network_server] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options[:cloud] = val
    end
    opts.on('--enabled [on|off]', String, "Can be used to enable / disable the network router. Default is on") do |val|
      options[:enabled] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--hostname VALUE', String, "Hostname for this network pool IP") do |val|
      options[:options]['hostname'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a network router."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-2 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  if args.count > 0
    options[:options]['routerType'] = args[0]
  end
  if args.count > 1
    params['name'] = args[1]
  end
  begin
    if options[:payload]
      payload = options[:payload]
    else
      router_type = prompt_router_type(options)
      router = {'type' => {'id' => router_type['id']}, 'enabled' => options[:enabled].nil? || options[:enabled] }

      group_options = available_groups

      if options[:group]
        group = available_groups.find {|it| it['name'] == options[:group] || "#{it['value']}" == "#{options[:group]}".downcase}

        if group.nil?
          print_red_alert "Group #{options[:group]} not found"
          exit 1
        end
        router['site'] = {'id' => group['value']}
      else
        default_group = group_options.find {|it| it['value'] == 'shared'} ? 'shared' : nil
        group_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'type' => 'select', 'fieldLabel' => 'Group', 'required' => true, 'selectOptions' => group_options, 'defaultValue' => default_group}], options[:options], @api_client, params, nil, true)['group']
        router['site'] = {'id' => group_id}
      end

      # add router type to be used for option prompts
      params = {'router' => {'site' => router['site']}, 'routerType' => {'id' => router_type['id']}}

      if router_type['hasNetworkServer']
        if options[:network_server]
          # This is using network_services instead of network_servers though, hrmm
          # server = find_network_server(options[:network_server])
          services = @network_services_interface.list()['networkServices']
          server = (options[:network_server].to_s =~ /\A\d{1,}\Z/) ? services.find {|it| it['id'].to_i == options[:network_server].to_i} : services.find {|it| it['name'] == options[:network_server]}
          if server.nil?
            print_red_alert "Network server #{options[:network_server]} not found"
            exit 1
          end
        else
          server_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'networkServer', 'type' => 'select', 'fieldLabel' => 'Network Server', 'required' => true, 'optionSource' => 'networkServer'}], options[:options], @api_client, params, nil, true)['networkServer']
          server = {'id' => server_id}
        end
        params['router']['networkServer'] = router['networkServer'] = {'id' => server['id']}
        params['networkServerId'] = server['id']
      else
        # prompt cloud
        if options[:cloud]
          cloud = find_cloud_by_name_or_id(options[:cloud])
          if cloud.nil?
            print_red_alert "Cloud #{options[:cloud]} not found"
            exit 1
          end
        else
          cloud_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'zone', 'type' => 'select', 'fieldLabel' => 'Cloud', 'required' => true, 'optionSource' => 'routerTypeCloud'}], options[:options], @api_client, params, nil, true)['zone']
          cloud = {'id' => cloud_id}
        end
        router['zone'] = params['zone'] = {'id' => cloud['id']}
      end

      # prompt for enabled
      router['enabled'] = options[:enabled].nil? ? Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'enabled', 'fieldLabel' => 'Enabled', 'type' => 'checkbox', 'description' => 'Enable Router.', 'defaultValue' => true, 'required' => false}], options, @api_client, {})['enabled'] == 'on' : options[:enabled]

      option_types = router_type['optionTypes'].reject {|it| ['enabled'].include?(it['fieldName']) || it['showOnCreate'] === false}.sort {|it| it['displayOrder']}

      # prompt options
      option_opts = options[:options].deep_merge!({'config' => options[:options].clone})
      option_result = Morpheus::Cli::OptionTypes.prompt(option_types, option_opts.merge({:context_map => {'networkRouter' => ''}}), @api_client, params)
      payload = {'networkRouter' => router.deep_merge(option_result)}
      payload['networkRouter']['config'] = option_result['config'] if option_result['config']
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.create(payload)
      return
    end

    json_response = @network_routers_interface.create(payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "Added Network Router #{payload['networkRouter']['name']}"
    _get(json_response['id'], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_bgp_neighbor(args) ⇒ Object



1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1996

def add_bgp_neighbor(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a network router BGP neighbor."
  end
  optparse.parse!(args)
  connect(options)
  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end

  router = find_router(args[0])

  if router.nil?
    return 1
  end

  if !router['type']['hasNat']
    print_red_alert "BGP not supported for #{router['type']['name']}"
    return 1
  end

  if options[:payload]
    payload = options[:payload]
  else
    option_types = router['type']['bgpNeighborOptionTypes'].sort_by {|it| it['displayOrder']}

    # prompt options
    option_result = Morpheus::Cli::OptionTypes.prompt(option_types, options[:options].deep_merge({:context_map => {'bgpNeighbor' => ''}}), @api_client, {'networkRouterId' => router['id']}, nil, true)
    payload = {'networkRouterBgpNeighbor' => params.deep_merge(option_result)}
  end

  @network_routers_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @network_routers_interface.dry.create_bgp_neighbor(router['id'], payload)
    return
  end

  json_response = @network_routers_interface.create_bgp_neighbor(router['id'], payload)
  render_response(json_response, options, 'networkRouterBgpNeighbor') do
    print_green_success "\nAdded Network Router BGP neighbor #{json_response['id']}\n"
    _bgp_neighbors(router['id'], options)
  end
end

#add_firewall_rule(args) ⇒ Object



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

def add_firewall_rule(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [name]")
    opts.on('-n', '--name VALUE', String, "Name for this firewall rule") do |val|
      params['name'] = val
    end
    opts.on('--enabled [on|off]', String, "Can be used to enable / disable the rule. Default is on") do |val|
      params['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on( '-g', '--group GROUP', "Firewall rule group name or ID (not applicable to all firewall types)" ) do |val|
      options[:group] = val
    end
    opts.on('--priority VALUE', Integer, "Priority for this rule (not applicable to all firewall types)") do |val|
      params['priority'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a network router firewall rule."
  end
  optparse.parse!(args)
  connect(options)
  if args.count < 1 || args.count > 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1-2 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  if args.count > 1
    params['name'] = args[1]
  end
  begin
    router = find_router(args[0])

    if router.nil?
      return 1
    end

    if !router['type']['hasFirewall']
      print_red_alert "Firewall not supported for #{router['type']['name']}"
      return 1
    end

    if options[:payload]
      payload = options[:payload]
    else
      params['name'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Rule Name', 'required' => true}], options[:options], @api_client, params)['name']

      if router['type']['hasFirewallGroups']
        if !router['firewall']['ruleGroups'].count
          print_red_alert "No firewall rule group found for #{router['type']['name']}"
          return 1
        end

        if options[:group]
          group = router['firewall']['ruleGroups'].find {|it| it['name'] == options[:group] || it['id'] == options[:group].to_i}
          if !group
            print_red_alert "Firewall rule group #{options[:group]} not found for #{router['type']['name']}"
            return 1
          end
          group_id = group['id']
        else
          group_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'type' => 'select', 'fieldLabel' => 'Rule Group', 'required' => true, 'selectOptions' => router['firewall']['ruleGroups'].collect {|it| {'name' => it['name'], 'value' => it['id']}}}])['group']
        end

        params['config'] = {} if params['config'].nil?
        params['config']['parentId'] = "group-#{group_id}"
      end

      params['enabled'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'enabled', 'fieldLabel' => 'Enabled', 'type' => 'checkbox', 'description' => 'Enable Rule.', 'defaultValue' => true, 'required' => false}], options, @api_client, {})['enabled'] == 'on'

      if router['type']['code'].start_with?('nsx-t')
        params['priority'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'priority', 'type' => 'number', 'fieldLabel' => 'Priority', 'required' => false}], options[:options], @api_client, params)['priority']
      end

      option_types = router['type']['ruleOptionTypes'].reject {|it| ['name'].include?(it['fieldName'])}.sort {|it| it['displayOrder']}

      # prompt options
      api_params = {}
      api_params['networkServerId'] = router['networkServer']['id'] if router['networkServer']
      api_params['zoneId'] = router['zone']['id'] if router['networkServer'].nil?
      option_result = Morpheus::Cli::OptionTypes.prompt(option_types, options[:options].deep_merge({:context_map => {'rule' => ''}}), @api_client, api_params, nil, true)
      payload = {'rule' => params.deep_merge(option_result)}
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.create_firewall_rule(router['id'], payload)
      return
    end

    json_response = @network_routers_interface.create_firewall_rule(router['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "\nAdded Network Router Firewall Rule #{payload['rule']['name']}\n"
    _firewall_rule(router['id'], json_response['id'], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_firewall_rule_group(args) ⇒ Object



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

def add_firewall_rule_group(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [name]")
    opts.on('-n', '--name VALUE', String, "Name for this firewall rule group") do |val|
      params['name'] = val
    end
    opts.on('-D', '--description VALUE', String, "Description for this firewall rule group") do |val|
      params['description'] = val
    end
    opts.on('--priority VALUE', Integer, "Priority for this firewall rule group (not applicable to all firewall types)") do |val|
      params['priority'] = val
    end
    add_perms_options(opts, options, ['plans', 'groups'])
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a network router firewall rule group."
  end
  optparse.parse!(args)
  connect(options)
  if args.count < 1 || args.count > 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1-2 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  if args.count > 1
    params['name'] = args[1]
  end
  begin
    router = find_router(args[0])

    if router.nil?
      return 1
    end

    if !router['type']['hasFirewallGroups']
      print_red_alert "Firewall rule groups not supported for #{router['type']['name']}"
      return 1
    end

    if options[:payload]
      payload = options[:payload]
    else
      params['name'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Group Name', 'required' => true}], options[:options], @api_client, params)['name']
      params['description'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'type' => 'text', 'fieldLabel' => 'Description', 'required' => false}], options[:options], @api_client, params)['description']

      if router['type']['hasSecurityGroupPriority']
        params['priority'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'priority', 'type' => 'number', 'fieldLabel' => 'Priority', 'required' => false}], options[:options], @api_client, params)['priority']
      end

      option_types = router['type']['ruleGroupOptionTypes'].reject {|it| ['name'].include?(it['fieldName'])}.sort {|it| it['displayOrder']}

      # prompt options
      option_result = Morpheus::Cli::OptionTypes.prompt(option_types, options[:options].deep_merge({:context_map => {'group' => ''}}), @api_client, {}, nil, true)

      rule_group = params.deep_merge(option_result)

      # prompt perms
      if 
        rule_group.merge!(prompt_permissions_v2(options, ['plans', 'groups']))
      end
      payload = {'ruleGroup' => rule_group}
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.create_firewall_rule_group(router['id'], payload)
      return
    end

    json_response = @network_routers_interface.create_firewall_rule_group(router['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "\nAdded Network Router Firewall Rule Group #{payload['ruleGroup']['name']}\n"
    _firewall_rule_group(router['id'], json_response['id'], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_nat(args) ⇒ Object



1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1706

def add_nat(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [name]")
    opts.on('-n', '--name VALUE', String, "Name for this NAT") do |val|
      params['name'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a network router NAT."
  end
  optparse.parse!(args)
  connect(options)
  if args.count < 1 || args.count > 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1-2 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  if args.count > 1
    params['name'] = args[1]
  end
  begin
    router = find_router(args[0])

    if router.nil?
      return 1
    end

    if !router['type']['hasNat']
      print_red_alert "NATs not supported for #{router['type']['name']}"
      return 1
    end

    if options[:payload]
      payload = options[:payload]
    else
      params['name'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Name', 'required' => true}], options[:options], @api_client, params)['name']

      option_types = router['type']['natOptionTypes'].reject {|it| ['name'].include?(it['fieldName'])}.sort {|it| it['displayOrder']}

      # prompt options
      option_result = Morpheus::Cli::OptionTypes.prompt(option_types, options[:options].deep_merge({:context_map => {'nat' => ''}}), @api_client, {'networkServer' => {'id' => router['networkServer']['id']}}, nil, true)
      payload = {'networkRouterNAT' => params.deep_merge(option_result)}
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.create_nat(router['id'], payload)
      return
    end

    json_response = @network_routers_interface.create_nat(router['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "\nAdded Network Router NAT #{payload['networkRouterNAT']['name']}\n"
    _nats(router['id'], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_route(args) ⇒ Object



1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
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
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1421

def add_route(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [name]")
    opts.on('-n', '--name VALUE', String, "Name for this route") do |val|
      params['name'] = val
    end
    opts.on('-D', '--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('--enabled [on|off]', String, "Can be used to enable / disable the route. Default is on") do |val|
      options[:enabled] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--default [on|off]', String, "Can be used to enable / disable as default route. Default is off") do |val|
      options[:defaultRoute] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--source VALUE', String, "Network for this route") do |val|
      params['source'] = val
    end
    opts.on('--destination VALUE', String, "Next hop for this route") do |val|
      params['destination'] = val
    end
    opts.on('--mtu VALUE', String, "MTU for this route") do |val|
      params['networkMtu'] = val
    end
    opts.on('--priority VALUE', Integer, "Priority for this route") do |val|
      params['priority'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a network router route."
  end
  optparse.parse!(args)
  connect(options)
  if args.count < 1 || args.count > 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1-2 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  if args.count > 1
    params['name'] = args[1]
  end
  begin
    router = find_router(args[0])

    if router.nil?
      return 1
    end

    if !router['type']['hasRouting']
      print_red_alert "Routes not supported for #{router['type']['name']}"
      return 1
    end

    if options[:payload]
      payload = options[:payload]
      payload = {'networkRoute' => payload['route']} if payload['route']
    else
      params['name'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Name', 'required' => true}], options[:options], @api_client, params)['name']
      params['description'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'type' => 'text', 'fieldLabel' => 'Description', 'required' => false}], options[:options], @api_client, params)['description']

      # prompt for enabled if not set
      params['enabled'] = options[:enabled].nil? ? Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'enabled', 'fieldLabel' => 'Enabled', 'type' => 'checkbox', 'description' => 'Enabling Route.', 'defaultValue' => true, 'required' => false}], options, @api_client, {})['enabled'] == 'on' : options[:enabled]

      # default route
      params['defaultRoute'] = options[:defaultRoute].nil? ? Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'defaultRoute', 'fieldLabel' => 'Default Route', 'type' => 'checkbox', 'description' => 'Default Route.', 'defaultValue' => false, 'required' => false}], options, @api_client, {})['defaultRoute'] == 'on' : options[:defaultRoute]

      params['source'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'source', 'type' => 'text', 'fieldLabel' => 'Network', 'required' => true}], options[:options], @api_client, params)['source']
      params['destination'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'destination', 'type' => 'text', 'fieldLabel' => 'Next Hop', 'required' => true}], options[:options], @api_client, params)['destination']
      params['networkMtu'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'networkMtu', 'type' => 'text', 'fieldLabel' => 'MTU', 'required' => false}], options[:options], @api_client, params)['networkMtu']
      params['priority'] ||= Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'priority', 'type' => 'number', 'fieldLabel' => 'Priority', 'required' => false}], options[:options], @api_client, params)['priority']

      payload = {'networkRoute' => params}
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.create_route(router['id'], payload)
      return
    end

    json_response = @network_routers_interface.create_route(router['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "\nAdded Network Router Route #{payload['networkRoute']['name']}"
    _routes(router['id'], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#bgp_neighbor(args) ⇒ Object



1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1937

def bgp_neighbor(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [BGP neighbor]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display details on network router BGP neighbor." + "\n" +
      "[router] is required. This is the name or id of a network router.\n" +
      "[BGP neighbor] is required. This is the id of a BGP neighbor.\n"
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 2
    puts optparse
    return 1
  end

  @network_routers_interface.setopts(options)
  if options[:dry_run]
    if args[0].to_s =~ /\A\d{1,}\Z/
      print_dry_run @network_routers_interface.dry.get(args[0].to_i)
    else
      print_dry_run @network_routers_interface.dry.list({name:args[0]})
    end
    return
  end
  router = find_router(args[0])
  if router.nil?
    return 1
  end

  if router['type']['hasBgp']
    bgp_neighbor = (router['bgpNeighbors'] || []).find {|it| it['id'] == args[1].to_i}

    if bgp_neighbor
      json_response = {'networkRouterBgpNeighbor' => bgp_neighbor}
      render_response(json_response, options, 'networkRouterBgpNeighbor') do
        print_h1 "Network Router BGP Neighbor Details"
        print cyan

        description_cols = {
          "ID" => lambda {|it| it['id']}
        }

        router['type']['bgpNeighborOptionTypes'].sort_by {|it| it['displayOrder']}.each do |option_type|
          description_cols[option_type['fieldLabel']] = lambda {|it| Morpheus::Cli::OptionTypes.get_option_value(it, option_type, true)}
        end
        print_description_list(description_cols, bgp_neighbor)
      end
    else
      print_red_alert "BGP Neighbors #{args[1]} not found for router #{router['name']}"
    end
  else
    print_red_alert "BGP Neighbors not supported for #{router['type']['name']}"
  end
  println reset
end

#bgp_neighbors(args) ⇒ Object



1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1890

def bgp_neighbors(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List network router BGP neighbors." + "\n" +
      "[router] is required. This is the name or id of a network router."
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 1
    puts optparse
    return 1
  end
  _bgp_neighbors(args[0], options)
end

#connect(opts) ⇒ Object



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

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @network_routers_interface = @api_client.network_routers
  @network_services_interface = @api_client.network_services
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
  @accounts_interface = @api_client.accounts
end

#dhcp(args) ⇒ Object



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

def dhcp(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router DHCP details." + "\n" +
        "[router] is required. This is the name or id of a network router."
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 1
    puts optparse
    return 1
  end

  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(args[0].to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:args[0]})
      end
      return
    end
    router = find_router(args[0])
    if router.nil?
      return 1
    end

    json_response = {'networkRouter' => router}

    if options[:json]
      puts as_json(json_response, options, "networkRouter")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networkRouter")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['networkRouter']], options)
      return 0
    end

    print_h1 "Network Router DHCP Details For: #{router['name']}"
    print cyan

    if router['type']['hasDhcp']
      print_dhcp(router, true)
    else
      print_red_alert "DHCP not supported for #{router['type']['name']}"
    end
    println reset
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#firewall(args) ⇒ Object



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

def firewall(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    opts.on('--details', "Display details." ) do
      options[:details] = true
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router firewall details." + "\n" +
        "[router] is required. This is the name or id of a network router."
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 1
    puts optparse
    return 1
  end

  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(args[0].to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:args[0]})
      end
      return
    end
    router = find_router(args[0])
    if router.nil?
      return 1
    end

    json_response = {'networkRouter' => router}

    if options[:json]
      puts as_json(json_response, options, "networkRouter")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networkRouter")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['networkRouter']], options)
      return 0
    end

    print_h1 "Network Router Firewall Details For: #{router['name']}"
    print cyan

    if router['type']['hasFirewall']
      print_firewall(router, options)
    else
      print_red_alert "Firewall not supported for #{router['type']['name']}"
    end
    println reset
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#firewall_rule(args) ⇒ Object



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

def firewall_rule(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [rule]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router firewall rule details." + "\n" +
      "[router] is required. This is the name or id of a network router.\n" +
      "[rule] is required. This is the name or id of a firewall rule.\n"
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 2
    puts optparse
    return 1
  end
  @network_routers_interface.setopts(options)
  if options[:dry_run]
    if args[0].to_s =~ /\A\d{1,}\Z/
      print_dry_run @network_routers_interface.dry.get(args[0].to_i)
    else
      print_dry_run @network_routers_interface.dry.list({name:args[0]})
    end
    return
  end
  _firewall_rule(args[0], args[1], options)
end

#firewall_rule_group(args) ⇒ Object



619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 619

def firewall_rule_group(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router firewall rule group details." + "\n" +
      "[router] is required. This is the name or id of a network router.\n" +
      "[group] is required. This is the name or id of a firewall rule group.\n"
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 2
    puts optparse
    return 1
  end
  _firewall_rule_group(args[0], args[1], options)
end

#firewall_rule_groups(args) ⇒ Object



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

def firewall_rule_groups(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router firewall rule groups.\n" +
      "[router] is required. This is the name or id of a network router."
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 1
    puts optparse
    return 1
  end

  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if router_id.to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(router_id.to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:router_id})
      end
      return
    end

    router = find_router(args[0])
    if router.nil?
      return 1
    end
    _firewall_rule_groups(router, options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#firewall_rules(args) ⇒ Object



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

def firewall_rules(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router firewall rules.\n" +
      "[router] is required. This is the name or id of a network router."
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 1
    puts optparse
    return 1
  end

  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(args[0].to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:args[0]})
      end
      return
    end
    router = find_router(args[0])
    if router.nil?
      return 1
    end

    _firewall_rules(router, options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#get(args) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 105

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    opts.on('--details', "Display details: firewall, DHCP, routing, and NATs." ) do
      options[:details] = true
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router details." + "\n" +
        "[router] is required. This is the name or id of a network router."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end

#handle(args) ⇒ Object



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

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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

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.footer = "List network routers."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.list(params)
      return
    end
    json_response = @network_routers_interface.list(params)
    routers = json_response["networkRouters"]
    if options[:json]
      puts as_json(json_response, options, "networkRouters")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "networkRouters")
      return 0
    elsif options[:csv]
      puts records_as_csv(routers, options)
      return 0
    end
    title = "Morpheus Network Routers"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if routers.empty?
      print cyan,"No network routers found.",reset,"\n"
    else
      # STATUS	NAME	ROUTER TYPE	SERVICE	NETWORKS	EXTERNAL IP
      rows = routers.collect {|router|
        row = {
          id: router['id'],
          name: router['name'],
          status: format_router_status(router),
          router_type: (router['type'] || {})['name'],
          group: router['site'] ? router['site']['name'] : 'Shared',
          service: (router['networkServer'] || {})['name'],
          networks: (router['externalNetwork'] || {})['name'],
          external_ip: router['externalIp']
        }
        row
      }
      columns = [:id, :name, :status, :router_type, :group, :service, :networks, :external_ip]
      if options[:include_fields]
        columns = options[:include_fields]
      end
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      if json_response['meta']
        print_results_pagination(json_response, {:label => "network routers", :n_label => "network routers"})
      else
        print_results_pagination({'meta'=>{'total'=>rows.size,'size'=>rows.size,'max'=>options[:max] || rows.size,'offset'=>0}}, {:label => "network routers", :n_label => "network routers"})
      end
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#nat(args) ⇒ Object



1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1628

def nat(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [nat]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Display network router firewall rule details." + "\n" +
      "[router] is required. This is the name or id of a network router.\n" +
      "[nat] is required. This is the name or id of a NAT.\n"
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 2
    puts optparse
    return 1
  end

  begin
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @network_routers_interface.dry.get(args[0].to_i)
      else
        print_dry_run @network_routers_interface.dry.list({name:args[0]})
      end
      return
    end
    router = find_router(args[0])
    if router.nil?
      return 1
    end

    if router['type']['hasNat']
      nat = (router['nats'] || []).find {|it| it['id'] == args[1].to_i || it['name'] == args[1]}

      if nat
        json_response = {'networkRouterNAT' => nat}

        if options[:json]
          puts as_json(json_response, options, "networkRouterNAT")
          return 0
        elsif options[:yaml]
          puts as_yaml(json_response, options, "networkRouterNAT")
          return 0
        elsif options[:csv]
          puts records_as_csv([json_response['networkRouterNAT']], options)
          return 0
        end

        print_h1 "Network Router NAT Details"
        print cyan

        description_cols = {
          "ID" => lambda {|it| it['id'] },
          "Name" => lambda {|it| it['name'] },
          "Description" => lambda {|it| it['description'] },
          "Enabled" => lambda {|it| format_boolean(it['enabled'])},
          "Source Network" => lambda {|it| it['sourceNetwork']},
          "Destination Network" => lambda {|it| it['destinationNetwork']},
          "Translated Network" => lambda {|it| it['translatedNetwork']},
          "Translated Port" => lambda {|it| it['translatedPorts']},
          "Priority" => lambda {|it| it['priority'] }
        }
        print_description_list(description_cols, nat)
      else
        print_red_alert "NAT #{args[1]} not found for router #{router['name']}"
      end
    else
      print_red_alert "NATs not supported for #{router['type']['name']}"
    end
    println reset
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#nats(args) ⇒ Object



1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1565

def nats(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List network router NATs." + "\n" +
      "[router] is required. This is the name or id of a network router."
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 1
    puts optparse
    return 1
  end
  _nats(args[0], options)
end

#remove(args) ⇒ Object



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

def remove(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a network router.\n" +
        "[router] is required. This is the name or id of an existing network router."
  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
    router = find_router(args[0])

    return if !router

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the network router '#{router['name']}'?", options)
      return 9, "aborted command"
    end
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.destroy(router['id'], query_params)
      return
    end
    json_response = @network_routers_interface.destroy(router['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Network router #{router['name']} is being removed..."
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_bgp_neighbor(args) ⇒ Object



2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 2107

def remove_bgp_neighbor(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [BGP neighbor]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a network router BGP neighbor.\n" +
      "[router] is required. This is the name or id of an existing network router."
      "[BGP neighbor] is required. This is the id of an existing network router BGP neighbor."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  router = find_router(args[0])
  return if !router

  if !router['type']['hasBgp']
    print_red_alert "BGP not supported for #{router['type']['name']}"
    return 1
  end

  bgp_neighbor = router['bgpNeighbors'] ? router['bgpNeighbors'].find {|it| it['id'] == args[1].to_i} : nil

  if !bgp_neighbor
    print_red_alert "BGP neighbor #{args[1]} not found for router #{router['name']}"
    exit 1
  end

  unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the BGP neighbor '#{bgp_neighbor['id']}' from router '#{router['name']}'?", options)
    return 9, "aborted command"
  end
  @network_routers_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @network_routers_interface.dry.destroy_bgp_neighbor(router['id'], bgp_neighbor['id'])
    return
  end
  json_response = @network_routers_interface.destroy_bgp_neighbor(router['id'], bgp_neighbor['id'])
  render_response(json_response, options, 'networkRouterBgpNeighbor') do
    print_green_success "\nDeleted Network Router BGP Neighbor #{bgp_neighbor['id']}\n"
    _bgp_neighbors(router['id'], options)
  end
end

#remove_firewall_rule(args) ⇒ Object



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

def remove_firewall_rule(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [rule]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a network router firewall rule.\n" +
        "[router] is required. This is the name or id of an existing network router."
        "[rule] is required. This is the name or id of an existing network router firewall rule."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    router = find_router(args[0])
    return if !router

    rule = find_firewall_rule(router, args[1])

    if !rule
      print_red_alert "Firewall rule #{args[1]} not found for router #{router['name']}"
      exit 1
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the firewall rule '#{rule['name']}' from router '#{router['name']}'?", options)
      return 9, "aborted command"
    end
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.destroy_firewall_rule(router['id'], rule['id'])
      return
    end
    json_response = @network_routers_interface.destroy_firewall_rule(router['id'], rule['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "\nFirewall rule #{rule['name']} for router #{router['name']} is being removed...\n"
      _firewall_rules(find_router(router['id']), options)
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_firewall_rule_group(args) ⇒ Object



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

def remove_firewall_rule_group(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [group]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a network router firewall rule group.\n" +
      "[router] is required. This is the name or id of an existing network router."
      "[group] is required. This is the name or id of an existing network router firewall rule group."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    router = find_router(args[0])
    return if !router

    group = router['firewall'] && router['firewall']['ruleGroups'] ? router['firewall']['ruleGroups'].find {|it| it['name'] == args[1] || it['id'] == args[1].to_i} : nil

    if !group
      print_red_alert "Firewall rule group #{args[1]} not found for router #{router['name']}"
      exit 1
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the firewall rule group '#{group['name']}' from router '#{router['name']}'?", options)
      return 9, "aborted command"
    end
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.destroy_firewall_rule_group(router['id'], group['id'])
      return
    end
    json_response = @network_routers_interface.destroy_firewall_rule_group(router['id'], group['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "\nFirewall rule group #{group['name']} for router #{router['name']} is being removed...\n"
      _firewall_rule_groups(find_router(router['id']), options)
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_nat(args) ⇒ Object



1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1836

def remove_nat(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [NAT]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a network router NAT.\n" +
      "[router] is required. This is the name or id of an existing network router."
      "[NAT] is required. This is the name or id of an existing network router NAT."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    router = find_router(args[0])
    return if !router

    if !router['type']['hasNat']
      print_red_alert "NATs not supported for #{router['type']['name']}"
      return 1
    end

    nat = router['nats'] ? router['nats'].find {|it| it['name'] == args[1] || it['id'] == args[1].to_i} : nil

    if !nat
      print_red_alert "NAT #{args[1]} not found for router #{router['name']}"
      exit 1
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the NAT '#{nat['name']}' from router '#{router['name']}'?", options)
      return 9, "aborted command"
    end
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.destroy_nat(router['id'], nat['id'])
      return
    end
    json_response = @network_routers_interface.destroy_nat(router['id'], nat['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "\nNAT #{nat['name']} for router #{router['name']} is being removed...\n"
      _nats(router['id'], options)
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_route(args) ⇒ Object



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

def remove_route(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router] [route]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a network router route.\n" +
      "[router] is required. This is the name or id of an existing network router."
      "[route] is required. This is the name or id of an existing network router route."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  begin
    router = find_router(args[0])
    return if !router

    route = router['routes'] ? router['routes'].find {|it| it['name'] == args[1] || it['id'] == args[1].to_i} : nil

    if !route
      print_red_alert "Route #{args[1]} not found for router #{router['name']}"
      exit 1
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the route '#{route['name']}' from router '#{router['name']}'?", options)
      return 9, "aborted command"
    end
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.destroy_route(router['id'], route['id'])
      return
    end
    json_response = @network_routers_interface.destroy_route(router['id'], route['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "\nRoute #{route['name']} for router #{router['name']} is being removed..."
      _routes(router['id'], options)
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#routes(args) ⇒ Object



1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1358

def routes(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[router]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List network router routes." + "\n" +
        "[router] is required. This is the name or id of a network router."
  end

  optparse.parse!(args)
  connect(options)

  if args.count < 1
    puts optparse
    return 1
  end
  _routes(args[0], options)
end

#type(args) ⇒ Object



2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 2199

def type(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[type]")
    opts.on('-t', '--type VALUE', String, "Name or ID of router type") do |val|
      options[:options]['routerType'] = val
    end
    build_common_options(opts, options, [:list, :json, :dry_run, :remote])
    opts.footer = "Display network router type details."
  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}) #{args.inspect}\n#{optparse}"
    return 1
  end

  if args.count > 0
    options[:options]['routerType'] = args[0]
  end

  begin
    connect(options)
    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.types(params)
      return
    end

    router_type = prompt_router_type(options)

    if options[:json]
      print JSON.pretty_generate({'networkRouterType' => router_type})
      print "\n"
      return
    end

    print_h1 "Network Router Type Details For: #{router_type['name']}"
    print cyan

    description_cols = {
        "ID" => lambda {|it| it['id'] },
        "Name" => lambda {|it| it['name'] },
        "Code" => lambda {|it| it['code'] },
        "Enabled" => lambda {|it| format_boolean(it['enabled'])},
        "Creatable" => lambda {|it| format_boolean(it['creatable'])},
        "Selectable" => lambda {|it| format_boolean(it['selectable'])},
        "Firewall" => lambda {|it| format_boolean(it['hasFirewall'])},
        "DHCP" => lambda {|it| format_boolean(it['hasDhcp'])},
        "Routing" => lambda {|it| format_boolean(it['hasRouting'])},
        "Network Server" => lambda {|it| format_boolean(it['hasNetworkServer'])}
    }
    print_description_list(description_cols, router_type)

    {'optionTypes' => 'Router', 'ruleOptionTypes' => 'Firewall Rule', 'ruleGroupOptionTypes' => 'Firewall Rule Group', 'natOptionTypes' => 'NAT', 'bgpNeighborOptionTypes' => 'BGP Neighbor'}.each_pair do |field, title|
      if !router_type[field].nil? && router_type[field].count > 0
        println cyan
        print Morpheus::Cli::OptionTypes.display_option_types_help(
          router_type[field].reject {|it| ['enabled'].include?(it['fieldName'])},
          {:include_context => true, :context_map => {'networkRouter' => ''}, :color => cyan, :title => "Available #{title} Options"}
        )
      end
    end
    print reset
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#types(args) ⇒ Object



2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 2152

def types(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "List network router types."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.types(params)
      return
    end

    json_response = @network_routers_interface.types(params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end

    title = "Morpheus Network Router Types"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    router_types = json_response['networkRouterTypes']

    if router_types.empty?
      println yellow,"No network router types found.",reset
    else
      print as_pretty_table(router_types, {'ID' => 'id', 'NAME' => 'name'}, options)
    end
    println reset
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



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

def update(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router]")
    opts.on('-n', '--name VALUE', String, "Name for this network") do |val|
      params['name'] = val
    end
    opts.on('-D', '--description VALUE', String, "Description for this network") do |val|
      params['description'] = val
    end
    opts.on('--enabled [on|off]', String, "Can be used to enable / disable the network router. Default is on") do |val|
      options[:enabled] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network router."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end

  begin
    router = find_router(args[0])
    if router.nil?
      return 1
    end

    payload = parse_payload(options)

    if payload.nil?
      if !options[:enabled].nil?
        params['enabled'] = options[:enabled]
      end

      if options[:options]
        params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) || ['name', 'routerType', 'enabled', 'description'].include?(k)})
      end
      payload = {'networkRouter' => params}
    end

    if payload['networkRouter'].empty?
      print_green_success "Nothing to update"
      return
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.update(router['id'], payload)
      return
    end

    json_response = @network_routers_interface.update(router['id'], payload)

    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Network router updated"
        _get(router['id'], options)
      else
        print_red_alert "Error updating network router: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_bgp_neighbor(args) ⇒ Object



2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 2046

def update_bgp_neighbor(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [BGP neighbor]")
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network router BGP neighbor.\n" +
      "[router] is required. This is the name or id of an existing network router.\n" +
      "[BGP neighbor] is required. This is the id of an existing network router BGP neighbor."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)

  router = find_router(args[0])

  if router.nil?
    return 1
  end

  if !router['type']['hasBgp']
    print_red_alert "BGP not supported for #{router['type']['name']}"
    return 1
  end

  bgp_neighbor = router['bgpNeighbors'] ? router['bgpNeighbors'].find {|it| it['id'] == args[1].to_i} : nil

  if !bgp_neighbor
    print_red_alert "BGP neighbor #{args[1]} not found for router #{router['name']}"
    exit 1
  end

  payload = parse_payload(options) || {'networkRouterBgpNeighbor' => params}
  payload['networkRouterBgpNeighbor'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options] && !payload['networkRouterBgpNeighbor'].nil?

  if payload['networkRouterBgpNeighbor'].empty?
    option_types = router['type']['bgpNeighborOptionTypes'].sort_by {|it| it['displayOrder']}
    print_green_success "Nothing to update"
    println cyan
    print Morpheus::Cli::OptionTypes.display_option_types_help(
      option_types,
      {:include_context => true, :context_map => {'bgpNeighbor' => ''}, :color => cyan, :title => "Available BGP Neighbor Options"}
    )
    exit 1
  end

  @network_routers_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @network_routers_interface.dry.update_bgp_neighbor(router['id'], bgp_neighbor['id'], payload)
    return
  end

  json_response = @network_routers_interface.update_bgp_neighbor(router['id'], bgp_neighbor['id'], payload)
  render_response(json_response, options, 'networkRouterBgpNeighbor') do
    print_green_success "\nUpdated Network Router BGP Neighbor #{bgp_neighbor['id']}\n"
    _bgp_neighbors(router['id'], options)
  end
end

#update_firewall_rule(args) ⇒ Object



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

def update_firewall_rule(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [name]")
    opts.on('-n', '--name VALUE', String, "Name for this firewall rule") do |val|
      params['name'] = val
    end
    opts.on('--enabled [on|off]', String, "Can be used to enable / disable the rule. Default is on") do |val|
      params['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on('--priority VALUE', Integer, "Priority for this rule (not applicable to all firewall types)") do |val|
      params['priority'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network router firewall rule.\n" +
      "[router] is required. This is the name or id of an existing network router.\n" +
      "[name] is required. This is the name or id of an existing network router firewall rule."
  end

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

  begin
    router = find_router(args[0])

    if router.nil?
      return 1
    end

    if !router['type']['hasFirewall']
      print_red_alert "Firewall not supported for #{router['type']['name']}"
      return 1
    end

    rule = find_firewall_rule(router, args[1])

    if !rule
      print_red_alert "Firewall rule #{args[1]} not found for router #{router['name']}"
      exit 1
    end

    payload = parse_payload(options) || {'rule' => params}
    payload['rule'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    if payload['rule'].empty?
      print_green_success "Nothing to update"
      exit 1
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.update_firewall_rule(router['id'], rule['id'], payload)
      return
    end

    json_response = @network_routers_interface.update_firewall_rule(router['id'], rule['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "\nUpdated Network Router Firewall Rule #{payload['rule']['name']}\n"
    _firewall_rule(router['id'], args[1], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_firewall_rule_group(args) ⇒ Object



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

def update_firewall_rule_group(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [name]")
    opts.on('-n', '--name VALUE', String, "Name for this firewall rule group") do |val|
      params['name'] = val
    end
    opts.on('-D', '--description VALUE', String, "Description for this firewall rule group") do |val|
      params['description'] = val
    end
    opts.on('--priority VALUE', Integer, "Priority for this firewall rule group (not applicable to all firewall types)") do |val|
      params['priority'] = val
    end
    add_perms_options(opts, options, ['plans', 'groups'])
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network router firewall rule group.\n" +
      "[router] is required. This is the name or id of an existing network router.\n" +
      "[name] is required. This is the name or id of an existing network router firewall rule group."
  end

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

  begin
    router = find_router(args[0])

    if router.nil?
      return 1
    end

    if !router['type']['hasFirewallGroups']
      print_red_alert "Firewall rule group not supported for #{router['type']['name']}"
      return 1
    end

    group = router['firewall'] && router['firewall']['ruleGroups'] ? router['firewall']['ruleGroups'].find {|it| it['name'] == args[1] || it['id'] == args[1].to_i} : nil

    if !group
      print_red_alert "Firewall rule group #{args[1]} not found for router #{router['name']}"
      exit 1
    end

    if 
      params['visibility'] = options[:visibility] if !options[:visibility].nil?
      params['tenants'] = options[:tenants].collect {|it| {'id' => it}} if !options[:tenants].nil?
    end

    payload = parse_payload(options) || {'ruleGroup' => params}
    payload['ruleGroup'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    if payload['ruleGroup'].empty?
      print_green_success "Nothing to update"
      exit 1
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.update_firewall_rule_group(router['id'], group['id'], payload)
      return
    end

    json_response = @network_routers_interface.update_firewall_rule_group(router['id'], group['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "\nUpdated Network Router Firewall Rule Group #{payload['ruleGroup']['name']}\n"
    _firewall_rule_group(router['id'], args[1], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_nat(args) ⇒ Object



1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 1771

def update_nat(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router] [NAT]")
    opts.on('-n', '--name VALUE', String, "Name for this NAT") do |val|
      params['name'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network router NAT.\n" +
      "[router] is required. This is the name or id of an existing network router.\n" +
      "[NAT] is required. This is the name or id of an existing network router NAT."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}"
  end
  connect(options)
  begin
    router = find_router(args[0])

    if router.nil?
      return 1
    end

    if !router['type']['hasNat']
      print_red_alert "NATs not supported for #{router['type']['name']}"
      return 1
    end

    nat = router['firewall'] && router['nats'] ? router['nats'].find {|it| it['name'] == args[1] || it['id'] == args[1].to_i} : nil

    if !nat
      print_red_alert "NAT #{args[1]} not found for router #{router['name']}"
      exit 1
    end

    payload = parse_payload(options) || {'networkRouterNAT' => params}
    payload['networkRouterNAT'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options] && !payload['networkRouterNAT'].nil?

    if payload['networkRouterNAT'].empty?
      print_green_success "Nothing to update"
      exit 1
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.update_nat(router['id'], nat['id'], payload)
      return
    end

    json_response = @network_routers_interface.update_nat(router['id'], nat['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end
    print_green_success "\nUpdated Network Router NAT #{nat['name']}\n"
    _nats(router['id'], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_permissions(args) ⇒ Object



2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
# File 'lib/morpheus/cli/commands/network_routers_command.rb', line 2271

def update_permissions(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[router]")
    add_perms_options(opts, options, ['plans', 'groups'])
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a network router permissions.\n" +
        "[router] is required. This is the name or id of an existing network router."
  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
    if !
      print_red_alert "Permissions only available for master tenant"
      return 1
    end

    router = find_router(args[0])
    return 1 if router.nil?

    if options[:payload]
      payload = options[:payload]
      # support -O OPTION switch on top of --payload
      if options[:options]
        payload['permissions'] ||= {}
        payload['permissions'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) })
      end
    else
      perms = {}
      if !options[:visibility].nil?
        perms['visibility'] = options[:visibility]
      end
      if !options[:tenants].nil?
        perms['tenantPermissions'] = {'accounts' => options[:tenants].collect {|id| id.to_i}}
      end
      payload = {'permissions' => perms}
    end

    @network_routers_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @network_routers_interface.dry.update_permissions(router['id'], payload)
      return
    end
    json_response = @network_routers_interface.update_permissions(router['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif json_response['success']
      print_green_success "\nUpdated Network Router Permissions\n"
    else
      print_rest_errors(json_response, options)
    end
  end
end