Class: Morpheus::Cli::Apps
Instance Attribute Summary
Attributes included from CliCommand
#no_prompt
Instance Method Summary
collapse
#api_client, #execution_request_interface, included, #wait_for_execution_request
Methods included from LogsHelper
#clusters_interface, #containers_interface, #format_log_level, #format_log_records, #format_log_table, included, #instances_interface, #logs_interface, #servers_interface
#format_process_duration, #format_process_error, #format_process_output, #format_process_status, included, #print_process_details, #print_process_event_details
#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
#find_available_user_option, #find_cloud_option, #find_group_option, #find_tenant_option, #get_available_user_options, #get_cloud_options, #get_group_options, #get_tenant_options, included, #load_option_source_data, #options_interface, #parse_cloud_id_list, #parse_group_id_list, #parse_option_source_id_list, #parse_project_id_list, #parse_tenant_id_list, #parse_user_id_list
#account_column_definitions, #account_users_interface, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_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
#initialize ⇒ Apps
Returns a new instance of Apps.
26
27
28
|
# File 'lib/morpheus/cli/commands/apps.rb', line 26
def initialize()
end
|
Instance Method Details
#_get(id, options = {}) ⇒ Object
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
|
# File 'lib/morpheus/cli/commands/apps.rb', line 670
def _get(id, options={})
app = nil
if id.to_s !~ /\A\d{1,}\Z/
app = find_app_by_name_or_id(id)
id = app['id']
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.get(id)
return
end
json_response = @apps_interface.get(id.to_i)
render_response(json_response, options, 'app') do
app = json_response['app']
app_tiers = []
instances = []
if app['appTiers'] && !app['appTiers'].empty?
app_tiers = app['appTiers']
app_tiers.each do |app_tier|
instances += (app_tier['appInstances'] || []).collect {|it| it['instance']}.flatten().compact
end
elsif app['instances'] && !app['instances'].empty?
instance_ids = app['instances'].collect {|it| it['id'] }
instances = @instances_interface.list({id: instance_ids})['instances']
end
print_h1 "App Details", [], options
print cyan
description_cols = {
"ID" => 'id',
"Name" => 'name',
"Labels" => lambda {|it| format_list(it['labels']) rescue '' },
"Description" => 'description',
"Type" => lambda {|it|
if it['type']
format_blueprint_type(it['type'])
else
format_blueprint_type(it['blueprint'] ? it['blueprint']['type'] : nil)
end
},
"Blueprint" => lambda {|it| it['blueprint'] ? it['blueprint']['name'] : '' },
"Group" => lambda {|it| it['group'] ? it['group']['name'] : it['siteId'] },
"Environment" => lambda {|it| it['appContext'] },
"Owner" => lambda {|it| it['owner'] ? it['owner']['username'] : '' },
"Tiers" => lambda {|it|
tiers = []
app_tiers.each do |app_tier|
tiers << app_tier['tier']
end
"(#{(tiers || []).size()}) #{tiers.collect {|it| it.is_a?(Hash) ? it['name'] : it }.join(',')}"
},
"Instances" => lambda {|it|
"(#{instances.count}) #{instances.collect {|it| it['name'] }.join(',')}"
},
"Containers" => lambda {|it|
containers = []
instances.each do |instance|
containers += (instance['containers'] || [])
end
"(#{containers.count}) #{containers.collect {|it| it }.join(',')}"
},
"Status" => lambda {|it| format_app_status(it) }
}
description_cols["Removal Date"] = lambda {|it| format_local_dt(it['removalDate'])} if app['status'] == 'pendingRemoval'
print_description_list(description_cols, app)
stats = app['stats']
if app['instanceCount'].to_i > 0
print_h2 "App Usage", options
print_stats_usage(stats, {include: [:memory, :storage]})
end
if app_tiers.empty?
print reset,"\n"
if instances.empty?
print cyan, "This app is empty", reset, "\n\n"
else
print_h2 "Instances", options
instances_rows = instances.collect do |instance|
connection_string = ''
if !instance['connectionInfo'].nil? && instance['connectionInfo'].empty? == false
connection_string = "#{instance['connectionInfo'][0]['ip']}:#{instance['connectionInfo'][0]['port']}"
end
{id: instance['id'], name: instance['name'], connection: connection_string, environment: instance['instanceContext'], nodes: (instance['containers'] || []).count, status: format_instance_status(instance), type: instance['instanceType']['name'], group: !instance['group'].nil? ? instance['group']['name'] : nil, cloud: !instance['cloud'].nil? ? instance['cloud']['name'] : nil}
end
instances_rows = instances_rows.sort {|x,y| x[:id] <=> y[:id] } print cyan
print as_pretty_table(instances_rows, [:id, :name, :cloud, :type, :environment, :nodes, :connection, :status], {border_style: options[:border_style]})
print reset
print "\n"
end
else
app_tiers.each do |app_tier|
print_h2 "#{app_tier['tier']['name']}", options
print cyan
tier_instances = (app_tier['appInstances'] || []).collect {|it| it['instance']}
instance_list = tier_instances.collect { |tier_instance| instances.find { |i| i['id'] == tier_instance['id'] } }
if instance_list.empty?
puts yellow, "This tier is empty", reset
else
instances_rows = instance_list.collect do |instance|
connection_string = ''
if !instance['connectionInfo'].nil? && instance['connectionInfo'].empty? == false
connection_string = "#{instance['connectionInfo'][0]['ip']}:#{instance['connectionInfo'][0]['port']}"
end
{id: instance['id'], name: instance['displayName'] ? instance['displayName'] : instance['name'], connection: connection_string, environment: instance['instanceContext'], nodes: (instance['containers'] || []).count, status: format_instance_status(instance), type: instance['instanceType']['name'], group: !instance['group'].nil? ? instance['group']['name'] : nil, cloud: !instance['cloud'].nil? ? instance['cloud']['name'] : nil}
end
instances_rows = instances_rows.sort {|x,y| x[:id] <=> y[:id] } print cyan
print as_pretty_table(instances_rows, [:id, :name, :cloud, :type, :environment, :nodes, :connection, :status], {border_style: options[:border_style]})
print reset
print "\n"
end
end
end
print cyan
if options[:refresh_until_status]
if options[:refresh_interval].nil? || options[:refresh_interval].to_f < 0
options[:refresh_interval] = default_refresh_interval
end
statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
if !statuses.include?(app['status'])
print cyan, "Refreshing in #{options[:refresh_interval] > 1 ? options[:refresh_interval].to_i : options[:refresh_interval]} seconds"
sleep_with_dots(options[:refresh_interval])
print "\n"
_get(app['id'], options)
end
end
end
return 0, nil
end
|
#_restart(app_id, options) ⇒ Object
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1775
def _restart(app_id, options)
app = find_app_by_name_or_id(app_id)
return 1 if app.nil?
tier_records = (app)
if options[:dry_run]
print_h1 "Dry Run", [], options
end
tier_records.each do |tier_record|
tier_record[:instances].each do |instance|
restart_cmd = "instances restart #{instance['id']} -y"
if options[:dry_run]
puts restart_cmd
else
my_terminal.execute(restart_cmd)
end
end
end
return 0
end
|
#_start(app_id, options) ⇒ Object
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1731
def _start(app_id, options)
app = find_app_by_name_or_id(app_id)
return 1 if app.nil?
tier_records = (app)
if options[:dry_run]
print_h1 "Dry Run", [], options
end
tier_records.each do |tier_record|
tier_record[:instances].each do |instance|
start_cmd = "instances start #{instance['id']} -y"
if options[:dry_run]
puts start_cmd
else
my_terminal.execute(start_cmd)
end
end
end
return 0
end
|
#_stop(app_id, options) ⇒ Object
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1687
def _stop(app_id, options)
app = find_app_by_name_or_id(app_id)
return 1 if app.nil?
tier_records = (app)
if options[:dry_run]
print_h1 "Dry Run", [], options
end
tier_records.each do |tier_record|
tier_record[:instances].each do |instance|
stop_cmd = "instances stop #{instance['id']} -y"
if options[:dry_run]
puts stop_cmd
else
my_terminal.execute(stop_cmd)
end
end
end
return 0
end
|
#_view(arg, options = {}) ⇒ Object
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/apps.rb', line 2131
def _view(arg, options={})
begin
app = find_app_by_name_or_id(arg)
return 1 if app.nil?
link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/provisioning/apps/#{app['id']}"
if options[:link_tab]
link << "#!#{options[:link_tab]}"
end
if options[:dry_run]
puts Morpheus::Util.open_url_command(link)
return 0
end
return Morpheus::Util.open_url(link)
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#add(args) ⇒ Object
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
|
# File 'lib/morpheus/cli/commands/apps.rb', line 211
def add(args)
options = {}
params = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[name] [options]")
opts.on( '-b', '--blueprint BLUEPRINT', "Blueprint Name or ID. The default value is 'existing' which means no blueprint, for creating a blank app and adding existing instances." ) do |val|
options[:blueprint] = val
end
opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
options[:group] = val
end
opts.on( '-c', '--cloud CLOUD', "Default Cloud Name or ID." ) do |val|
options[:cloud] = val
end
opts.on( '--name VALUE', String, "Name" ) do |val|
options[:name] = val
end
opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
options[:options]['labels'] = parse_labels(val)
end
opts.on( '--description VALUE', String, "Description" ) do |val|
options[:description] = val
end
opts.on( '-e', '--environment VALUE', "Environment Name" ) do |val|
options[:environment] = val.to_s == 'null' ? nil : val
end
opts.on('--validate','--validate', "Validate Only. Validates the configuration and skips creating it.") do
options[:validate_only] = true
end
opts.on('--refresh [SECONDS]', String, "Refresh until status is running,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
end
build_common_options(opts, options, [:options, :payload, :json, :yaml, :dry_run, :quiet])
opts. = "Create a new app.\n" +
"[name] is required. This is the name of the new app. It may also be passed as --name or inside your config."
end
optparse.parse!(args)
if args.count > 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} add expects 0-1 arguments and received #{args.count}: #{args}\n#{optparse}"
return 1
end
if args[0] options[:name] = args[0]
end
connect(options)
begin
options[:options] ||= {}
passed_options = (options[:options] || {}).reject {|k,v| k.is_a?(Symbol) }
payload = {}
if options[:payload]
payload = options[:payload]
payload.deep_merge!(passed_options) unless passed_options.empty?
[:name, :description, :environment].each do |k|
if options.key?(k)
payload[k.to_s] = options[k]
end
end
else
payload = {}
payload.deep_merge!(passed_options) unless passed_options.empty?
blueprint_id = 'existing'
blueprint = nil
if options[:blueprint]
blueprint_id = options[:blueprint]
options[:options]['blueprint'] = options[:blueprint]
end
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'blueprint', 'fieldLabel' => 'Blueprint', 'type' => 'select', 'selectOptions' => get_available_blueprints(), 'required' => true, 'defaultValue' => 'existing', 'description' => "The blueprint to use. The default value is 'existing' which means no template, for creating a blank app and adding existing instances."}], options[:options])
blueprint_id = v_prompt['blueprint']
if blueprint_id.to_s.empty? || blueprint_id == 'existing'
blueprint = {"id" => "existing", "name" => "Existing Instances", "value" => "existing", "type" => "morpheus"}
else
blueprint = find_blueprint_by_name_or_id(blueprint_id)
if blueprint.nil?
return 1
end
end
payload['templateId'] = blueprint['id'] payload['blueprintId'] = blueprint['id']
payload['blueprintName'] = blueprint['name']
options[:options]['name'] = options[:name] if options.key?(:name)
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Enter a name for this app'}], options[:options])
payload['name'] = v_prompt['name']
options[:options]['description'] = options[:description] if options.key?(:description)
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'required' => false}], options[:options])
payload['description'] = v_prompt['description']
group_id = nil
options[:options]['group'] = options[:group] if options.key?(:group)
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'fieldLabel' => 'Group', 'type' => 'select', 'selectOptions' => get_available_groups(), 'required' => true, 'defaultValue' => @active_group_id}], options[:options])
group_id = v_prompt['group']
group = find_group_by_name_or_id_for_provisioning(group_id)
return 1 if group.nil?
payload['group'] = {'id' => group['id'], 'name' => group['name']}
cloud_id = nil
cloud = nil
scoped_available_clouds = get_available_clouds(group['id'])
if options[:cloud]
cloud_id = options[:cloud]
else
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'fieldLabel' => 'Default Cloud', 'type' => 'select', 'selectOptions' => scoped_available_clouds}], options[:options])
cloud_id = v_prompt['cloud'] unless v_prompt['cloud'].to_s.empty?
end
if cloud_id
cloud = find_cloud_by_name_or_id_for_provisioning(group['id'], cloud_id)
payload['defaultCloud'] = {'id' => cloud ? cloud['id'] : cloud_id}
end
selected_environment = nil
available_environments = get_available_environments()
if options[:environment]
payload['environment'] = options[:environment]
else
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'environment', 'fieldLabel' => 'Environment', 'type' => 'select', 'selectOptions' => available_environments}], options[:options], @api_client)
payload['environment'] = v_prompt['environment'] unless v_prompt['environment'].to_s.empty?
end
selected_environment = nil
if payload['environment']
selected_environment = available_environments.find {|it| it['code'] == payload['environment'] || it['name'] == payload['environment'] }
if selected_environment.nil?
print_red_alert "Environment not found by name or code '#{payload['environment']}'"
return 1
end
end
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'labels', 'fieldLabel' => 'Labels', 'type' => 'text'}], options[:options])
payload['labels'] = parse_labels(v_prompt['labels']) unless v_prompt['labels'].to_s.empty?
if !payload['tiers']
if payload['blueprintId'] != 'existing'
blueprint = find_blueprint_by_name_or_id(payload['blueprintId'])
return 1 if blueprint.nil?
unless options[:quiet]
print cyan, "Configuring app with blueprint id: #{blueprint['id']}, name: #{blueprint['name']}, type: #{blueprint['type']}\n"
end
blueprint_type = blueprint['type'] || 'morpheus'
if blueprint_type == 'morpheus'
tiers = blueprint["config"]["tiers"] ? blueprint["config"]["tiers"] : (blueprint["tiers"] || {})
sorted_tiers = tiers.collect {|k,v| [k,v] }.sort {|a,b| a[1]['tierIndex'] <=> b[1]['tierIndex'] }
payload.delete('defaultCloud')
sorted_tiers.each do |tier_obj|
tier_name = tier_obj[0]
tier_config = tier_obj[1]
payload['tiers'] ||= {}
payload['tiers'][tier_name] ||= tier_config.clone
tier_instances = payload['tiers'][tier_name].delete("instances")
if payload['tiers'][tier_name]['linkedTiers'] && payload['tiers'][tier_name]['linkedTiers'].empty?
payload['tiers'][tier_name].delete('linkedTiers')
end
= {}
if payload[tier_name]
= payload.delete(tier_name)
end
tier_instance_types = tier_instances ? tier_instances.collect {|it| (it['instance'] && it['instance']['type']) ? it['instance']['type'].to_s : 'unknown'}.compact : []
unless options[:quiet]
print cyan, "Configuring tier #{tier_name}", reset, "\n"
end
if tier_instances
tier_instances = tier_config['instances'] || []
tier_instances.each_with_index do |instance_config, instance_index|
instance_type_code = instance_config['type']
if instance_config['instance'] && instance_config['instance']['type']
instance_type_code = instance_config['instance']['type']
end
if instance_type_code.nil?
print_red_alert "Unable to determine instance type for tier: #{tier_name} index: #{instance_index}"
return 1
else
unless options[:quiet]
print cyan, "Configuring #{instance_type_code} instance #{tier_name}.#{instance_index}", reset, "\n"
end
scoped_instance_config = get_scoped_instance_config(instance_config.clone, selected_environment ? selected_environment['name'] : nil, group ? group['name'] : nil, cloud ? cloud['name'] : nil)
instance_prompt_options = {}
instance_prompt_options[:group] = group ? group['id'] : nil
instance_prompt_options[:default_cloud] = cloud ? cloud['name'] : nil
instance_prompt_options[:environment] = selected_environment ? selected_environment['code'] : nil
instance_prompt_options[:default_security_groups] = scoped_instance_config['securityGroups'] ? scoped_instance_config['securityGroups'] : nil
instance_prompt_options[:no_prompt] = options[:no_prompt]
instance_prompt_options[:options] = scoped_instance_config instance_prompt_options[:options][:no_prompt] = instance_prompt_options[:no_prompt]
= {}
if && [instance_index.to_s]
= [instance_index.to_s]
end
instance_prompt_options[:options].deep_merge!()
instance_prompt_options[:instance_type_code] = instance_type_code
help_field_prefix = "#{tier_name}.#{instance_index}"
instance_prompt_options[:help_field_prefix] = help_field_prefix
instance_prompt_options[:options][:help_field_prefix] = help_field_prefix
instance_prompt_options[:locked_fields] = scoped_instance_config['lockedFields']
instance_prompt_options[:for_app] = true
instance_prompt_options[:skip_labels_prompt] = true
scoped_instance_config = Marshal.load( Marshal.dump(scoped_instance_config) )
instance_config_payload = prompt_new_instance(instance_prompt_options)
instance_config_payload.deep_compact!
final_config = scoped_instance_config.clone
final_config.deep_merge!(instance_config_payload)
final_config.delete('environments')
final_config.delete('groups')
final_config.delete('clouds')
final_config.delete('lockedFields')
final_config.delete('userRemovedFields')
final_config.delete(:no_prompt)
final_config.delete(:help_field_prefix)
payload['tiers'][tier_name]['instances'] ||= []
payload['tiers'][tier_name]['instances'] << final_config
end
end
else
puts yellow, "Tier '#{tier_name}' is empty", reset
end
end
elsif blueprint_type == 'terraform'
elsif blueprint_type == 'arm'
elsif blueprint_type == 'cloudFormation'
else
print yellow, "Unknown template type: #{template_type})", "\n"
end
end
end
end
@apps_interface.setopts(options)
if options[:validate_only] == true
if options[:dry_run]
if options[:json]
puts as_json(payload, options)
elsif options[:yaml]
puts as_yaml(payload, options)
else
print_dry_run @apps_interface.dry.validate(payload)
end
return 0
end
json_response = @apps_interface.validate(payload)
if options[:json]
puts as_json(json_response, options)
else
if !options[:quiet]
if json_response['success'] == true
print_green_success "New app '#{payload['name']}' validation passed. #{json_response['msg']}".strip
else
print_red_alert "New app '#{payload['name']}' validation failed. #{json_response['msg']}".strip
if json_response['errors'] && json_response['errors']['instances']
json_response['errors']['instances'].each do |error_obj|
tier_name = error_obj['tier']
instance_index = error_obj['index']
instance_errors = error_obj['instanceErrors']
print_error red, "#{tier_name} : #{instance_index}", reset, "\n"
if instance_errors
instance_errors.each do |err_key, err_msg|
print_error red, " * #{err_key} : #{err_msg}", reset, "\n"
end
end
end
else
(json_response['errors'] || {}).each do |error_key, error_msg|
if error_key != 'instances'
print_error red, " * #{error_key} : #{error_msg}", reset, "\n"
end
end
end
end
end
end
if json_response['success'] == true
return 0
else
return 1
end
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.create(payload)
return 0
end
json_response = @apps_interface.create(payload)
if options[:json]
puts as_json(json_response, options)
print "\n"
elsif !options[:quiet]
app = json_response["app"]
print_green_success "Added app #{app['name']}"
if !options[:no_prompt] && !payload['tiers'] && payload['id'] == 'existing'
if ::Morpheus::Cli::OptionTypes::confirm("Would you like to add an instance now?", options.merge({default: false}))
add_instance([app['id']])
while ::Morpheus::Cli::OptionTypes::confirm("Add another instance?", options.merge({default: false})) do
add_instance([app['id']])
end
end
end
get_args = [app['id']] + (options[:remote] ? ["-r",options[:remote]] : []) + (options[:refresh_interval] ? ['--refresh', options[:refresh_interval].to_s] : [])
get(get_args)
end
return 0
rescue RestClient::Exception => e
json_response = nil
begin
json_response = JSON.parse(e.response.to_s)
rescue TypeError, JSON::ParserError => ex
print_error red, "Failed to parse JSON response: #{ex}", reset, "\n"
end
if json_response && (json_response['errors'].nil? || json_response['errors'].empty?)
print_rest_exception(e, options)
else
(json_response['errors'] || {}).each do |error_key, error_msg|
if error_key != 'instances'
print_error red, " * #{error_key} : #{error_msg}", reset, "\n"
end
end
if json_response['errors'] && json_response['errors']['instances']
json_response['errors']['instances'].each do |error_obj|
tier_name = error_obj['tier']
instance_index = error_obj['index']
instance_errors = error_obj['instanceErrors']
print_error red, "#{tier_name} : #{instance_index}", reset, "\n"
if instance_errors
instance_errors.each do |err_key, err_msg|
print_error red, " * #{err_key} : #{err_msg}", reset, "\n"
end
end
end
end
end
exit 1
end
end
|
#add_instance(args) ⇒ Object
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1304
def add_instance(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [instance] [tier]")
build_common_options(opts, options, [:options, :json, :dry_run])
opts. = "Add an existing instance to an app.\n" +
"[app] is required. This is the name or id of an app." + "\n" +
"[instance] is required. This is the name or id of an instance." + "\n" +
"[tier] is required. This is the name of the tier."
end
optparse.parse!(args)
if args.count < 1 || args.count > 3
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} add-instance expects 1-3 arguments and received #{args.count}: #{args}\n#{optparse}"
return 1
end
if args[1] && args[1] !~ /\A\-/
options[:instance_name] = args[1]
if args[2] && args[2] !~ /\A\-/
options[:tier_name] = args[2]
end
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
payload = {}
if options[:instance_name]
instance = find_instance_by_name_or_id(options[:instance_name])
else
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'instance', 'fieldLabel' => 'Instance', 'type' => 'text', 'required' => true, 'description' => 'Enter the instance name or id'}], options[:options])
instance = find_instance_by_name_or_id(v_prompt['instance'])
end
payload[:instanceId] = instance['id']
if options[:tier_name]
payload[:tierName] = options[:tier_name]
else
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'tier', 'fieldLabel' => 'Tier', 'type' => 'text', 'required' => true, 'description' => 'Enter the name of the tier'}], options[:options])
payload[:tierName] = v_prompt['tier']
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.add_instance(app['id'], payload)
return
end
json_response = @apps_interface.add_instance(app['id'], payload)
if options[:json]
print JSON.pretty_generate(json_response)
print "\n"
else
print_green_success "Added instance #{instance['name']} to app #{app['name']}"
end
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#apply(args) ⇒ Object
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1022
def apply(args)
default_refresh_interval = 5
params, payload, options = {}, {}, {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [options]")
opts.on( '-p', '--parameter NAME=VALUE', "Template parameter name and value" ) do |val|
k, v = val.split("=")
options[:options]['templateParameter'] ||= {}
options[:options]['templateParameter'][k] = v
end
opts.on('--refresh [SECONDS]', String, "Refresh until execution is complete. Default interval is #{default_refresh_interval} seconds.") do |val|
options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
end
opts.on(nil, '--no-refresh', "Do not refresh" ) do
options[:no_refresh] = true
end
opts.on(nil, '--no-validate', "Do not validate planned changes before apply" ) do
options[:no_validate] = true
end
opts.on(nil, '--validate-only', "Only validate planned changes, do not execute the apply command." ) do
options[:validate_only] = true
end
build_standard_update_options(opts, options, [:auto_confirm])
opts. = <<-EOT
Apply an app.
[app] is required. This is the name or id of an app.
This is only supported by certain types of apps such as terraform.
By default this executes two requests to validate and then apply the changes.
The first request corresponds to the terraform plan command only.
Use --no-validate to skip this step apply changes in one step.
EOT
end
optparse.parse!(args)
verify_args!(args:args, optparse:optparse, count:1)
connect(options)
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
params.merge!(parse_query_options(options))
payload = {}
if options[:payload]
payload = options[:payload]
payload.deep_merge!(parse_passed_options(options))
else
payload.deep_merge!(parse_passed_options(options))
begin
prepare_apply_json_response = @apps_interface.prepare_apply(app["id"])
config = prepare_apply_json_response['data']
variable_map = config['templateParameter']
first_instance = app['instances'][0]
instance = first_instance ? find_instance_by_name_or_id(first_instance['id']) : nil
zone_id = instance ? instance['cloud']['id'] : nil
api_params = {templateId: app['blueprint']['id'], appId: app['id'], zoneId: zone_id, siteId: app['group']['id']}
layout_parameters = @options_interface.options_for_source('templateParameters',api_params)['data']
if layout_parameters && !layout_parameters.empty?
variable_option_types = []
i = 0
layout_parameters.each do |layout_parameter|
var_label = layout_parameter['displayName'] || layout_parameter['name']
var_name = layout_parameter['name']
var_value = variable_map ? variable_map[var_name] : layout_parameter['defaultValue']
if var_value.nil? && layout_parameter['defaultValue']
var_value = layout_parameter['defaultValue']
end
var_type = (layout_parameter['passwordType'] || layout_parameter['sensitive']) ? 'password' : 'text'
option_type = {'fieldContext' => 'templateParameter', 'fieldName' => var_name, 'fieldLabel' => var_label, 'type' => var_type, 'required' => true, 'defaultValue' => (var_value.to_s.empty? ? nil : var_value.to_s), 'displayOrder' => (i+1) }
variable_option_types << option_type
i+=1
end
blueprint_type_display = format_blueprint_type(config['type'])
if blueprint_type_display == "terraform"
blueprint_type_display = "Terraform"
end
print_h2 "#{blueprint_type_display} Variables"
v_prompt = Morpheus::Cli::OptionTypes.prompt(variable_option_types, options[:options], @api_client)
v_prompt.deep_compact!
payload.deep_merge!(v_prompt)
end
rescue RestClient::Exception => ex
Morpheus::Logging::DarkPrinter.puts "Unable to load config for app apply, skipping parameter prompting" if Morpheus::Logging.debug?
end
end
@apps_interface.setopts(options)
if options[:validate_only]
if options[:dry_run]
print_dry_run @apps_interface.dry.validate_apply(app["id"], params, payload)
return
end
json_response = @apps_interface.validate_apply(app["id"], params, payload)
print_green_success "Validating app #{app['name']}"
execution_id = json_response['executionId']
if !options[:no_refresh]
validate_execution_request = wait_for_execution_request(execution_id, options)
end
elsif options[:no_validate]
if options[:dry_run]
print_dry_run @apps_interface.dry.apply(app["id"], params, payload)
return
end
json_response = @apps_interface.apply(app["id"], params, payload)
render_response(json_response, options) do
print_green_success "Applying app #{app['name']}"
execution_id = json_response['executionId']
if !options[:no_refresh]
apply_execution_request = wait_for_execution_request(execution_id, options)
end
end
else
if options[:dry_run]
print_dry_run @apps_interface.dry.validate_apply(app["id"], params, payload)
print_dry_run @apps_interface.dry.apply(app["id"], params, payload)
return
end
json_response = @apps_interface.validate_apply(app["id"], params, payload)
print_green_success "Validating app #{app['name']}"
execution_id = json_response['executionId']
validate_execution_request = wait_for_execution_request(execution_id, options)
if validate_execution_request['status'] != 'complete'
print_red_alert "Validation failed. Changes will not be applied."
return 1, "Validation failed. Changes will not be applied."
else
unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to apply these changes?")
return 9, "aborted command"
end
json_response = @apps_interface.apply(app["id"], params, payload)
render_response(json_response, options) do
print_green_success "Applying app #{app['name']}"
execution_id = json_response['executionId']
if !options[:no_refresh]
apply_execution_request = wait_for_execution_request(execution_id, options)
end
end
end
end
return 0, nil
end
|
#apply_security_groups(args) ⇒ Object
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
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
1936
1937
1938
1939
1940
1941
1942
1943
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1895
def apply_security_groups(args)
options = {}
params = {}
clear_or_secgroups_specified = false
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [--clear] [-s]")
opts.on( '-c', '--clear', "Clear all security groups" ) do
params[:securityGroupIds] = []
clear_or_secgroups_specified = true
end
opts.on( '-s', '--secgroups SECGROUPS', "Apply the specified comma separated security group ids" ) do |secgroups|
params[:securityGroupIds] = secgroups.split(",")
clear_or_secgroups_specified = true
end
opts.on( '-h', '--help', "Print this help" ) do
puts opts
exit
end
build_common_options(opts, options, [:json, :dry_run])
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} apply-security-groups expects 1 argument and received #{args.count}: #{args}\n#{optparse}"
return 1
end
if !clear_or_secgroups_specified
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} apply-security-groups requires either --clear or --secgroups\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
payload = params
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.apply_security_groups(app['id'], payload)
return
end
@apps_interface.apply_security_groups(app['id'], payload)
security_groups([args[0]])
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#cancel_removal(args) ⇒ Object
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
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1436
def cancel_removal(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
end
optparse.parse!(args)
if args.count < 1
puts optparse
exit 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.cancel_removal(app['id'])
return
end
json_response = @apps_interface.cancel_removal(app['id'])
if options[:json]
print as_json(json_response, options), "\n"
return
elsif !options[:quiet]
get([app['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
end
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#connect(opts) ⇒ Object
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# File 'lib/morpheus/cli/commands/apps.rb', line 30
def connect(opts)
@api_client = establish_remote_appliance_connection(opts)
@accounts_interface = @api_client.accounts
@account_users_interface = @api_client.account_users
@apps_interface = @api_client.apps
@blueprints_interface = @api_client.blueprints
@instance_types_interface = @api_client.instance_types
@library_layouts_interface = @api_client.library_layouts
@instances_interface = @api_client.instances
@options_interface = @api_client.options
@groups_interface = @api_client.groups
@clouds_interface = @api_client.clouds
@logs_interface = @api_client.logs
@processes_interface = @api_client.processes
@active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
end
|
#count(args) ⇒ Object
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
|
# File 'lib/morpheus/cli/commands/apps.rb', line 163
def count(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[options]")
opts.on( '--owner USER', "Owner Username or ID" ) do |val|
options[:owner] = val
end
opts.on( '--created-by USER', "Alias for --owner" ) do |val|
options[:owner] = val
end
opts.add_hidden_option('--created-by')
opts.on( '-s', '--search PHRASE', "Search Phrase" ) do |phrase|
options[:phrase] = phrase
end
build_common_options(opts, options, [:query, :remote, :dry_run])
opts. = "Get the number of apps."
end
optparse.parse!(args)
connect(options)
begin
params = {}
params.merge!(parse_list_options(options))
account = nil
if options[:owner]
created_by_ids = find_all_user_ids(account ? account['id'] : nil, options[:owner])
return if created_by_ids.nil?
params['createdBy'] = created_by_ids
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.list(params)
return
end
json_response = @apps_interface.list(params)
if json_response['meta'] && json_response['meta']['total']
print cyan, json_response['meta']['total'], reset, "\n"
else
print yellow, "unknown", reset, "\n"
end
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#firewall_disable(args) ⇒ Object
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
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1795
def firewall_disable(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
build_common_options(opts, options, [:json, :dry_run])
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} firewall-disable expects 1 argument and received #{args.count}: #{args}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.firewall_disable(app['id'])
return
end
@apps_interface.firewall_disable(app['id'])
security_groups([args[0]])
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#firewall_enable(args) ⇒ Object
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1824
def firewall_enable(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
build_common_options(opts, options, [:json, :dry_run])
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} firewall-enable expects 1 argument and received #{args.count}: #{args}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.firewall_enable(app['id'])
return
end
@apps_interface.firewall_enable(app['id'])
security_groups([args[0]])
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#get(args) ⇒ Object
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
|
# File 'lib/morpheus/cli/commands/apps.rb', line 637
def get(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
opts.on('--refresh [SECONDS]', String, "Refresh until status is running,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
options[:refresh_until_status] ||= "running,failed"
if !val.to_s.empty?
options[:refresh_interval] = val.to_f
end
end
opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
options[:refresh_until_status] = val.to_s.downcase
end
build_standard_get_options(opts, options)
opts. = "Get details about an app.\n" +
"[app] is required. This is the name or id of an app. Supports 1-N [app] arguments."
end
optparse.parse!(args)
if args.count < 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} get expects 1 argument and received #{args.count}: #{args}\n#{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
47
48
49
|
# File 'lib/morpheus/cli/commands/apps.rb', line 47
def handle(args)
handle_subcommand(args)
end
|
#history(args) ⇒ Object
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
1995
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
2045
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
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1945
def history(args)
raw_args = args.dup
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
opts.on( nil, '--events', "Display sub processes (events)." ) do
options[:show_events] = true
end
opts.on( nil, '--output', "Display process output." ) do
options[:show_output] = true
end
opts.on(nil, '--details', "Display more details. Shows everything, untruncated." ) do
options[:show_events] = true
options[:show_output] = true
options[:details] = true
end
build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
opts. = "List historical processes for a specific app.\n" +
"[app] is required. This is the name or id of an app."
end
optparse.parse!(args)
if args.count != 1
puts optparse
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
instance_ids = []
app_tiers = app['appTiers'] || []
instances = app['instances']
if instances.nil?
instances = []
app_tiers.each do |app_tier|
instances += (app_tier['appInstances'] || []).collect {|it| it['instance']}.flatten().compact
end
end
instances.each do |instance|
instance_ids << instance['id']
end
params = {}
params['instanceIds'] = instance_ids
params.merge!(parse_list_options(options))
@processes_interface.setopts(options)
if options[:dry_run]
print_dry_run @processes_interface.dry.list(params)
return
end
json_response = @processes_interface.list(params)
if options[:json]
puts as_json(json_response, options, "processes")
return 0
elsif options[:yaml]
puts as_yaml(json_response, options, "processes")
return 0
elsif options[:csv]
puts records_as_csv(json_response['processes'], options)
return 0
else
title = "App History: #{app['name']}"
subtitles = []
if params[:query]
subtitles << "Search: #{params[:query]}".strip
end
subtitles += parse_list_subtitles(options)
print_h1 title, subtitles, options
if json_response['processes'].empty?
print "#{cyan}No process history found.#{reset}\n\n"
else
history_records = []
json_response["processes"].each do |process|
row = {
id: process['id'],
eventId: nil,
uniqueId: process['uniqueId'],
name: process['displayName'],
description: process['description'],
processType: process['processType'] ? (process['processType']['name'] || process['processType']['code']) : process['processTypeName'],
createdBy: process['createdBy'] ? (process['createdBy']['displayName'] || process['createdBy']['username']) : '',
startDate: format_local_dt(process['startDate']),
duration: format_process_duration(process),
status: format_process_status(process),
error: format_process_error(process),
output: format_process_output(process)
}
history_records << row
process_events = process['events'] || process['processEvents']
if options[:show_events]
if process_events
process_events.each do |process_event|
event_row = {
id: process['id'],
eventId: process_event['id'],
uniqueId: process_event['uniqueId'],
name: process_event['displayName'], description: process_event['description'],
processType: process_event['processType'] ? (process_event['processType']['name'] || process_event['processType']['code']) : process['processTypeName'],
createdBy: process_event['createdBy'] ? (process_event['createdBy']['displayName'] || process_event['createdBy']['username']) : '',
startDate: format_local_dt(process_event['startDate']),
duration: format_process_duration(process_event),
status: format_process_status(process_event),
error: format_process_error(process_event, options[:details] ? nil : 20),
output: format_process_output(process_event, options[:details] ? nil : 20)
}
history_records << event_row
end
else
end
end
end
columns = [
{:id => {:display_name => "PROCESS ID"} },
:name,
:description,
{:processType => {:display_name => "PROCESS TYPE"} },
{:createdBy => {:display_name => "CREATED BY"} },
{:startDate => {:display_name => "START DATE"} },
{:duration => {:display_name => "ETA/DURATION"} },
:status,
:error
]
if options[:show_events]
columns.insert(1, {:eventId => {:display_name => "EVENT ID"} })
end
if options[:show_output]
columns << :output
end
if options[:include_fields]
columns = options[:include_fields]
end
print cyan
print as_pretty_table(history_records, columns, options)
(json_response, {:label => "process", :n_label => "processes"})
print reset, "\n"
return 0
end
end
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#list(args) ⇒ Object
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
|
# File 'lib/morpheus/cli/commands/apps.rb', line 51
def list(args)
params = {}
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage()
opts.on( '-t', '--type TYPE', "Filter by type" ) do |val|
options[:type] = val
end
opts.on( '--blueprint BLUEPRINT', "Blueprint Name or ID" ) do |val|
options[:blueprint] = val
end
opts.on( '--owner USER', "Owner Username or ID" ) do |val|
options[:owner] = val
end
opts.on( '--created-by USER', "[DEPRECATED] Alias for --owner" ) do |val|
options[:owner] = val
end
opts.add_hidden_option('--created-by')
opts.on('--pending-removal', "Include apps pending removal.") do
options[:showDeleted] = true
end
opts.on('--pending-removal-only', "Only apps pending removal.") do
options[:deleted] = true
end
opts.on('--environment ENV', "Filter by environment code (appContext)") do |val|
params['environment'] = (params['environment'] || []) + val.to_s.split(',').collect {|s| s.strip }.select {|s| s != "" }
end
opts.on('--status STATUS', "Filter by status.") do |val|
params['status'] = (params['status'] || []) + val.to_s.split(',').collect {|s| s.strip }.select {|s| s != "" }
end
opts.on('-l', '--labels LABEL', String, "Filter by labels, can match any of the values") do |val|
add_query_parameter(params, 'labels', parse_labels(val))
end
opts.on('--all-labels LABEL', String, "Filter by labels, must match all of the values") do |val|
add_query_parameter(params, 'allLabels', parse_labels(val))
end
opts.on('-a', '--details', "Display all details: memory and storage usage used / max values." ) do
options[:details] = true
end
build_standard_list_options(opts, options)
opts. = "List apps."
end
optparse.parse!(args)
if args.count > 0
options[:phrase] = args.join(" ")
end
connect(options)
if options[:type]
params['type'] = [options[:type]].flatten.collect {|it| it.to_s.strip.split(",") }.flatten.collect {|it| it.to_s.strip }
end
if options[:blueprint]
blueprint_ids = [options[:blueprint]].flatten.collect {|it| it.to_s.strip.split(",") }.flatten.collect {|it| it.to_s.strip }
params['blueprintId'] = blueprint_ids.collect do |blueprint_id|
if blueprint_id.to_s =~ /\A\d{1,}\Z/
return blueprint_id
else
blueprint = find_blueprint_by_name_or_id(blueprint_id)
return 1 if blueprint.nil?
blueprint['id']
end
end
end
if options[:owner]
owner_ids = [options[:owner]].flatten.collect {|it| it.to_s.strip.split(",") }.flatten.collect {|it| it.to_s.strip }
params['ownerId'] = owner_ids.collect do |owner_id|
if owner_id.to_s =~ /\A\d{1,}\Z/
return owner_id
else
user = find_available_user_option(owner_id)
return 1 if user.nil?
user['id']
end
end
end
params.merge!(parse_list_options(options))
account = nil
if options[:owner]
created_by_ids = find_all_user_ids(account ? account['id'] : nil, options[:owner])
return if created_by_ids.nil?
params['createdBy'] = created_by_ids
end
params['showDeleted'] = options[:showDeleted] if options.key?(:showDeleted)
params['deleted'] = options[:deleted] if options.key?(:deleted)
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.list(params)
return
end
json_response = @apps_interface.list(params)
render_response(json_response, options, "apps") do
apps = json_response['apps']
title = "Morpheus Apps"
subtitles = []
subtitles += parse_list_subtitles(options)
print_h1 title, subtitles, options
if apps.empty?
print cyan,"No apps found.",reset,"\n"
else
print_apps_table(apps, options)
(json_response)
end
print reset,"\n"
end
return 0, nil
end
|
#logs(args) ⇒ Object
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1524
def logs(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
opts.on( '-n', '--node NODE_ID', "Scope logs to specific Container or VM" ) do |node_id|
options[:node_id] = node_id.to_i
end
opts.on('--start TIMESTAMP','--start TIMESTAMP', "Start timestamp. Default is 30 days ago.") do |val|
options[:start] = parse_time(val) end
opts.on('--end TIMESTAMP','--end TIMESTAMP', "End timestamp. Default is now.") do |val|
options[:end] = parse_time(val) end
opts.on('--level VALUE', String, "Log Level. DEBUG,INFO,WARN,ERROR") do |val|
params['level'] = params['level'] ? [params['level'], val].flatten : [val]
end
opts.on('--table', '--table', "Format ouput as a table.") do
options[:table] = true
end
opts.on('-a', '--all', "Display all details: entire message." ) do
options[:details] = true
end
build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
opts. = "List logs for an app.\n" +
"[app] is required. This is the name or id of an app."
end
optparse.parse!(args)
if args.count !=1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} logs expects 1 argument and received #{args.count}: #{args}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
container_ids = []
app_tiers = app['appTiers'] || []
instances = app['instances']
if instances.nil?
instances = []
app_tiers.each do |app_tier|
instances += (app_tier['appInstances'] || []).collect {|it| it['instance']}.flatten().compact
end
end
instances.each do |instance|
container_ids += instance['containers']
end
if container_ids.empty?
print cyan,"app is empty",reset,"\n"
return 0
end
if options[:node_id]
if container_ids.include?(options[:node_id])
container_ids = [options[:node_id]]
else
print_red_alert "App does not include node #{options[:node_id]}"
return 1
end
end
params = {}
params['level'] = params['level'].collect {|it| it.to_s.upcase }.join('|') if params['level'] params.merge!(parse_list_options(options))
params['query'] = params.delete('phrase') if params['phrase']
params['order'] = params['direction'] unless params['direction'].nil? params['startMs'] = (options[:start].to_i * 1000) if options[:start]
params['endMs'] = (options[:end].to_i * 1000) if options[:end]
params['interval'] = options[:interval].to_s if options[:interval]
@logs_interface.setopts(options)
if options[:dry_run]
print_dry_run @logs_interface.dry.container_logs(container_ids, params)
return
end
json_response = @logs_interface.container_logs(container_ids, params)
render_result = json_response['logs'] ? render_with_format(json_response, options, 'logs') : render_with_format(json_response, options, 'data')
return 0 if render_result
title = "App Logs: #{app['name']}"
subtitles = parse_list_subtitles(options)
if options[:start]
subtitles << "Start: #{options[:start]}".strip
end
if options[:end]
subtitles << "End: #{options[:end]}".strip
end
if params[:query]
subtitles << "Search: #{params[:query]}".strip
end
if params['servers']
subtitles << "Servers: #{params['servers']}".strip
end
if params['containers']
subtitles << "Containers: #{params['containers']}".strip
end
if params[:query]
subtitles << "Search: #{params[:query]}".strip
end
if params['level']
subtitles << "Level: #{params['level']}"
end
logs = json_response['data'] || json_response['logs']
print_h1 title, subtitles, options
if logs.empty?
print "#{cyan}No logs found.#{reset}\n"
else
print format_log_records(logs, options)
({'meta'=>{'total'=>(json_response['total']['value'] rescue json_response['total']),'size'=>logs.size,'max'=>(json_response['max'] || options[:max]),'offset'=>(json_response['offset'] || options[:offset] || 0)}})
end
print reset,"\n"
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#prepare_apply(args) ⇒ Object
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
|
# File 'lib/morpheus/cli/commands/apps.rb', line 969
def prepare_apply(args)
params, payload, options = {}, {}, {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [options]")
build_standard_update_options(opts, options, [:auto_confirm])
opts. = <<-EOT
Prepare to apply an app.
[app] is required. This is the name or id of an app.
Displays the current configuration data used by the apply command.
This is only supported by certain types of apps such as terraform.
EOT
end
optparse.parse!(args)
if args.count != 1
raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(', ')}\n#{optparse}"
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
params.merge!(parse_query_options(options))
payload = {}
if options[:payload]
payload = options[:payload]
payload.deep_merge!(parse_passed_options(options))
else
payload.deep_merge!(parse_passed_options(options))
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.prepare_apply(app["id"], params)
return
end
json_response = @apps_interface.prepare_apply(app["id"], params)
render_result = render_with_format(json_response, options)
return 0 if render_result
print_h1 "Prepared App: #{app['name']}"
app_config = json_response['data']
puts as_yaml(app_config, options)
print "\n", reset
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#refresh(args) ⇒ Object
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
|
# File 'lib/morpheus/cli/commands/apps.rb', line 921
def refresh(args)
params, payload, options = {}, {}, {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [options]")
build_standard_update_options(opts, options, [:auto_confirm])
opts. = <<-EOT
Refresh an app.
[app] is required. This is the name or id of an app.
This is only supported by certain types of apps.
EOT
end
optparse.parse!(args)
verify_args!(args:args, optparse:optparse, count:1)
connect(options)
begin
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
params.merge!(parse_query_options(options))
payload = {}
if options[:payload]
payload = options[:payload]
payload.deep_merge!(parse_passed_options(options))
else
payload.deep_merge!(parse_passed_options(options))
end
unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to refresh this app: #{app['name']}?")
return 9, "aborted command"
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.refresh(app["id"], params, payload)
return
end
json_response = @apps_interface.refresh(app["id"], params, payload)
render_response(json_response, options) do
print_green_success "Refreshing app #{app['name']}"
end
return 0, nil
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#remove(args) ⇒ Object
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1369
def remove(args)
options = {}
query_params = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
opts.on('--remove-instances [on|off]', ['on','off'], "Remove instances. Default is off.") do |val|
query_params[:removeInstances] = val.nil? ? 'on' : val
end
opts.on('--preserve-volumes [on|off]', ['on','off'], "Preserve Volumes. Default is off. Applies to certain types only.") do |val|
query_params[:preserveVolumes] = val.nil? ? 'on' : val
end
opts.on( '--keep-backups', '--keep-backups', "Preserve copy of backups" ) do
query_params[:keepBackups] = 'on'
end
opts.on('--release-ips [on|off]', ['on','off'], "Release Floating IPs. Default is on. Applies to certain types only. Only applies when used with --remove-instances") do |val|
query_params[:releaseFloatingIps] = val.nil? ? 'on' : val
query_params[:releaseEIPs] = query_params[:releaseFloatingIps] end
opts.on('--releaseEIPs [on|off]', ['on','off'], "Alias for Release Floating IPs") do |val|
query_params[:releaseFloatingIps] = val.nil? ? 'on' : val
query_params[:releaseEIPs] = query_params[:releaseFloatingIps] end
opts.add_hidden_option('--releaseEIPs')
opts.on( '-f', '--force', "Force Delete" ) do
query_params[:force] = 'on'
end
build_common_options(opts, options, [:json, :dry_run, :quiet, :auto_confirm])
opts. = "Delete an app.\n" +
"[app] is required. This is the name or id of an app."
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} remove expects 1 argument and received #{args.count}: #{args}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the app '#{app['name']}'?", options)
return 9
end
if query_params[:preserveVolumes].nil?
query_params[:removeVolumes] = 'on'
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.destroy(app['id'], query_params)
return
end
json_response = @apps_interface.destroy(app['id'], query_params)
if options[:json]
print JSON.pretty_generate(json_response)
print "\n"
elsif !options[:quiet]
print_green_success "Removed app #{app['name']}"
end
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#remove_instance(args) ⇒ Object
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
1515
1516
1517
1518
1519
1520
1521
1522
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1468
def remove_instance(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [instance]")
build_common_options(opts, options, [:options, :json, :dry_run])
opts. = "Remove an instance from an app.\n" +
"[app] is required. This is the name or id of an app." + "\n" +
"[instance] is required. This is the name or id of an instance."
end
optparse.parse!(args)
if args.count < 1 || args.count > 2
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} remove-instance expects 1-2 arguments and received #{args.count}: #{args}\n#{optparse}"
return 1
end
if args[1] && args[1] !~ /\A\-/
options[:instance_name] = args[1]
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
payload = {}
if options[:instance_name]
instance = find_instance_by_name_or_id(options[:instance_name])
else
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'instance', 'fieldLabel' => 'Instance', 'type' => 'text', 'required' => true, 'description' => 'Enter the instance name or id'}], options[:options])
instance = find_instance_by_name_or_id(v_prompt['instance'])
end
payload[:instanceId] = instance['id']
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.remove_instance(app['id'], payload)
return
end
json_response = @apps_interface.remove_instance(app['id'], payload)
if options[:json]
print JSON.pretty_generate(json_response)
print "\n"
else
print_green_success "Removed instance #{instance['name']} from app #{app['name']}"
end
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#restart(args) ⇒ Object
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1751
def restart(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
opts. = "Restart an app.\n" +
"[app] is required. This is the name or id of an app. Supports 1-N [app] arguments."
end
optparse.parse!(args)
if args.count < 1
puts_error "[id] argument is required"
puts_error optparse
return 1
end
connect(options)
id_list = parse_id_list(args)
unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart #{id_list.size == 1 ? 'app' : 'apps'} #{anded_list(id_list)}?", options)
return 9, "aborted command"
end
return run_command_for_each_arg(id_list) do |arg|
_restart(arg, options)
end
end
|
#security_groups(args) ⇒ Object
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
1889
1890
1891
1892
1893
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1853
def security_groups(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
build_common_options(opts, options, [:json, :dry_run])
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} security-groups expects 1 argument and received #{args.count}: #{args}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.security_groups(app['id'])
return
end
json_response = @apps_interface.security_groups(app['id'])
securityGroups = json_response['securityGroups']
print_h1 "Morpheus Security Groups for App: #{app['name']}", options
print cyan
print_description_list({"Firewall Enabled" => lambda {|it| format_boolean it['firewallEnabled'] } }, json_response)
if securityGroups.empty?
print cyan,"\n","No security groups currently applied.",reset,"\n"
else
print "\n"
securityGroups.each do |securityGroup|
print cyan, "= #{securityGroup['id']} (#{securityGroup['name']}) - (#{securityGroup['description']})\n"
end
end
print reset,"\n"
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#start(args) ⇒ Object
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1707
def start(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
opts. = "Start an app.\n" +
"[app] is required. This is the name or id of an app. Supports 1-N [app] arguments."
end
optparse.parse!(args)
if args.count < 1
puts_error "[id] argument is required"
puts_error optparse
return 1
end
connect(options)
id_list = parse_id_list(args)
unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to start #{id_list.size == 1 ? 'app' : 'apps'} #{anded_list(id_list)}?", options)
return 9, "aborted command"
end
return run_command_for_each_arg(id_list) do |arg|
_start(arg, options)
end
end
|
#state(args) ⇒ Object
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1174
def state(args)
params, payload, options = {}, {}, {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [options]")
opts.on('--data', "Display State Data") do
options[:include_state_data] = true
end
opts.on('--specs', "Display Spec Templates") do
options[:include_spec_templates] = true
end
opts.on('--plan', "Display Plan Data") do
options[:include_plan_data] = true
end
opts.on('--input', "Display Input") do
options[:include_input] = true
end
opts.on('--output', "Display Output") do
options[:include_output] = true
end
opts.on('-a','--all', "Display All Details") do
options[:include_state_data] = true
options[:include_spec_templates] = true
options[:include_plan_data] = true
options[:include_input] = true
options[:include_output] = true
options[:details] = true
end
build_standard_get_options(opts, options)
opts. = <<-EOT
View state of an app.
[app] is required. This is the name or id of an app.
This is only supported by certain types of apps such as terraform.
EOT
end
optparse.parse!(args)
verify_args!(args:args, optparse:optparse, count:1)
connect(options)
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
params.merge!(parse_query_options(options))
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.state(app["id"], params)
return
end
json_response = @apps_interface.state(app["id"], params)
render_result = render_with_format(json_response, options)
return 0 if render_result
print_h1 "App State: #{app['name']}", options
if json_response['workloads'] && !json_response['workloads'].empty?
workload_columns = {
"Name" => lambda {|it| it['subRefName'].to_s.empty? ? "#{it['refName']}" : "#{it['refName']} - #{it['subRefName']}" },
"Last Check" => lambda {|it| format_local_dt(it['stateDate']) },
"Status" => lambda {|it| format_ok_status(it['status'] || 'ok') },
"Drift Status" => lambda {|it| it['iacDrift'] ? "Drift" : "No Drift" }
}
print as_pretty_table(json_response['workloads'], workload_columns.upcase_keys!, options)
else
print cyan,"No workloads found.",reset,"\n"
end
if options[:include_state_data]
print_h2 "State Data", options
puts json_response['stateData']
end
if options[:include_spec_templates]
print_h2 "Spec Templates", options
spec_templates_columns = {
"Resource Spec" => lambda {|it| it['name'] || (it['template'] ? it['template']['name'] : nil) },
"Attached to Source Template" => lambda {|it| format_boolean(!it['isolated']) },
"Source Spec Template" => lambda {|it| (it['template'] ? it['template']['name'] : nil) || it['name'] }
}
print as_pretty_table(json_response['specs'], spec_templates_columns.upcase_keys!, options)
end
if options[:include_plan_data]
if app['type'] == 'terraform'
print_h2 "Terraform Plan", options
else
print_h2 "Plan Data", options
end
puts json_response['planData']
end
if options[:include_input]
if json_response['input'] && json_response['input']['variables']
print_h2 "VARIABLES", options
input_variable_columns = {
"Name" => lambda {|it| it['name'] },
"Value" => lambda {|it| it['value'] }
}
print as_pretty_table(json_response['input']['variables'], input_variable_columns.upcase_keys!, options)
end
if json_response['input'] && json_response['input']['providers']
print_h2 "PROVIDERS", options
input_provider_columns = {
"Name" => lambda {|it| it['name'] }
}
print as_pretty_table(json_response['input']['providers'], input_provider_columns.upcase_keys!, options)
end
if json_response['input'] && json_response['input']['data']
print_h2 "DATA", options
input_data_columns = {
"Type" => lambda {|it| it['type'] },
"Key" => lambda {|it| it['key'] },
"Name" => lambda {|it| it['name'] }
}
print as_pretty_table(json_response['input']['data'], input_data_columns.upcase_keys!, options)
end
end
if options[:include_output]
if json_response['output'] && json_response['output']['outputs']
print_h2 "OUTPUTS", options
input_variable_columns = {
"Name" => lambda {|it| it['name'] },
"Value" => lambda {|it| it['value'] }
}
print as_pretty_table(json_response['output']['outputs'], input_variable_columns.upcase_keys!, options)
end
end
print "\n", reset
return 0
end
|
#stop(args) ⇒ Object
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
|
# File 'lib/morpheus/cli/commands/apps.rb', line 1663
def stop(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
opts. = "Stop an app.\n" +
"[app] is required. This is the name or id of an app. Supports 1-N [app] arguments."
end
optparse.parse!(args)
if args.count < 1
puts_error "[id] argument is required"
puts_error optparse
return 1
end
connect(options)
id_list = parse_id_list(args)
unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop #{id_list.size == 1 ? 'app' : 'apps'} #{anded_list(id_list)}?", options)
return 9, "aborted command"
end
return run_command_for_each_arg(id_list) do |arg|
_stop(arg, options)
end
end
|
#update(args) ⇒ Object
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
|
# File 'lib/morpheus/cli/commands/apps.rb', line 823
def update(args)
params, payload, options = {}, {}, {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [options]")
opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
options[:group] = val
end
opts.on( '--name VALUE', String, "Name" ) do |val|
options[:name] = val
end
opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
options[:options]['labels'] = parse_labels(val)
end
opts.on( '--description VALUE', String, "Description" ) do |val|
options[:description] = val
end
opts.on( '--environment VALUE', String, "Environment" ) do |val|
options[:environment] = val
end
opts.on( '--owner USER', "Owner Username or ID" ) do |val|
options[:owner] = val == 'null' ? nil : val
end
build_common_options(opts, options, [:options, :payload, :json, :dry_run])
opts. = "Update an app.\n" +
"[app] is required. This is the name or id of an app."
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} update expects 1 argument and received #{args.count}: #{args}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
if options[:payload]
payload = options[:payload]
end
payload['app'] ||= {}
payload.deep_merge!({'app' => parse_passed_options(options)})
if options[:name]
payload['app']['name'] = options[:name]
end
if options[:description]
payload['app']['description'] = options[:description]
end
if options[:environment]
payload['app']['appContext'] = options[:environment]
end
if options[:group]
group = find_group_by_name_or_id_for_provisioning(options[:group])
return 1 if group.nil?
payload['app']['group'] = {'id' => group['id'], 'name' => group['name']}
end
if options.key?(:owner)
owner_id = options[:owner]
if owner_id.to_s.empty?
owner_id = nil
elsif options[:owner]
if owner_id.to_s =~ /\A\d{1,}\Z/
else
user = find_available_user_option(owner_id)
return 1 if user.nil?
owner_id = user['id']
end
end
payload['app']['ownerId'] = owner_id
end
if payload['app'] && payload['app'].empty?
payload.delete('app')
end
if payload.empty?
raise_command_error "Specify at least one option to update.\n#{optparse}" if payload.empty?
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.update(app["id"], payload)
return
end
json_response = @apps_interface.update(app["id"], payload)
render_result = render_with_format(json_response, options)
return 0 if render_result
print_green_success "Updated app #{app['name']}"
get([app['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#update_wiki(args) ⇒ Object
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
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
2330
2331
2332
2333
2334
2335
2336
2337
|
# File 'lib/morpheus/cli/commands/apps.rb', line 2261
def update_wiki(args)
options = {}
params = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app] [options]")
build_option_type_options(opts, options, update_wiki_page_option_types)
opts.on('--file FILE', "File containing the wiki content. This can be used instead of --content") do |filename|
full_filename = File.expand_path(filename)
if File.exist?(full_filename)
params['content'] = File.read(full_filename)
else
print_red_alert "File not found: #{full_filename}"
return 1
end
if !params['name']
params['name'] = File.basename(full_filename)
end
end
opts.on(nil, '--clear', "Clear current page content") do |val|
params['content'] = ""
end
build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
end
optparse.parse!(args)
if args.count != 1
puts_error "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 1 and received #{args.count} #{args.inspect}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
payload = nil
if options[:payload]
payload = options[:payload]
payload.deep_merge!({'page' => passed_options}) unless passed_options.empty?
else
payload = {
'page' => {
}
}
payload.deep_merge!({'page' => passed_options}) unless passed_options.empty?
params.deep_merge!(passed_options)
if params.empty?
raise_command_error "Specify at least one option to update.\n#{optparse}"
end
payload.deep_merge!({'page' => params}) unless params.empty?
end
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.update_wiki(app["id"], payload)
return
end
json_response = @apps_interface.update_wiki(app["id"], payload)
if options[:json]
puts as_json(json_response, options)
else
print_green_success "Updated wiki page for app #{app['name']}"
wiki([app['id']])
end
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#view(args) ⇒ Object
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
|
# File 'lib/morpheus/cli/commands/apps.rb', line 2106
def view(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
opts.on('-w','--wiki', "Open the wiki tab for this app") do
options[:link_tab] = "wiki"
end
opts.on('--tab VALUE', String, "Open a specific tab") do |val|
options[:link_tab] = val.to_s
end
build_common_options(opts, options, [:dry_run, :remote])
opts. = "View an app in a web browser" + "\n" +
"[app] is required. This is the name or id of an app. Supports 1-N [app] arguments."
end
optparse.parse!(args)
if args.count < 1
raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
id_list = parse_id_list(args)
return run_command_for_each_arg(id_list) do |arg|
_view(arg, options)
end
end
|
#view_wiki(args) ⇒ Object
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
|
# File 'lib/morpheus/cli/commands/apps.rb', line 2230
def view_wiki(args)
params = {}
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id]")
build_common_options(opts, options, [:dry_run, :remote])
opts. = "View app wiki page in a web browser" + "\n" +
"[app] is required. This is the name or id of an app."
end
optparse.parse!(args)
if args.count != 1
raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/provisioning/apps/#{app['id']}#!wiki"
if options[:dry_run]
puts Morpheus::Util.open_url_command(link)
return 0
end
return Morpheus::Util.open_url(link)
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|
#wiki(args) ⇒ Object
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
2198
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
|
# File 'lib/morpheus/cli/commands/apps.rb', line 2152
def wiki(args)
options = {}
params = {}
open_wiki_link = false
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[app]")
opts.on('--view', '--view', "View wiki page in web browser.") do
open_wiki_link = true
end
build_common_options(opts, options, [:json, :dry_run, :remote])
opts. = "View wiki page details for an app." + "\n" +
"[app] is required. This is the name or id of an app."
end
optparse.parse!(args)
if args.count != 1
puts_error "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 1 and received #{args.count} #{args.inspect}\n#{optparse}"
return 1
end
connect(options)
begin
app = find_app_by_name_or_id(args[0])
return 1 if app.nil?
@apps_interface.setopts(options)
if options[:dry_run]
print_dry_run @apps_interface.dry.wiki(app["id"], params)
return
end
json_response = @apps_interface.wiki(app["id"], params)
page = json_response['page']
render_result = render_with_format(json_response, options, 'page')
return 0 if render_result
if page
print_h1 "App Wiki Page: #{app['name']}"
print cyan
print_description_list({
"Page ID" => 'id',
"Name" => 'name',
"Created" => lambda {|it| format_local_dt(it['dateCreated']) },
"Created By" => lambda {|it| it['createdBy'] ? it['createdBy']['username'] : '' },
"Updated" => lambda {|it| format_local_dt(it['lastUpdated']) },
"Updated By" => lambda {|it| it['updatedBy'] ? it['updatedBy']['username'] : '' }
}, page)
print reset,"\n"
print_h2 "Page Content"
print cyan, page['content'], reset, "\n"
else
print "\n"
print cyan, "No wiki page found.", reset, "\n"
end
print reset,"\n"
if open_wiki_link
return view_wiki([args[0]])
end
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
|