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 Thor::Error, 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



678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/engineyard/cli.rb', line 678

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



732
733
734
735
# File 'lib/engineyard/cli.rb', line 732

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

#loginObject



756
757
758
# File 'lib/engineyard/cli.rb', line 756

def 
  whoami
end

#logoutObject



761
762
763
764
765
766
767
768
769
# File 'lib/engineyard/cli.rb', line 761

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



648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/engineyard/cli.rb', line 648

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



391
392
393
394
395
# File 'lib/engineyard/cli.rb', line 391

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

#rollbackObject



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/engineyard/cli.rb', line 417

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

#scp(from_path, to_path) ⇒ Object



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

def scp(from_path, to_path)
  environment = fetch_environment(options[:environment], options[:account])
  instances   = filter_servers(environment, options, default: {app_master: true})
  user        = environment.username

  ui.info "Copying '#{from_path}' to '#{to_path}' on #{instances.count} server#{instances.count == 1 ? '' : 's'} serially..."

  # default to `scp FROM_PATH HOST:TO_PATH`
  unless [from_path, to_path].detect { |path| path =~ /HOST:/ }
    to_path = "HOST:#{to_path}"
  end

  exits = []
  instances.each do |instance|
    host = instance.public_hostname
    authority = "#{user}@#{host}:"

    name = instance.name ? "#{instance.role} (#{instance.name})" : instance.role
    ui.info "# #{name} #{host}"

    from = from_path.sub(/^HOST:/, authority)
    to   =   to_path.sub(/^HOST:/, authority)

    cmd  = Escape.shell_command(["scp", from, to])
    ui.debug "$ #{cmd}"
    system cmd
    exits << $?.exitstatus
  end

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

#serversObject



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/engineyard/cli.rb', line 351

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 = filter_servers(environment, options, default: {all: true})

  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



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

def ssh(cmd=nil)
  environment = fetch_environment(options[:environment], options[:account])
  instances = filter_servers(environment, options, default: {app_master: true})
  user = environment.username
  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.each 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
    sshcmd = Escape.shell_command((ssh_cmd + ["#{user}@#{host}"] + [cmd]).compact)
    ui.debug "$ #{sshcmd}"
    system sshcmd
    exits << $?.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



672
673
674
# File 'lib/engineyard/cli.rb', line 672

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

#whoamiObject



738
739
740
741
# File 'lib/engineyard/cli.rb', line 738

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