Class: EY::CLI

Inherits:
Thor show all
Includes:
Thor::Actions
Defined in:
lib/engineyard/cli.rb,
lib/engineyard/cli/ui.rb,
lib/engineyard/cli/api.rb,
lib/engineyard/cli/web.rb,
lib/engineyard/cli/recipes.rb

Defined Under Namespace

Classes: API, Recipes, UI, Web

Constant Summary

Constants inherited from Thor

Thor::DynamicTask, Thor::HELP_MAPPINGS, Thor::HiddenTask, Thor::THOR_RESERVED_WORDS, Thor::UndefinedTaskError, Thor::VERSION

Instance Attribute Summary

Attributes included from Thor::Base

#args, #options, #parent_options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Thor

check_unknown_options!, check_unknown_options?, command_help, default_command, desc, help, long_desc, map, method_option, method_options, package_name, printable_commands, register, stop_on_unknown_option!, stop_on_unknown_option?, subcommand, subcommands

Methods included from Thor::Base

included, #initialize, register_klass_file, shell, shell=, subclass_files, subclasses

Class Method Details

.start(given_args = ARGV, config = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/engineyard/cli.rb', line 20

def self.start(given_args=ARGV, config={})
  Thor::Base.shell = EY::CLI::UI
  ui = EY::CLI::UI.new
  super(given_args, {:shell => ui}.merge(config))
rescue EY::Error, EY::CloudClient::Error => e
  ui.print_exception(e)
  raise
rescue Interrupt => e
  puts
  ui.print_exception(e)
  ui.say("Quitting...")
  raise
rescue SystemExit, Errno::EPIPE
  # don't print a message for safe exits
  raise
rescue Exception => e
  ui.print_exception(e)
  raise
end

Instance Method Details

#deployObject



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
# File 'lib/engineyard/cli.rb', line 123

def deploy
  app_env = fetch_app_environment(options[:app], options[:environment], options[:account])

  env_config    = config.environment_config(app_env.environment_name)
  deploy_config = EY::DeployConfig.new(options, env_config, repo, ui)

  deployment = app_env.new_deployment({
    :ref                => deploy_config.ref,
    :migrate            => deploy_config.migrate,
    :migrate_command    => deploy_config.migrate_command,
    :extra_config       => deploy_config.extra_config,
    :serverside_version => serverside_version,
  })

  runner = serverside_runner(app_env, deploy_config.verbose, deployment.serverside_version, options[:ignore_bad_master])

  out = EY::CLI::UI::Tee.new(ui.out, deployment.output)
  err = EY::CLI::UI::Tee.new(ui.err, deployment.output)

  ui.info  "Beginning deploy...", :green
  begin
    deployment.start
  rescue
    ui.error "Error encountered before deploy. Deploy not started."
    raise
  end

  begin
    ui.show_deployment(deployment)
    out << "Deploy initiated.\n"

    runner.deploy do |args|
      args.config  = deployment.config          if deployment.config
      if deployment.migrate
        args.migrate = deployment.migrate_command
      else
        args.migrate = false
      end
      args.ref     = deployment.resolved_ref
    end
    deployment.successful = runner.call(out, err)
  rescue Interrupt
    Signal.trap(:INT) { # The fingers you have used to dial are too fat...
      ui.info "\nRun `ey timeout-deploy` to mark an unfinished deployment as failed."
      exit 1
    }
    err << "Interrupted. Deployment halted.\n"
    ui.warn <<-WARN
Recording interruption of this unfinished deployment in Engine Yard Cloud...

WARNING: Interrupting again may prevent Engine Yard Cloud from recording this
     failed deployment. Unfinished deployments can block future deploys.
    WARN
    raise
  rescue StandardError => e
    deployment.err << "Error encountered during deploy.\n#{e.class} #{e}\n"
    ui.print_exception(e)
    raise
  ensure
    ui.info "Saving log... ", :green
    deployment.finished

    if deployment.successful?
      ui.info "Successful deployment recorded on Engine Yard Cloud.", :green
      ui.info "Run `ey launch` to open the application in a browser."
    else
      ui.info "Failed deployment recorded on Engine Yard Cloud", :green
      raise EY::Error, "Deploy failed"
    end
  end
end

#environmentsObject



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
# File 'lib/engineyard/cli.rb', line 276

def environments
  if options[:all] && options[:simple]
    ui.print_simple_envs api.environments
  elsif options[:all]
    ui.print_envs api.apps
  else
    remotes = nil
    if options[:app] == ''
      repo.fail_on_no_remotes!
      remotes = repo.remotes
    end

    resolver = api.resolve_app_environments({
      :account_name     => options[:account],
      :app_name         => options[:app],
      :environment_name => options[:environment],
      :remotes          => remotes,
    })

    resolver.no_matches do |errors|
      messages = errors
      messages << "Use #{self.class.send(:banner_base)} environments --all to see all environments."
      raise EY::NoMatchesError.new(messages.join("\n"))
    end

    apps = resolver.matches.map { |app_env| app_env.app }.uniq

    if options[:simple]
      if apps.size > 1
        message = "# This app matches multiple Applications in Engine Yard Cloud:\n"
        apps.each { |app| message << "#\t#{app.name}\n" }
        message << "# The following environments contain those applications:\n\n"
        ui.warn(message)
      end
      ui.print_simple_envs(apps.map{ |app| app.environments }.flatten)
    else
      ui.print_envs(apps, config.default_environment)
    end
  end
end

#help(*cmds) ⇒ Object



576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/engineyard/cli.rb', line 576

def help(*cmds)
  if cmds.empty?
    base = self.class.send(:banner_base)
    list = self.class.printable_tasks

    ui.say "Usage:"
    ui.say "  #{base} [--help] [--version] COMMAND [ARGS]"
    ui.say

    ui.say "Deploy commands:"
    deploy_cmds = %w(deploy environments logs rebuild rollback status)
    deploy_cmds.map! do |name|
      list.find{|task| task[0] =~ /^#{base} #{name}/ }
    end
    list -= deploy_cmds

    ui.print_help(deploy_cmds)
    ui.say

    self.class.subcommands.each do |name|
      klass = self.class.subcommand_class_for(name)
      list.reject!{|cmd| cmd[0] =~ /^#{base} #{name}/}
      ui.say "#{name.capitalize} commands:"
      tasks = klass.printable_tasks.reject{|t| t[0] =~ /help$/ }
      ui.print_help(tasks)
      ui.say
    end

    %w(help version).each{|n| list.reject!{|c| c[0] =~ /^#{base} #{n}/ } }
    if list.any?
      ui.say "Other commands:"
      ui.print_help(list)
      ui.say
    end

    self.class.send(:class_options_help, shell)
    ui.say "See '#{base} help COMMAND' for more information on a specific command."
  elsif klass = self.class.subcommand_class_for(cmds.first)
    klass.new.help(*cmds[1..-1])
  else
    super
  end
end

#initObject



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
# File 'lib/engineyard/cli.rb', line 58

def init
  unless EY::Repo.exist?
    raise EY::Error, "Working directory is not a repository. Aborting."
  end

  path = Pathname.new(options['path'] || EY::Config.pathname_for_write)

  existing = {}
  if path.exist?
    ui.warn "Reinitializing existing file: #{path}"
    existing = EY::Config.load_config
  end

  template = EY::Templates::EyYml.new(existing)
  template.write(path)

  ui.info <<-GIT

Configuration generated: #{path}
Go look at it, then add it to your repository!

\tgit add #{path}
\tgit commit -m "Add generated #{path} from ey init"

  GIT
end

#launchObject



630
631
632
633
# File 'lib/engineyard/cli.rb', line 630

def launch
  app_env = fetch_app_environment(options[:app], options[:environment], options[:account])
  Launchy.open(app_env.uri)
end

#loginObject



654
655
656
# File 'lib/engineyard/cli.rb', line 654

def 
  whoami
end

#logoutObject



659
660
661
662
663
664
665
666
667
# File 'lib/engineyard/cli.rb', line 659

def logout
  eyrc = EYRC.load
  if eyrc.delete_api_token
    ui.info "API token removed: #{eyrc.path}"
    ui.info "Run any other command to login again."
  else
    ui.info "Already logged out. Run any other command to login again."
  end
end

#logsObject



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'lib/engineyard/cli.rb', line 546

def logs
  environment = fetch_environment(options[:environment], options[:account])
  environment.logs.each do |log|
    ui.say "Instance: #{log.instance_name}"

    if log.main
      ui.say "Main logs for #{environment.name}:", :green
      ui.say  log.main
    end

    if log.custom
      ui.say "Custom logs for #{environment.name}:", :green
      ui.say  log.custom
    end
  end
end

#rebuildObject



376
377
378
379
380
# File 'lib/engineyard/cli.rb', line 376

def rebuild
  environment = fetch_environment(options[:environment], options[:account])
  ui.info "Updating instances on #{environment.hierarchy_name}"
  environment.rebuild
end

#rollbackObject



402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/engineyard/cli.rb', line 402

def rollback
  app_env = fetch_app_environment(options[:app], options[:environment], options[:account])
  env_config    = config.environment_config(app_env.environment_name)
  deploy_config = EY::DeployConfig.new(options, env_config, repo, ui)

  ui.info "Rolling back #{app_env.hierarchy_name}"

  runner = serverside_runner(app_env, deploy_config.verbose)
  runner.rollback do |args|
    args.config = {'deployed_by' => api.current_user.name, 'input_ref' => 'N/A'}.merge(deploy_config.extra_config || {})
  end

  if runner.call(ui.out, ui.err)
    ui.info "Rollback complete"
  else
    raise EY::Error, "Rollback failed"
  end
end

#serversObject



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/engineyard/cli.rb', line 337

def servers
  if options[:environment] == '' && options[:account] == ''
    repo.fail_on_no_remotes!
  end

  environment = nil
  ui.mute_if(options[:simple] || options[:host]) do
    environment = fetch_environment(options[:environment], options[:account])
  end

  username = options[:user] && environment.username
  servers = environment.instances

  if options[:host]
    ui.print_hostnames(servers, username)
  elsif options[:simple]
    ui.print_simple_servers(servers, username)
  else
    ui.print_servers(servers, environment.hierarchy_name, username)
  end
end

#ssh(cmd = nil) ⇒ Object



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
# File 'lib/engineyard/cli.rb', line 461

def ssh(cmd=nil)
  environment = fetch_environment(options[:environment], options[:account])
  instances = ssh_hosts(options, environment)
  ssh_opts = []

  if cmd
    if options[:shell]
      cmd = Escape.shell_command([options[:shell],'-lc',cmd])
    end

    if options[:pty]
      ssh_opts = ["-t"]
    elsif cmd =~ /sudo/
      ui.warn "sudo commands often need a tty to run correctly. Use -t option to spawn a tty."
    end
  else
    if instances.size != 1 && options[:each] == false
      raise NoCommandError.new
    end

    if options[:bind_address]
      ssh_opts = ["-L", options[:bind_address]]
    end
  end

  ssh_cmd = ["ssh"]
  ssh_cmd += ssh_opts

  trap(:INT) { abort "Aborting..." }

  exits = instances.map do |instance|
    host = instance.public_hostname
    name = instance.name ? "#{instance.role} (#{instance.name})" : instance.role
    ui.info "\nConnecting to #{name} #{host}..."
    unless cmd
      ui.info "Ctrl + C to abort"
      sleep 1.3
    end
    system Escape.shell_command((ssh_cmd + ["#{environment.username}@#{host}"] + [cmd]).compact)
    $?.exitstatus
  end

  exit exits.detect {|status| status != 0 } || 0
end

#statusObject



247
248
249
250
251
252
253
254
255
# File 'lib/engineyard/cli.rb', line 247

def status
  app_env = fetch_app_environment(options[:app], options[:environment], options[:account])
  deployment = app_env.last_deployment
  if deployment
    ui.deployment_status(deployment)
  else
    raise EY::Error, "Application #{app_env.app.name} has not been deployed on #{app_env.environment.name}."
  end
end

#timeout_deployObject



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/engineyard/cli.rb', line 216

def timeout_deploy
  app_env = fetch_app_environment(options[:app], options[:environment], options[:account])
  deployment = app_env.last_deployment
  if deployment && !deployment.finished?
    begin
      ui.info  "Marking last deployment failed...", :green
      deployment.timeout
      ui.deployment_status(deployment)
    rescue EY::CloudClient::RequestFailed => e
      ui.error "Error encountered attempting to timeout previous deployment."
      raise
    end
  else
    raise EY::Error, "No unfinished deployment was found for #{app_env.hierarchy_name}."
  end
end

#versionObject



570
571
572
# File 'lib/engineyard/cli.rb', line 570

def version
  ui.say %{engineyard version #{EY::VERSION}}
end

#whoamiObject



636
637
638
639
# File 'lib/engineyard/cli.rb', line 636

def whoami
  current_user = api.current_user
  ui.say "#{current_user.name} (#{current_user.email})"
end