Module: Makitzo::SSH::Multi
- Included in:
- Application, Migrations::Migrator
- Defined in:
- lib/makitzo/ssh/multi.rb
Overview
mixing providing ability to run multiple SSH connections in parallel. clients mixing in this module should also include ApplicationAware, or provide config
and logger
methods.
Instance Method Summary collapse
-
#multi_connect(hosts, &block) ⇒ Object
connect to an array of hosts, returning an array of arrays.
- #multi_session(hosts, &block) ⇒ Object
-
#multi_ssh(hosts, &block) ⇒ Object
execute a block on each host, in parallel block receives host, connection object and error object only one of connection, error will be non-nil returns after block has finished executing on all hosts returns array of block return values for each host.
- #ssh_context_class ⇒ Object
Instance Method Details
#multi_connect(hosts, &block) ⇒ Object
connect to an array of hosts, returning an array of arrays. each array has the form [host, connection, error] only one of connection and error will be non-nil
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/makitzo/ssh/multi.rb', line 10 def multi_connect(hosts, &block) connection_threads = hosts.map { |h| Thread.new do begin = {} password = h.read_merged(:ssh_password) [:password] = password if password timeout = h.read_merged(:ssh_timeout) [:timeout] = timeout if timeout [h, Net::SSH.start(h.name, h.read_merged(:ssh_username), ), nil] rescue => e [h, nil, e] end end } connection_threads.map(&:value) end |
#multi_session(hosts, &block) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/makitzo/ssh/multi.rb', line 49 def multi_session(hosts, &block) context_klass = ssh_context_class multi_ssh(hosts) do |host, conn, error| context = context_klass.new(host, conn) logger.with_host(host) do if error logger.error("could not connect to host: #{error.class}") context.connection_error = error else begin block.call(context, host) rescue => e logger.error("unhandled exception: #{e.class} (#{e.})") ensure conn.close unless conn.closed? end end end context end end |
#multi_ssh(hosts, &block) ⇒ Object
execute a block on each host, in parallel block receives host, connection object and error object only one of connection, error will be non-nil returns after block has finished executing on all hosts returns array of block return values for each host
36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/makitzo/ssh/multi.rb', line 36 def multi_ssh(hosts, &block) result = [] groups = config.concurrency.nil? ? [hosts] : (hosts.in_groups_of(config.concurrency)) groups.each do |hosts| group_result = multi_connect(hosts).map { |host, conn, error| conn[:logger] = logger if conn # ick? Thread.new { block.call(host, conn, error) } }.map(&:value) group_result.each { |gr| result << gr } end result end |