Class: Morpheus::Cli::Apps

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

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

#api_client, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #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_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #get_available_clouds, #get_available_groups, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_types_interface, #instances_interface, #options_interface, #prompt_evars, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_resize_volumes, #prompt_security_groups, #prompt_volumes, #reject_networking_option_types, #reject_service_plan_option_types, #reject_volume_option_types

Methods included from AccountsHelper

#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_role_type, #format_user_role_names, #get_access_string, included, #print_accounts_table, #print_roles_table, #print_users_table, #roles_interface, #user_groups_interface, #users_interface

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_refresh_interval, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #render_with_format, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeApps

Returns a new instance of Apps.



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

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

Instance Method Details

#_get(arg, options = {}) ⇒ Object



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# File 'lib/morpheus/cli/apps.rb', line 580

def _get(arg, options={})
  begin
    app = find_app_by_name_or_id(arg)
    @apps_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @apps_interface.dry.get(app['id'])
      return
    end
    json_response = @apps_interface.get(app['id'])

    render_result = render_with_format(json_response, options, 'blueprint')
    return 0 if render_result

    app = json_response['app']
    app_tiers = app['appTiers']
    print_h1 "App Details", [], options
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Description" => 'description',
      "Blueprint" => lambda {|it| it['blueprint'] ? it['blueprint']['name'] : '' },
      "Group" => lambda {|it| it['group'] ? it['group']['name'] : it['siteId'] },
      "Account" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Tiers" => lambda {|it| 
        # it['instanceCount']
        tiers = []
        app_tiers = it['appTiers'] || []
        app_tiers.each do |app_tier|
          tiers << app_tier['tier']
        end
        "#{tiers.collect {|it| it.is_a?(Hash) ? it['name'] : it }.join(',')}"
      },
      "Instances" => lambda {|it| 
        # it['instanceCount']
        instances = []
        app_tiers = it['appTiers'] || []
        app_tiers.each do |app_tier|
          instances += (app_tier['appInstances'] || []).collect {|it| it['instance']}.flatten().compact
        end
        #"(#{instances.count})"
        "(#{instances.count}) #{instances.collect {|it| it['name'] }.join(',')}"
      },
      "Containers" => lambda {|it| 
        #it['containerCount'] 
        containers = []
        app_tiers = it['appTiers'] || []
        app_tiers.each do |app_tier|
          containers += (app_tier['appInstances'] || []).collect {|it| it['instance']['containers']}.flatten().compact
        end
        #"(#{containers.count})"
        "(#{containers.count}) #{containers.collect {|it| it }.join(',')}"
      },
      "Status" => lambda {|it| format_app_status(it) }
    }
    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?
      puts yellow, "This app is empty", reset
    else
      app_tiers.each do |app_tier|
        # print_h2 "Tier: #{app_tier['tier']['name']}", options
        print_h2 "#{app_tier['tier']['name']}", options
        print cyan
        instances = (app_tier['appInstances'] || []).collect {|it| it['instance']}
        if instances.empty?
          puts yellow, "This tier is empty", reset
        else
          instances_rows = instances.collect do |instance|
            # JD: fix bug here, status is not returned because withStats: false !?
            status_string = instance['status'].to_s
            if status_string == 'running'
              status_string = "#{green}#{status_string.upcase}#{cyan}"
            elsif status_string == 'provisioning'
              status_string = "#{cyan}#{status_string.upcase}#{cyan}"
            elsif status_string == 'stopped' or status_string == 'failed'
              status_string = "#{red}#{status_string.upcase}#{cyan}"
            elsif status_string == 'unknown'
              status_string = "#{white}#{status_string.upcase}#{cyan}"
            else
              status_string = "#{yellow}#{status_string.upcase}#{cyan}"
            end
            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: status_string, 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(arg, options)
      end
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#_restart(app_id, options) ⇒ Object



1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
# File 'lib/morpheus/cli/apps.rb', line 1168

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



1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
# File 'lib/morpheus/cli/apps.rb', line 1124

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



1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
# File 'lib/morpheus/cli/apps.rb', line 1080

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



1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
# File 'lib/morpheus/cli/apps.rb', line 1516

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

    open_command = nil
    if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
      open_command = "start #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /darwin/
      open_command = "open #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
      open_command = "xdg-open #{link}"
    end

    if options[:dry_run]
      puts "system: #{open_command}"
      return 0
    end

    system(open_command)
    
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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
# File 'lib/morpheus/cli/apps.rb', line 157

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( '--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
      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['cloud'] = {'id' => cloud['id'], 'name' => cloud['name']}
      end
      
      # Environment
      if options[:environment]
        payload['environment'] = options[:environment]
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'environment', 'fieldLabel' => 'Environment', 'type' => 'text', 'required' => false}], options[:options])
        payload['environment'] = v_prompt['environment'] unless v_prompt['environment'].to_s.empty?
      end
      # payload['appContext'] = payload['environment'] if payload['environment']


      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'] }
            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, payload['environment'], 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[: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
                    instance_prompt_options[:extra_field_context] = "#{tier_name}.#{instance_index}" 
                    # this provisioning helper method handles all (most) of the parsing and prompting
                    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')
                    # 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

    # 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
    exit 1
  end
end

#add_instance(args) ⇒ Object



802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
# File 'lib/morpheus/cli/apps.rb', line 802

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



1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
# File 'lib/morpheus/cli/apps.rb', line 1288

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

#connect(opts) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/morpheus/cli/apps.rb', line 30

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @accounts_interface = @api_client.accounts
  @users_interface = @api_client.users
  @apps_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).apps
  @blueprints_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).blueprints
  @instance_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instance_types
  @instances_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instances
  @options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).options
  @groups_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).groups
  @logs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).logs
  @processes_interface = @api_client.processes
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
end

#count(args) ⇒ Object



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

def count(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[options]")
    opts.on( '--created-by USER', "Created By User Username or ID" ) do |val|
      options[:created_by] = val
    end
    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[:created_by]
      created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:created_by])
      return if created_by_ids.nil?
      params['createdBy'] = created_by_ids
    end
    @apps_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @apps_interface.dry.list(params)
      return
    end
    json_response = @apps_interface.list(params)
    # 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



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

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



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

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



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

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_common_options(opts, options, [:json, :yaml, :csv, :fields, :outfile, :dry_run, :remote])
    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



45
46
47
# File 'lib/morpheus/cli/apps.rb', line 45

def handle(args)
  handle_subcommand(args)
end

#history(args) ⇒ Object



1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
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
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
# File 'lib/morpheus/cli/apps.rb', line 1338

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 = []
    app['appTiers'].each do |app_tier|
      app_tier['appInstances'].each do |app_instance|
        instance_ids << app_instance['instance']['id']
      end
    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) unless params[:phrase].nil?
    @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



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/morpheus/cli/apps.rb', line 49

def list(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '--created-by USER', "Created By User Username or ID" ) do |val|
      options[:created_by] = val
    end
    opts.on('--details', "Display more details: memory and storage usage used / max values." ) do
      options[:details] = true
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List apps."
  end
  optparse.parse!(args)
  if args.count != 0
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} list expects 0 arguments and received #{args.count}: #{args}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
     = nil
    if options[:created_by]
      created_by_ids = find_all_user_ids( ? ['id'] : nil, options[:created_by])
      return if created_by_ids.nil?
      params['createdBy'] = created_by_ids
    end
    @apps_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @apps_interface.dry.list(params)
      return
    end

    json_response = @apps_interface.list(params)
    if options[:json]
      puts as_json(json_response, options, "apps")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "apps")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['apps'], options)
      return 0
    end
    
    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"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#logs(args) ⇒ Object



984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
# File 'lib/morpheus/cli/apps.rb', line 984

def logs(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[app]")
    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])
    containers = []
    app['appTiers'].each do |app_tier|
      app_tier['appInstances'].each do |app_instance|
        containers += app_instance['instance']['containers']
      end
    end
    params = {}
    params.merge!(parse_list_options(options))
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    @logs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @logs_interface.dry.container_logs(containers, params)
      return
    end
    json_response = @logs_interface.container_logs(containers, params)
    render_result = render_with_format(json_response, options, 'data')
    return 0 if render_result

    logs = json_response
    title = "App Logs: #{app['name']}"
    subtitles = parse_list_subtitles(options)
    if params[:query]
      subtitles << "Search: #{params[:query]}".strip
    end
    # todo: startMs, endMs, sorts insteaad of sort..etc
    print_h1 title, subtitles, options
    if logs['data'].empty?
      puts "#{cyan}No logs found.#{reset}"
    else
      logs['data'].reverse.each do |log_entry|
        log_level = ''
        case log_entry['level']
        when 'INFO'
          log_level = "#{blue}#{bold}INFO#{reset}"
        when 'DEBUG'
          log_level = "#{white}#{bold}DEBUG#{reset}"
        when 'WARN'
          log_level = "#{yellow}#{bold}WARN#{reset}"
        when 'ERROR'
          log_level = "#{red}#{bold}ERROR#{reset}"
        when 'FATAL'
          log_level = "#{red}#{bold}FATAL#{reset}"
        end
        puts "[#{log_entry['ts']}] #{log_level} - #{log_entry['message'].to_s.strip}"
      end
      print_results_pagination({'meta'=>{'total'=>json_response['total'],'size'=>json_response['data'].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

#remove(args) ⇒ Object



867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
# File 'lib/morpheus/cli/apps.rb', line 867

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('--releaseEIPs [on|off]', ['on','off'], "Release EIPs. Default is on. Applies to Amazon only.") do |val|
      query_params[:releaseEIPs] = val.nil? ? 'on' : val
    end
    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



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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/morpheus/cli/apps.rb', line 928

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



1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
# File 'lib/morpheus/cli/apps.rb', line 1144

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



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

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



1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
# File 'lib/morpheus/cli/apps.rb', line 1100

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

#stop(args) ⇒ Object



1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
# File 'lib/morpheus/cli/apps.rb', line 1056

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



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

def update(args)
  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( '--description VALUE', String, "Description" ) do |val|
      options[:description] = val
    end
    opts.on( '--environment VALUE', String, "Environment" ) do |val|
      options[:environment] = 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?

    payload = {}
    if options[:payload]
      payload = options[:payload]
    else
      payload = {
        'app' => {id: app["id"]}
      }
      params = options[:options] || {}
      if options[:name]
        params['name'] = options[:name]
      end
      if options[:description]
        params['description'] = options[:description]
      end
      if options[:environment]
        # params['environment'] = options[:environment]
        params['appContext'] = options[:environment]
      end
      if options[:group]
        group = find_group_by_name_or_id_for_provisioning(options[:group])
        return 1 if group.nil?
        params['group'] = {'id' => group['id'], 'name' => group['name']}
      end
      if params.empty?
        print_red_alert "Specify at least one option to update"
        puts optparse
        return 1
      end
      payload['app'].merge!(params)
      # api bug requires this to be at the root level as well right now
      if payload['app'] && payload['app']['group']
        payload['group'] = payload['app']['group']
      end
    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)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Updated app #{app['name']}"
      # print details
      get_args = [app['id']] + (options[:remote] ? ["-r",options[:remote]] : [])
      get(get_args)
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_wiki(args) ⇒ Object



1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
# File 'lib/morpheus/cli/apps.rb', line 1670

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.exists?(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



1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
# File 'lib/morpheus/cli/apps.rb', line 1491

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



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
1661
1662
1663
1664
1665
1666
1667
1668
# File 'lib/morpheus/cli/apps.rb', line 1627

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"

    open_command = nil
    if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
      open_command = "start #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /darwin/
      open_command = "open #{link}"
    elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
      open_command = "xdg-open #{link}"
    end

    if options[:dry_run]
      puts "system: #{open_command}"
      return 0
    end

    system(open_command)
    
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#wiki(args) ⇒ Object



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

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