add http_response_code condition
[god.git] / lib / god / conditions / http_response_code.rb
blob95d677b9b43c0e063b2c10e19ebfb904bc8941a8
1 require 'net/http'
3 module God
4   module Conditions
5     
6     class HttpResponseCode < PollCondition
7       attr_accessor :code_is, :code_is_not, :times, :host, :port, :timeout, :path
8     
9       def initialize
10         super
11         self.times = [1, 1]
12       end
13       
14       def prepare
15         self.code_is = Array(self.code) if self.code_is
16         self.code_is_not = Array(self.code_is_not) if self.code_is_not
17         
18         if self.times.kind_of?(Integer)
19           self.times = [self.times, self.times]
20         end
21         
22         @timeline = Timeline.new(self.times[1])
23       end
24     
25       def valid?
26         valid = true
27         valid &= complain("Attribute 'host' must be specified", self) if self.host.nil?
28         valid &= complain("Attribute 'port' must be specified", self) if self.port.nil?
29         valid &= complain("Attribute 'path' must be specified", self) if self.path.nil?
30         valid &= complain("One (and only one) of attributes 'code_is' and 'code_is_not' must be specified", self) if
31           (self.code_is.nil? && self.code_is_not.nil?) || (self.code_is && self.code_is_not)
32         valid &= complain("Attribute 'timeout' must be specified", self) if self.timeout.nil?
33         valid
34       end
35     
36       def test
37         response = nil
38         
39         Net::HTTP.start(self.host, self.port) do |http|
40           http.read_timeout = self.timeout
41           response = http.head(self.path)
42         end
43         
44         if self.code_is && self.code_is.include?(response.code)
45           pass
46         elsif self.code_is_not && !self.code.include?(response.code)
47           pass
48         else
49           false
50         end
51       rescue Timeout::Error
52         self.code_is ? false : pass
53       end
54       
55       private
56       
57       def pass
58         @timeline.clear
59         return true
60       end
61       
62     end
63     
64   end
65 end