【APISIX源码探究】初始化

apisix.lua

这里开始是APISIX的真正初始化过程:

...
# 加载基础环境信息
local env = require("apisix.cli.env")(apisix_home, pkg_cpath_org, pkg_path_org)

# 控制台命令解析执行
local ops = require("apisix.cli.ops")
ops.execute(env, arg)
复制代码

apisix.cli.env

这个文件很简单,就是初始化一些环境信息

  • apisix_home : apisix源码根目录
  • is_root_path: 源码是否在/root下
  • openresty_args: 这个比较有意思,通过拼接得到一串命令字符串 0 /usr/local/openresty/bin/openresty -p /usr/local/apisix -c /usr/local/apisix/conf/nginx.conf,APISIX最后就通过这个命令来执行openresty
  • pkg_cpath_org: lua模块查找路径
  • pkg_path_org: lua模块查找路径
  • min_etcd_version: etcd最小版本
  • ulimit: 可打开文件句柄数

apisix.cli.ops

这里就是解析命令行参数来执行具体任务代码,下面简要分析几关键命令

init

该函数主要用来根据环境和配置输出nginx.conf,作为openresty启动配置。

...
# 加载APISIX配置
local local_conf_path = profile:yaml_path("config-default")
...
# 端口监听检查&其他配置
...
# 渲染nginx配置模板
local conf_render = template.compile(ngx_tpl)
local ngxconf = conf_render(sys_conf)
local ok, err = util.write_file(env.apisix_home .. "/conf/nginx.conf", ngxconf)
复制代码

init_etcd

APISIX可选使用etcd或本地yaml文件来存放路由信息等配置,在选用etcd时就会调用改函数进行初始化。

  • 首先根据配置检查etcd集群的版本及健康状态
  • 如果有配置用户名密码,则去登录获取token
  • 在etcd上创建配置

start

该函数初始化后直接启动openresty

...
init(env)
init_etcd(env, args)
util.execute_cmd(env.openresty_args)
复制代码

reload

  • 重新初始化nginx.conf
  • 调用openresty -t测试nginx.conf是否正常
  • 调用openresty -s reload重启
local function reload(env)
    init(env)
    local test_cmd = env.openresty_args .. [[ -t -q ]]
    local test_ret = execute((test_cmd))
    if (test_ret == 0 or test_ret == true) then
        local cmd = env.openresty_args .. [[ -s reload]]
        execute(cmd)
        return
    end
end
复制代码

总结

到这里我们就基本弄清楚APISIX的启动方式了,核心是根据APISIX配置生成nginx.conf,接着直接运行openresty,初始化结束,后续APISIX将会接管openresty的各种生命周期。

分类:
后端