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