Class: Capistrano::Actor
- Inherits:
-
Object
- Object
- Capistrano::Actor
- Defined in:
- lib/capistrano/actor.rb
Overview
An Actor is the entity that actually does the work of determining which servers should be the target of a particular task, and of executing the task on each of them in parallel. An Actor is never instantiated directly–rather, you create a new Configuration instance, and access the new actor via Configuration#actor.
Defined Under Namespace
Classes: DefaultConnectionFactory, Task, TaskCallFrame
Class Attribute Summary collapse
-
.command_factory ⇒ Object
Returns the value of attribute command_factory.
-
.connection_factory ⇒ Object
Returns the value of attribute connection_factory.
-
.default_io_proc ⇒ Object
Returns the value of attribute default_io_proc.
-
.transfer_factory ⇒ Object
Returns the value of attribute transfer_factory.
Instance Attribute Summary collapse
-
#configuration ⇒ Object
readonly
The configuration instance associated with this actor.
-
#sessions ⇒ Object
readonly
A hash of the SSH sessions that are currently open and available.
-
#task_call_frames ⇒ Object
readonly
The call stack of the tasks.
-
#task_call_history ⇒ Object
readonly
The history of executed tasks.
-
#tasks ⇒ Object
readonly
A hash of the tasks known to this actor, keyed by name.
Instance Method Summary collapse
-
#capture(command, options = {}) ⇒ Object
Executes the given command on the first server targetted by the current task, collects it’s stdout into a string, and returns the string.
-
#connect!(options = {}) ⇒ Object
Used to force connections to be made to the current task’s servers.
-
#current_release ⇒ Object
Returns the most recent deployed release.
- #current_task ⇒ Object
-
#default_io_proc ⇒ Object
An instance-level reader for the class’ #default_io_proc attribute.
-
#define_task(name, options = {}, &block) ⇒ Object
Define a new task for this actor.
-
#delete(path, options = {}) ⇒ Object
Deletes the given file from all servers targetted by the current task.
-
#dump_tasks ⇒ Object
Dump all tasks and (brief) descriptions in YAML format for consumption by other processes.
-
#each_task ⇒ Object
Iterates over each task, in alphabetical order.
-
#get(remote_path, path, options = {}) ⇒ Object
Get file remote_path from FIRST server targetted by the current task and transfer it to local machine as path.
-
#initialize(config) ⇒ Actor
constructor
:nodoc:.
- #metaclass ⇒ Object
-
#on_rollback(&block) ⇒ Object
Specifies an on_rollback hook for the currently executing task.
-
#previous_release ⇒ Object
Returns the release immediately before the currently deployed one.
-
#put(data, path, options = {}) ⇒ Object
Store the given data at the given location on all servers targetted by the current task.
-
#releases ⇒ Object
Inspects the remote servers to determine the list of all released versions of the software.
-
#render(*args) ⇒ Object
Renders an ERb template and returns the result.
-
#run(cmd, options = {}, &block) ⇒ Object
Execute the given command on all servers that are the target of the current task.
-
#stream(command) ⇒ Object
Streams the result of the command from all servers that are the target of the current task.
-
#sudo(command, options = {}, &block) ⇒ Object
Like #run, but executes the command via
sudo
. -
#transaction ⇒ Object
Invoke a set of tasks in a transaction.
Constructor Details
#initialize(config) ⇒ Actor
:nodoc:
142 143 144 145 146 147 148 |
# File 'lib/capistrano/actor.rb', line 142 def initialize(config) #:nodoc: @configuration = config @tasks = {} @task_call_frames = [] @sessions = {} @factory = self.class.connection_factory.new(configuration) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(sym, *args, &block) ⇒ Object (private)
558 559 560 561 562 563 564 |
# File 'lib/capistrano/actor.rb', line 558 def method_missing(sym, *args, &block) if @configuration.respond_to?(sym) @configuration.send(sym, *args, &block) else super end end |
Class Attribute Details
.command_factory ⇒ Object
Returns the value of attribute command_factory.
31 32 33 |
# File 'lib/capistrano/actor.rb', line 31 def command_factory @command_factory end |
.connection_factory ⇒ Object
Returns the value of attribute connection_factory.
30 31 32 |
# File 'lib/capistrano/actor.rb', line 30 def connection_factory @connection_factory end |
.default_io_proc ⇒ Object
Returns the value of attribute default_io_proc.
33 34 35 |
# File 'lib/capistrano/actor.rb', line 33 def default_io_proc @default_io_proc end |
.transfer_factory ⇒ Object
Returns the value of attribute transfer_factory.
32 33 34 |
# File 'lib/capistrano/actor.rb', line 32 def transfer_factory @transfer_factory end |
Instance Attribute Details
#configuration ⇒ Object (readonly)
The configuration instance associated with this actor.
46 47 48 |
# File 'lib/capistrano/actor.rb', line 46 def configuration @configuration end |
#sessions ⇒ Object (readonly)
A hash of the SSH sessions that are currently open and available. Because sessions are constructed lazily, this will only contain connections to those servers that have been the targets of one or more executed tasks.
56 57 58 |
# File 'lib/capistrano/actor.rb', line 56 def sessions @sessions end |
#task_call_frames ⇒ Object (readonly)
The call stack of the tasks. The currently executing task may inspect this to see who its caller was. The current task is always the last element of this stack.
61 62 63 |
# File 'lib/capistrano/actor.rb', line 61 def task_call_frames @task_call_frames end |
#task_call_history ⇒ Object (readonly)
The history of executed tasks. This will be an array of all tasks that have been executed, in the order in which they were called.
65 66 67 |
# File 'lib/capistrano/actor.rb', line 65 def task_call_history @task_call_history end |
#tasks ⇒ Object (readonly)
A hash of the tasks known to this actor, keyed by name. The values are instances of Actor::Task.
50 51 52 |
# File 'lib/capistrano/actor.rb', line 50 def tasks @tasks end |
Instance Method Details
#capture(command, options = {}) ⇒ Object
Executes the given command on the first server targetted by the current task, collects it’s stdout into a string, and returns the string.
295 296 297 298 299 300 301 302 303 304 |
# File 'lib/capistrano/actor.rb', line 295 def capture(command, ={}) output = "" run(command, .merge(:once => true)) do |ch, stream, data| case stream when :out then output << data when :err then raise "error processing #{command.inspect}: #{data.inspect}" end end output end |
#connect!(options = {}) ⇒ Object
Used to force connections to be made to the current task’s servers. Connections are normally made lazily in Capistrano–you can use this to force them open before performing some operation that might be time-sensitive.
472 473 474 |
# File 'lib/capistrano/actor.rb', line 472 def connect!(={}) execute_on_servers() { } end |
#current_release ⇒ Object
Returns the most recent deployed release
410 411 412 |
# File 'lib/capistrano/actor.rb', line 410 def current_release release_path(releases.last) end |
#current_task ⇒ Object
476 477 478 479 |
# File 'lib/capistrano/actor.rb', line 476 def current_task return nil if task_call_frames.empty? tasks[task_call_frames.last.name] end |
#default_io_proc ⇒ Object
An instance-level reader for the class’ #default_io_proc attribute.
464 465 466 |
# File 'lib/capistrano/actor.rb', line 464 def default_io_proc self.class.default_io_proc end |
#define_task(name, options = {}, &block) ⇒ Object
Define a new task for this actor. The block will be invoked when this task is called.
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
# File 'lib/capistrano/actor.rb', line 152 def define_task(name, ={}, &block) @tasks[name] = ([:task_class] || Task).new(name, self, ) define_method(name) do send "before_#{name}" if respond_to? "before_#{name}" logger.debug "executing task #{name}" begin push_task_call_frame name result = instance_eval(&block) ensure pop_task_call_frame end send "after_#{name}" if respond_to? "after_#{name}" result end end |
#delete(path, options = {}) ⇒ Object
Deletes the given file from all servers targetted by the current task. If :recursive => true
is specified, it may be used to remove directories.
238 239 240 241 |
# File 'lib/capistrano/actor.rb', line 238 def delete(path, ={}) cmd = "rm -%sf #{path}" % ([:recursive] ? "r" : "") run(cmd, ) end |
#dump_tasks ⇒ Object
Dump all tasks and (brief) descriptions in YAML format for consumption by other processes. Returns a string containing the YAML-formatted data.
185 186 187 188 189 190 191 192 193 |
# File 'lib/capistrano/actor.rb', line 185 def dump_tasks data = "" each_task do |info| desc = info[:desc].split(/\. /).first || "" desc << "." if !desc.empty? && desc[-1] != ?. data << "#{info[:task]}: #{desc}\n" end data end |
#each_task ⇒ Object
Iterates over each task, in alphabetical order. A hash object is yielded for each task, which includes the task’s name (:name), the length of the longest task name (:longest), and the task’s description, reformatted as a single line (:desc).
172 173 174 175 176 177 178 179 180 181 |
# File 'lib/capistrano/actor.rb', line 172 def each_task keys = tasks.keys.sort_by { |a| a.to_s } longest = keys.inject(0) { |len,key| key.to_s.length > len ? key.to_s.length : len } + 2 keys.sort_by { |a| a.to_s }.each do |key| desc = (tasks[key].[:desc] || "").gsub(/(?:\r?\n)+[ \t]*/, " ").strip info = { :task => key, :longest => longest, :desc => desc } yield info end end |
#get(remote_path, path, options = {}) ⇒ Object
Get file remote_path from FIRST server targetted by the current task and transfer it to local machine as path. It will use SFTP if Net::SFTP is installed; otherwise it will fall back to using ‘cat’, which may cause corruption in binary files.
get “#deploy_to/current/log/production.log”, “log/production.log.web”
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
# File 'lib/capistrano/actor.rb', line 271 def get(remote_path, path, = {}) if Capistrano::SFTP && .fetch(:sftp, true) execute_on_servers(.merge(:once => true)) do |servers| logger.debug "downloading #{servers.first}:#{remote_path} to #{path}" sftp = sessions[servers.first].sftp sftp.connect unless sftp.state == :open sftp.get_file remote_path, path logger.trace "download finished" end else logger.important "Net::SFTP is not available; using remote 'cat' to get file, which may cause file corruption" File.open(path, "w") do |destination| run "cat #{remote_path}", :once => true do |ch, stream, data| case stream when :out then destination << data when :err then raise "error while downloading #{remote_path}: #{data.inspect}" end end end end end |
#metaclass ⇒ Object
481 482 483 |
# File 'lib/capistrano/actor.rb', line 481 def class << self; self; end end |
#on_rollback(&block) ⇒ Object
Specifies an on_rollback hook for the currently executing task. If this or any subsequent task then fails, and a transaction is active, this hook will be executed.
459 460 461 |
# File 'lib/capistrano/actor.rb', line 459 def on_rollback(&block) task_call_frames.last.rollback = block end |
#previous_release ⇒ Object
Returns the release immediately before the currently deployed one
415 416 417 |
# File 'lib/capistrano/actor.rb', line 415 def previous_release release_path(releases[-2]) if releases[-2] end |
#put(data, path, options = {}) ⇒ Object
Store the given data at the given location on all servers targetted by the current task. If :mode
is specified it is used to set the mode on the file.
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
# File 'lib/capistrano/actor.rb', line 246 def put(data, path, ={}) if Capistrano::SFTP execute_on_servers() do |servers| transfer = self.class.transfer_factory.new(servers, self, path, :data => data, :mode => [:mode]) transfer.process! end else # Poor-man's SFTP... just run a cat on the remote end, and send data # to it. cmd = "cat > #{path}" cmd << " && chmod #{[:mode].to_s(8)} #{path}" if [:mode] run(cmd, .merge(:data => data + "\n\4")) do |ch, stream, out| logger.important out, "#{stream} :: #{ch[:host]}" if stream == :err end end end |
#releases ⇒ Object
Inspects the remote servers to determine the list of all released versions of the software. Releases are sorted with the most recent release last.
398 399 400 401 402 403 404 405 406 407 |
# File 'lib/capistrano/actor.rb', line 398 def releases @releases ||= begin buffer = "" run "ls -x1 #{releases_path}", :once => true do |ch, str, out| buffer << out if str == :out raise "could not determine releases #{out.inspect}" if str == :err end buffer.split.sort end end |
#render(*args) ⇒ Object
Renders an ERb template and returns the result. This is useful for dynamically building documents to store on the remote servers.
Usage:
render("something", :foo => "hello")
look for "something.rhtml" in the current directory, or in the
capistrano/recipes/templates directory, and render it with
foo defined as a local variable with the value "hello".
render(:file => "something", :foo => "hello")
same as above
render(:template => "<%= foo %> world", :foo => "hello")
treat the given string as an ERb template and render it with
the given hash of local variables active.
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 |
# File 'lib/capistrano/actor.rb', line 358 def render(*args) = args.last.is_a?(Hash) ? args.pop : {} [:file] = args.shift if args.first.is_a?(String) raise ArgumentError, "too many parameters" unless args.empty? case when [:file] file = .delete :file unless file[0] == ?/ dirs = [".", File.join(File.dirname(__FILE__), "recipes", "templates")] dirs.each do |dir| if File.file?(File.join(dir, file)) file = File.join(dir, file) break elsif File.file?(File.join(dir, file + ".rhtml")) file = File.join(dir, file + ".rhtml") break end end end render .merge(:template => File.read(file)) when [:template] erb = ERB.new([:template]) b = Proc.new { binding }.call .each do |key, value| next if key == :template eval "#{key} = options[:#{key}]", b end erb.result(b) else raise ArgumentError, "no file or template given for rendering" end end |
#run(cmd, options = {}, &block) ⇒ Object
Execute the given command on all servers that are the target of the current task. If a block is given, it is invoked for all output generated by the command, and should accept three parameters: the SSH channel (which may be used to send data back to the remote process), the stream identifier (:err
for stderr, and :out
for stdout), and the data that was received.
If pretend
mode is active, this does nothing.
203 204 205 206 207 208 209 210 211 212 |
# File 'lib/capistrano/actor.rb', line 203 def run(cmd, ={}, &block) block ||= default_io_proc logger.debug "executing #{cmd.strip.inspect}" execute_on_servers() do |servers| # execute the command on each server in parallel command = self.class.command_factory.new(servers, cmd, block, , self) command.process! # raises an exception if command fails on any server end end |
#stream(command) ⇒ Object
Streams the result of the command from all servers that are the target of the current task. All these streams will be joined into a single one, so you can, say, watch 10 log files as though they were one. Do note that this is quite expensive from a bandwidth perspective, so use it with care.
Example:
desc "Run a tail on multiple log files at the same time"
task :tail_fcgi, :roles => :app do
stream "tail -f #{shared_path}/log/fastcgi.crash.log"
end
225 226 227 228 229 230 231 232 233 |
# File 'lib/capistrano/actor.rb', line 225 def stream(command) run(command) do |ch, stream, out| puts out if stream == :out if stream == :err puts "[err : #{ch[:host]}] #{out}" break end end end |
#sudo(command, options = {}, &block) ⇒ Object
Like #run, but executes the command via sudo
. This assumes that the sudo password (if required) is the same as the password for logging in to the server.
Also, this module accepts a :sudo
configuration variable, which (if specified) will be used as the full path to the sudo executable on the remote machine:
set :sudo, "/opt/local/bin/sudo"
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 |
# File 'lib/capistrano/actor.rb', line 315 def sudo(command, ={}, &block) block ||= default_io_proc # in order to prevent _each host_ from prompting when the password was # wrong, let's track which host prompted first and only allow subsequent # prompts from that host. prompt_host = nil user = [:as].nil? ? '' : "-u #{[:as]}" run "#{sudo_command} #{user} #{command}", do |ch, stream, out| if out =~ /^Password:/ ch.send_data "#{password}\n" elsif out =~ /try again/ if prompt_host.nil? || prompt_host == ch[:host] prompt_host = ch[:host] logger.important out, "#{stream} :: #{ch[:host]}" # reset the password to it's original value and prepare for another # pass (the reset allows the password prompt to be attempted again # if the password variable was originally a proc (the default) set :password, self[:original_value][:password] || self[:password] end else block.call(ch, stream, out) end end end |
#transaction ⇒ Object
Invoke a set of tasks in a transaction. If any task fails (raises an exception), all tasks executed within the transaction are inspected to see if they have an associated on_rollback hook, and if so, that hook is called.
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 |
# File 'lib/capistrano/actor.rb', line 423 def transaction if task_call_history yield else logger.info "transaction: start" begin @task_call_history = [] yield logger.info "transaction: commit" rescue Object => e current = task_call_history.last logger.important "transaction: rollback", current ? current.name : "transaction start" task_call_history.reverse.each do |task| begin # throw the task back on the stack so that roles are properly # interpreted in the scope of the task in question. push_task_call_frame(task.name) logger.debug "rolling back", task.name task.rollback.call if task.rollback rescue Object => e logger.info "exception while rolling back: #{e.class}, #{e.}", task.name ensure pop_task_call_frame end end raise ensure @task_call_history = nil end end end |