Class: Vana::Element::Shell

Inherits:
BaseElement show all
Defined in:
lib/vana/element/shell.rb

Overview

shell element

Instance Method Summary collapse

Methods inherited from BaseElement

#execute, #initialize, #name=

Constructor Details

This class inherits a constructor from Vana::Element::BaseElement

Instance Method Details

#action(host, *_args) ⇒ Object



24
25
26
27
28
29
30
31
32
33
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
# File 'lib/vana/element/shell.rb', line 24

def action(host, *_args)
  if host == 'localhost'
    stdout, stderr, status = Open3.capture3(@opts[:cmd])
    {
      cmd: @opts[:cmd],
      stdout: stdout,
      stderr: stderr,
      success: status.success?,
      status: status.exitstatus,
      pid: status.pid
    }
  else
    Net::SSH.start(host) do |ssh|
      output = {
        cmd: @opts[:cmd],
        stdout: '',
        stderr: ''
      }

      ssh.open_channel do |channel|
        channel.exec(@opts[:cmd]) do |_ch, _success|
          # stdout
          channel.on_data { |_ch, data| output[:stdout] << data }

          # stderr
          channel.on_extended_data { |_ch, data| output[:stderr] << data }

          # exit status
          channel.on_request('exit-status') do |_ch, data|
            output[:status] = data.read_long
            output[:success] = output[:status].zero?
          end
        end
      end

      ssh.loop

      output
    end
  end
end

#cmd=(cmd) ⇒ Object



20
21
22
# File 'lib/vana/element/shell.rb', line 20

def cmd=(cmd)
  @opts[:cmd] = cmd
end

#setup(*args) ⇒ Object



15
16
17
18
# File 'lib/vana/element/shell.rb', line 15

def setup(*args)
  @opts[:cmd] ||= args.first
  @element_opts[:name] ||= @opts[:cmd]
end