Class: Bash::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/bash/session.rb,
lib/bash/session/version.rb

Defined Under Namespace

Classes: TimeoutError

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(default_timeout = nil) ⇒ Session

Returns a new instance of Session.



9
10
11
12
13
# File 'lib/bash/session.rb', line 9

def initialize(default_timeout=nil)
  start_session
  @default_timeout = default_timeout
  @separator = SecureRandom.hex
end

Instance Method Details

#closeObject



49
50
51
52
53
54
55
56
# File 'lib/bash/session.rb', line 49

def close
  return unless @wait_thr.alive?
  return if (Process.kill('TERM', @wait_thr.pid) rescue nil)
  return unless @wait_thr.alive?
  return if (Process.kill('KILL', @wait_thr.pid) rescue nil)
  return unless @wait_thr.alive?
  raise "Could not kill process(PID #{@wait_thr.pid})"
end

#execute(command, options = {}, &callback) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/bash/session.rb', line 15

def execute(command, options={}, &callback)
  exit_status = nil
  out = options[:out]
  timeout = options[:timeout] || @default_timeout

  cmd = command.dup
  cmd << ";" if cmd !~ /[;&]$/
  cmd << "\n" if cmd =~ /#/
  cmd << %Q{DONTEVERUSETHIS=$?; echo "\n#{@separator} $DONTEVERUSETHIS"; echo "exit $DONTEVERUSETHIS"|sh}

  @stdin.puts(cmd)

  until exit_status do
    begin
      data = @outstr.read_nonblock(160000)
      if data.strip =~ /^#{@separator} (\d+)\s*/
        exit_status = $1
        data.gsub!(/\n^#{@separator} (\d+)\s*$/, '')
      end
      callback.call(data) if callback
      out.write data if out
    rescue IO::WaitReadable
      ready = IO.select([@outstr], nil, nil, timeout)
      unless ready
        raise TimeoutError.new("No output received for the last #{timeout} seconds. Timing out...")
      else
        retry
      end
    end
  end

  exit_status.to_i
end