upstream.lua
1.98 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
local upstream = require "ngx.upstream"
local json=require "cjson"
local get_servers = upstream.get_servers
local get_upstreams = upstream.get_upstreams
local cache=ngx.shared.upstream
function list()
local t={}
local us=get_upstreams()
for _,u in ipairs(us) do
local peers,err = upstream.get_primary_peers(u)
if err then
ngx.say("failed to get servers in upstream ", u)
return
end
local d={}
d["name"]=u
d["value"]={}
for _,p in ipairs(peers) do
local s={}
s["id"]=p.id
s["down"]=p.down and p.down or false
s["name"]=p.name
s["backup"]=false
table.insert(d["value"],s)
end
peers,err = upstream.get_backup_peers(u)
if err then
ngx.say("failed to get servers in upstream ", u)
return
end
for _,p in ipairs(peers) do
local s={}
s["id"]=p.id
s["down"]=p.down and p.down or false
s["name"]=p.name
s["backup"]=true
table.insert(d["value"],s)
end
table.insert(t,d)
end
ngx.header["Content-type"]="application/json;charset=utf-8"
ngx.say(json.encode(t))
end
function upordown(upstream_name,is_backup,peer_id,down_value)
local ok, err = upstream.set_peer_down(upstream_name, is_backup, peer_id, down_value)
local t={}
t["upstream"]=upstream_name
t["backup"]=is_backup
t["id"]=peer_id
t["value"]=down_value
local suc=cache:set("d:" .. upstream_name .. ":" .. tostring(id) .. ":" .. tostring(is_backup),json.encode(t))
return suc
end
local args=ngx.req.get_uri_args()
local method=args["method"]
if method == "list" then
list()
elseif(method=="down" or method=="up") then
local upstream=args["upstream"]
local backup=args["backup"]=="true" and true or false
local id=tonumber(args["id"])
local down= method=="down" and true or false
local suc=upordown(upstream,backup,id,down)
local t={}
t["suc"]=suc
ngx.header["Content-type"]="application/json;charset=utf-8"
ngx.say(json.encode(t))
end