[英]Strange io.popen behaviour in lua
我在nginx config中有lua塊,它檢查redis服務器連接以及是否有4個Java進程啟動,然后根據此檢查返回200或500狀態。
location = /healthcheck {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.status = 500
return
end
local ps = io.popen("/bin/ps aux |grep -c '[j]ava.*63'")
local output = tostring(ps:read('*a'))
ps:close()
if string.match(output, '4') then
ngx.status = 200
else
ngx.status = 500
end
}
}
但是定期output
變量采用nil
值,而不應這樣做。 只是不知道為什么會發生。
預先感謝同志。
UPD:
使用tonumber
失敗
bad argument #2 to 'tonumber' (number expected, got string)
更新了位置配置:
location = /healthcheck {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.status = 500
return
end
local ps = io.popen("/bin/ps aux |grep -c '[j]ava.*63'")
local output = tonumber(ps:read())
ps:close()
if (output == 4) then
ngx.status = 200
else
ngx.status = 500
end
}
}
UPD2:
記錄到nginx錯誤(帶有tostring)將顯示以下內容:
grep: write error: Broken pipe
2016/04/19 17:54:48 [error] 301#0: *5 [lua] content_by_lua(healthcheck.conf:33):20: OUTPUT:nil
UPD3:
使用命令grep -c '[j]ava.*63' <(/bin/ps aux)
避免使用管道:
local ps = io.popen("grep -c '[j]ava.*63' <(/bin/ps aux)")
得到下一個錯誤:
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `grep -c '[j]ava.*63' <(/bin/ps aux)'
根據這個答案和一些測試下一個配置做的工作:
location = /healthcheck {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.status = 500
return
end
local ps = io.popen("/bin/ps aux >/tmp/ps.out", "w")
ps:close()
local ps = io.popen("grep -c '[j]ava.*63' /tmp/ps.out")
local output = tostring(ps:read())
ps:close()
if string.match(output, '4') then
ngx.status = 200
else
ngx.status = 500
end
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.