Class: Morpheus::Cli::NetworkRoutersCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, InfrastructureHelper, ProvisioningHelper, WhoamiHelper
Defined in:
lib/morpheus/cli/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_resize_volumes, #prompt_security_groups, #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_type_by_id, #find_network_type_by_name, #find_network_type_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, #get_available_cloud_types, #groups_interface, included, #network_groups_interface, #network_types_interface, #networks_interface, #prompt_for_network, #prompt_for_networks, #prompt_for_subnets, #subnet_types_interface, #subnets_interface

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_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, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #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.



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

def initialize()
end

Instance Method Details

#_firewall(router_id, options) ⇒ Object



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

def _firewall(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 = {'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

    if !options[:rules_only]
      print_h1 "Network Router Firewall Details for: #{router['name']}"
    end

    print cyan

    if router['type']['hasFirewall']
      print_firewall(router, true, options[:rules_only])
    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

#_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
# File 'lib/morpheus/cli/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[:details])
    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['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

#_routes(router_id, options) ⇒ Object



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

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 = {'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 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



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

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
    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 = avail_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[:server]
          server = find_network_server(options[:server])
          if server.nil?
            print_red_alert "Network server #{options[: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
        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'])}.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_firewall_rule(args) ⇒ Object



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/morpheus/cli/network_routers_command.rb', line 529

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
    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']

      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 => {'networkRouter' => ''}}), @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(router['id'], options.merge({:rules_only => true}))
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_route(args) ⇒ Object



769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/morpheus/cli/network_routers_command.rb', line 769

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
    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]
    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' => true}], 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 ruote
      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' => true}], options[:options], @api_client, params)['networkMtu']

      payload = {'route' => 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['route']['name']}"
    _routes(router['id'], options)
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



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

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

#dhcp(args) ⇒ Object



646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
# File 'lib/morpheus/cli/network_routers_command.rb', line 646

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



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/morpheus/cli/network_routers_command.rb', line 463

def firewall(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 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
  _firewall(args[0], options)
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/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, and routing." ) 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/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/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

#remove(args) ⇒ Object



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/morpheus/cli/network_routers_command.rb', line 422

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_firewall_rule(args) ⇒ Object



597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/morpheus/cli/network_routers_command.rb', line 597

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 = router['firewall'] && router['firewall']['rules'] ? router['firewall']['rules'].find {|it| it['name'] == args[1] || it['id'] == args[1].to_i} : nil

    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(router['id'], options.merge({:rules_only => true}))
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_route(args) ⇒ Object



859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/morpheus/cli/network_routers_command.rb', line 859

def remove_route(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 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



706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/morpheus/cli/network_routers_command.rb', line 706

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



955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'lib/morpheus/cli/network_routers_command.rb', line 955

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)

    if router_type['optionTypes'].count > 0
      println cyan
      print Morpheus::Cli::OptionTypes.display_option_types_help(
          router_type['optionTypes'].reject {|it| ['enabled'].include?(it['fieldName'])},
          {:include_context => true, :context_map => {'networkRouter' => ''}, :color => cyan, :title => "Available Router Options"}
      )
    end
    print reset
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#types(args) ⇒ Object



908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
# File 'lib/morpheus/cli/network_routers_command.rb', line 908

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



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/morpheus/cli/network_routers_command.rb', line 354

def update(args)
  options = {:options=>{}}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[router]")
    opts.on('-D', '--description VALUE', String, "Description") do |val|
      params['description'] = val
    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'].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_permissions(args) ⇒ 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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
# File 'lib/morpheus/cli/network_routers_command.rb', line 1025

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