Divide the MSB source codes into two repos
[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 local rrcache = require('lib.tools.rr_cache')\r
25 \r
26 function _M.select_backserver(servers,svckey)\r
27         local length = #servers\r
28         local index = ngx.ctx.last_peer_index\r
29 \r
30         if index then\r
31                 --if it is a retry request,use the index in the context as the base\r
32                 index = index%length+1\r
33         else\r
34                 --if it is a normal request,fetch index from cache as the base\r
35                 index = rrcache.get(svckey) or 0\r
36                 index = index%length+1\r
37                 rrcache.set(svckey,index)\r
38         end\r
39         ngx.ctx.last_peer_index = index\r
40 \r
41         --[[\r
42         local resty_lock = require "resty.lock"\r
43         local roundrobin_cache = ngx.shared.rr_cache\r
44 \r
45         --step1:acquire lock\r
46         local opts = {["timeout"] = 0.002,["exptime"] = 0.05}--this can be set using the conf file\r
47         local rrlock = resty_lock:new("rr_locks",opts)\r
48         local elapsed, err = rrlock:lock(svckey)\r
49         if not elapsed then\r
50                 --return fail("failed to acquire the lock: ", err)\r
51         end\r
52         --step2:lock successfully acquired!incr the index\r
53         local index, err = roundrobin_cache:get(svckey)\r
54         if not index then\r
55                 index = 0\r
56         end\r
57         index = index%length+1\r
58 \r
59         --step3:update the shm cache with the new index\r
60         roundrobin_cache:set(svckey,index)\r
61 \r
62         --step4:release the lock\r
63         local ok, err = rrlock:unlock()\r
64         ]]\r
65         return servers[index],nil\r
66 end\r
67 \r
68 return _M