Class: Toolshed::Timeout

Inherits:
Object
  • Object
show all
Defined in:
lib/toolshed/timeout.rb

Overview

github.com/ruby/ruby/blob/trunk/lib/timeout.rb This code had to be modified so the timeout could be extended instead of just being a fixnum. This is import for the SSH client as we want it to keep running for an unlimited time period as long as we are getting output from the client. When that stops then the timeout needs to kick in just in case the server is no longer responding or a connection got lost. Too bad ruby core doesn’t already support something like this.

Defined Under Namespace

Classes: Error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ Timeout

Returns a new instance of Timeout.



18
19
20
21
22
# File 'lib/toolshed/timeout.rb', line 18

def initialize(options = nil)
  options ||= {}
  @timeout_period = options[:timeout_period] || 30
  @start_time = options[:start_time] || Time.now.utc.to_i
end

Instance Attribute Details

#start_timeObject

Returns the value of attribute start_time.



15
16
17
# File 'lib/toolshed/timeout.rb', line 15

def start_time
  @start_time
end

#timeout_periodObject (readonly)

Returns the value of attribute timeout_period.



16
17
18
# File 'lib/toolshed/timeout.rb', line 16

def timeout_period
  @timeout_period
end

Instance Method Details

#reset_start_timeObject



24
25
26
# File 'lib/toolshed/timeout.rb', line 24

def reset_start_time
  @start_time = Time.now.utc.to_i
end

#start(klass = nil) ⇒ Object

:yield: sec

Raises:

  • (e)


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
65
66
# File 'lib/toolshed/timeout.rb', line 28

def start(klass = nil)   #:yield: +sec+
  return yield(timeout_period) if timeout_period == nil or timeout_period.zero?
  message = "execution expired in #{timeout_period} seconds".freeze
  e = Error
  bl = proc do |exception|
    begin
      x = Thread.current
      y = Thread.start {
        begin
          sleep(1) until timed_out?
        rescue => e
          x.raise e
        else
          x.raise exception, message
        end
      }
      return yield(timeout_period)
    ensure
      if y
        y.kill
        y.join # make sure y is dead.
      end
    end
  end
  if klass
    begin
      bl.call(klass)
    rescue klass => e
      bt = e.backtrace
    end
  else
    bt = Error.catch(message, &bl)
  end
  level = -caller(CALLER_OFFSET).size-2
  while THIS_FILE =~ bt[level]
    bt.delete_at(level)
  end
  raise(e, message, bt)
end

#timed_out?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/toolshed/timeout.rb', line 68

def timed_out?
  Time.now.utc.to_i - start_time > timeout_period
end