Class: Morpheus::Cli::Apps

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand, ExecutionRequestHelper, LogsHelper, OptionSourceHelper, ProcessesHelper, ProvisioningHelper
Defined in:
lib/morpheus/cli/commands/apps.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from ExecutionRequestHelper

#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

Methods included from ProcessesHelper

#format_process_duration, #format_process_error, #format_process_output, #format_process_status, included, #print_process_details, #print_process_event_details

Methods included from ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_host_by_id, #find_host_by_name, #find_host_by_name_or_id, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_permissions_v2, #prompt_resize_volumes, #prompt_security_groups, #prompt_service_plan_options, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from OptionSourceHelper

#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

Methods included from AccountsHelper

#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

#initializeApps

Returns a new instance of Apps.



26
27
28
# File 'lib/morpheus/cli/commands/apps.rb', line 26

def initialize()
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
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']
    # API used to only return apps.appTiers including instances with lots of detail
    # now returns simplified instance list as "instances" for terraform, etc with only id,name
    # so load the instance details if needed
    app_tiers = []
    instances = []
    if app['appTiers'] && !app['appTiers'].empty?
      # appTiers contains instances with lots of detail
      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?
      # need to load instance details which are not returned in this simple list
      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'] : '' },
      #"Tenant" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Tiers" => lambda {|it| 
        # it['instanceCount']
        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| 
        # it['instanceCount']
        "(#{instances.count}) #{instances.collect {|it| it['name'] }.join(',')}"
      },
      "Containers" => lambda {|it| 
        #it['containerCount'] 
        containers = []
        instances.each do |instance|
          containers += (instance['containers'] || [])
        end
        #"(#{containers.count})"
        "(#{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'

    # if app['blueprint'].nil?
    #   description_cols.delete("Blueprint")
    # end
    # if app['description'].nil?
    #   description_cols.delete("Description")
    # end
    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] } #oldest to newest..
        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 "Tier: #{app_tier['tier']['name']}", options
        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] } #oldest to newest..
          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


    # refresh until a status is reached
    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 = extract_app_tiers(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 = extract_app_tiers(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 = extract_app_tiers(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]")
    #build_option_type_options(opts, options, add_app_option_types(false))
    # these come from build_options_types
    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
    # config is being deprecated in favor of the standard --payload options
    # opts.add_hidden_option(['config', 'config-dir', 'config-file', 'config-yaml'])
    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.footer = "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
  # allow name as first argument
  if args[0] # && !options[:name]
    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 is from parsed json|yaml files or arguments.
      payload = options[:payload]
      # merge -O options
      payload.deep_merge!(passed_options) unless passed_options.empty?
      # support some options on top of --payload
      [:name, :description, :environment].each do |k|
        if options.key?(k)
          payload[k.to_s] = options[k]
        end
      end
    else
      # prompt for payload
      payload = {}
      # merge -O options
      payload.deep_merge!(passed_options) unless passed_options.empty?

      # this could have some special -O context, like -O tier.Web.0.instance.name
      # tier_config_options = payload.delete('tier')

      # Blueprint
      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?
          #print_red_alert "Blueprint not found by name or id '#{blueprint_id}'"
          return 1
        end
      end
      
      payload['templateId'] = blueprint['id'] # for pre-3.6 api
      payload['blueprintId'] = blueprint['id']
      payload['blueprintName'] = blueprint['name'] #for future api plz

      # 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']
      
      # Description
      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
      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']}

      # Default Cloud
      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
      
      # Environment
      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
      # payload['appContext'] = payload['environment'] if payload['environment']

      # Labels
      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?

      # Configure (Tiers and their instances)
      if !payload['tiers']
        if payload['blueprintId'] != 'existing'
          
          # fetch the app template
          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'
            # configure each tier and instance in the blueprint
            # tiers are a map, heh, sort them by tierIndex
            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
              # remove instances, they will be iterated over and merged back in
              tier_instances = payload['tiers'][tier_name].delete("instances")
              # remove other blank stuff
              if payload['tiers'][tier_name]['linkedTiers'] && payload['tiers'][tier_name]['linkedTiers'].empty?
                payload['tiers'][tier_name].delete('linkedTiers')
              end
              # remove extra instance options at tierName.index, probabl need a namespace here like tier.TierName.index
              tier_extra_options = {}
              if payload[tier_name]
                tier_extra_options = 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} (#{tier_instance_types.empty? ? 'empty' : tier_instance_types.join(', ')})", "\n"
                print cyan, "Configuring tier #{tier_name}", reset, "\n"
              end
              # todo: also prompt for tier settings here, like linkedTiers: []
              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

                    # Cloud
                    # cloud_id = nil
                    # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'fieldLabel' => 'Cloud', 'type' => 'select', 'selectOptions' => scoped_available_clouds, 'defaultValue' => cloud ? cloud['name'] : nil}], options[:options])
                    # cloud_id = v_prompt['cloud'] unless v_prompt['cloud'].to_s.empty?
                    # if cloud_id
                    #   # cloud = find_cloud_by_name_or_id_for_provisioning(group['id'], cloud_id)
                    #   cloud = scoped_available_clouds.find {|it| it['name'] == cloud_id.to_s } || scoped_available_clouds.find {|it| it['id'].to_s == cloud_id.to_s }
                    #   return 1 if cloud.nil?
                    # else
                    #   # prompt still happens inside get_scoped_instance_config
                    # end
                    
                    
                    # prompt for the cloud for this instance
                    # the cloud is part of finding the scoped config in the blueprint
                    scoped_instance_config = get_scoped_instance_config(instance_config.clone, selected_environment ? selected_environment['name'] : nil, group ? group['name'] : nil, cloud ? cloud['name'] : nil)

                    # now configure an instance like normal, use the config as default options with :always_prompt
                    instance_prompt_options = {}
                    instance_prompt_options[:group] = group ? group['id'] : nil
                    #instance_prompt_options[:cloud] = cloud ? cloud['name'] : 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[:always_prompt] = options[:no_prompt] != true # options[:always_prompt]
                    instance_prompt_options[:options] = scoped_instance_config # meh, actually need to make these default values instead..
                    #instance_prompt_options[:options][:always_prompt] = instance_prompt_options[:no_prompt] != true
                    instance_prompt_options[:options][:no_prompt] = instance_prompt_options[:no_prompt]
                    # also allow arbritrary options passed as tierName.instanceIndex like Web.0.instance.layout.id=75
                    instance_extra_options = {}
                    if tier_extra_options && tier_extra_options[instance_index.to_s]
                      instance_extra_options = tier_extra_options[instance_index.to_s]
                    end
                    instance_prompt_options[:options].deep_merge!(instance_extra_options)

                    #instance_prompt_options[:name_required] = true
                    instance_prompt_options[:instance_type_code] = instance_type_code
                    # todo: an effort to render more useful help eg.  -O Web.0.instance.name
                    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
                    # or could do this: instance_prompt_options[:labels] = default_labels
                    # this provisioning helper method handles all (most) of the parsing and prompting
                    scoped_instance_config = Marshal.load( Marshal.dump(scoped_instance_config) )
                    instance_config_payload = prompt_new_instance(instance_prompt_options)

                    # strip all empty string and nil
                    instance_config_payload.deep_compact!
                    # use the blueprint config as the base
                    final_config = scoped_instance_config.clone
                    # merge the prompted values
                    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')
                    # should not need this...
                    final_config.delete(:no_prompt)
                    final_config.delete(:help_field_prefix)
                    # add config to payload
                    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'
            # prompt for Terraform config
            # todo
          elsif blueprint_type == 'arm'
            # prompt for ARM config
            # todo
          elsif blueprint_type == 'cloudFormation'
            # prompt for cloudFormation config
            # todo
          else
            print yellow, "Unknown template type: #{template_type})", "\n"
          end
        end
      end
    end

    @apps_interface.setopts(options)

    # Validate Only
    if options[:validate_only] == true
      # Validate Only Dry run 
      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
            # looks for special error format like instances.instanceErrors 
            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
              # a default way to print errors
              (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']}"
      # add existing instances to blank app now?
      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
      # print details
      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
    #print_rest_exception(e, options)
    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?)
      # The default way to print error msg
      print_rest_exception(e, options)
    else
      # print errors and look for special errors.instances
      # todo: just handle sub lists of errors default error handler (print_rest_exception)
      (json_response['errors'] || {}).each do |error_key, error_msg|
        if error_key != 'instances'
          print_error red, " * #{error_key} : #{error_msg}", reset, "\n"
        end
      end
      # looks for special error format like instances.instanceErrors 
      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.footer = "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
  # optional [tier] and [instance] arguments
  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])

    # Only supports adding an existing instance right now..

    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']}"
      #get(app['id'])
    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.footer = <<-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?
  # construct request
  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))
    # attempt to load prepare-apply to get templateParameter values and prompt for them
    # ok, actually use options/layoutParameters to get the list of parameters
    begin
      prepare_apply_json_response = @apps_interface.prepare_apply(app["id"])
      config = prepare_apply_json_response['data']
      variable_map = config['templateParameter']
      # need to load the instance details to get the app cloud...ugh
      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
      # if e.response && e.response.code == 404
      Morpheus::Logging::DarkPrinter.puts "Unable to load config for app apply, skipping parameter prompting" if Morpheus::Logging.debug?
      # print_rest_exception(ex, options)
      # end
    end
  end

  @apps_interface.setopts(options)
  if options[:validate_only]
    # 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]
      #Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_id, "--refresh", options[:refresh_interval].to_s]+ (options[:remote] ? ["-r",options[:remote]] : []))
      validate_execution_request = wait_for_execution_request(execution_id, options)
    end
  elsif options[:no_validate]
    # skip validate, apply only
    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]
        #Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_id, "--refresh", options[:refresh_interval].to_s]+ (options[:remote] ? ["-r",options[:remote]] : []))
        apply_execution_request = wait_for_execution_request(execution_id, options)
      end
    end
  else
    # validate and then apply
    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]
          #Morpheus::Cli::ExecutionRequestCommand.new.handle(["get", execution_id, "--refresh", options[:refresh_interval].to_s]+ (options[:remote] ? ["-r",options[:remote]] : []))
          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.
  @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.footer = "Get the number of apps."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
     = nil
    if options[:owner]
      created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:owner])
      return if created_by_ids.nil?
      params['createdBy'] = created_by_ids
      # params['ownerId'] = created_by_ids # 4.2.1+
    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)
    # print number only
    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.footer = "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 = {}
  #options[:show_output] = true
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[app]")
    # opts.on( '-n', '--node NODE_ID', "Scope history to specific Container or VM" ) do |node_id|
    #   options[:node_id] = node_id.to_i
    # end
    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.footer = "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 = []
    # API used to only return apps.appTiers
    # now returns detailed instance list as "instances"
    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
    
    # container_ids = instance['containers']
    # if options[:node_id] && container_ids.include?(options[:node_id])
    #   container_ids = [options[:node_id]]
    # end
    params = {}
    params['instanceIds'] = instance_ids
    params.merge!(parse_list_options(options))
    # params['query'] = params.delete('phrase') if params['phrase']
    @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'], # blank like the UI
                  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
        # custom pretty table columns ...
        if options[:include_fields]
          columns = options[:include_fields]
        end
        print cyan
        print as_pretty_table(history_records, columns, options)
        #print_results_pagination(json_response)
        print_results_pagination(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|
      # environment means appContext
      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.footer = "List apps."
  end
  optparse.parse!(args)
  # verify_args!(args:args, optparse:optparse, count:0)
  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))
   = nil
  if options[:owner]
    created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:owner])
    return if created_by_ids.nil?
    params['createdBy'] = created_by_ids
    # params['ownerId'] = created_by_ids # 4.2.1+
  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)
      print_results_pagination(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('--hosts HOSTS', String, "Filter logs to specific Host ID(s)") do |val|
    #   params['servers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    # opts.on('--servers HOSTS', String, "alias for --hosts") do |val|
    #   params['servers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    # opts.on('--vms HOSTS', String, "alias for --hosts") do |val|
    #   params['servers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    # opts.on('--container CONTAINER', String, "Filter logs to specific Container ID(s)") do |val|
    #   params['containers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    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('--nodes HOST', String, "alias for --containers") do |val|
    #   params['containers'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    # end
    opts.on('--start TIMESTAMP','--start TIMESTAMP', "Start timestamp. Default is 30 days ago.") do |val|
      options[:start] = parse_time(val) #.utc.iso8601
    end
    opts.on('--end TIMESTAMP','--end TIMESTAMP', "End timestamp. Default is now.") do |val|
      options[:end] = parse_time(val) #.utc.iso8601
    end
    # opts.on('--interval TIME','--interval TIME', "Interval of time to include, in seconds. Default is 30 days ago.") do |val|
    #   options[:interval] = parse_time(val).utc.iso8601
    # 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.footer = "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 = []
    # API used to only return apps.appTiers
    # now returns detailed instance list as 'instances'
    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
      # print_error yellow,"app is empty",reset,"\n"
      # return 1
    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'] # api works with INFO|WARN
    params.merge!(parse_list_options(options))
    params['query'] = params.delete('phrase') if params['phrase']
    params['order'] = params['direction'] unless params['direction'].nil? # old api version expects order instead of direction
    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)
      print_results_pagination({'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.footer = <<-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?
    # construct request
    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))
      # 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.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_green_success "Prepared to apply app: #{app['name']}"
    print_h1 "Prepared App: #{app['name']}"
    app_config = json_response['data'] 
    # app_config = json_response if app_config.nil?
    puts as_yaml(app_config, options)
    #return get([app['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    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.footer = <<-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?
    # construct request
    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))
      # raise_command_error "Specify at least one option to update.\n#{optparse}" if payload.empty?
    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']}"
      # return _get(app['id'], options)
    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]")
    #JD: UI defaults to on, but perhaps better to be explicate for now.
    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] # old parameter before 6.0
    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] # old parameter before 6.0
    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.footer = "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
    # JD: removeVolumes to maintain the old behavior with pre-3.5.2 appliances, remove me later
    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']}"
      #list([])
    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.footer = "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
  # optional [tier] and [instance] arguments
  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']}"
      #list([])
      # details_options = [app['name']]
      # details(details_options)
    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.footer = "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.footer = "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.footer = <<-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?
  # construct request
  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
  # print_h2 "Workloads", 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)
    # print "\n", reset
  end
  if options[:include_plan_data]
    # print_h2 "Plan Data", options
    if app['type'] == 'terraform'
      print_h2 "Terraform Plan", options
    else
      print_h2 "Plan Data", options
    end
    puts json_response['planData']
    # print "\n", reset
  end
  if options[:include_input]
    # print_h2 "Input", options
    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
    # print "\n", reset
  end
  if options[:include_output]
    # print_h2 "Output", options
    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
    # print "\n", reset
  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.footer = "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]")
    #build_option_type_options(opts, options, update_app_option_types(false))
    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.footer = "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']['environment'] = 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?
        # allow clearing
        owner_id = nil
      elsif options[:owner]
        if owner_id.to_s =~ /\A\d{1,}\Z/
          # allow id without lookup
        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
      # use the filename as the name by default.
      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?
    # construct payload
    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' => {
        }
      }
      # allow arbitrary -O options
      payload.deep_merge!({'page' => passed_options}) unless passed_options.empty?
      # prompt for options
      #params = Morpheus::Cli::OptionTypes.prompt(update_wiki_page_option_types, options[:options], @api_client, options[:params])
      #params = passed_options
      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.footer = "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.footer = "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.footer = "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

      # my_terminal.exec("wiki get #{page['id']}")

      print_h1 "App Wiki Page: #{app['name']}"
      # print_h1 "Wiki Page Details"
      print cyan

      print_description_list({
        "Page ID" => 'id',
        "Name" => 'name',
        #"Category" => 'category',
        #"Ref Type" => 'refType',
        #"Ref ID" => 'refId',
        #"Owner" => lambda {|it| it['account'] ? it['account']['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