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

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
        ssh_options = {}
      
        password = h.read_merged(:ssh_password)
        ssh_options[:password] = password if password

        timeout = h.read_merged(:ssh_timeout)
        ssh_options[:timeout] = timeout if timeout
      
        [h, Net::SSH.start(h.name, h.read_merged(:ssh_username), ssh_options), 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.message})")
        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

#ssh_context_classObject



72
73
74
75
76
# File 'lib/makitzo/ssh/multi.rb', line 72

def ssh_context_class
  session_klass = Class.new(Makitzo::SSH::Context)
  session_klass.send(:include, config.helpers)
  session_klass
end