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