Class: Rake::RemoteTask
- Inherits:
-
Task
- Object
- Task
- Rake::RemoteTask
- Includes:
- Open4
- Defined in:
- lib/remote_task.rb,
lib/test_case.rb
Overview
Rake::RemoteTask is a subclass of Rake::Task that adds remote_actions that execute in parallel on multiple hosts via ssh.
Defined Under Namespace
Constant Summary collapse
- @@current_roles =
[]
Instance Attribute Summary collapse
-
#action ⇒ Object
Returns the value of attribute action.
-
#commands ⇒ Object
Returns the value of attribute commands.
-
#error ⇒ Object
Returns the value of attribute error.
-
#input ⇒ Object
Returns the value of attribute input.
-
#options ⇒ Object
Options for execution of this task.
-
#output ⇒ Object
Returns the value of attribute output.
-
#remote_actions ⇒ Object
readonly
An Array of Actions this host will perform during execution.
-
#target_dir ⇒ Object
readonly
The directory on the host this task is running in during execution.
-
#target_host ⇒ Object
The host this task is running on during execution.
Class Method Summary collapse
-
.all_hosts ⇒ Object
Returns an Array with every host configured.
- .current_roles ⇒ Object
-
.default_env ⇒ Object
The default environment values.
-
.env ⇒ Object
The vlad environment.
-
.fetch(name, default = nil) ⇒ Object
Fetches environment variable
name
from the environment using defaultdefault
. -
.host(host_name, *roles) ⇒ Object
Add host
host_name
that belongs toroles
. -
.hosts_for(*roles) ⇒ Object
Returns an Array of all hosts in
roles
. -
.mandatory(name, desc) ⇒ Object
:nodoc:.
- .per_thread ⇒ Object
-
.protect_env(name) ⇒ Object
Ensures exclusive access to
name
. -
.remote_task(name, *args, &block) ⇒ Object
Adds a remote task named
name
with optionsoptions
that will executeblock
. -
.reserved_name?(name) ⇒ Boolean
Ensures
name
does not conflict with an existing method. -
.reset ⇒ Object
Resets vlad, restoring all roles, tasks and environment variables to the defaults.
-
.role(role_name, host = nil, args = {}) ⇒ Object
Adds role
role_name
withhost
andargs
for that host. -
.roles ⇒ Object
The configured roles.
-
.set(name, value = nil, &default_block) ⇒ Object
Set environment variable
name
tovalue
ordefault_block
. -
.set_defaults ⇒ Object
Sets all the default values.
-
.set_path(name, subdir) ⇒ Object
:nodoc:.
-
.simple_set(*args) ⇒ Object
:nodoc:.
-
.task ⇒ Object
The Rake::RemoteTask executing in this Thread.
-
.tasks ⇒ Object
The configured Rake::RemoteTasks.
Instance Method Summary collapse
-
#defined_target_hosts? ⇒ Boolean
Similar to target_hosts, but returns true if user defined any hosts, even an empty list.
-
#enhance(deps = nil, &block) ⇒ Object
Add remote action
block
to this task with dependenciesdeps
. -
#execute(args = nil) ⇒ Object
Execute this action.
-
#get(local_dir, *files) ⇒ Object
Pull
files
from the remotehost
using rsync tolocal_dir
. -
#initialize(task_name, app) ⇒ RemoteTask
constructor
Create a new task named
task_name
attached to Rake::Applicationapp
. -
#original_enhance ⇒ Object
Add a local action to this task.
- #popen4(*command) ⇒ Object
-
#put(remote_path, base_name = File.basename(remote_path)) ⇒ Object
Copy a (usually generated) file to
remote_path
. -
#rsync(*args) ⇒ Object
Execute rsync with
args
. -
#run(command) ⇒ Object
Use ssh to execute
command
on target_host. - #select(reads, writes, errs, timeout) ⇒ Object
-
#sudo(command) ⇒ Object
Execute
command
under sudo using run. - #system(*command) ⇒ Object
-
#target_hosts ⇒ Object
The hosts this task will execute on.
Constructor Details
#initialize(task_name, app) ⇒ RemoteTask
Create a new task named task_name
attached to Rake::Application app
.
75 76 77 78 79 80 |
# File 'lib/remote_task.rb', line 75 def initialize(task_name, app) super @remote_actions = [] @happy = false # used for deprecation warnings on get/put/rsync end |
Instance Attribute Details
#action ⇒ Object
Returns the value of attribute action.
27 28 29 |
# File 'lib/test_case.rb', line 27 def action @action end |
#commands ⇒ Object
Returns the value of attribute commands.
27 28 29 |
# File 'lib/test_case.rb', line 27 def commands @commands end |
#error ⇒ Object
Returns the value of attribute error.
27 28 29 |
# File 'lib/test_case.rb', line 27 def error @error end |
#input ⇒ Object
Returns the value of attribute input.
27 28 29 |
# File 'lib/test_case.rb', line 27 def input @input end |
#options ⇒ Object
Options for execution of this task.
50 51 52 |
# File 'lib/remote_task.rb', line 50 def @options end |
#output ⇒ Object
Returns the value of attribute output.
27 28 29 |
# File 'lib/test_case.rb', line 27 def output @output end |
#remote_actions ⇒ Object (readonly)
An Array of Actions this host will perform during execution. Use enhance to add new actions to a task.
66 67 68 |
# File 'lib/remote_task.rb', line 66 def remote_actions @remote_actions end |
#target_dir ⇒ Object (readonly)
The directory on the host this task is running in during execution.
60 61 62 |
# File 'lib/remote_task.rb', line 60 def target_dir @target_dir end |
#target_host ⇒ Object
The host this task is running on during execution.
55 56 57 |
# File 'lib/remote_task.rb', line 55 def target_host @target_host end |
Class Method Details
.all_hosts ⇒ Object
Returns an Array with every host configured.
240 241 242 |
# File 'lib/remote_task.rb', line 240 def self.all_hosts hosts_for(roles.keys) end |
.current_roles ⇒ Object
68 69 70 |
# File 'lib/remote_task.rb', line 68 def self.current_roles @@current_roles end |
.default_env ⇒ Object
The default environment values. Used for resetting (mostly for tests).
248 249 250 |
# File 'lib/remote_task.rb', line 248 def self.default_env @@default_env end |
.env ⇒ Object
The vlad environment.
259 260 261 |
# File 'lib/remote_task.rb', line 259 def self.env @@env end |
.fetch(name, default = nil) ⇒ Object
Fetches environment variable name
from the environment using default default
.
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/remote_task.rb', line 267 def self.fetch name, default = nil name = name.to_s if Symbol === name if @@env.has_key? name then protect_env(name) do v = @@env[name] v = @@env[name] = v.call if Proc === v unless per_thread[name] v = v.call if Proc === v v end elsif default || default == false v = @@env[name] = default else raise Rake::FetchError end end |
.host(host_name, *roles) ⇒ Object
Add host host_name
that belongs to roles
. Extra arguments may be specified for the host as a hash as the last argument.
host is the inversion of role:
host 'db1.example.com', :db, :master_db
Is equivalent to:
role :db, 'db1.example.com'
role :master_db, 'db1.example.com'
296 297 298 299 300 301 302 |
# File 'lib/remote_task.rb', line 296 def self.host host_name, *roles opts = Hash === roles.last ? roles.pop : {} roles.each do |role_name| role role_name, host_name, opts.dup end end |
.hosts_for(*roles) ⇒ Object
Returns an Array of all hosts in roles
.
307 308 309 310 311 |
# File 'lib/remote_task.rb', line 307 def self.hosts_for *roles roles.flatten.map { |r| self.roles[r].keys }.flatten.uniq.sort end |
.mandatory(name, desc) ⇒ Object
:nodoc:
313 314 315 316 317 318 |
# File 'lib/remote_task.rb', line 313 def self.mandatory name, desc # :nodoc: self.set(name) do raise(Rake::ConfigurationError, "Please specify the #{desc} via the #{name.inspect} variable") end end |
.per_thread ⇒ Object
252 253 254 |
# File 'lib/remote_task.rb', line 252 def self.per_thread @@per_thread end |
.protect_env(name) ⇒ Object
Ensures exclusive access to name
.
323 324 325 326 327 |
# File 'lib/remote_task.rb', line 323 def self.protect_env name # :nodoc: @@env_locks[name].synchronize do yield end end |
.remote_task(name, *args, &block) ⇒ Object
Adds a remote task named name
with options options
that will execute block
.
333 334 335 336 337 338 339 340 |
# File 'lib/remote_task.rb', line 333 def self.remote_task name, *args, &block = (Hash === args.last) ? args.pop : {} t = Rake::RemoteTask.define_task(name, *args, &block) [:roles] = Array [:roles] [:roles] |= @@current_roles t. = t end |
.reserved_name?(name) ⇒ Boolean
Ensures name
does not conflict with an existing method.
345 346 347 |
# File 'lib/remote_task.rb', line 345 def self.reserved_name? name # :nodoc: !@@env.has_key?(name.to_s) && self.respond_to?(name) end |
.reset ⇒ Object
Resets vlad, restoring all roles, tasks and environment variables to the defaults.
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'lib/remote_task.rb', line 353 def self.reset @@def_role_hash = {} # official default role value @@env = {} @@tasks = {} @@roles = Hash.new { |h,k| h[k] = @@def_role_hash } @@env_locks = Hash.new { |h,k| h[k] = Mutex.new } @@default_env.each do |k,v| case v when Symbol, Fixnum, nil, true, false, 42 then # ummmm... yeah. bite me. @@env[k] = v else @@env[k] = v.dup end end end |
.role(role_name, host = nil, args = {}) ⇒ Object
Adds role role_name
with host
and args
for that host. TODO: merge: Declare a role and assign a remote host to it. Equivalent to the host
method; provided for capistrano compatibility.
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
# File 'lib/remote_task.rb', line 376 def self.role role_name, host = nil, args = {} if block_given? then raise ArgumentError, 'host not allowed with block' unless host.nil? begin current_roles << role_name yield ensure current_roles.delete role_name end else raise ArgumentError, 'host required' if host.nil? [*host].each do |hst| raise ArgumentError, "invalid host: #{hst}" if hst.nil? or hst.empty? end @@roles[role_name] = {} if @@def_role_hash.eql? @@roles[role_name] @@roles[role_name][host] = args end end |
.roles ⇒ Object
The configured roles.
400 401 402 403 404 |
# File 'lib/remote_task.rb', line 400 def self.roles host domain, :app, :web, :db if @@roles.empty? @@roles end |
.set(name, value = nil, &default_block) ⇒ Object
Set environment variable name
to value
or default_block
.
If default_block
is defined, the block will be executed the first time the variable is fetched, and the value will be used for every subsequent fetch.
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 |
# File 'lib/remote_task.rb', line 413 def self.set name, value = nil, &default_block raise ArgumentError, "cannot provide both a value and a block" if value and default_block unless value == :per_thread raise ArgumentError, "cannot set reserved name: '#{name}'" if Rake::RemoteTask.reserved_name?(name) unless $TESTING name = name.to_s Rake::RemoteTask.per_thread[name] = true if default_block && value == :per_thread Rake::RemoteTask.default_env[name] = Rake::RemoteTask.env[name] = default_block || value Object.send :define_method, name do Rake::RemoteTask.fetch name end end |
.set_defaults ⇒ Object
Sets all the default values. Should only be called once. Use reset if you need to restore values.
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 |
# File 'lib/remote_task.rb', line 437 def self.set_defaults @@default_env ||= {} @@per_thread ||= {} self.reset mandatory :repository, "repository path" mandatory :deploy_to, "deploy path" mandatory :domain, "server domain" simple_set(:deploy_timestamped, true, :deploy_via, :export, :keep_releases, 5, :rake_cmd, "rake", :revision, "head", :rsync_cmd, "rsync", :rsync_flags, ['-azP', '--delete'], :ssh_cmd, "ssh", :ssh_flags, [], :sudo_cmd, "sudo", :sudo_flags, ['-p Password:'], :sudo_prompt, /^Password:/, :umask, '02', :mkdirs, [], :shared_paths, {}, :prefix_output, false, :prepend_cmd, false) set(:current_release) { File.join(releases_path, releases[-1]) } set(:latest_release) { ? release_path : current_release} set(:previous_release) { File.join(releases_path, releases[-2]) } set(:release_name) { Time.now.utc.strftime("%Y%m%d%H%M%S") } set(:release_path) { File.join(releases_path, release_name) } set(:releases) { task.run("ls -x #{releases_path}").split.sort } set_path :current_path, "current" set_path :releases_path, "releases" set_path :scm_path, "scm" set_path :shared_path, "shared" set(:sudo_password) do state = `stty -g` raise Rake::Error, "stty(1) not found" unless $?.success? begin system "stty -echo" $stdout.print "sudo password: " $stdout.flush sudo_password = $stdin.gets $stdout.puts ensure system "stty #{state}" end sudo_password end end |
.set_path(name, subdir) ⇒ Object
:nodoc:
494 495 496 |
# File 'lib/remote_task.rb', line 494 def self.set_path(name, subdir) # :nodoc: set(name) { File.join(deploy_to, subdir) } end |
.simple_set(*args) ⇒ Object
:nodoc:
498 499 500 501 502 503 |
# File 'lib/remote_task.rb', line 498 def self.simple_set(*args) # :nodoc: args = Hash[*args] args.each do |k, v| set k, v end end |
.task ⇒ Object
The Rake::RemoteTask executing in this Thread.
508 509 510 |
# File 'lib/remote_task.rb', line 508 def self.task Thread.current[:task] end |
.tasks ⇒ Object
The configured Rake::RemoteTasks.
515 516 517 |
# File 'lib/remote_task.rb', line 515 def self.tasks @@tasks end |
Instance Method Details
#defined_target_hosts? ⇒ Boolean
Similar to target_hosts, but returns true if user defined any hosts, even an empty list.
569 570 571 572 573 574 575 576 577 578 |
# File 'lib/remote_task.rb', line 569 def defined_target_hosts? return true if ENV["HOSTS"] roles = Array [:roles] return true if roles.empty? # borrowed from hosts_for: roles.flatten.each { |r| return true unless @@def_role_hash.eql? Rake::RemoteTask.roles[r] } return false end |
#enhance(deps = nil, &block) ⇒ Object
Add remote action block
to this task with dependencies deps
. See Rake::Task#enhance.
91 92 93 94 95 |
# File 'lib/remote_task.rb', line 91 def enhance(deps=nil, &block) original_enhance(deps) # can't use super because block passed regardless. @remote_actions << Action.new(self, block) if block_given? self end |
#execute(args = nil) ⇒ Object
Execute this action. Local actions will be performed first, then remote actions will be performed in parallel on each host configured for this RemoteTask.
102 103 104 105 106 107 108 109 110 |
# File 'lib/remote_task.rb', line 102 def execute(args = nil) raise(Rake::ConfigurationError, "No target hosts specified on task #{self.name} for roles #{[:roles].inspect}") unless defined_target_hosts? super args @remote_actions.each { |act| act.execute(target_hosts, self, args) } end |
#get(local_dir, *files) ⇒ Object
Pull files
from the remote host
using rsync to local_dir
. TODO: what if role has multiple hosts & the files overlap? subdirs?
116 117 118 119 120 121 |
# File 'lib/remote_task.rb', line 116 def get local_dir, *files @happy = true host = target_host rsync files.map { |f| "#{host}:#{f}" }, local_dir @happy = false end |
#original_enhance ⇒ Object
Add a local action to this task. This calls Rake::Task#enhance.
85 |
# File 'lib/remote_task.rb', line 85 alias_method :original_enhance, :enhance |
#popen4(*command) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/test_case.rb', line 40 def popen4 *command @commands << command @input = StringIO.new out = StringIO.new @output.shift.to_s err = StringIO.new @error.shift.to_s raise if block_given? status = self.action ? self.action[command.join(' ')] : 0 Process.expected Status.new(status) return 42, @input, out, err end |
#put(remote_path, base_name = File.basename(remote_path)) ⇒ Object
Copy a (usually generated) file to remote_path
. Contents of block are copied to remote_path
and you may specify an optional base_name for the tempfile (aids in debugging).
128 129 130 131 132 133 134 135 136 137 |
# File 'lib/remote_task.rb', line 128 def put remote_path, base_name = File.basename(remote_path) require 'tempfile' Tempfile.open base_name do |fp| fp.puts yield fp.flush @happy = true rsync fp.path, "#{target_host}:#{remote_path}" @happy = false end end |
#rsync(*args) ⇒ Object
Execute rsync with args
. Tacks on pre-specified rsync_cmd
and rsync_flags
.
Favor #get and #put for most tasks. Old-style direct use where the target_host was implicit is now deprecated.
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/remote_task.rb', line 146 def rsync *args unless @happy || args[-1] =~ /:/ then warn "rsync deprecation: pass target_host:remote_path explicitly" args[-1] = "#{target_host}:#{args[-1]}" end cmd = [rsync_cmd, rsync_flags, args].flatten.compact cmdstr = cmd.join ' ' warn cmdstr if $TRACE success = system(*cmd) raise Rake::CommandFailedError, "execution failed: #{cmdstr}" unless success end |
#run(command) ⇒ Object
Use ssh to execute command
on target_host. If command
uses sudo, the sudo password will be prompted for then saved for subsequent sudo commands.
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 |
# File 'lib/remote_task.rb', line 166 def run command command = "cd #{target_dir} && #{command}" if target_dir command = "#{prepend_cmd} '#{command}'" if prepend_cmd cmd = [ssh_cmd, ssh_flags, target_host, command].flatten result = [] trace = [ssh_cmd, ssh_flags, target_host, "'#{command}'"].flatten.join(' ') warn trace if $TRACE pid, inn, out, err = popen4(*cmd) inn.sync = true streams = [out, err] out_stream = { out => $stdout, err => $stderr, } # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 next if selected.nil? or selected.empty? selected.each do |stream| if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) # Add the prefix to each line if (prefix_output) # prefix target hostname unless prefix_output is a custom string prefix = String === prefix_output ? prefix_output : "#{target_host}: " # don't prefix sudo prompts data.gsub!(/^/, prefix) unless stream == err and data =~ sudo_prompt end out_stream[stream].write data if stream == err and data =~ sudo_prompt then inn.puts sudo_password data << "\n" $stderr.write "\n" end result << data end end unless status.success? then raise(Rake::CommandFailedError, "execution failed with status #{status.exitstatus}: #{cmd.join ' '}") end result.join ensure inn.close rescue nil out.close rescue nil err.close rescue nil end |
#select(reads, writes, errs, timeout) ⇒ Object
55 56 57 |
# File 'lib/test_case.rb', line 55 def select reads, writes, errs, timeout [reads, writes, errs] end |
#sudo(command) ⇒ Object
Execute command
under sudo using run.
522 523 524 |
# File 'lib/remote_task.rb', line 522 def sudo command run [sudo_cmd, sudo_flags, command].flatten.compact.join(" ") end |
#system(*command) ⇒ Object
35 36 37 38 |
# File 'lib/test_case.rb', line 35 def system *command @commands << command self.action ? self.action[command.join(' ')] : true end |
#target_hosts ⇒ Object
The hosts this task will execute on. The hosts are determined from the role this task belongs to.
The target hosts may be overridden by providing a comma-separated list of commands to the HOSTS environment variable:
rake my_task HOSTS=app1.example.com,app2.example.com
551 552 553 554 555 556 557 558 559 560 561 562 563 |
# File 'lib/remote_task.rb', line 551 def target_hosts if hosts = ENV["HOSTS"] then hosts.strip.gsub(/\s+/, '').split(",") else roles = Array [:roles] if roles.empty? then Rake::RemoteTask.all_hosts else Rake::RemoteTask.hosts_for roles end end end |