function Kong.init()

in kong/kong/init.lua [500:602]


function Kong.init()
  local pl_path = require "pl.path"
  local conf_loader = require "kong.conf_loader"

  
  if not kong.version then
    error("configuration error: make sure your template is not setting a " ..
          "global named 'kong' (please use 'Kong' instead)")
  end

  
  local conf_path = pl_path.join(ngx.config.prefix(), ".kong_env")
  local config = assert(conf_loader(conf_path, nil, { from_kong_env = true }))

  reset_kong_shm(config)

  
  
  
  math.randomseed()

  kong_global.init_pdk(kong, config)
  instrumentation.init(config)

  local db = assert(DB.new(config))
  instrumentation.db_query(db.connector)
  assert(db:init_connector())

  schema_state = assert(db:schema_state())
  migrations_utils.check_state(schema_state)

  if schema_state.missing_migrations or schema_state.pending_migrations then
    if schema_state.missing_migrations then
      ngx_log(ngx_WARN, "database is missing some migrations:\n",
                        schema_state.missing_migrations)
    end

    if schema_state.pending_migrations then
      ngx_log(ngx_WARN, "database has pending migrations:\n",
                        schema_state.pending_migrations)
    end
  end

  assert(db:connect())

  kong.db = db
  kong.dns = dns(config)

  if config.proxy_ssl_enabled or config.stream_ssl_enabled then
    certificate.init()
  end

  if is_http_module and (config.role == "data_plane" or config.role == "control_plane")
  then
    kong.clustering = require("kong.clustering").new(config)
  end

  assert(db.vaults:load_vault_schemas(config.loaded_vaults))

  
  assert(db.plugins:load_plugin_schemas(config.loaded_plugins))

  if is_stream_module then
    stream_api.load_handlers()
  end

  if config.database == "off" then
    if is_http_module or
       (#config.proxy_listeners == 0 and
        #config.admin_listeners == 0 and
        #config.status_listeners == 0)
    then
      local err
      declarative_entities, err, declarative_meta = parse_declarative_config(kong.configuration)
      if not declarative_entities then
        error(err)
      end
    end

  else
    local default_ws = db.workspaces:select_by_name("default")
    kong.default_workspace = default_ws and default_ws.id

    local ok, err = runloop.build_plugins_iterator("init")
    if not ok then
      error("error building initial plugins: " .. tostring(err))
    end

    if config.role ~= "control_plane" then
      assert(runloop.build_router("init"))

      ok, err = runloop.set_init_versions_in_cache()
      if not ok then
        error("error setting initial versions for router and plugins iterator in cache: " ..
              tostring(err))
      end
    end
  end

  db:close()

  require("resty.kong.var").patch_metatable()
end