Class: RHC::SSHHelpers::MultipleGearTask

Inherits:
Object
  • Object
show all
Defined in:
lib/rhc/ssh_helpers.rb

Instance Method Summary collapse

Constructor Details

#initialize(command, over, opts = {}) ⇒ MultipleGearTask

Returns a new instance of MultipleGearTask.



26
27
28
29
30
31
32
# File 'lib/rhc/ssh_helpers.rb', line 26

def initialize(command, over, opts={})
  requires_ssh_multi!

  @command = command
  @over = over
  @opts = opts
end

Instance Method Details

#run(&block) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/rhc/ssh_helpers.rb', line 34

def run(&block)
  out = nil

  Net::SSH::Multi.start(
    :concurrent_connections => @opts[:limit],
    :on_error => lambda{ |server| $stderr.puts RHC::Helpers.color("Unable to connect to gear #{server}", :red) }
  ) do |session|

    @over.each do |item|
      case item
      when RHC::Rest::GearGroup
        item.gears.each do |gear|
          session.use ssh_host_for(gear), :properties => {:gear => gear, :group => item}
        end
      #when RHC::Rest::Gear
      #  session.use ssh_host_for(item), :properties => {:gear => item}
      #end
      else
        raise "Cannot establish an SSH session to this type"
      end
    end
    session.exec @command, &(
      case
      when @opts[:raw]
        lambda { |ch, dest, data|
          (dest == :stdout ? $stdout : $stderr).puts data
        }
      when @opts[:as] == :table
        out = []
        lambda { |ch, dest, data|
          label = label_for(ch)
          data.chomp.each_line do |line|
            row = out.find{ |row| row[0] == label } || (out << [label, []])[-1]
            row[1] << line
          end
        }
      when @opts[:as] == :gear
        lambda { |ch, dest, data| (ch.connection.properties[:gear]['data'] ||= "") << data }
      else
        width = 0
        lambda { |ch, dest, data|
          label = label_for(ch)
          io = dest == :stdout ? $stdout : $stderr
          data.chomp!

          if data.each_line.to_a.count < 2
            io.puts "[#{label}] #{data}"
          elsif @opts[:always_prefix]
            data.each_line do |line|
              io.puts "[#{label}] #{line}"
            end
          else
            io.puts "=== #{label}"
            io.puts data
          end
        }
      end)
    session.loop
  end

  if block_given? && !@opts[:raw]
    case
    when @opts[:as] == :gear
      out = []
      @over.each do |item|
        case item
        when RHC::Rest::GearGroup then item.gears.each{ |gear| out << yield(gear, gear['data'], item) }
        #when RHC::Rest::Gear      then out << yield(gear, gear['data'], nil)
        end
      end
    end
  end

  out
end