Module: Capistrano::Configuration::Connections

Included in:
Capistrano::Configuration
Defined in:
lib/capistrano/configuration/connections.rb

Defined Under Namespace

Classes: DefaultConnectionFactory, GatewayConnectionFactory

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:


9
10
11
12
# File 'lib/capistrano/configuration/connections.rb', line 9

def self.included(base) #:nodoc:
  base.send :alias_method, :initialize_without_connections, :initialize
  base.send :alias_method, :initialize, :initialize_with_connections
end

Instance Method Details

#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.


80
81
82
# File 'lib/capistrano/configuration/connections.rb', line 80

def connect!(options={})
  execute_on_servers(options) { }
end

#connection_factoryObject

Returns the object responsible for establishing new SSH connections. The factory will respond to #connect_to, which can be used to establish connections to servers defined via ServerDefinition objects.


87
88
89
90
91
92
93
94
95
96
# File 'lib/capistrano/configuration/connections.rb', line 87

def connection_factory
  @connection_factory ||= begin
    if exists?(:gateway)
      logger.debug "establishing connection to gateway `#{fetch(:gateway)}'"
      GatewayConnectionFactory.new(fetch(:gateway), self)
    else
      DefaultConnectionFactory.new(self)
    end
  end
end

#establish_connections_to(servers) ⇒ Object

Ensures that there are active sessions for each server in the list.


99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/capistrano/configuration/connections.rb', line 99

def establish_connections_to(servers)
  failed_servers = []

  # force the connection factory to be instantiated synchronously,
  # otherwise we wind up with multiple gateway instances, because
  # each connection is done in parallel.
  connection_factory

  threads = Array(servers).map { |server| establish_connection_to(server, failed_servers) }
  threads.each { |t| t.join }

  if failed_servers.any?
    errors = failed_servers.map { |h| "#{h[:server]} (#{h[:error].class}: #{h[:error].message})" }
    error = ConnectionError.new("connection failed for: #{errors.join(', ')}")
    error.hosts = failed_servers.map { |h| h[:server] }
    raise error
  end
end

#execute_on_servers(options = {}) ⇒ Object

Determines the set of servers within the current task's scope and establishes connections to them, and then yields that list of servers.

Raises:

  • (ArgumentError)

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
# File 'lib/capistrano/configuration/connections.rb', line 129

def execute_on_servers(options={})
  raise ArgumentError, "expected a block" unless block_given?

  if task = current_task
    servers = find_servers_for_task(task, options)

    if servers.empty?
      if ENV['HOSTFILTER']
        logger.info "skipping `#{task.fully_qualified_name}' because no servers matched"
        return
      else
        raise Capistrano::NoMatchingServersError, "`#{task.fully_qualified_name}' is only run for servers matching #{task.options.inspect}, but no servers matched"
      end
    end

    if task.continue_on_error?
      servers.delete_if { |s| has_failed?(s) }
      return if servers.empty?
    end
  else
    servers = find_servers(options)
    raise Capistrano::NoMatchingServersError, "no servers found to match #{options.inspect}" if servers.empty?
  end

  servers = [servers.first] if options[:once]
  logger.trace "servers: #{servers.map { |s| s.host }.inspect}"

  max_hosts = (options[:max_hosts] || (task && task.max_hosts) || servers.size).to_i
  is_subset = max_hosts < servers.size

  # establish connections to those servers in groups of max_hosts, as necessary
  servers.each_slice(max_hosts) do |servers_slice|
    begin
      establish_connections_to(servers_slice)
    rescue ConnectionError => error
      raise error unless task && task.continue_on_error?
      error.hosts.each do |h|
        servers_slice.delete(h)
        failed!(h)
      end
    end

    begin
      yield servers_slice
    rescue RemoteError => error
      raise error unless task && task.continue_on_error?
      error.hosts.each { |h| failed!(h) }
    end

    # if dealing with a subset (e.g., :max_hosts is less than the
    # number of servers available) teardown the subset of connections
    # that were just made, so that we can make room for the next subset.
    teardown_connections_to(servers_slice) if is_subset
  end
end

#failed!(server) ⇒ Object

Indicate that the given server could not be connected to.


66
67
68
# File 'lib/capistrano/configuration/connections.rb', line 66

def failed!(server)
  Thread.current[:failed_sessions] << server
end

#has_failed?(server) ⇒ Boolean

Query whether previous connection attempts to the given server have failed.

Returns:

  • (Boolean)

72
73
74
# File 'lib/capistrano/configuration/connections.rb', line 72

def has_failed?(server)
  Thread.current[:failed_sessions].include?(server)
end

#initialize_with_connections(*args) ⇒ Object

:nodoc:


59
60
61
62
63
# File 'lib/capistrano/configuration/connections.rb', line 59

def initialize_with_connections(*args) #:nodoc:
  initialize_without_connections(*args)
  Thread.current[:sessions] = {}
  Thread.current[:failed_sessions] = []
end

#sessionsObject

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. Stored on a per-thread basis to improve thread-safety.


55
56
57
# File 'lib/capistrano/configuration/connections.rb', line 55

def sessions
  Thread.current[:sessions] ||= {}
end

#teardown_connections_to(servers) ⇒ Object

Destroys sessions for each server in the list.


119
120
121
122
123
124
# File 'lib/capistrano/configuration/connections.rb', line 119

def teardown_connections_to(servers)
  servers.each do |server|
    sessions[server].close
    sessions.delete(server)
  end
end