2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local plugin_dir = CFG_PLUGINDIR or "./plugins/";
11 local logger = require "util.logger";
12 local log = logger.init("modulemanager");
13 local config = require "core.configmanager";
14 local multitable_new = require "util.multitable".new;
15 local st = require "util.stanza";
16 local pluginloader = require "util.pluginloader";
19 local prosody = prosody;
20 local prosody_events = prosody.events;
22 local loadfile, pcall, xpcall = loadfile, pcall, xpcall;
23 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
24 local pairs, ipairs = pairs, ipairs;
25 local t_insert, t_concat = table.insert, table.concat;
28 local rawget = rawget;
30 local tostring, tonumber = tostring, tonumber;
32 local debug_traceback = debug.traceback;
33 local unpack, select = unpack, select;
34 pcall = function(f, ...)
35 local n = select("#", ...);
37 return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
40 local array, set = require "util.array", require "util.set";
42 local autoload_modules = {"presence", "message", "iq"};
44 -- We need this to let modules access the real global namespace
47 module "modulemanager"
50 local api = api; -- Module API container
52 local modulemap = { ["*"] = {} };
54 local modulehelpers = setmetatable({}, { __index = _G });
56 local hooks = multitable_new();
60 -- Load modules when a host is activated
61 function load_modules_for_host(host)
62 local disabled_set = {};
63 local modules_disabled = config.get(host, "core", "modules_disabled");
64 if modules_disabled then
65 for _, module in ipairs(modules_disabled) do
66 disabled_set[module] = true;
70 -- Load auto-loaded modules for this host
71 if hosts[host].type == "local" then
72 for _, module in ipairs(autoload_modules) do
73 if not disabled_set[module] then
79 -- Load modules from global section
80 if config.get(host, "core", "load_global_modules") ~= false then
81 local modules_enabled = config.get("*", "core", "modules_enabled");
82 if modules_enabled then
83 for _, module in ipairs(modules_enabled) do
84 if not disabled_set[module] and not is_loaded(host, module) then
91 -- Load modules from just this host
92 local modules_enabled = config.get(host, "core", "modules_enabled");
93 if modules_enabled and modules_enabled ~= config.get("*", "core", "modules_enabled") then
94 for _, module in pairs(modules_enabled) do
95 if not is_loaded(host, module) then
101 prosody_events.add_handler("host-activated", load_modules_for_host);
102 prosody_events.add_handler("component-activated", load_modules_for_host);
105 function load(host, module_name, config)
106 if not (host and module_name) then
107 return nil, "insufficient-parameters";
110 if not modulemap[host] then
111 modulemap[host] = {};
114 if modulemap[host][module_name] then
115 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
116 return nil, "module-already-loaded";
117 elseif modulemap["*"][module_name] then
118 return nil, "global-module-already-loaded";
122 local mod, err = pluginloader.load_code(module_name);
124 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
128 local _log = logger.init(host..":"..module_name);
129 local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
131 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
132 api_instance.environment = pluginenv;
134 setfenv(mod, pluginenv);
135 if not hosts[host] then
136 local create_component = _G.require "core.componentmanager".create_component;
137 hosts[host] = create_component(host);
138 log("debug", "Created new component: %s", host);
140 hosts[host].modules = modulemap[host];
141 modulemap[host][module_name] = pluginenv;
143 local success, err = pcall(mod);
145 if module_has_method(pluginenv, "load") then
146 success, err = call_module_method(pluginenv, "load");
148 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
152 -- Use modified host, if the module set one
153 if api_instance.host == "*" and host ~= "*" then
154 modulemap[host][module_name] = nil;
155 modulemap["*"][module_name] = pluginenv;
156 api_instance:set_global();
159 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
162 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host });
164 else -- load failed, unloading
165 unload(api_instance.host, module_name);
170 function get_module(host, name)
171 return modulemap[host] and modulemap[host][name];
174 function is_loaded(host, name)
175 return modulemap[host] and modulemap[host][name] and true;
178 function unload(host, name, ...)
179 local mod = get_module(host, name);
180 if not mod then return nil, "module-not-loaded"; end
182 if module_has_method(mod, "unload") then
183 local ok, err = call_module_method(mod, "unload");
184 if (not ok) and err then
185 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
188 -- unhook event handlers hooked by module:hook
189 for event, handlers in pairs(hooks:get(host, name) or NULL) do
190 for handler in pairs(handlers or NULL) do
191 (hosts[host] or prosody).events.remove_handler(event, handler);
194 hooks:remove(host, name);
195 if mod.module.items then -- remove items
196 for key,t in pairs(mod.module.items) do
200 hosts[host].events.fire_event("item-removed/"..key, {source = self, item = value});
204 modulemap[host][name] = nil;
205 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
209 function reload(host, name, ...)
210 local mod = get_module(host, name);
211 if not mod then return nil, "module-not-loaded"; end
213 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
215 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
221 if module_has_method(mod, "save") then
222 local ok, ret, err = call_module_method(mod, "save");
226 log("warn", "Error saving module '%s:%s' state: %s", host, module, ret);
227 if not config.get(host, "core", "force_module_reload") then
228 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
229 return nil, "save-state-failed";
231 log("warn", "Continuing with reload (using the force)");
236 unload(host, name, ...);
237 local ok, err = load(host, name, ...);
239 mod = get_module(host, name);
240 if module_has_method(mod, "restore") then
241 local ok, err = call_module_method(mod, "restore", saved or {})
242 if (not ok) and err then
243 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
251 function module_has_method(module, method)
252 return type(module.module[method]) == "function";
255 function call_module_method(module, method, ...)
256 if module_has_method(module, method) then
257 local f = module.module[method];
258 return pcall(f, ...);
260 return false, "no-such-method";
264 ----- API functions exposed to modules -----------
265 -- Must all be in api.*
267 -- Returns the name of the current module
268 function api:get_name()
272 -- Returns the host that the current module is serving
273 function api:get_host()
277 function api:get_host_type()
278 return hosts[self.host].type;
281 function api:set_global()
284 local _log = logger.init("mod_"..self.name);
285 self.log = function (self, ...) return _log(...); end;
289 function api:add_feature(xmlns)
290 self:add_item("feature", xmlns);
292 function api:add_identity(category, type, name)
293 self:add_item("identity", {category = category, type = type, name = name});
296 function api:fire_event(...)
297 return (hosts[self.host] or prosody).events.fire_event(...);
300 function api:hook(event, handler, priority)
301 hooks:set(self.host, self.name, event, handler, true);
302 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
305 function api:hook_stanza(xmlns, name, handler, priority)
306 if not handler and type(name) == "function" then
307 -- If only 2 options then they specified no xmlns
308 xmlns, name, handler, priority = nil, xmlns, name, handler;
309 elseif not (handler and name) then
310 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
313 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
316 function api:require(lib)
317 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
319 f, n = pluginloader.load_code(lib, lib..".lib.lua");
321 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
322 setfenv(f, self.environment);
326 function api:get_option(name, default_value)
327 local value = config.get(self.host, self.name, name);
329 value = config.get(self.host, "core", name);
331 value = default_value;
337 function api:get_option_string(name, default_value)
338 local value = self:get_option(name, default_value);
339 if type(value) == "table" then
341 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
348 return tostring(value);
351 function api:get_option_number(name, ...)
352 local value = self:get_option(name, ...);
353 if type(value) == "table" then
355 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
359 local ret = tonumber(value);
360 if value ~= nil and ret == nil then
361 self:log("error", "Config option '%s' not understood, expecting a number", name);
366 function api:get_option_boolean(name, ...)
367 local value = self:get_option(name, ...);
368 if type(value) == "table" then
370 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
377 local ret = value == true or value == "true" or value == 1 or nil;
379 ret = (value == false or value == "false" or value == 0);
387 self:log("error", "Config option '%s' not understood, expecting true/false", name);
392 function api:get_option_array(name, ...)
393 local value = self:get_option(name, ...);
399 if type(value) ~= "table" then
400 return array{ value }; -- Assume any non-list is a single-item list
403 return array():append(value); -- Clone
406 function api:get_option_set(name, ...)
407 local value = self:get_option_array(name, ...);
413 return set.new(value);
416 local t_remove = _G.table.remove;
417 local module_items = multitable_new();
418 function api:add_item(key, value)
419 self.items = self.items or {};
420 self.items[key] = self.items[key] or {};
421 t_insert(self.items[key], value);
422 self:fire_event("item-added/"..key, {source = self, item = value});
424 function api:remove_item(key, value)
425 local t = self.items and self.items[key] or NULL;
427 if t[i] == value then
428 t_remove(self.items[key], i);
429 self:fire_event("item-removed/"..key, {source = self, item = value});
435 function api:get_host_items(key)
437 for mod_name, module in pairs(modulemap[self.host]) do
438 module = module.module;
440 for _, item in ipairs(module.items[key] or NULL) do
441 t_insert(result, item);
445 for mod_name, module in pairs(modulemap["*"]) do
446 module = module.module;
448 for _, item in ipairs(module.items[key] or NULL) do
449 t_insert(result, item);