Class: Morpheus::Cli::Apps

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

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_name, #get_available_clouds, #get_available_groups, included, #instance_context_options, #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_volumes, #reject_networking_option_types, #reject_service_plan_option_types, #reject_volume_option_types

Methods included from CliCommand

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

Constructor Details

#initializeApps

Returns a new instance of Apps.



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

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

Instance Method Details

#add(args) ⇒ Object



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

def add(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    build_option_type_options(opts, options, add_app_option_types(false))
    # opts.on( '-t', '--template ID', "App Template ID. The app template to use. The default value is 'existing' which means no template, for creating a blank app and adding existing instances." ) do |val|
    #   options['template'] = val
    # end
    # opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
    #   options[:group] = val
    # end
    # opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID." ) do |val|
    #   options[:cloud] = val
    # end
    opts.on('--config JSON', String, "App Config JSON") do |val|
      options['config'] = JSON.parse(val.to_s)
    end
    opts.on('--config-yaml YAML', String, "App Config YAML") do |val|
      options['config'] = YAML.load(val.to_s)
    end
    opts.on('--config-file FILE', String, "App Config from a local JSON or YAML file") do |val|
      options['configFile'] = val.to_s
    end
    build_common_options(opts, options, [:options, :json, :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.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    options[:options] ||= {}
    if args[0] && !options[:options]['name']
      options[:options]['name'] = args[0]
    end
    # options[:options]['template'] ||= options['template']
    if options[:group] # || @active_group_id
      options[:options]['group'] ||= options[:group] # || @active_group_id
    end

    payload = {}
    config_payload = {}
    if options['config']
      config_payload = options['config']
      payload = config_payload
    elsif options['configFile']
      config_file = File.expand_path(options['configFile'])
      if !File.exists?(config_file) || !File.file?(config_file)
        print_red_alert "File not found: #{config_file}"
        return false
      end
      if config_file =~ /\.ya?ml\Z/
        config_payload = YAML.load_file(config_file)
      else
        config_payload = JSON.parse(File.read(config_file))
      end
      payload = config_payload
    else
      # prompt for Name, Description, Group, Environment
      payload = {}
      params = Morpheus::Cli::OptionTypes.prompt(add_app_option_types, options[:options], @api_client, options[:params])
      params = params.deep_compact! # remove nulls and blank strings
      group = find_group_by_name_or_id_for_provisioning(params.delete('group'))
      return if group.nil?
      payload.merge!(params)
      payload['group'] = {id: group['id'], name: group['name']}
    end

    # allow creating a blank app by default
    # sux having go merge this into user passed config/configFile
    # but it's better than making them know to enter it.
    if !payload['id']
      payload['id'] = 'existing'
      payload['templateName'] = 'Existing Instances'
    else
      # maybe validate template id
      # app_template = find_app_template_by_id(payload['id'])
    end

    if options[:dry_run]
      print_dry_run @apps_interface.dry.create(payload)
      return
    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']
        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([app['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_instance(args) ⇒ Object



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

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.join(' ')}\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

    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



782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# File 'lib/morpheus/cli/apps.rb', line 782

def apply_security_groups(args)
  options = {}
  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
      options[:securityGroupIds] = []
      clear_or_secgroups_specified = true
    end
    opts.on( '-s', '--secgroups SECGROUPS', "Apply the specified comma separated security group ids" ) do |secgroups|
      options[:securityGroupIds] = secgroups.split(",")
      clear_or_secgroups_specified = true
    end
    opts.on( '-h', '--help', "Prints 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.join(' ')}\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])
    if options[:dry_run]
      print_dry_run @apps_interface.dry.apply_security_groups(app['id'], options)
      return
    end
    @apps_interface.apply_security_groups(app['id'], options)
    security_groups([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/morpheus/cli/apps.rb', line 22

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @apps_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).apps
  @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
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
end

#firewall_disable(args) ⇒ Object

def stop(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} stop expects 1 argument and received #{args.count}: #{args.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    app = find_app_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @apps_interface.dry.stop(app['id'])
      return
    end
    @apps_interface.stop(app['id'])
    list([])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

def start(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} start expects 1 argument and received #{args.count}: #{args.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    app = find_app_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @apps_interface.dry.start(app['id'])
      return
    end
    @apps_interface.start(app['id'])
    list([])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

def restart(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} restart expects 1 argument and received #{args.count}: #{args.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    app = find_app_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @apps_interface.dry.restart(app['id'])
      return
    end
    @apps_interface.restart(app['id'])
    list([])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end


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

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.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    app = find_app_by_name_or_id(args[0])
    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



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

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.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    app = find_app_by_name_or_id(args[0])
    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



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

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[app]")
    build_common_options(opts, options, [:json, :dry_run])
    opts.footer = "Get details about 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} get expects 1 argument and received #{args.count}: #{args.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    app = find_app_by_name_or_id(args[0])
    if options[:dry_run]
      print_dry_run @apps_interface.dry.get(app['id'])
      return
    end
    json_response = @apps_interface.get(app['id'])
    app = json_response['app']
    if options[:json]
      print JSON.pretty_generate(json_response)
      return
    end
    print_h1 "App Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Description" => 'description',
      # "Group" => lambda {|it| it['group'] ? it['group']['name'] : it['siteId'] },
      "Account" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Status" => lambda {|it| format_app_status(it) }
    }
    print_description_list(description_cols, app)

    stats = app['stats']
    if app['instanceCount'].to_i > 0
      print_h2 "App Usage"
      print_stats_usage(stats, {include: [:memory, :storage]})
    end

    app_tiers = app['appTiers']
    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']}\n"
        print cyan
        instances = (app_tier['appInstances'] || []).collect {|it| it['instance']}
        if instances.empty?
          puts yellow, "This tier is empty", reset
        else
          instance_table = 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 == '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
          tp instance_table, :id, :name, :cloud, :type, :environment, :nodes, :connection, :status
        end
      end
    end
    print cyan

    print reset,"\n"

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

#handle(args) ⇒ Object



33
34
35
# File 'lib/morpheus/cli/apps.rb', line 33

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/morpheus/cli/apps.rb', line 37

def list(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :json, :dry_run])
    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.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    params = {}
    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end

    if options[:dry_run]
      print_dry_run @apps_interface.dry.get(params)
      return
    end

    json_response = @apps_interface.get(params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    apps = json_response['apps']
    title = "Morpheus Apps"
    subtitles = []
    # if group
    #   subtitles << "Group: #{group['name']}".strip
    # end
    # if cloud
    #   subtitles << "Cloud: #{cloud['name']}".strip
    # end
    if params[:phrase]
      subtitles << "Search: #{params[:phrase]}".strip
    end
    print_h1 title, subtitles
    if apps.empty?
      print cyan,"No apps found.",reset,"\n"
    else
      print_apps_table(apps)
      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



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

def logs(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[app]")
    build_common_options(opts, options, [:list, :json, :dry_run])
    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.join(' ')}\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 = {}
    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end
    params[:query] = params.delete(:phrase) unless params[:phrase].nil?
    if options[:dry_run]
      print_dry_run @logs_interface.dry.container_logs(containers, params)
      return
    end
    logs = @logs_interface.container_logs(containers, params)
    if options[:json]
      puts as_json(logs, options)
      return 0
    else
      title = "App Logs: #{app['name']}"
      subtitles = []
      if params[:query]
        subtitles << "Search: #{params[:query]}".strip
      end
      # todo: startMs, endMs, sorts insteaad of sort..etc
      print_h1 title, subtitles
      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 reset,"\n"
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/morpheus/cli/apps.rb', line 422

def remove(args)
  options = {}
  query_params = {keepBackups: 'off', force: 'off'}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[app] [-fB]")
    opts.on( '-f', '--force', "Force Delete" ) do
      query_params[:force] = 'on'
    end
    opts.on( '-B', '--keep-backups', "Preserve copy of backups" ) do
      query_params[:keepBackups] = 'on'
    end
    opts.on('--remove-instances [on|off]', ['on','off'], "Remove instances. Default is on.") do |val|
      query_params[:removeInstances] = val
    end
    opts.on('--remove-volumes [on|off]', ['on','off'], "Remove Volumes. Default is on. Applies to certain types only.") do |val|
      query_params[:removeVolumes] = val
    end
    opts.on('--releaseEIPs', ['on','off'], "Release EIPs. Default is false. Applies to Amazon only.") do |val|
      query_params[:releaseEIPs] = val
    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.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    app = find_app_by_name_or_id(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the app '#{app['name']}'?", options)
      return 9
    end
    if 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



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

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.join(' ')}\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']

    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

#security_groups(args) ⇒ Object



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

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.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    app = find_app_by_name_or_id(args[0])
    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']}"
    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

#update(args) ⇒ Object



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

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))
    build_common_options(opts, options, [:options, :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.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    app = find_app_by_name_or_id(args[0])

    payload = {
      'app' => {id: app["id"]}
    }

    params = options[:options] || {}

    if params.empty?
      print_red_alert "Specify atleast one option to update"
      puts optparse
      exit 1
    end

    #puts "parsed params is : #{params.inspect}"
    app_keys = ['name', 'description', 'environment']
    params = params.select {|k,v| app_keys.include?(k) }
    payload['app'].merge!(params)

    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']}"
      list([])
      # details_options = [payload['app']['name']]
      # details(details_options)
    end

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