zhangguanzhang's Blog

lua列出所有upsteam

字数统计: 430阅读时长: 2 min
2017/06/26 Share

需要在http的路由上暴露出所有的upsteam配置段

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
upstream names{
server 127.0.0.1:8050 ;
server 127.0.0.1:8060 ;
}

upstream tuling {
server 127.0.0.1:8051 weight=5;
server 127.0.0.1:8062 weight=1;
}

server {
listen 80;
server_name localhost;

#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;

location / {
root /usr/local/openresty/nginx/html;
index index.html index.htm;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/openresty/nginx/html;
}

location /clusterinfo {
content_by_lua '
local cjson = require "cjson"

local upstream = require "ngx.upstream"
local get_servers = upstream.get_servers
local get_upstreams = upstream.get_upstreams

-- get all upstream config block
local function get_all_upstream()
local us = get_upstreams()
local upstreams = {}

for _, u in ipairs(us) do
local srvs = get_servers(u)
upstreams[u] = srvs
end

return upstreams
end

ngx.say(cjson.encode(get_all_upstream()))


';
}
}

限制下只让内网ip访问

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
...
location /clusterinfo {
allow 100.64.0.0/24;
allow 10.0.0.0/8;
deny all;
content_by_lua '
local cjson = require "cjson"

local upstream = require "ngx.upstream"
local get_servers = upstream.get_servers
local get_upstreams = upstream.get_upstreams

-- get all upstream config block
local function get_all_upstream()
local us = get_upstreams()
local upstreams = {}

for _, u in ipairs(us) do
local srvs = get_servers(u)
upstreams[u] = srvs
end

return upstreams
end

ngx.say(cjson.encode(get_all_upstream()))


';
}
...

单独要地址的话

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
...
location /clusterinfo {
content_by_lua '
local cjson = require "cjson"

local upstream = require "ngx.upstream"
local get_servers = upstream.get_servers
local get_upstreams = upstream.get_upstreams

-- get all upstream config block
local function get_all_upstream()
local us = get_upstreams()
local upstreams = {}

for _, u in ipairs(us) do
local srvs = get_servers(u)
local servers = {}
for i,s in ipairs(srvs) do
servers[i]=s["addr"]
end
upstreams[u] = servers
end

return upstreams
end

ngx.say(cjson.encode(get_all_upstream()))


';
}

参考

CATALOG