From: Michal Fojtik <[email protected]> This method implement very basic polling mechanism that can be used to poll different instance states or conditions (like IP address is ready.)
Signed-off-by: Michal fojtik <[email protected]> --- server/lib/deltacloud/models/instance.rb | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/server/lib/deltacloud/models/instance.rb b/server/lib/deltacloud/models/instance.rb index 303691d..97f202f 100644 --- a/server/lib/deltacloud/models/instance.rb +++ b/server/lib/deltacloud/models/instance.rb @@ -14,8 +14,12 @@ # License for the specific language governing permissions and limitations # under the License. +require 'timeout' + class Instance < BaseModel + include Timeout + attr_accessor :owner_id attr_accessor :image_id attr_accessor :name @@ -73,4 +77,39 @@ class Instance < BaseModel return true unless authn_error.nil? end + # This method will pool the instance until condition is true + # Will raise 'Timeout' when it reach retry count + # + # default opts[:retries] => 10 + # default opts[:time_between_retry] => 10 (seconds) + # default opts[:timeout] => 60 (seconds) -> single request timeout + # + # opts[:before] => Proc -> executed 'before' making each request + # opts[:after] => Proc -> executed 'after' making each request + # + def wait_for!(driver, opts={}, &block) + opts[:retries] ||= 10 + opts[:time_between_retry] ||= 10 + opts[:timeout] ||= 60 + opts[:retries].downto(0) do |r| + result = begin + timeout(opts[:timeout]) do + if opts[:before] + new_instance = opts[:before].call(r) { driver.instance(:id => self.id) } + else + new_instance = driver.instance(:id => self.id) + end + ((yield new_instance) == true) ? new_instance : false + end + rescue Timeout::Error + false + ensure + opts[:after].call(r) if opts[:after] + end + return result unless result == false + sleep(opts[:time_between_retry]) + end + raise Timeout::Error + end + end -- 1.7.10.2
