comparison core/modulemanager.lua @ 4797:e239668aa6d2

Merge 0.9->trunk
author Matthew Wild <mwild1@gmail.com>
date Sun, 29 Apr 2012 02:10:55 +0100
parents dbe9d75c0452
children 83cedf648b46
comparison
equal deleted inserted replaced
4796:04a34287dc12 4797:e239668aa6d2
7 -- 7 --
8 8
9 local logger = require "util.logger"; 9 local logger = require "util.logger";
10 local log = logger.init("modulemanager"); 10 local log = logger.init("modulemanager");
11 local config = require "core.configmanager"; 11 local config = require "core.configmanager";
12 local multitable_new = require "util.multitable".new;
13 local st = require "util.stanza";
14 local pluginloader = require "util.pluginloader"; 12 local pluginloader = require "util.pluginloader";
15 13
16 local hosts = hosts; 14 local hosts = hosts;
17 local prosody = prosody; 15 local prosody = prosody;
18 local prosody_events = prosody.events; 16
19 17 local pcall, xpcall = pcall, xpcall;
20 local loadfile, pcall, xpcall = loadfile, pcall, xpcall; 18 local setmetatable, rawget, setfenv = setmetatable, rawget, setfenv;
21 local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv; 19 local pairs, type, tostring = pairs, type, tostring;
22 local pairs, ipairs = pairs, ipairs;
23 local t_insert, t_concat = table.insert, table.concat;
24 local type = type;
25 local next = next;
26 local rawget = rawget;
27 local error = error;
28 local tostring, tonumber = tostring, tonumber;
29 20
30 local debug_traceback = debug.traceback; 21 local debug_traceback = debug.traceback;
31 local unpack, select = unpack, select; 22 local unpack, select = unpack, select;
32 pcall = function(f, ...) 23 pcall = function(f, ...)
33 local n = select("#", ...); 24 local n = select("#", ...);
34 local params = {...}; 25 local params = {...};
35 return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end); 26 return xpcall(function() return f(unpack(params, 1, n)) end, function(e) return tostring(e).."\n"..debug_traceback(); end);
36 end 27 end
37 28
38 local array, set = require "util.array", require "util.set"; 29 local set = require "util.set";
39 30
40 local autoload_modules = {"presence", "message", "iq", "offline"}; 31 local autoload_modules = {"presence", "message", "iq", "offline", "c2s", "s2s"};
41 local component_inheritable_modules = {"tls", "dialback", "iq"}; 32 local component_inheritable_modules = {"tls", "dialback", "iq"};
42 33
43 -- We need this to let modules access the real global namespace 34 -- We need this to let modules access the real global namespace
44 local _G = _G; 35 local _G = _G;
45 36
46 module "modulemanager" 37 module "modulemanager"
47 38
48 api = {}; 39 local api = _G.require "core.moduleapi"; -- Module API container
49 local api = api; -- Module API container 40
50 41 -- [host] = { [module] = module_env }
51 local modulemap = { ["*"] = {} }; 42 local modulemap = { ["*"] = {} };
52
53 local modulehelpers = setmetatable({}, { __index = _G });
54
55 local hooks = multitable_new();
56
57 local NULL = {};
58 43
59 -- Load modules when a host is activated 44 -- Load modules when a host is activated
60 function load_modules_for_host(host) 45 function load_modules_for_host(host)
61 local component = config.get(host, "core", "component_module"); 46 local component = config.get(host, "core", "component_module");
62 47
86 end 71 end
87 for module in modules do 72 for module in modules do
88 load(host, module); 73 load(host, module);
89 end 74 end
90 end 75 end
91 prosody_events.add_handler("host-activated", load_modules_for_host); 76 prosody.events.add_handler("host-activated", load_modules_for_host);
92 -- 77 prosody.events.add_handler("host-deactivated", function (host)
93 78 modulemap[host] = nil;
94 function load(host, module_name, config) 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 handler, event in pairs(mod.module.event_handlers) do
95 event.object.remove_handler(event.name, 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)
95 if not (host and module_name) then 114 if not (host and module_name) then
96 return nil, "insufficient-parameters"; 115 return nil, "insufficient-parameters";
97 elseif not hosts[host] then 116 elseif not hosts[host] and host ~= "*"then
98 return nil, "unknown-host"; 117 return nil, "unknown-host";
99 end 118 end
100 119
101 if not modulemap[host] then 120 if not modulemap[host] then
102 modulemap[host] = {}; 121 modulemap[host] = {};
122 if host ~= "*" then
123 hosts[host].modules = modulemap[host];
124 end
103 end 125 end
104 126
105 if modulemap[host][module_name] then 127 if modulemap[host][module_name] then
106 log("warn", "%s is already loaded for %s, so not loading again", module_name, host); 128 log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
107 return nil, "module-already-loaded"; 129 return nil, "module-already-loaded";
108 elseif modulemap["*"][module_name] then 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
109 return nil, "global-module-already-loaded"; 150 return nil, "global-module-already-loaded";
110 end 151 end
111 152
112 153
113 local mod, err = pluginloader.load_code(module_name); 154 local mod, err = pluginloader.load_code(module_name);
115 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil"); 156 log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
116 return nil, err; 157 return nil, err;
117 end 158 end
118 159
119 local _log = logger.init(host..":"..module_name); 160 local _log = logger.init(host..":"..module_name);
120 local api_instance = setmetatable({ name = module_name, host = host, path = err, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api }); 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 });
121 164
122 local pluginenv = setmetatable({ module = api_instance }, { __index = _G }); 165 local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
123 api_instance.environment = pluginenv; 166 api_instance.environment = pluginenv;
124 167
125 setfenv(mod, pluginenv); 168 setfenv(mod, pluginenv);
126 hosts[host].modules = modulemap[host]; 169
127 modulemap[host][module_name] = pluginenv; 170 modulemap[host][module_name] = pluginenv;
128 171 local ok, err = pcall(mod);
129 local success, err = pcall(mod); 172 if ok then
130 if success then 173 -- Call module's "load"
131 if module_has_method(pluginenv, "load") then 174 if module_has_method(pluginenv, "load") then
132 success, err = call_module_method(pluginenv, "load"); 175 ok, err = call_module_method(pluginenv, "load");
133 if not success then 176 if not ok then
134 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil"); 177 log("warn", "Error loading module '%s' on '%s': %s", module_name, host, err or "nil");
135 end 178 end
136 end 179 end
137 180
138 -- Use modified host, if the module set one 181 if api_instance.host == "*" then
139 if api_instance.host == "*" and 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
140 modulemap[host][module_name] = nil; 186 modulemap[host][module_name] = nil;
141 modulemap["*"][module_name] = pluginenv; 187 modulemap[api_instance.host][module_name] = pluginenv;
142 api_instance:set_global(); 188 if host ~= api_instance.host and module_has_method(pluginenv, "add_host") then
143 end 189 -- Now load the module again onto the host it was originally being loaded on
144 else 190 ok, err = do_load_module(host, module_name);
191 end
192 end
193 end
194 if not ok then
195 modulemap[api_instance.host][module_name] = nil;
145 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil"); 196 log("error", "Error initializing module '%s' on '%s': %s", module_name, host, err or "nil");
146 end 197 end
147 if success then 198 return ok and pluginenv, err;
148 (hosts[api_instance.host] or prosody).events.fire_event("module-loaded", { module = module_name, host = host }); 199 end
149 return true; 200
150 else -- load failed, unloading 201 local function do_reload_module(host, name)
151 unload(api_instance.host, module_name);
152 return nil, err;
153 end
154 end
155
156 function get_module(host, name)
157 return modulemap[host] and modulemap[host][name];
158 end
159
160 function is_loaded(host, name)
161 return modulemap[host] and modulemap[host][name] and true;
162 end
163
164 function unload(host, name, ...)
165 local mod = get_module(host, name);
166 if not mod then return nil, "module-not-loaded"; end
167
168 if module_has_method(mod, "unload") then
169 local ok, err = call_module_method(mod, "unload");
170 if (not ok) and err then
171 log("warn", "Non-fatal error unloading module '%s' on '%s': %s", name, host, err);
172 end
173 end
174 -- unhook event handlers hooked by module:hook
175 for event, handlers in pairs(hooks:get(host, name) or NULL) do
176 for handler in pairs(handlers or NULL) do
177 (hosts[host] or prosody).events.remove_handler(event, handler);
178 end
179 end
180 -- unhook event handlers hooked by module:hook_global
181 for event, handlers in pairs(hooks:get("*", name) or NULL) do
182 for handler in pairs(handlers or NULL) do
183 prosody.events.remove_handler(event, handler);
184 end
185 end
186 hooks:remove(host, name);
187 if mod.module.items then -- remove items
188 for key,t in pairs(mod.module.items) do
189 for i = #t,1,-1 do
190 local value = t[i];
191 t[i] = nil;
192 hosts[host].events.fire_event("item-removed/"..key, {source = mod.module, item = value});
193 end
194 end
195 end
196 modulemap[host][name] = nil;
197 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
198 return true;
199 end
200
201 function reload(host, name, ...)
202 local mod = get_module(host, name); 202 local mod = get_module(host, name);
203 if not mod then return nil, "module-not-loaded"; end 203 if not mod then return nil, "module-not-loaded"; end
204 204
205 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors 205 local _mod, err = pluginloader.load_code(name); -- checking for syntax errors
206 if not _mod then 206 if not _mod then
207 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil"); 207 log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
208 return nil, err; 208 return nil, err;
209 end 209 end
210 210
211 local saved; 211 local saved;
212
213 if module_has_method(mod, "save") then 212 if module_has_method(mod, "save") then
214 local ok, ret, err = call_module_method(mod, "save"); 213 local ok, ret, err = call_module_method(mod, "save");
215 if ok then 214 if ok then
216 saved = ret; 215 saved = ret;
217 else 216 else
223 log("warn", "Continuing with reload (using the force)"); 222 log("warn", "Continuing with reload (using the force)");
224 end 223 end
225 end 224 end
226 end 225 end
227 226
228 unload(host, name, ...); 227 do_unload_module(host, name);
229 local ok, err = load(host, name, ...); 228 local ok, err = do_load_module(host, name);
230 if ok then 229 if ok then
231 mod = get_module(host, name); 230 mod = get_module(host, name);
232 if module_has_method(mod, "restore") then 231 if module_has_method(mod, "restore") then
233 local ok, err = call_module_method(mod, "restore", saved or {}) 232 local ok, err = call_module_method(mod, "restore", saved or {})
234 if (not ok) and err then 233 if (not ok) and err then
235 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err); 234 log("warn", "Error restoring module '%s' from '%s': %s", name, host, err);
236 end 235 end
237 end 236 end
238 return true; 237 end
238 return ok and mod, err;
239 end
240
241 --- Public API ---
242
243 -- Load a module and fire module-loaded event
244 function load(host, name)
245 local mod, err = do_load_module(host, name);
246 if mod then
247 (hosts[mod.module.host] or prosody).events.fire_event("module-loaded", { module = name, host = host });
248 end
249 return mod, err;
250 end
251
252 -- Unload a module and fire module-unloaded
253 function unload(host, name)
254 local ok, err = do_unload_module(host, name);
255 if ok then
256 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
239 end 257 end
240 return ok, err; 258 return ok, err;
241 end 259 end
242 260
261 function reload(host, name)
262 local ok, err = do_reload_module(host, name);
263 if ok then
264 (hosts[host] or prosody).events.fire_event("module-reloaded", { module = name, host = host });
265 elseif not is_loaded(host, name) then
266 (hosts[host] or prosody).events.fire_event("module-unloaded", { module = name, host = host });
267 end
268 return ok, err;
269 end
270
271 function get_module(host, name)
272 return modulemap[host] and modulemap[host][name];
273 end
274
275 function get_modules(host)
276 return modulemap[host];
277 end
278
279 function is_loaded(host, name)
280 return modulemap[host] and modulemap[host][name] and true;
281 end
282
243 function module_has_method(module, method) 283 function module_has_method(module, method)
244 return type(module.module[method]) == "function"; 284 return type(rawget(module.module, method)) == "function";
245 end 285 end
246 286
247 function call_module_method(module, method, ...) 287 function call_module_method(module, method, ...)
248 if module_has_method(module, method) then 288 local f = rawget(module.module, method);
249 local f = module.module[method]; 289 if type(f) == "function" then
250 return pcall(f, ...); 290 return pcall(f, ...);
251 else 291 else
252 return false, "no-such-method"; 292 return false, "no-such-method";
253 end 293 end
254 end 294 end
255 295
256 ----- API functions exposed to modules -----------
257 -- Must all be in api.*
258
259 -- Returns the name of the current module
260 function api:get_name()
261 return self.name;
262 end
263
264 -- Returns the host that the current module is serving
265 function api:get_host()
266 return self.host;
267 end
268
269 function api:get_host_type()
270 return hosts[self.host].type;
271 end
272
273 function api:set_global()
274 self.host = "*";
275 -- Update the logger
276 local _log = logger.init("mod_"..self.name);
277 self.log = function (self, ...) return _log(...); end;
278 self._log = _log;
279 end
280
281 function api:add_feature(xmlns)
282 self:add_item("feature", xmlns);
283 end
284 function api:add_identity(category, type, name)
285 self:add_item("identity", {category = category, type = type, name = name});
286 end
287 function api:add_extension(data)
288 self:add_item("extension", data);
289 end
290
291 function api:fire_event(...)
292 return (hosts[self.host] or prosody).events.fire_event(...);
293 end
294
295 function api:hook(event, handler, priority)
296 hooks:set(self.host, self.name, event, handler, true);
297 (hosts[self.host] or prosody).events.add_handler(event, handler, priority);
298 end
299
300 function api:hook_global(event, handler, priority)
301 hooks:set("*", self.name, event, handler, true);
302 prosody.events.add_handler(event, handler, priority);
303 end
304
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()");
311 return;
312 end
313 return api.hook(self, "stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
314 end
315
316 function api:require(lib)
317 local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
318 if not f then
319 f, n = pluginloader.load_code(lib, lib..".lib.lua");
320 end
321 if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
322 setfenv(f, self.environment);
323 return f();
324 end
325
326 function api:get_option(name, default_value)
327 local value = config.get(self.host, self.name, name);
328 if value == nil then
329 value = config.get(self.host, "core", name);
330 if value == nil then
331 value = default_value;
332 end
333 end
334 return value;
335 end
336
337 function api:get_option_string(name, default_value)
338 local value = self:get_option(name, default_value);
339 if type(value) == "table" then
340 if #value > 1 then
341 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
342 end
343 value = value[1];
344 end
345 if value == nil then
346 return nil;
347 end
348 return tostring(value);
349 end
350
351 function api:get_option_number(name, ...)
352 local value = self:get_option(name, ...);
353 if type(value) == "table" then
354 if #value > 1 then
355 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
356 end
357 value = value[1];
358 end
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);
362 end
363 return ret;
364 end
365
366 function api:get_option_boolean(name, ...)
367 local value = self:get_option(name, ...);
368 if type(value) == "table" then
369 if #value > 1 then
370 self:log("error", "Config option '%s' does not take a list, using just the first item", name);
371 end
372 value = value[1];
373 end
374 if value == nil then
375 return nil;
376 end
377 local ret = value == true or value == "true" or value == 1 or nil;
378 if ret == nil then
379 ret = (value == false or value == "false" or value == 0);
380 if ret then
381 ret = false;
382 else
383 ret = nil;
384 end
385 end
386 if ret == nil then
387 self:log("error", "Config option '%s' not understood, expecting true/false", name);
388 end
389 return ret;
390 end
391
392 function api:get_option_array(name, ...)
393 local value = self:get_option(name, ...);
394
395 if value == nil then
396 return nil;
397 end
398
399 if type(value) ~= "table" then
400 return array{ value }; -- Assume any non-list is a single-item list
401 end
402
403 return array():append(value); -- Clone
404 end
405
406 function api:get_option_set(name, ...)
407 local value = self:get_option_array(name, ...);
408
409 if value == nil then
410 return nil;
411 end
412
413 return set.new(value);
414 end
415
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});
423 end
424 function api:remove_item(key, value)
425 local t = self.items and self.items[key] or NULL;
426 for i = #t,1,-1 do
427 if t[i] == value then
428 t_remove(self.items[key], i);
429 self:fire_event("item-removed/"..key, {source = self, item = value});
430 return value;
431 end
432 end
433 end
434
435 function api:get_host_items(key)
436 local result = {};
437 for mod_name, module in pairs(modulemap[self.host]) do
438 module = module.module;
439 if module.items then
440 for _, item in ipairs(module.items[key] or NULL) do
441 t_insert(result, item);
442 end
443 end
444 end
445 for mod_name, module in pairs(modulemap["*"]) do
446 module = module.module;
447 if module.items then
448 for _, item in ipairs(module.items[key] or NULL) do
449 t_insert(result, item);
450 end
451 end
452 end
453 return result;
454 end
455
456 function api:handle_items(type, added_cb, removed_cb, existing)
457 self:hook("item-added/"..type, added_cb);
458 self:hook("item-removed/"..type, removed_cb);
459 if existing ~= false then
460 for _, item in ipairs(self:get_host_items(type)) do
461 added_cb({ item = item });
462 end
463 end
464 end
465
466 return _M; 296 return _M;