kong:
根據Nginx的不同執行階段,kong先執行初始化master和worker進程。
init_by_lua_block {
require 'resty.core'
kong = require 'kong'
kong.init()
}
安裝完之后加載/usr/local/share/lua/5.1/下面的kong.lua,調用init()方法,加載配置文件,創建事件,建立路由。
singletons.dns = dns(config)
singletons.loaded_plugins = assert(load_plugins(config, dao, events))
singletons.serf = Serf.new(config, dao)
singletons.dao = dao
singletons.events = events
singletons.configuration = config
在數據庫中檢查所有的可用的插件,然后加載插件,插件必須有兩個文件handler.lua和schema.lua。以keyauth插件為例,格式為:kong.plugins.keyauth.handler和kong.plugins.keyauth.schema。
如果存在kong.plugins.keyauth.hooks則注冊相應的事件。
不同的插件有不同的優先級,根據插件PRIORITY大小排序。
init_worker_by_lua_block {
kong.init_worker()
}
初始化worker_events(這里我不懂,根據worker的pid,建立路由和注冊事件)
kong入口server監聽8000端口,還開放一個8001端口提供了restful接口,用於后台查詢api的調用,插件等。
處理中間任務,然后init_worker(),調用后台任務:
local function keepalive_handler(premature)
if premature then
return
end
-- all workers need to register a recurring timer, in case one of them
-- crashes. Hence, this must be called before the `get_lock()` call.
create_timer(KEEPALIVE_INTERVAL, keepalive_handler)
if not get_lock(KEEPALIVE_KEY, KEEPALIVE_INTERVAL) then
return
end
log(DEBUG, "sending keepalive event to datastore")
local nodes, err = singletons.dao.nodes:find_all {
name = singletons.serf.node_name
}
if err then
log(ERR, "could not retrieve nodes from datastore: ", err)
elseif #nodes == 1 then
local node = nodes[1]
local _, err = singletons.dao.nodes:update(node, node, {
ttl = singletons.configuration.cluster_ttl_on_failure,
quiet = true
})
if err then
log(ERR, "could not update node in datastore:", err)
end
end
end
在8000端口中:
access_by_lua_block {
kong.access()
}
before()方法相當於api的一個middleware,檢測路由和http方法,獲取ip端口,域名等。
after()方法返回一些kong的執行時間等。
在access中加載kong.plugins.keyauth.handler.lua的方法中的access方法,調用前后分別調用before()和after()方法。
for plugin, plugin_conf in plugins_iterator(singletons.loaded_plugins, true) do
plugin.handler:access(plugin_conf)
end
遍歷插件列表,存儲在ngx.ctx.plugins_for_request中
header_filter_by_lua_block {
kong.header_filter()
}
body_filter_by_lua_block {
kong.body_filter()
}
log_by_lua_block {
kong.log()
}
