Divide the MSB source codes into two repos
[msb/apigateway.git] / openresty-ext / src / assembly / resources / openresty / nginx / luaext / loadbalance / balancer.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 b = require "ngx.balancer"\r
20 local baseupstream = require "loadbalance.baseupstream"\r
21 local log_util  =  require('lib.utils.log_util')\r
22 local error_handler  =  require('lib.utils.error_handler')\r
23 \r
24 local log = log_util.log\r
25 local ngx_ctx = ngx.ctx\r
26 local servers = ngx_ctx.backservers\r
27 local svc_key = ngx_ctx.svc_key\r
28 local error_svc_not_found = error_handler.svc_not_found\r
29 \r
30 local status = b.get_last_failure()\r
31 if status == nil then\r
32         --only reset the server status table of the service in the first attempt\r
33         baseupstream.check_and_reset_srv_status_ifneed(svc_key,servers)\r
34 elseif status == "failed" then\r
35         local last_peer = ngx.ctx.last_peer\r
36         --mark the srv failed one time\r
37         baseupstream.mark_srv_failed(svc_key,last_peer)\r
38 end\r
39 \r
40 local server,err = baseupstream.get_backserver(svc_key,servers)\r
41 if server == nil then \r
42         ngx.log(ngx.WARN, ngx.var.request_id.." ".."No active backend server found! detail_info: key--"..svc_key.." "..(err or ""))\r
43         return\r
44 end\r
45 if baseupstream.can_retry(svc_key,servers) then\r
46         b.set_more_tries(1)\r
47 end\r
48 b.set_current_peer(server["ip"],server["port"])\r
49 --log("upstreamserver",server["ip"]..":"..server["port"])\r
50 ngx.ctx.last_peer = { ip=server["ip"], port=server["port"] }