configuration.lua 2.78 KiB
local configuration = {}
local safer = require("safer")
local schema = require("schema")
function configuration.read(filename, sga_name)
   local config_fd = io.open(filename, "r")
   if not config_fd then
      return nil, "Could not read config file "..filename
   end
   local config_data = config_fd:read("*a")
   config_fd:close()
   local config, err = {}
   config.sga = {}
   config, err = configuration.get(config_data, filename, config)
   if not config then
      return nil, err
   end
   local is_multiple = config.sga and next(config.sga)
   if is_multiple then
      if not sga_name then
         return nil, "Failed getting config from file "..filename..": missing sga_name argument"
      end
      if config.sga_name then
         -- TODO: O que fazer nesse caso? Avisar que foi ignorado?
         config.sga_name = nil
      end
      config, err = configuration.get(config.sga[sga_name], filename, config)
      if not config then
         return nil, "["..sga_name.."] "..err
      end
      -- TODO: O que fazer se sga_name tiver diferente na configuração? Erro?
      config.sga_name = config.sga_name or sga_name
   end
   config = safer.readonly(config)
   return config
end
function configuration.get(config_data, filename, config)
   local config = config or {}
   local chunk, err = load(config_data, filename, "t", config)
   if not chunk then
      return nil, "Failed loading config file "..filename..": "..err
   end
   config.os = { getenv = os.getenv }
   config.tonumber = tonumber
   local ok, err = pcall(chunk)
   config.os = nil
   if not ok then
      return nil, "Failed processing config file "..filename..": "..err
   end
   return config
end
function configuration.check(config)
   local config_schema = schema.Record {
      csbase_server = schema.Pattern("https?://.*"),
      platform = schema.String,
      sgad_host = schema.String,
      sgad_port = schema.NumberFrom(1,65535),
      sga_name = schema.Pattern("[A-Za-z0-9_]+"),
      sga_type = schema.Optional(schema.String),
      status_interval_s = schema.PositiveNumber,
      exec_polling_interval_s = schema.PositiveNumber,
7172737475767778798081828384858687888990
driver = schema.Test(function(v) local ok, err = pcall(require, v) if not ok then io.stderr:write("Failed loading driver '"..tostring(v).."': "..err.."\n") end return ok end, "must be a valid module"), driver_config = schema.Optional(schema.Map(schema.String, schema.Any)), resources = schema.Optional(schema.Collection(schema.String)), extra_config = schema.Optional(schema.Map(schema.String, schema.Any)), } local err = schema.CheckSchema(config, config_schema) if err then io.stderr:write("["..config.sga_name.."] Configuration error: "..tostring(err).."\n") os.exit(1) end end return configuration