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