root/src/modules-lua/noit/module/http.lua

Revision 1581bb9cbc2230831b3d94d346397c1c030124ea, 20.7 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 2 years ago)

Make the read_limit config param in http module pass-thru to the
gunzip deflate limit transparently so that the limit is not hardcoded
in the lua module (only a sane default is).

Also, enable the resmon module to use the same config parameter in
the same way

  • Property mode set to 100644
Line 
1 -- Copyright (c) 2008, OmniTI Computer Consulting, Inc.
2 -- All rights reserved.
3 --
4 -- Redistribution and use in source and binary forms, with or without
5 -- modification, are permitted provided that the following conditions are
6 -- met:
7 --
8 --     * Redistributions of source code must retain the above copyright
9 --       notice, this list of conditions and the following disclaimer.
10 --     * Redistributions in binary form must reproduce the above
11 --       copyright notice, this list of conditions and the following
12 --       disclaimer in the documentation and/or other materials provided
13 --       with the distribution.
14 --     * Neither the name OmniTI Computer Consulting, Inc. nor the names
15 --       of its contributors may be used to endorse or promote products
16 --       derived from this software without specific prior written
17 --       permission.
18 --
19 -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 module(..., package.seeall)
32
33 function onload(image)
34   image.xml_description([=[
35 <module>
36   <name>http</name>
37   <description><para>The http module performs GET requests over either HTTP or HTTPS and checks the return code and optionally the body.</para>
38   </description>
39   <loader>lua</loader>
40   <object>noit.module.http</object>
41   <checkconfig>
42     <parameter name="url"
43                required="required"
44                allowed=".+">The URL including schema and hostname (as you would type into a browser's location bar).</parameter>
45     <parameter name="header_(\S+)"
46                required="optional"
47                allowed=".+">Allows the setting of arbitrary HTTP headers in the request.</parameter>
48     <parameter name="method"
49                required="optional"
50                allowed="\S+"
51                default="GET">The HTTP method to use.</parameter>
52     <parameter name="payload"
53                required="optional"
54                allowed=".*">The information transferred as the payload of an HTTP request.</parameter>
55     <parameter name="auth_method"
56                required="optional"
57                allowed="^(?:Basic|Digest|Auto)$">HTTP Authentication method to use.</parameter>
58     <parameter name="auth_user"
59                required="optional"
60                allowed="[^:]*">The user to authenticate as.</parameter>
61     <parameter name="auth_password"
62                required="optional"
63                allowed=".*">The password to use during authentication.</parameter>
64     <parameter name="ca_chain"
65                required="optional"
66                allowed=".+">A path to a file containing all the certificate authorities that should be loaded to validate the remote certificate (for SSL checks).</parameter>
67     <parameter name="certificate_file"
68                required="optional"
69                allowed=".+">A path to a file containing the client certificate that will be presented to the remote server (for SSL checks).</parameter>
70     <parameter name="key_file"
71                required="optional"
72                allowed=".+">A path to a file containing key to be used in conjunction with the cilent certificate (for SSL checks).</parameter>
73     <parameter name="ciphers"
74                required="optional"
75                allowed=".+">A list of ciphers to be used in the SSL protocol (for SSL checks).</parameter>
76     <parameter name="code"
77                required="optional"
78                default="^200$"
79                allowed=".+">The HTTP code that is expected.  If the code received does not match this regular expression, the check is marked as "bad."</parameter>
80     <parameter name="redirects"
81                required="optional"
82                default="0"
83                allowed="\d+">The maximum number of Location header redirects to follow.</parameter>
84     <parameter name="body"
85                required="optional"
86                allowed=".+">This regular expression is matched against the body of the response. If a match is not found, the check will be marked as "bad."</parameter>
87     <parameter name="body_match_*"
88                required="optional"
89                allowed=".+">This regular expression is matched against the body of the response. If a match is found it is captured and added as a metric. For example, if setting is named 'body_match_foo_bar' and a match is found new metric called 'foo_bar' will be added.</parameter>
90     <parameter name="extract"
91                required="optional"
92                allowed=".+">This regular expression is matched against the body of the response globally.  The first capturing match is the key and the second capturing match is the value.  Each key/value extracted is registered as a metric for the check.</parameter>
93     <parameter name="pcre_match_limit"
94                required="optional"
95                default="10000"
96                allowed="\d+">This sets the PCRE internal match limit (see pcreapi documentation).</parameter>
97     <parameter name="include_body"
98                required="optional"
99                allowed="^(?:true|false|on|off)$"
100                default="false">Include whole response body as a metric with the key 'body'.</parameter>
101     <parameter name="read_limit"
102                required="optional"
103                default="0"
104                allowed="\d+">Sets an approximate limit on the data read (0 means no limit).</parameter>
105   </checkconfig>
106   <examples>
107     <example>
108       <title>Checking an HTTP and HTTPS URL.</title>
109       <para>This example checks the OmniTI Labs website over both HTTP and HTTPS.</para>
110       <programlisting><![CDATA[
111       <noit>
112         <modules>
113           <loader image="lua" name="lua">
114             <config><directory>/opt/reconnoiter/libexec/modules-lua/?.lua</directory></config>
115           </loader>
116           <module loader="lua" name="http" object="noit.module.http" />
117         </modules>
118         <checks>
119           <labs target="8.8.38.5" module="http">
120             <check uuid="fe3e984c-7895-11dd-90c1-c74c31b431f0" name="http">
121               <config><url>http://labs.omniti.com/</url></config>
122             </check>
123             <check uuid="1ecd887a-7896-11dd-b28d-0b4216877f83" name="https">
124               <config><url>https://labs.omniti.com/</url></config>
125             </check>
126           </labs>
127         </checks>
128       </noit>
129     ]]></programlisting>
130     </example>
131   </examples>
132 </module>
133 ]=]);
134   return 0
135 end
136
137 function init(module)
138   return 0
139 end
140
141 function config(module, options)
142   return 0
143 end
144
145 local HttpClient = require 'noit.HttpClient'
146
147 local BODY_MATCHES_PREFIX = 'body_match_'
148
149 function elapsed(check, name, starttime, endtime)
150     local elapsedtime = endtime - starttime
151     local seconds = string.format('%.3f', noit.timeval.seconds(elapsedtime))
152     check.metric_uint32(name, math.floor(seconds * 1000 + 0.5))
153     return seconds
154 end
155
156 function rand_string(t, l)
157     local n = table.getn(t)
158     local o = ''
159     while l > 0 do
160       o = o .. t[math.random(1,n)]
161       l = l - 1
162     end
163     return o
164 end
165
166 function auth_digest(method, uri, user, pass, challenge)
167     local c = ', ' .. challenge
168     local nc = '00000001'
169     local cnonce =
170         rand_string({'a','b','c','d','e','f','g','h','i','j','k','l','m',
171                      'n','o','p','q','r','s','t','u','v','x','y','z','A',
172                      'B','C','D','E','F','G','H','I','J','K','L','M','N',
173                      'O','P','Q','R','S','T','U','V','W','X','Y','Z','0',
174                      '1','2','3','4','5','6','7','8','9'}, 8)
175     local p = {}
176     for k,v in string.gmatch(c, ',%s+(%a+)="([^"]+)"') do p[k] = v end
177     for k,v in string.gmatch(c, ',%s+(%a+)=([^",][^,]*)') do p[k] = v end
178
179     -- qop can be a list
180     for q in string.gmatch(p.qop, '([^,]+)') do
181         if q == "auth" then p.qop = "auth" end
182     end
183
184     -- calculate H(A1)
185     local ha1 = noit.md5_hex(user .. ':' .. p.realm .. ':' .. pass)
186     if string.lower(p.qop or '') == 'md5-sess' then
187         ha1 = noit.md5_hex(ha1 .. ':' .. p.nonce .. ':' .. cnonce)
188     end
189     -- calculate H(A2)
190     local ha2 = ''
191     if p.qop == "auth" or p.qop == nil then
192         ha2 = noit.md5_hex(method .. ':' .. uri)
193     else
194         -- we don't support auth-int
195         error("qop=" .. p.qop .. " is unsupported")
196     end
197     local resp = ''
198     if p.qop == "auth" then
199         resp = noit.md5_hex(ha1 .. ':' .. p.nonce .. ':' .. nc
200                                 .. ':' .. cnonce .. ':' .. p.qop
201                                 .. ':' .. ha2)
202     else
203         resp = noit.md5_hex(ha1 .. ':' .. p.nonce .. ':' .. ha2)
204     end
205     local o = {}
206     o.username = user
207     o.realm = p.realm
208     o.nonce = p.nonce
209     o.uri = uri
210     o.cnonce = cnonce
211     o.qop = p.qop
212     o.response = resp
213     o.algorithm = p.algorithm
214     if p.opaque then o.opaque = p.opaque end
215     local hdr = ''
216     for k,v in pairs(o) do
217       if hdr == '' then hdr = k .. '="' .. v .. '"'
218       else hdr = hdr .. ', ' .. k .. '="' .. v .. '"' end
219     end
220     hdr = hdr .. ', nc=' .. nc
221     return hdr
222 end
223
224 function populate_cookie_jar(cookies, host, hdr)
225     if hdr ~= nil then
226         local name, value, trailer =
227             string.match(hdr, "([^=]+)=([^;]+)\;?%s*(.*)")
228         if name ~= nil then
229             local jar = { }
230             jar.name = name;
231             jar.value = value;
232             for k, v in string.gmatch(trailer, "%s*(%w+)(=%w+)?;?") do
233                 if v == nil then jar[string.lower(k)] = true
234                 else jar[string.lower(k)] = v:sub(2)
235                 end
236             end
237             if jar.domain ~= nil then host = jar.domain end
238             if cookies[host] == nil then cookies[host] = { } end
239             table.insert(cookies[host], jar)
240         end
241     end
242 end
243
244 function has_host(pat, host)
245     if pat == host then return true end
246     if pat:sub(1,1) ~= "." then return false end
247     local revpat = pat:sub(2):reverse()
248     local revhost = host:reverse()
249     if revpat == revhost then return true end
250     if revpat == revhost:sub(1, revpat:len()) then
251         if revhost:sub(pat:len(), pat:len()) == "." then return true end
252     end
253     return false
254 end
255
256 function apply_cookies(headers, cookies, host, uri)
257     for h, jars in pairs(cookies) do
258         if has_host(h, host) then
259             for i, jar in ipairs(jars) do
260                 if jar.path == nil or
261                    uri:sub(1, jar.path:len()) == jar.path then
262                     if headers["Cookie"] == nil then
263                         headers["Cookie"] = jar.name .. "=" .. jar.value
264                     else
265                         headers["Cookie"] = headers["Cookie"] .. "; " ..
266                                             jar.name .. "=" .. jar.value
267                     end
268                 end
269             end
270         end
271     end
272 end
273
274 function initiate(module, check)
275     local url = check.config.url or 'http:///'
276     local schema, host, port, uri = string.match(url, "^(https?)://([^:/]*):?([0-9]*)(/?.*)$");
277     local use_ssl = false
278     local codere = noit.pcre(check.config.code or '^200$')
279     local good = false
280     local starttime = noit.timeval.now()
281     local method = check.config.method or "GET"
282     local max_len = 80
283     local pcre_match_limit = check.config.pcre_match_limit or 10000
284     local redirects = check.config.redirects or 0
285     local include_body = false
286     local read_limit = tonumber(check.config.read_limit) or nil
287
288     -- expect the worst
289     check.bad()
290     check.unavailable()
291
292     if host == nil then host = check.target end
293     if schema == nil then
294         schema = 'http'
295         uri = '/'
296     end
297     if uri == '' then
298         uri = '/'
299     end
300     if port == '' or port == nil then
301         if schema == 'http' then
302             port = check.config.port or 80
303         elseif schema == 'https' then
304             port = check.config.port or 443
305         else
306             error(schema .. " not supported")
307         end
308     end
309     if schema == 'https' then
310         use_ssl = true
311     end
312
313     -- Include body as a metric
314     if check.config.include_body == "true" or check.config.include_body == "on" then
315         include_body = true
316     end
317
318     local output = ''
319     local connecttime, firstbytetime
320     local next_location
321     local cookies = { }
322
323     -- callbacks from the HttpClient
324     local callbacks = { }
325     callbacks.consume = function (str)
326         if firstbytetime == nil then firstbytetime = noit.timeval.now() end
327         output = output .. (str or '')
328     end
329     callbacks.headers = function (hdrs)
330         next_location = hdrs.location
331         populate_cookie_jar(cookies, host, hdrs["set-cookie"])
332         populate_cookie_jar(cookies, hdrs["set-cookie2"])
333     end
334
335     callbacks.connected = function () connecttime = noit.timeval.now() end
336
337     -- setup SSL info
338     local default_ca_chain =
339         noit.conf_get_string("/noit/eventer/config/default_ca_chain")
340     callbacks.certfile = function () return check.config.certificate_file end
341     callbacks.keyfile = function () return check.config.key_file end
342     callbacks.cachain = function ()
343         return check.config.ca_chain and check.config.ca_chain
344                                       or default_ca_chain
345     end
346     callbacks.ciphers = function () return check.config.ciphers end
347
348     -- set the stage
349     local headers = {}
350     headers.Host = host
351     for header, value in pairs(check.config) do
352         hdr = string.match(header, '^header_(.+)$')
353         if hdr ~= nil then
354           headers[hdr] = value
355         end
356     end
357     if check.config.auth_method == "Basic" then
358         local user = check.config.auth_user or ''
359         local password = check.config.auth_password or ''
360         local encoded = noit.base64_encode(user .. ':' .. password)
361         headers["Authorization"] = "Basic " .. encoded
362     elseif check.config.auth_method == "Digest" or
363            check.config.auth_method == "Auto" then
364         -- this is handled later as we need our challenge.
365         local client = HttpClient:new()
366         local rv, err = client:connect(check.target_ip, port, use_ssl)
367         if rv ~= 0 then
368             check.status(str or "unknown error")
369             return
370         end
371         local headers_firstpass = {}
372         for k,v in pairs(headers) do
373             headers_firstpass[k] = v
374         end
375         client:do_request(method, uri, headers_firstpass)
376         client:get_response(read_limit)
377         if client.code ~= 401 or
378            client.headers["www-authenticate"] == nil then
379             check.status("expected digest challenge, got " .. client.code)
380             return
381         end
382         local user = check.config.auth_user or ''
383         local password = check.config.auth_password or ''
384         local ameth, challenge =
385             string.match(client.headers["www-authenticate"], '^(%S+)%s+(.+)$')
386         if check.config.auth_method == "Auto" and ameth == "Basic" then
387             local encoded = noit.base64_encode(user .. ':' .. password)
388             headers["Authorization"] = "Basic " .. encoded
389         elseif ameth == "Digest" then
390             headers["Authorization"] =
391                 "Digest " .. auth_digest(method, uri,
392                                          user, password, challenge)
393         else
394             check.status("Unexpected auth '" .. ameth .. "' in challenge")
395             return
396         end
397     elseif check.config.auth_method ~= nil then
398       check.status("Unknown auth method: " .. check.config.auth_method)
399       return
400     end
401
402     -- perform the request
403     local client
404     local dns = noit.dns()
405     local target = check.target_ip
406     local payload = check.config.payload
407     -- artificially increase redirects as the initial request counts
408     redirects = redirects + 1
409     repeat
410         starttime = noit.timeval.now()
411         local optclient = HttpClient:new(callbacks)
412         local rv, err = optclient:connect(target, port, use_ssl)
413
414         if rv ~= 0 then
415             check.status(err or "unknown error")
416             return
417         end
418         optclient:do_request(method, uri, headers, payload)
419         optclient:get_response(read_limit)
420
421         redirects = redirects - 1
422         client = optclient
423
424         if next_location ~= nil then
425             -- reset some stuff for the redirect
426             local prev_port = port
427             local prev_host = host
428             method = 'GET'
429             payload = nil
430             schema, host, port, uri =
431                 string.match(next_location,
432                              "^(https?)://([^:/]*):?([0-9]*)(/?.*)$")
433             if schema == nil then
434                 port = prev_port
435                 host = prev_host
436                 uri = next_location
437             elseif schema == 'http' then
438                 use_ssl = false
439                 if port == "" then port = 80 end
440             elseif schema == 'https' then
441                 use_ssl = true
442                 if port == "" then port = 443 end
443             end
444             if host ~= nil then
445                 headers.Host = host
446                 local r = dns:lookup(host)
447                 if r.a == nil then
448                     check.status("failed to resolve " + host)
449                     return
450                 end
451                 target = r.a
452             end
453             headers["Cookie"] = check.config["header_Cookie"]
454             apply_cookies(headers, cookies, host, uri)
455         end
456     until redirects <= 0 or next_location == nil
457
458     local endtime = noit.timeval.now()
459     check.available()
460
461     local status = ''
462     -- setup the code
463     check.metric_string("code", client.code)
464     status = status .. 'code=' .. client.code
465     if codere ~= nil and codere(client.code) then
466       good = true
467     end
468
469     -- truncated response
470     check.metric_uint32("truncated", client.truncated and 1 or 0)
471
472     -- turnaround time
473     local seconds = elapsed(check, "duration", starttime, endtime)
474     status = status .. ',rt=' .. seconds .. 's'
475     elapsed(check, "tt_connect", starttime, connecttime)
476     elapsed(check, "tt_firstbyte", starttime, firstbytetime)
477
478     -- size
479     status = status .. ',bytes=' .. client.content_bytes
480     check.metric_int32("bytes", client.content_bytes)
481
482     if check.config.extract ~= nil then
483       local exre = noit.pcre(check.config.extract)
484       local rv = true
485       local m = nil
486       while rv and m ~= '' do
487         rv, m, key, value = exre(output or '', { limit = pcre_match_limit })
488         if rv and key ~= nil then
489           check.metric(key, value)
490         end
491       end
492     end
493
494     -- check body
495     if check.config.body ~= nil then
496       local bodyre = noit.pcre(check.config.body)
497       local rv, m, m1 = bodyre(output or '')
498       if rv then
499         m = m1 or m or output
500         if string.len(m) > max_len then
501           m = string.sub(m,1,max_len)
502         end
503         status = status .. ',body=matched'
504         check.metric_string('body_match', m)
505       else
506         status = status .. ',body=failed'
507         check.metric_string('body_match', nil)
508         good = false
509       end
510     end
511
512     -- check body matches
513     local matches = 0
514     has_body_matches = false
515     for key, value in pairs(check.config) do
516       m = string.find(key, BODY_MATCHES_PREFIX)
517
518       if m == 1 then
519         has_body_matches = true
520         key = string.gsub(key, BODY_MATCHES_PREFIX, '')
521
522         local bodyre = noit.pcre(value)
523         local rv, m, m1 = bodyre(output or '')
524
525         if rv then
526           matches = matches + 1
527           m = m1 or m or output
528           if string.len(m) > max_len then
529             m = string.sub(m,1,max_len)
530           end
531           check.metric_string('body_match_' .. key, m)
532         else
533           check.metric_string('body_match_' .. key, nil)
534         end
535       end
536     end
537
538     if has_body_matches then
539       status = status .. ',body_matches=' .. tostring(matches) .. ' matches'
540     end
541
542     -- Include body
543     if include_body then
544         check.metric_string('body', output or '')
545     end
546
547     -- ssl ctx
548     local ssl_ctx = client:ssl_ctx()
549     if ssl_ctx ~= nil then
550       if ssl_ctx.error ~= nil then status = status .. ',sslerror' end
551       check.metric_string("cert_error", ssl_ctx.error)
552       check.metric_string("cert_issuer", ssl_ctx.issuer)
553       check.metric_string("cert_subject", ssl_ctx.subject)
554       check.metric_uint32("cert_start", ssl_ctx.start_time)
555       check.metric_uint32("cert_end", ssl_ctx.end_time)
556       check.metric_int32("cert_end_in", ssl_ctx.end_time - os.time())
557       if noit.timeval.seconds(starttime) > ssl_ctx.end_time then
558         good = false
559         status = status .. ',ssl=expired'
560       end
561     end
562
563     if good then check.good() else check.bad() end
564     check.status(status)
565 end
566
Note: See TracBrowser for help on using the browser.