-- Copyright (C) Maohai Zhu (admin@centos.bz). local json = require "resty.dkjson" local aes = require "resty.aes" local resty_str = require "resty.string" local http = require "resty.http" local config = require "resty.config" local config_util = require "resty.config_util" local ntp = require "resty.ntp" local logger = require "resty.logger" local resolver = require "resty.resolver" local resty_lock = require "resty.lock" local encode_base64 = ngx.encode_base64 local decode_base64 = ngx.decode_base64 local pcall = pcall local ngx_header = ngx.header local ngx_print = ngx.print local ngx_exit = ngx.exit local math_randomseed = math.randomseed local math_random = math.random local table_concat = table.concat local table_getn = table.getn local ngx_time = ngx.time local string_sub = string.sub local type = type local io_open = io.open local re_match = ngx.re.match local ngx_md5 = ngx.md5 local ngx_worker_id = ngx.worker.id local ngx_timer_at = ngx.timer.at local string_reverse = string.reverse local string_find = string.find local dict = ngx.shared.guard local log_dict = ngx.shared.log local log = ngx.log local ERR = ngx.ERR local current_script_path = debug.getinfo(1, "S").source:sub(2) local lua_root_path = current_script_path:sub( 1, 0 - string.len("/lib/resty/util.lua") -1 ) local re_gsub = ngx.re.gsub local ngx_var = ngx.var local table_insert = table.insert local function echo_html(content) ngx_header.content_type = "text/html; charset=utf-8" ngx_print(content) ngx_exit(200) end local function echo_html_gz(content) ngx_header.content_type = "text/html; charset=utf-8" ngx_header.content_encoding= "gzip" ngx_print(content) ngx_exit(200) end local function echo_json(content) ngx_header.content_type = "application/json" ngx_print(json.encode(content)) ngx_exit(200) end function is_in_table(value, t) return (t[value] == true) end local function get_client_ip(remote_ip, ip_from_header) local client_ip = remote_ip if not (ip_from_header == "") and ip_from_header then if type(ip_from_header) == "table" then client_ip = ip_from_header[1] else local m, err = re_match(ip_from_header, "(\\d+\\.){3}\\d+") if m then client_ip = m[0] end end end return client_ip end -- post请求 local function http_post(uri, body) local httpc = http.new() httpc:set_timeout(5000) local res, err = httpc:request_uri(uri, { method = "POST", body = body }) return res, err end -- get请求 local function http_get(uri) local httpc = http.new() httpc:set_timeout(5000) local res, err = httpc:request_uri(uri, { method = "GET", }) return res, err end local function mark_config_reload() local worker_count = ngx.worker.count() for i=0, worker_count -1 do dict:set("reload"..i, true) end end local function save_worker_pid() local worker_pid = ngx.worker.pid() local worker_id = ngx.worker.id() dict:set(worker_id,worker_pid) end local function count_cpu_usage(premature) -- 首次获取cpu时间 local worker_cpu_total1 = 0 local cpu_total1 = 0 local worker_count = ngx.worker.count() for i=0, worker_count - 1 do local worker_pid = dict:get(i) local fp = io_open("/proc/"..worker_pid.."/stat","r") if not fp then log(ERR,"failed to open /proc/"..worker_pid.."/stat") return end local data = fp:read("*all") fp:close() local res, err = ngx.re.match(data, "(.*? ){13}(.*?) (.*?) ", "jio") worker_cpu = res[2] + res[3] worker_cpu_total1 = worker_cpu_total1 + worker_cpu end local fp = io_open("/proc/stat","r") local cpu_line = fp:read() fp:close() local iterator, err = ngx.re.gmatch(cpu_line,"(\\d+)") while true do local m, err = iterator() if not m then break end cpu_total1 = cpu_total1 + m[0] end -- 第二次获取cpu时间 ngx.sleep(0.5) local worker_cpu_total2 = 0 local cpu_total2 = 0 for i=0, worker_count -1 do local worker_pid = dict:get(i) local fp = io_open("/proc/"..worker_pid.."/stat","r") local data = fp:read("*all") fp:close() local res, err = ngx.re.match(data, "(.*? ){13}(.*?) (.*?) ", "jio") worker_cpu = res[2] + res[3] worker_cpu_total2 = worker_cpu_total2 + worker_cpu end local fp = io_open("/proc/stat","r") local cpu_line = fp:read() fp:close() local iterator, err = ngx.re.gmatch(cpu_line,"(\\d+)") while true do local m, err = iterator() if not m then break end cpu_total2 = cpu_total2 + m[0] end -- 获取cpu核心数 local cpu_core = 0 local fp = io_open("/proc/cpuinfo") local data = fp:read("*all") fp:close() local iterator, err = ngx.re.gmatch(data, "processor","jio") while true do local m, err = iterator() if not m then break end cpu_core = cpu_core + 1 end -- 计算出cpu时间 local nginx_workers_cpu_time = ((worker_cpu_total2 - worker_cpu_total1) / (cpu_total2 - cpu_total1)) * 100*cpu_core nginx_workers_cpu_time = string.format("%d", nginx_workers_cpu_time) dict:set("nginx_workers_cpu_time",nginx_workers_cpu_time) end -- 定时统计nginx worker cpu使用率 local function count_cpu_usage_timed_job() -- 定义间隔执行时间 local delay = 2 local count count = function(premature) if not premature then local ok, err = pcall(count_cpu_usage, premature) if not ok then log(ERR, "count cpu usage error:",err) end local ok, err = ngx_timer_at(delay, count) if not ok then return end end end local ok, err = ngx_timer_at(delay, count) if not ok then return end end local function reload_config(premature) -- 重载配置 local worker_id = ngx_worker_id() if dict:get("reload"..worker_id) then local config_path = lua_root_path .. "/conf/config.json" local fp = io.open(config_path, "r") if fp == nil then log(ERR, "open config file failed") return false, "open config file failed" end local data = fp:read("*all") fp:close() local config_from_file = json.decode(data) if not config_from_file then log(ERR, "json decode config file failed.") return false, "json decode config file failed." end for k, v in pairs(config_from_file) do config[k] = v end config.other.white_ip_list = config_util.load_ip_from_string(config.whitelist) config.other.black_ip_list = config_util.load_ip_from_string(config.blacklist) if config.pkey ~= "" then config.other.pkey = config.pkey end config_util.add_internal_rule(config) log(ERR,"reload config") dict:delete("reload"..worker_id) end end local function reload_config_timed_job() -- 定义间隔执行时间 local delay = 2 local count count = function(premature) if not premature then local ok, err = pcall(reload_config, premature) if not ok then log(ERR, "reload_config error:",err) end local ok, err = ngx_timer_at(delay, count) if not ok then return end end end local ok, err = ngx_timer_at(delay, count) if not ok then return end end local function get_host_list() res, err = http_get("http://127.0.0.1:5000/v1/get-host-list") if err then return nil,err end res = json.decode(res.body) msg = res["msg"] return msg end local function host_qps(host) local now = ngx_time() local now10 = now - (now % 10) local last_1minutes = now10 - 60 local sum = 0 local valid_times = 0 for i=now10,last_1minutes,-10 do local key = table_concat({host,i,"req"}) local req = log_dict:get(key) if req then sum = sum + req valid_times = valid_times + 1 end end if valid_times == 0 then return 0 end return tonumber(string.format("%.1f", sum/(valid_times*10))) end local function auto_enable_cc(premature) local auto_cc_rule = config.auto_cc_rule if auto_cc_rule == nil then return end for host,_ in pairs(auto_cc_rule) do local qps = host_qps(host) local auto_rule_key = host .. "-auto_rule" local trigger_times_key = host .. "-times" local switch_cond = auto_cc_rule[host]["switch_cond"] local restore_cond = auto_cc_rule[host]["restore_cond"] local rule = auto_cc_rule[host]["rule"] -- 切换的状态 if dict:get(auto_rule_key) then -- 在切换的状态下,如果继续超过切换值,那计数器清零 if qps > tonumber(switch_cond) then dict:set(trigger_times_key,0) end -- 在切换的状态下,如果小于恢复值,那开始计算,超过30次才恢复 if qps < tonumber(restore_cond) then local trigger_times = dict:incr(trigger_times_key, 1) or 1 if trigger_times == 1 then dict:set(trigger_times_key, 1) end -- 连续30次低于恢复值,恢复默认规则 if trigger_times >= 30 then log(ERR, "host:",host, " qps:",qps," disabled cc.") dict:delete(auto_rule_key) dict:set(trigger_times_key,0) end end -- 正常状态 else -- 如果超过,立即开启 if qps > tonumber(switch_cond) then log(ERR, "host:",host, " qps:",qps," enable cc.") dict:set(auto_rule_key,rule) end end end end local function auto_enable_cc_time_job() -- 定义间隔执行时间 local delay = 10 local count count = function(premature) if not premature then local ok, err = pcall(auto_enable_cc, premature) if not ok then log(ERR, "auto_enable_cc error:",err) end local ok, err = ngx_timer_at(delay, count) if not ok then return end end end local ok, err = ngx_timer_at(delay, count) if not ok then return end end local function spider_check(premature) local ip_siteid while true do ip_siteid = dict:rpop("spider-to-be-check") if not ip_siteid then break end local m,err = re_match(ip_siteid,"(.*)-(.*)") local ip = m[1] local site_id = m[2] log(ERR, "spider_check ip:",ip) local r, err = resolver:new{ nameservers = {"119.29.29.29", {"114.114.114.114", 53} }, retrans = 5, -- 5 retransmissions on receive timeout timeout = 2000, -- 2 sec } local answers, err = r:reverse_query(ip) if answers then local spider_key = table.concat({ip,"spider"}) dict:delete(spider_key) local ptr = answers[1] and answers[1].ptrdname or "" for _,v in pairs(config.allow_spider) do if string_find(ptr, v.domain, 0, "plain") then -- 白名单 local white_key = table_concat({site_id,"-",ip, "white"}) dict:set(white_key, true) goto continue end end -- 黑名单 for filter_name,_ in pairs(config.filter) do local black_key = table_concat({site_id,"-",ip,"-",filter_name,"black"}) dict:set(black_key, true) end end ::continue:: end end local function spider_check_timed_job() -- 定义间隔执行时间 local delay = 5 local count count = function(premature) if not premature then local ok, err = pcall(spider_check, premature) if not ok then log(ERR, "spider_check error:",err) end local ok, err = ngx_timer_at(delay, count) if not ok then return end end end local ok, err = ngx_timer_at(delay, count) if not ok then return end end local function block_ip(premature) local max_export = 5000 local ip local ip_table = {} for i=1, max_export do ip = dict:rpop("pending-to-iptables") if not ip then break end local pending_key = table.concat({ip,"pending"}) local lock, err = resty_lock:new("guard") local lock_key = table.concat({ip,"lock"}) local elapsed, err = lock:lock(lock_key) dict:delete(pending_key) local ok, err = lock:unlock() table_insert(ip_table, ip) end local ip_list = table_concat(ip_table, " ") if (ip_list == "") then return end local res, err = http_post("http://127.0.0.1:5000/v1/block-ip",ip_list) if err then log(ERR,"post /v1/block-ip err:",err) end end local function block_ip_timed_job() -- 定义间隔执行时间 local delay = 2 local count count = function(premature) if not premature then local ok, err = pcall(block_ip, premature) if not ok then log(ERR, "block_ip error:",err) end local ok, err = ngx_timer_at(delay, count) if not ok then return end end end local ok, err = ngx_timer_at(delay, count) if not ok then return end end -- 定时任务 local function do_timed_job() local worker_id = ngx_worker_id() if worker_id == 0 then count_cpu_usage_timed_job() auto_enable_cc_time_job() block_ip_timed_job() end reload_config_timed_job() spider_check_timed_job() end -- 打乱table local function shuffleTable( t ) local rand = math.random assert( t, "shuffleTable() expected a table, got nil" ) local iterations = #t local j for i = iterations, 2, -1 do j = rand(i) t[i], t[j] = t[j], t[i] end end -- 加载验证码 local function load_captcha() local captcha_dir = config.captcha_dir local dict_captcha = ngx.shared.dict_captcha local file = io_open(captcha_dir, "r") if file == nil then log(ERR, "can not open 1",captcha_dir) return end local i = 0 log(ngx.DEBUG,"start loading captcha...") local captcha_t = {} for path in io.popen('ls -a '..captcha_dir..'/*.png'):lines() do local captcha = string.gsub(path,".*/(.*)%.png","%1") table.insert(captcha_t, captcha) end math.randomseed( os.time() ) shuffleTable(captcha_t) for i, captcha in ipairs(captcha_t) do local path = captcha_dir .. '/' .. captcha .. '.png' local fp = io_open(path,"rb") if fp == nil then log(ERR, "can not open 2",path) return else local img = fp:read("*all") captcha = string.lower(captcha) dict_captcha:set(i,captcha) dict_captcha:set(captcha,img) end end log(ngx.DEBUG,"loading captcha done.") end return { echo_html = echo_html, echo_json = echo_json, is_in_table = is_in_table, get_client_ip = get_client_ip, http_post = http_post, http_get = http_get, check_local_auth = check_local_auth, check_auth = check_auth, check_auth_timed_job = check_auth_timed_job, do_timed_job = do_timed_job, load_captcha = load_captcha, save_worker_pid = save_worker_pid, mark_config_reload = mark_config_reload, echo_html_gz = echo_html_gz, get_host_list = get_host_list }