Skip to content

Commit

Permalink
fix to really execute plugins in order (#8018)
Browse files Browse the repository at this point in the history
  • Loading branch information
anaclaudiar authored Dec 7, 2021
1 parent 3f9d443 commit 6163231
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
14 changes: 8 additions & 6 deletions rootfs/etc/nginx/lua/plugins.lua
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
local require = require
local ngx = ngx
local pairs = pairs
local ipairs = ipairs
local string_format = string.format
local ngx_log = ngx.log
Expand All @@ -20,8 +19,11 @@ local function load_plugin(name)
ngx_log(ERR, string_format("error loading plugin \"%s\": %s", path, plugin))
return
end

plugins[name] = plugin
local index = #plugins
if (plugin.name == nil or plugin.name == '') then
plugin.name = name
end
plugins[index + 1] = plugin
end

function _M.init(names)
Expand All @@ -39,9 +41,9 @@ end
function _M.run()
local phase = ngx.get_phase()

for name, plugin in pairs(plugins) do
for _, plugin in ipairs(plugins) do
if plugin[phase] then
ngx_log(INFO, string_format("running plugin \"%s\" in phase \"%s\"", name, phase))
ngx_log(INFO, string_format("running plugin \"%s\" in phase \"%s\"", plugin.name, phase))

-- TODO: consider sandboxing this, should we?
-- probably yes, at least prohibit plugin from accessing env vars etc
Expand All @@ -50,7 +52,7 @@ function _M.run()
local ok, err = pcall(plugin[phase])
if not ok then
ngx_log(ERR, string_format("error while running plugin \"%s\" in phase \"%s\": %s",
name, phase, err))
plugin.name, phase, err))
end
end
end
Expand Down
23 changes: 23 additions & 0 deletions rootfs/etc/nginx/lua/test/plugins_test.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
describe("plugins", function()
describe("#run", function()
it("runs the plugins in the given order", function()
ngx.get_phase = function() return "rewrite" end
local plugins = require("plugins")
local called_plugins = {}
local plugins_to_mock = {"plugins.pluginfirst.main", "plugins.pluginsecond.main", "plugins.pluginthird.main"}
for i=1, 3, 1
do
package.loaded[plugins_to_mock[i]] = {
rewrite = function()
called_plugins[#called_plugins + 1] = plugins_to_mock[i]
end
}
end
assert.has_no.errors(function()
plugins.init({"pluginfirst", "pluginsecond", "pluginthird"})
end)
assert.has_no.errors(plugins.run)
assert.are.same(plugins_to_mock, called_plugins)
end)
end)
end)

0 comments on commit 6163231

Please sign in to comment.