Initial code import
[msb/apigateway.git] / openresty-ext / src / assembly / resources / openresty / nginx / luaext / loadbalance / policy / roundrobin.lua
1 --[[\r
2 \r
3     Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE)\r
4 \r
5     Licensed under the Apache License, Version 2.0 (the "License");\r
6     you may not use this file except in compliance with the License.\r
7     You may obtain a copy of the License at\r
8 \r
9             http://www.apache.org/licenses/LICENSE-2.0\r
10 \r
11     Unless required by applicable law or agreed to in writing, software\r
12     distributed under the License is distributed on an "AS IS" BASIS,\r
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
14     See the License for the specific language governing permissions and\r
15     limitations under the License.\r
16 \r
17 --]]\r
18 \r
19 local _M = {}\r
20 _M._VERSION = '1.0.0'\r
21 \r
22 local tbl_util  = require('lib.utils.table_util')\r
23 local tbl_isempty = tbl_util.isempty\r
24 \r
25 function _M.get_backserver(servers,svckey)\r
26         if tbl_isempty(servers) then return nil,"input server list is empty" end\r
27 \r
28         local length = #servers\r
29         if length==1 then\r
30                 -- return it directly if there is only one server\r
31                 return servers[1],nil\r
32         end\r
33 \r
34         local resty_lock = require "resty.lock"\r
35         local roundrobin_cache = ngx.shared.rr_cache\r
36 \r
37         --step1:acquire lock\r
38         local opts = {["timeout"] = 0.002,["exptime"] = 0.05}--this can be set using the conf file\r
39         local rrlock = resty_lock:new("rr_locks",opts)\r
40         local elapsed, err = rrlock:lock(svckey)\r
41         if not elapsed then\r
42                 --return fail("failed to acquire the lock: ", err)\r
43         end\r
44         --step2:lock successfully acquired!incr the index\r
45         local index, err = roundrobin_cache:get(svckey)\r
46         if not index then\r
47                 index = 0\r
48         end\r
49         index = index%length+1\r
50 \r
51         --step3:update the shm cache with the new index\r
52         roundrobin_cache:set(svckey,index)\r
53 \r
54         --step4:release the lock\r
55         local ok, err = rrlock:unlock()\r
56 \r
57         return servers[index],nil\r
58 end\r
59 \r
60 return _M