diff --git a/README.markdown b/README.markdown index 961a636..78ff44d 100644 --- a/README.markdown +++ b/README.markdown @@ -3,6 +3,8 @@ Name lua-resty-upstream-healthcheck - Health-checker for Nginx upstream servers +Add the possibility to match a specific string in the beginning of the body + Table of Contents ================= @@ -64,6 +66,7 @@ http { fall = 3, -- # of successive failures before turning a peer down rise = 2, -- # of successive successes before turning a peer up valid_statuses = {200, 302}, -- a list valid HTTP status code + match_string = "OkiDoki", -- a string to match in the beginning of the body concurrency = 10, -- concurrency level for test requests } if not ok then diff --git a/lib/resty/upstream/healthcheck.lua b/lib/resty/upstream/healthcheck.lua index 2118282..8e76a7b 100644 --- a/lib/resty/upstream/healthcheck.lua +++ b/lib/resty/upstream/healthcheck.lua @@ -6,6 +6,7 @@ local WARN = ngx.WARN local DEBUG = ngx.DEBUG local str_find = string.find local sub = string.sub +local re_match = ngx.re.match local re_find = ngx.re.find local new_timer = ngx.timer.at local shared = ngx.shared @@ -214,6 +215,7 @@ local function check_peer(ctx, id, peer, is_backup) local name = peer.name local statuses = ctx.statuses local req = ctx.http_req + local match_string = ctx.match_string local sock, err = stream_sock() if not sock then @@ -273,6 +275,18 @@ local function check_peer(ctx, id, peer, is_backup) end end + if match_string then + local bytes, err, partial = sock:receive(1024) -- read the first 1k of data + local data = partial or bytes + local m, err = re_match(data, match_string, "jo") + if not m then + peer_error(ctx, is_backup, id, peer, + "match_string not found from ", name, ": ", match_string) + sock:close() + return + end + end + peer_ok(ctx, is_backup, id, peer) sock:close() end @@ -567,6 +581,11 @@ function _M.spawn_checker(opts) -- debug("interval: ", interval) + local match_string = opts.match_string + if not match_string then + match_string = nil + end + local concur = opts.concurrency if not concur then concur = 1 @@ -617,6 +636,7 @@ function _M.spawn_checker(opts) dict = dict, fall = fall, rise = rise, + match_string = match_string, statuses = statuses, version = 0, concurrency = concur,