rostermanager: Use storagemanager
[prosody.git] / core / modulemanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local logger = require "util.logger";
10 local log = logger.init("modulemanager");
11 local config = require "core.configmanager";
12 local pluginloader = require "util.pluginloader";
13 local set = require "util.set";
14
15 local new_multitable = require "util.multitable".new;
16 local api = require "core.moduleapi"; -- Module API container
17
18 local hosts = hosts;
19 local prosody = prosody;
20
21 local xpcall = xpcall;
22 local setmetatable, rawget = setmetatable, rawget;
23 local ipairs, pairs, type, tostring, t_insert = ipairs, pairs, type, tostring, table.insert;
24
25 local debug_traceback = debug.traceback;
26 local unpack, select = unpack, select;
27 local pcall = function(f, ...)
28         local n = select("#", ...);
29         local params = {...};
30         return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
31 end
32
33 local autoload_modules = {prosody.platform, "presence", "message", "iq", "offline", "c2s", "s2s", "s2s_auth_certs"};
34 local component_inheritable_modules = {"tls", "saslauth", "dialback", "iq", "s2s"};
35
36 -- We need this to let modules access the real global namespace
37 local _G = _G;
38
39 local _ENV = nil;
40
41 local load_modules_for_host, load, unload, reload, get_module, get_items, get_modules, is_loaded, module_has_method, call_module_method;
42
43 -- [host] = { [module] = module_env }
44 local modulemap = { ["*"] = {} };
45
46 -- Load modules when a host is activated
47 function load_modules_for_host(host)
48         local component = config.get(host, "component_module");
49
50         local global_modules_enabled = config.get("*", "modules_enabled");
51         local global_modules_disabled = config.get("*", "modules_disabled");
52         local host_modules_enabled = config.get(host, "modules_enabled");
53         local host_modules_disabled = config.get(host, "modules_disabled");
54
55         if host_modules_enabled == global_modules_enabled then host_modules_enabled = nil; end
56         if host_modules_disabled == global_modules_disabled then host_modules_disabled = nil; end
57
58         local global_modules = set.new(autoload_modules) + set.new(global_modules_enabled) - set.new(global_modules_disabled);
59         if component then
60                 global_modules = set.intersection(set.new(component_inheritable_modules), global_modules);
61         end
62         local modules = (global_modules + set.new(host_modules_enabled)) - set.new(host_modules_disabled);
63
64         -- COMPAT w/ pre 0.8
65         if modules:contains("console") then
66                 log("error", "The mod_console plugin has been renamed to mod_admin_telnet. Please update your config.");
67                 modules:remove("console");
68                 modules:add("admin_telnet");
69         end
70
71         if component then
72                 load(host, component);
73         end
74         for module in modules do
75                 load(host, module);
76         end
77 end
78 prosody.events.add_handler("host-activated", load_modules_for_host);
79 prosody.events.add_handler("host-deactivated", function (host)
80         modulemap[host] = nil;
81 end);
82
83 --- Private helpers ---
84
85 local function do_unload_module(host, name)
86         local mod = get_module(host, name);
87         if not mod then return nil, "module-not-loaded"; end
88
89         if module_has_method(mod, "unload") then
90                 local ok, err = call_module_method(mod, "unload");
91                 if (not ok) and err then
92                         log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
93                 end
94         end
95
96         for object, event, handler in mod.module.event_handlers:iter(nil, nil, nil) do
97                 object.remove_handler(event, handler);
98         end
99
100         if mod.module.items then -- remove items
101                 local events = (host == "*" and prosody.events) or hosts[host].events;
102                 for key,t in pairs(mod.module.items) do
103                         for i = #t,1,-1 do
104                                 local value = t[i];
105                                 t[i] = nil;
106                                 events.fire_event("item-removed/"..key, {source = mod.module, item = value});
107                         end
108                 end
109         end
110         mod.module.loaded = false;
111         modulemap[host][name] = nil;
112         return true;
113 end
114
115 local function do_load_module(host, module_name, state)
116         if not (host and module_name) then
117                 return nil, "insufficient-parameters";
118         elseif not hosts[host] and host ~= "*"then
119                 return nil, "unknown-host";
120         end
121
122         if not modulemap[host] then
123                 modulemap[host] = hosts[host].modules;
124         end
125
126         if modulemap[host][module_name] then
127                 log("debug", "%s is already loaded for %s, so not loading again", module_name, host);
128                 return nil, "module-already-loaded";
129         elseif modulemap["*"][module_name] then
130                 local mod = modulemap["*"][module_name];
131                 if module_has_method(mod, "add_host") then
132                         local _log = logger.init(host..":"..module_name);
133                         local host_module_api = setmetatable({
134                                 host = host, event_handlers = new_multitable(), items = {};
135                                 _log = _log, log = function (self, ...) return _log(...); end; --luacheck: ignore 212/self
136                         },{
137                                 __index = modulemap["*"][module_name].module;
138                         });
139                         local host_module = setmetatable({ module = host_module_api }, { __index = mod });
140                         host_module_api.environment = host_module;
141                         modulemap[host][module_name] = host_module;
142                         local ok, result, module_err = call_module_method(mod, "add_host", host_module_api);
143                         if not ok or result == false then
144                                 modulemap[host][module_name] = nil;
145                                 return nil, ok and module_err or result;
146                         end
147                         return host_module;
148                 end
149                 return nil, "global-module-already-loaded";
150         end
151
152
153
154         local _log = logger.init(host..":"..module_name);
155         local api_instance = setmetatable({ name = module_name, host = host,
156                 _log = _log, log = function (self, ...) return _log(...); end, --luacheck: ignore 212/self
157                 event_handlers = new_multitable(), reloading = not not state,
158                 saved_state = state~=true and state or nil }
159                 , { __index = api });
160
161         local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
162         api_instance.environment = pluginenv;
163
164         local mod, err = pluginloader.load_code(module_name, nil, pluginenv);
165         if not mod then
166                 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
167                 return nil, err;
168         end
169
170         api_instance.path = err;
171
172         modulemap[host][module_name] = pluginenv;
173         local ok, err = pcall(mod);
174         if ok then
175                 -- Call module's "load"
176                 if module_has_method(pluginenv, "load") then
177                         ok, err = call_module_method(pluginenv, "load");
178                         if not ok then
179                                 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
180                         end
181                 end
182                 api_instance.reloading, api_instance.saved_state = nil, nil;
183
184                 if api_instance.host == "*" then
185                         if not api_instance.global then -- COMPAT w/pre-0.9
186                                 if host ~= "*" then
187                                         log("warn", "mod_%s: Setting module.host = '*' deprecated, call module:set_global() instead", module_name);
188                                 end
189                                 api_instance:set_global();
190                         end
191                         modulemap[host][module_name] = nil;
192                         modulemap[api_instance.host][module_name] = pluginenv;
193                         if host ~= api_instance.host and module_has_method(pluginenv, "add_host") then
194                                 -- Now load the module again onto the host it was originally being loaded on
195                                 ok, err = do_load_module(host, module_name);
196                         end
197                 end
198         end
199         if not ok then
200                 modulemap[api_instance.host][module_name] = nil;
201                 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
202         end
203         return ok and pluginenv, err;
204 end
205
206 local function do_reload_module(host, name)
207         local mod = get_module(host, name);
208         if not mod then return nil, "module-not-loaded"; end
209
210         local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
211         if not _mod then
212                 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
213                 return nil, err;
214         end
215
216         local saved;
217         if module_has_method(mod, "save") then
218                 local ok, ret, err = call_module_method(mod, "save");
219                 if ok then
220                         saved = ret;
221                 else
222                         log("warn", "Error saving module '%s:%s' state: %s", host, name, ret);
223                         if not config.get(host, "force_module_reload") then
224                                 log("warn", "Aborting reload due to error, set force_module_reload to ignore this");
225                                 return nil, "save-state-failed";
226                         else
227                                 log("warn", "Continuing with reload (using the force)");
228                         end
229                 end
230         end
231
232         mod.module.reloading = true;
233         do_unload_module(host, name);
234         local ok, err = do_load_module(host, name, saved or true);
235         if ok then
236                 mod = get_module(host, name);
237                 if module_has_method(mod, "restore") then
238                         local ok, err = call_module_method(mod, "restore", saved or {})
239                         if (not ok) and err then
240                                 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
241                         end
242                 end
243         end
244         return ok and mod, err;
245 end
246
247 --- Public API ---
248
249 -- Load a module and fire module-loaded event
250 function load(host, name)
251         local mod, err = do_load_module(host, name);
252         if mod then
253                 (hosts[mod.module.host] or prosody).events.fire_event("module-loaded", { module = name, host = mod.module.host });
254         end
255         return mod, err;
256 end
257
258 -- Unload a module and fire module-unloaded
259 function unload(host, name)
260         local ok, err = do_unload_module(host, name);
261         if ok then
262                 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
263         end
264         return ok, err;
265 end
266
267 function reload(host, name)
268         local mod, err = do_reload_module(host, name);
269         if mod then
270                 modulemap[host][name].module.reloading = true;
271                 (hosts[host] or prosody).events.fire_event("module-reloaded", { module = name, host = host });
272                 mod.module.reloading = nil;
273         elseif not is_loaded(host, name) then
274                 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
275         end
276         return mod, err;
277 end
278
279 function get_module(host, name)
280         return modulemap[host] and modulemap[host][name];
281 end
282
283 function get_items(key, host)
284         local result = {};
285         local modules = modulemap[host];
286         if not key or not host or not modules then return nil; end
287
288         for _, module in pairs(modules) do
289                 local mod = module.module;
290                 if mod.items and mod.items[key] then
291                         for _, value in ipairs(mod.items[key]) do
292                                 t_insert(result, value);
293                         end
294                 end
295         end
296
297         return result;
298 end
299
300 function get_modules(host)
301         return modulemap[host];
302 end
303
304 function is_loaded(host, name)
305         return modulemap[host] and modulemap[host][name] and true;
306 end
307
308 function module_has_method(module, method)
309         return type(rawget(module.module, method)) == "function";
310 end
311
312 function call_module_method(module, method, ...)
313         local f = rawget(module.module, method);
314         if type(f) == "function" then
315                 return pcall(f, ...);
316         else
317                 return false, "no-such-method";
318         end
319 end
320
321 return {
322         load_modules_for_host = load_modules_for_host;
323         load = load;
324         unload = unload;
325         reload = reload;
326         get_module = get_module;
327         get_items = get_items;
328         get_modules = get_modules;
329         is_loaded = is_loaded;
330         module_has_method = module_has_method;
331         call_module_method = call_module_method;
332 };