Class: RHC::Commands::App

Inherits:
Base show all
Includes:
RHC::CartridgeHelpers, DeploymentHelpers, GitHelpers, SSHHelpers
Defined in:
lib/rhc/commands/app.rb

Direct Known Subclasses

Configure, Create, Delete, Deploy, ForceStop, Reload, Restart, Show, Start, Stop, Tidy

Constant Summary

Constants included from Helpers

Helpers::BOUND_WARNING, Helpers::PREFIX, Helpers::ROLES

Instance Method Summary collapse

Methods included from SSHHelpers

#check_ssh_executable!, #exe?, #fingerprint_for_default_key, #fingerprint_for_local_key, #generate_ssh_key_ruby, #has_ssh?, #restore_snapshot, #run_on_gears, #save_snapshot, #ssh_command_for_op, #ssh_key_triple_for, #ssh_key_triple_for_default_key, #ssh_keygen_fallback, #ssh_ruby, #ssh_send_file_ruby, #ssh_send_url_ruby, #ssh_version, #table_from_gears

Methods included from GitHelpers

#git_clone_application, #git_clone_deploy_hooks, #git_clone_repo, #git_cmd, #git_config_get, #git_config_set, #git_remote_add, #git_version, #has_git?

Methods inherited from Base

#initialize

Methods included from RHC::ContextHelpers

#find_app, #find_domain, #find_membership_container, #find_team, #from_local_git, included, #namespace_context, #server_context

Methods included from Helpers

#agree, #certificate_file, #client_from_options, #collect_env_vars, #color, #confirm_action, #date, #datetime_rfc3339, #debug, #debug?, #debug_error, #decode_json, #deprecated, #deprecated_command, #disable_deprecated?, #distance_of_time_in_words, #env_var_regex_pattern, #error, #exec, #host_exists?, #hosts_file_contains?, #human_size, #info, #interactive?, #jruby?, #mac?, #openshift_online_server?, #openshift_rest_endpoint, #openshift_server, #openshift_url, #pluralize, #results, #role_name, #run_with_tee, #ssh_string, #ssh_string_parts, #ssl_options, #success, #system_path, #table_heading, #to_host, #to_uri, #token_for_user, #unix?, #user_agent, #warn, #windows?, #with_tolerant_encoding

Methods included from OutputHelpers

#default_display_env_var, #display_app, #display_app_configurations, #display_authorization, #display_cart, #display_cart_storage_info, #display_cart_storage_list, #display_deployment, #display_deployment_list, #display_domain, #display_env_var_list, #display_key, #display_team, #format_cart_gears, #format_cart_header, #format_gear_info, #format_key_header, #format_scaling_info, #format_usage_message

Constructor Details

This class inherits a constructor from RHC::Commands::Base

Instance Method Details

#configure(app_name) ⇒ Object



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/rhc/commands/app.rb', line 467

def configure(app_name)
  rest_app = find_app

  app_options = {}
  app_options[:auto_deploy] = options.auto_deploy if !options.auto_deploy.nil?
  app_options[:keep_deployments] = options.keep_deployments if options.keep_deployments
  app_options[:deployment_branch] = options.deployment_branch if options.deployment_branch
  app_options[:deployment_type] = options.deployment_type if options.deployment_type

  if app_options.present?
    paragraph do
      say "Configuring application '#{app_name}' ... "
      rest_app.configure(app_options)
      success "done"
    end
  end

  paragraph { display_app(find_app, nil, [:auto_deploy, :keep_deployments, :deployment_type, :deployment_branch]) }

  paragraph { say "Your application '#{rest_app.name}' is #{app_options.empty? ? '' : 'now '}configured as listed above." }
  paragraph { say "Use 'app show-app #{rest_app.name} --configuration' to check your configuration values any time." } if app_options.present?

  0
end

#create(name, cartridges) ⇒ Object

Raises:

  • (ArgumentError)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
# File 'lib/rhc/commands/app.rb', line 65

def create(name, cartridges)
  check_config!

  check_name!(name)

  arg_envs, cartridges = cartridges.partition{|item| item.match(env_var_regex_pattern)}

  rest_domain = check_domain!
  rest_app = nil
  repo_dir = nil

  if options.from_app
    raise RHC::AppCloneNotSupportedException, "The server does not support creating apps based on others (rhc create-app --from-app)." if (!rest_domain.has_param?('ADD_APPLICATION', 'cartridges[][name]') || !rest_domain.has_param?('ADD_APPLICATION', 'cartridges[][url]'))
    raise ArgumentError, "Option --from-code is incompatible with --from--app. When creating an app based on another resource you can either specify a Git repository URL with --from-code or an existing app name with --from-app." if options.from_code
    raise ArgumentError, "Option --no-dns is incompatible with --from-app. We need to propagate the new app DNS to be able to configure it." if options.dns == false
    raise ArgumentError, "Do not specify cartridges when creating an app based on another one. All cartridges will be copied from the original app." if !(cartridges || []).empty?

    from_app = find_app(:app => options.from_app)

    arg_envs = from_app.environment_variables.collect {|env| "#{env.name}=#{env.value} "} + arg_envs
    cartridges = from_app.cartridges.reject{|c| c.tags.include?('web_proxy')}.collect{|c| c.custom? ? c.url : c.name}
  end

  cartridges = check_cartridges(cartridges, &require_one_web_cart)

  options.default \
    :dns => true,
    :git => true

  raise ArgumentError, "You have named both your main application and your Jenkins application '#{name}'. In order to continue you'll need to specify a different name with --enable-jenkins or choose a different application name." if jenkins_app_name == name && enable_jenkins?

  cart_names = cartridges.collect do |c|
    c.usage_rate? ? "#{c.short_name} (addtl. costs may apply)" : c.short_name
  end.join(', ')

  env = collect_env_vars(arg_envs.concat(Array(options.env)))
  if env.present? && !rest_domain.supports_add_application_with_env_vars?
    env = []
    warn "Server does not support environment variables."
  end

  scaling = options.scaling

  if from_app
    scaling = from_app.scalable if scaling.nil?

    cartridges = from_app.cartridges.reject{|c| c.tags.include?('web_proxy')}.collect do |cartridge|
      {
        :name => (cartridge.name if !cartridge.custom?),
        :url => (cartridge.url if cartridge.custom?),
        :gear_size => options.gear_size || cartridge.gear_profile,
        :additional_gear_storage => (cartridge.additional_gear_storage if cartridge.additional_gear_storage > 0),
        :scales_from => (cartridge.scales_from if cartridge.scalable?),
        :scales_to => (cartridge.scales_to if cartridge.scalable?)
      }.reject{|k,v| v.nil? }
    end
  end

  paragraph do
    header "Application Options"
    say table([["Domain:", options.namespace],
           ["Cartridges:", cart_names],
          (["Source Code:", options.from_code] if options.from_code),
           (["From app:", from_app.name] if from_app),
           ["Gear Size:", options.gear_size || (from_app ? "Copied from '#{from_app.name}'" : "default")],
           ["Scaling:", (scaling ? "yes" : "no") + (from_app && options.scaling.nil? ? " (copied from '#{from_app.name}')" : '')],
          (["Environment Variables:", env.map{|item| "#{item.name}=#{item.value}"}.join(', ')] if env.present?),
          ].compact
         )
  end

  paragraph do
    say "Creating application '#{name}' ... "

    # create the main app
    rest_app = create_app(name, cartridges, rest_domain, options.gear_size, scaling, options.from_code, env, options.auto_deploy, options.keep_deployments, options.deployment_branch, options.deployment_type)
    success "done"

    paragraph{ indent{ success rest_app.messages.map(&:strip) } }
  end

  build_app_exists = rest_app.building_app

  if enable_jenkins?

    unless build_app_exists
      paragraph do
        say "Setting up a Jenkins application ... "

        begin
          build_app_exists = add_jenkins_app(rest_domain)

          success "done"
          paragraph{ indent{ success build_app_exists.messages.map(&:strip) } }

        rescue Exception => e
          warn "not complete"
          add_issue("Jenkins failed to install - #{e}",
                    "Installing jenkins and jenkins-client",
                    "app create-app jenkins",
                    "app add-cartridge jenkins-client -a #{rest_app.name}")
        end
      end
    end

    paragraph do
      messages = []
      add_jenkins_client_to(rest_app, messages)
      paragraph{ indent{ success messages.map(&:strip) } }
    end if build_app_exists
  end

  debug "Checking SSH keys through the wizard"
  check_sshkeys! unless options.no_keys

  if options.dns
    paragraph do
      say "Waiting for your DNS name to be available ... "
      if dns_propagated? rest_app.host
        success "done"
      else
        warn "failure"
        add_issue("We were unable to lookup your hostname (#{rest_app.host}) in a reasonable amount of time and can not clone your application.",
                  "Clone your git repo",
                  "app git-clone #{rest_app.name}")

        output_issues(rest_app)
        return 0
      end
    end

    if from_app
      say "Setting deployment configuration ... "
      rest_app.configure({:auto_deploy => from_app.auto_deploy, :keep_deployments => from_app.keep_deployments , :deployment_branch => from_app.deployment_branch, :deployment_type => from_app.deployment_type})
      success 'done'

      snapshot_filename = temporary_snapshot_filename(from_app.name)
      save_snapshot(from_app, snapshot_filename)
      restore_snapshot(rest_app, snapshot_filename)
      File.delete(snapshot_filename) if File.exist?(snapshot_filename)

      paragraph { warn "The application '#{from_app.name}' has aliases set which were not copied. Please configure the aliases of your new application manually." } unless from_app.aliases.empty?
    end

    if options.git
      section(:now => true, :top => 1, :bottom => 1) do
        begin
          if has_git?
            repo_dir = git_clone_application(rest_app)
          else
            warn "You do not have git installed, so your application's git repo will not be cloned"
          end
        rescue RHC::GitException => e
          warn "#{e}"
          unless RHC::Helpers.windows? and windows_nslookup_bug?(rest_app)
            add_issue("We were unable to clone your application's git repo - #{e}",
                      "Clone your git repo",
                      "app git-clone #{rest_app.name}")
          end
        end
      end
    end
  end

  output_issues(rest_app) if issues?

  paragraph do
    say "Your application '#{rest_app.name}' is now available."
    paragraph do
      indent do
        say table [
            ['URL:', rest_app.app_url],
            ['SSH to:', rest_app.ssh_string],
            ['Git remote:', rest_app.git_url],
            (['Cloned to:', repo_dir] if repo_dir)
          ].compact
      end
    end
  end
  paragraph{ say "Run 'app show-app #{name}' for more details about your app." }

  0
end

#delete(app) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/rhc/commands/app.rb', line 257

def delete(app)
  rest_app = find_app

  confirm_action "#{color("This is a non-reversible action! Your application code and data will be permanently deleted if you continue!", :yellow)}\n\nAre you sure you want to delete the application '#{app}'?"

  say "Deleting application '#{rest_app.name}' ... "
  rest_app.destroy
  success "deleted"

  paragraph{ rest_app.messages.each{ |s| success s } }

  0
end

#deploy(ref) ⇒ Object



450
451
452
453
454
455
456
457
458
# File 'lib/rhc/commands/app.rb', line 450

def deploy(ref)
  rest_app = find_app

  raise RHC::DeploymentsNotSupportedException.new if !rest_app.supports? "DEPLOY"

  deploy_artifact(rest_app, ref, options.hot_deploy, options.force_clean_build)

  0
end

#force_stop(app) ⇒ Object



315
316
317
318
319
320
# File 'lib/rhc/commands/app.rb', line 315

def force_stop(app)
  app_action :stop, true

  results { say "#{app} force stopped" }
  0
end

#reload(app) ⇒ Object



335
336
337
338
339
340
# File 'lib/rhc/commands/app.rb', line 335

def reload(app)
  app_action :reload

  results { say "#{app} config reloaded" }
  0
end

#restart(app) ⇒ Object



325
326
327
328
329
330
# File 'lib/rhc/commands/app.rb', line 325

def restart(app)
  app_action :restart

  results { say "#{app} restarted" }
  0
end

#scale_down(app) ⇒ Object



304
305
306
307
308
309
# File 'lib/rhc/commands/app.rb', line 304

def scale_down(app)
  app_action :scale_down

  results { say "#{app} scaled down" }
  0
end

#scale_up(app) ⇒ Object



294
295
296
297
298
299
# File 'lib/rhc/commands/app.rb', line 294

def scale_up(app)
  app_action :scale_up

  results { say "#{app} scaled up" }
  0
end

#show(app_name) ⇒ Object



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
# File 'lib/rhc/commands/app.rb', line 382

def show(app_name)

  if options.state
    find_app(:with_gear_groups => true).each do |gg|
      say "Cartridge #{gg.cartridges.collect { |c| c['name'] }.join(', ')} is #{gear_group_state(gg.gears.map{ |g| g['state'] })}"
    end

  elsif options.gears && options.gears != true
    groups = find_app(:with_gear_groups => true)

    case options.gears
    when 'quota'
      opts = {:as => :gear, :split_cells_on => /\s*\t/, :header => ['Gear', 'Cartridges', 'Used', 'Limit'], :align => [nil, nil, :right, :right]}
      table_from_gears('echo "$(du --block-size=1 -s 2>/dev/null | cut -f 1)"', groups, opts) do |gear, data, group|
        [gear['id'], group.cartridges.collect{ |c| c['name'] }.join(' '), (human_size(data.chomp) rescue 'error'), human_size(group.quota)]
      end
    when 'ssh'
      groups.each{ |group| group.gears.each{ |g| say (ssh_string(g['ssh_url']) or raise NoPerGearOperations) } }
    else
      run_on_gears(ssh_command_for_op(options.gears), groups)
    end

  elsif options.gears
    gear_info = find_app(:with_gear_groups => true).map do |group|
      group.gears.map do |gear|
        [
          gear['id'],
          gear['state'] == 'started' ? gear['state'] : color(gear['state'], :yellow),
          group.cartridges.collect{ |c| c['name'] }.join(' '),
          group.gear_profile,
          ssh_string(gear['ssh_url'])
        ]
      end
    end.flatten(1)

    say table(gear_info, :header => ['ID', 'State', 'Cartridges', 'Size', 'SSH URL'])

  elsif options.configuration
    display_app_configurations(find_app)
    paragraph { say "Use 'app configure-app' to change the configuration values of this application." }

  else
    app = find_app(:include => :cartridges)
    display_app(app, app.cartridges, nil, options.verbose)
  end

  0
end

#start(app) ⇒ Object



274
275
276
277
278
279
# File 'lib/rhc/commands/app.rb', line 274

def start(app)
  app_action :start

  results { say "#{app} started" }
  0
end

#stop(app) ⇒ Object



284
285
286
287
288
289
# File 'lib/rhc/commands/app.rb', line 284

def stop(app)
  app_action :stop

  results { say "#{app} stopped" }
  0
end

#tidy(app) ⇒ Object



345
346
347
348
349
350
# File 'lib/rhc/commands/app.rb', line 345

def tidy(app)
  app_action :tidy

  results { say "#{app} cleaned up" }
  0
end