-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhaproxy-agent.lua
More file actions
executable file
·92 lines (80 loc) · 1.99 KB
/
haproxy-agent.lua
File metadata and controls
executable file
·92 lines (80 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env lua
local socket = require("socket")
local signal = require("posix.signal")
local cfg = {}
local reload_cfg_interval = 1
local socket_timeout = 10
local status_file = "haproxy-agent.conf"
local host = os.getenv("HOST") or "0.0.0.0"
local port = tonumber(os.getenv("PORT")) or 9090
local sock, err = socket.bind("0.0.0.0", port)
if sock then
print(string.format("haproxy-agent listening on %s:%d", host, port))
else
print(string.format("can't bind to socket with %s:%d, please check", host, port))
os.exit(2)
end
--[[
--example config
ready up maxconn:30 0% # test
myservice.paulbsd.com: ready up 93% maxconn:15
--]]--
local cfg_loader = coroutine.create(function()
while true do
cfg = get_cfg()
coroutine.yield()
end
end)
function get_cfg()
local res = {}
local lines = io.lines(status_file)
for line in lines do
local s, e, key, value = string.find(line, "([%w%p]+): ([%w %p]+)")
if value then
res[key] = value
else
local s, e, value = string.find(line, "([%w %p]+)")
if value then
res["all"] = value
end
end
end
return res
end
function close(conn)
conn:close()
conn:shutdown()
end
function run()
while true do
local conn = sock:accept()
conn:settimeout(socket_timeout)
local s, e = conn:receive("*l")
if e == "timeout" then close(conn) coroutine.yield() end
if s and e ~= "closed" then
local send = ""
if cfg[s] then
send = cfg[s]
elseif cfg["all"] then
send = cfg["all"]
end
conn:send(send.."\n")
end
close(conn)
coroutine.yield()
end
end
local runner = coroutine.create(function() run() end)
local last_time = os.time()
coroutine.resume(cfg_loader)
signal.signal(signal.SIGINT, function(signum)
if sock then sock:close() end
os.exit(128+signum)
end)
while true do
coroutine.resume(runner)
if os.time()-last_time > reload_cfg_interval then
coroutine.resume(cfg_loader)
last_time = os.time()
end
end