3 Copyright 2016 2015-2016 ZTE, Inc. and others. All rights reserved.
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
9 http://www.apache.org/licenses/LICENSE-2.0
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
18 email: meng.zhaoxing1@zte.com.cn
21 -- put red into the connection pool of size 100,
22 -- with 10 seconds max idle time
23 local function close_redis(red)
27 --release connection to the pool
28 local pool_max_idle_time = 10000
30 local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
32 ngx.log(ngx.ERR, "set keepalive error:", err)
37 local function rewrite_iui_url()
38 local iuiserver=ngx.var.iuiserver
39 if iuiserver=="fallback" then
40 ngx.status = ngx.HTTP_NOT_FOUND
43 local iuiurl=ngx.var.iuiurl
44 local uri = ngx.re.sub(ngx.var.uri, "^/openoui/([^/]+)(.*)", iuiurl.."$2", "o")
48 local function query_iui_info()
49 local iuiserver = ngx.var.iuiserver
50 local iuiname = ngx.var.iuiname
52 -- Check if key exists in local cache
53 local cache = ngx.shared.ceryx
54 local server, flags = cache:get("server:iui:"..iuiname)
55 local url, flags = cache:get("url:iui:"..iuiname)
56 if server and url then
57 ngx.var.iuiserver = server
59 ngx.log(ngx.WARN, "==using iui cache:", server.."&&"..url)
63 local redis = require "resty.redis"
64 local red = redis:new()
65 red:set_timeout(1000) -- 1000 ms
66 local redis_host = "127.0.0.1"
67 local redis_port = 6379
68 local res, err = red:connect(redis_host, redis_port)
70 -- Return if could not connect to Redis
72 ngx.log(ngx.ERR, "connect to redis error:", err)
76 -- Construct Redis key
78 local keyprefix = prefix..":routing:iui:"..iuiname
80 local infokey=keyprefix..":info"
81 -- first of all check whether the status is 1(enabled)
82 local status = red:hget(infokey,"status")
83 if not (status=="1") then
84 ngx.log(ngx.WARN, keyprefix.."is disabled.status=", status)
85 return close_redis(red)
88 -- Try to get url for iuiname
89 local url, err = red:hget(infokey,"url")
90 ngx.log(ngx.WARN, "==url:", url)
91 if not url or url == ngx.null then
92 return close_redis(red)
95 -- Try to get ip:port for iuiname
96 local serverkey=keyprefix..":lb:server1"
97 local server, err = red:hget(serverkey,"ip")..":"..red:hget(serverkey,"port")
98 ngx.log(ngx.WARN, "==server:", server)
99 if not server or server == ngx.null then
100 return close_redis(red)
104 -- Save found key to local cache for 5 seconds
105 cache:set("server:iui:"..iuiname, server, 5)
106 cache:set("url:iui:"..iuiname, url, 5)
108 ngx.log(ngx.WARN, "==iui result:", server.."&&"..url)
109 ngx.var.iuiserver = server
112 return close_redis(red)