modulemanager, util.pluginloader: Move logic for locating some module libraries to...
[prosody.git] / core / moduleapi.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2012 Matthew Wild
3 -- Copyright (C) 2008-2012 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 config = require "core.configmanager";
10 local array = require "util.array";
11 local set = require "util.set";
12 local it = require "util.iterators";
13 local logger = require "util.logger";
14 local pluginloader = require "util.pluginloader";
15 local timer = require "util.timer";
16 local resolve_relative_path = require"util.paths".resolve_relative_path;
17 local measure = require "core.statsmanager".measure;
18 local st = require "util.stanza";
19
20 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
21 local error, setmetatable, type = error, setmetatable, type;
22 local ipairs, pairs, select, unpack = ipairs, pairs, select, unpack;
23 local tonumber, tostring = tonumber, tostring;
24 local require = require;
25
26 local prosody = prosody;
27 local hosts = prosody.hosts;
28
29 -- FIXME: This assert() is to try and catch an obscure bug (2013-04-05)
30 local core_post_stanza = assert(prosody.core_post_stanza,
31         "prosody.core_post_stanza is nil, please report this as a bug");
32
33 -- Registry of shared module data
34 local shared_data = setmetatable({}, { __mode = "v" });
35
36 local NULL = {};
37
38 local api = {};
39
40 -- Returns the name of the current module
41 function api:get_name()
42         return self.name;
43 end
44
45 -- Returns the host that the current module is serving
46 function api:get_host()
47         return self.host;
48 end
49
50 function api:get_host_type()
51         return (self.host == "*" and "global") or hosts[self.host].type or "local";
52 end
53
54 function api:set_global()
55         self.host = "*";
56         -- Update the logger
57         local _log = logger.init("mod_"..self.name);
58         self.log = function (self, ...) return _log(...); end; --luacheck: ignore self
59         self._log = _log;
60         self.global = true;
61 end
62
63 function api:add_feature(xmlns)
64         self:add_item("feature", xmlns);
65 end
66 function api:add_identity(category, identity_type, name)
67         self:add_item("identity", {category = category, type = identity_type, name = name});
68 end
69 function api:add_extension(data)
70         self:add_item("extension", data);
71 end
72 function api:has_feature(xmlns)
73         for _, feature in ipairs(self:get_host_items("feature")) do
74                 if feature == xmlns then return true; end
75         end
76         return false;
77 end
78 function api:has_identity(category, identity_type, name)
79         for _, id in ipairs(self:get_host_items("identity")) do
80                 if id.category == category and id.type == identity_type and id.name == name then
81                         return true;
82                 end
83         end
84         return false;
85 end
86
87 function api:fire_event(...)
88         return (hosts[self.host] or prosody).events.fire_event(...);
89 end
90
91 function api:hook_object_event(object, event, handler, priority)
92         self.event_handlers:set(object, event, handler, true);
93         return object.add_handler(event, handler, priority);
94 end
95
96 function api:unhook_object_event(object, event, handler)
97         self.event_handlers:set(object, event, handler, nil);
98         return object.remove_handler(event, handler);
99 end
100
101 function api:hook(event, handler, priority)
102         return self:hook_object_event((hosts[self.host] or prosody).events, event, handler, priority);
103 end
104
105 function api:hook_global(event, handler, priority)
106         return self:hook_object_event(prosody.events, event, handler, priority);
107 end
108
109 function api:hook_tag(xmlns, name, handler, priority)
110         if not handler and type(name) == "function" then
111                 -- If only 2 options then they specified no xmlns
112                 xmlns, name, handler, priority = nil, xmlns, name, handler;
113         elseif not (handler and name) then
114                 self:log("warn", "Error: Insufficient parameters to module:hook_stanza()");
115                 return;
116         end
117         return self:hook("stanza/"..(xmlns and (xmlns..":") or "")..name, function (data) return handler(data.origin, data.stanza, data); end, priority);
118 end
119 api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
120
121 function api:unhook(event, handler)
122         return self:unhook_object_event((hosts[self.host] or prosody).events, event, handler);
123 end
124
125 function api:wrap_object_event(events_object, event, handler)
126         return self:hook_object_event(assert(events_object.wrappers, "no wrappers"), event, handler);
127 end
128
129 function api:wrap_event(event, handler)
130         return self:wrap_object_event((hosts[self.host] or prosody).events, event, handler);
131 end
132
133 function api:wrap_global(event, handler)
134         return self:hook_object_event(prosody.events, event, handler);
135 end
136
137 function api:require(lib)
138         local f, n = pluginloader.load_code_ext(self.name, lib, "lib.lua", self.environment);
139         if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
140         return f();
141 end
142
143 function api:depends(name)
144         local modulemanager = require"core.modulemanager";
145         if not self.dependencies then
146                 self.dependencies = {};
147                 self:hook("module-reloaded", function (event)
148                         if self.dependencies[event.module] and not self.reloading then
149                                 self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module);
150                                 modulemanager.reload(self.host, self.name);
151                                 return;
152                         end
153                 end);
154                 self:hook("module-unloaded", function (event)
155                         if self.dependencies[event.module] then
156                                 self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module);
157                                 modulemanager.unload(self.host, self.name);
158                         end
159                 end);
160         end
161         local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name);
162         if mod and mod.module.host == "*" and self.host ~= "*"
163         and modulemanager.module_has_method(mod, "add_host") then
164                 mod = nil; -- Target is a shared module, so we still want to load it on our host
165         end
166         if not mod then
167                 local err;
168                 mod, err = modulemanager.load(self.host, name);
169                 if not mod then
170                         return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) ));
171                 end
172         end
173         self.dependencies[name] = true;
174         return mod;
175 end
176
177 -- Returns one or more shared tables at the specified virtual paths
178 -- Intentionally does not allow the table at a path to be _set_, it
179 -- is auto-created if it does not exist.
180 function api:shared(...)
181         if not self.shared_data then self.shared_data = {}; end
182         local paths = { n = select("#", ...), ... };
183         local data_array = {};
184         local default_path_components = { self.host, self.name };
185         for i = 1, paths.n do
186                 local path = paths[i];
187                 if path:sub(1,1) ~= "/" then -- Prepend default components
188                         local n_components = select(2, path:gsub("/", "%1"));
189                         path = (n_components<#default_path_components and "/" or "")..t_concat(default_path_components, "/", 1, #default_path_components-n_components).."/"..path;
190                 end
191                 local shared = shared_data[path];
192                 if not shared then
193                         shared = {};
194                         if path:match("%-cache$") then
195                                 setmetatable(shared, { __mode = "kv" });
196                         end
197                         shared_data[path] = shared;
198                 end
199                 t_insert(data_array, shared);
200                 self.shared_data[path] = shared;
201         end
202         return unpack(data_array);
203 end
204
205 function api:get_option(name, default_value)
206         local value = config.get(self.host, name);
207         if value == nil then
208                 value = default_value;
209         end
210         return value;
211 end
212
213 function api:get_option_string(name, default_value)
214         local value = self:get_option(name, default_value);
215         if type(value) == "table" then
216                 if #value > 1 then
217                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
218                 end
219                 value = value[1];
220         end
221         if value == nil then
222                 return nil;
223         end
224         return tostring(value);
225 end
226
227 function api:get_option_number(name, ...)
228         local value = self:get_option(name, ...);
229         if type(value) == "table" then
230                 if #value > 1 then
231                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
232                 end
233                 value = value[1];
234         end
235         local ret = tonumber(value);
236         if value ~= nil and ret == nil then
237                 self:log("error", "Config option '%s' not understood, expecting a number", name);
238         end
239         return ret;
240 end
241
242 function api:get_option_boolean(name, ...)
243         local value = self:get_option(name, ...);
244         if type(value) == "table" then
245                 if #value > 1 then
246                         self:log("error", "Config option '%s' does not take a list, using just the first item", name);
247                 end
248                 value = value[1];
249         end
250         if value == nil then
251                 return nil;
252         end
253         local ret = value == true or value == "true" or value == 1 or nil;
254         if ret == nil then
255                 ret = (value == false or value == "false" or value == 0);
256                 if ret then
257                         ret = false;
258                 else
259                         ret = nil;
260                 end
261         end
262         if ret == nil then
263                 self:log("error", "Config option '%s' not understood, expecting true/false", name);
264         end
265         return ret;
266 end
267
268 function api:get_option_array(name, ...)
269         local value = self:get_option(name, ...);
270
271         if value == nil then
272                 return nil;
273         end
274
275         if type(value) ~= "table" then
276                 return array{ value }; -- Assume any non-list is a single-item list
277         end
278
279         return array():append(value); -- Clone
280 end
281
282 function api:get_option_set(name, ...)
283         local value = self:get_option_array(name, ...);
284
285         if value == nil then
286                 return nil;
287         end
288
289         return set.new(value);
290 end
291
292 function api:get_option_inherited_set(name, ...)
293         local value = self:get_option_set(name, ...);
294         local global_value = self:context("*"):get_option_set(name, ...);
295         if not value then
296                 return global_value;
297         elseif not global_value then
298                 return value;
299         end
300         value:include(global_value);
301         return value;
302 end
303
304 function api:context(host)
305         return setmetatable({host=host or "*"}, {__index=self,__newindex=self});
306 end
307
308 function api:add_item(key, value)
309         self.items = self.items or {};
310         self.items[key] = self.items[key] or {};
311         t_insert(self.items[key], value);
312         self:fire_event("item-added/"..key, {source = self, item = value});
313 end
314 function api:remove_item(key, value)
315         local t = self.items and self.items[key] or NULL;
316         for i = #t,1,-1 do
317                 if t[i] == value then
318                         t_remove(self.items[key], i);
319                         self:fire_event("item-removed/"..key, {source = self, item = value});
320                         return value;
321                 end
322         end
323 end
324
325 function api:get_host_items(key)
326         local modulemanager = require"core.modulemanager";
327         local result = modulemanager.get_items(key, self.host) or {};
328         return result;
329 end
330
331 function api:handle_items(item_type, added_cb, removed_cb, existing)
332         self:hook("item-added/"..item_type, added_cb);
333         self:hook("item-removed/"..item_type, removed_cb);
334         if existing ~= false then
335                 for _, item in ipairs(self:get_host_items(item_type)) do
336                         added_cb({ item = item });
337                 end
338         end
339 end
340
341 function api:provides(name, item)
342         -- if not item then item = setmetatable({}, { __index = function(t,k) return rawget(self.environment, k); end }); end
343         if not item then
344                 item = {}
345                 for k,v in pairs(self.environment) do
346                         if k ~= "module" then item[k] = v; end
347                 end
348         end
349         if not item.name then
350                 local item_name = self.name;
351                 -- Strip a provider prefix to find the item name
352                 -- (e.g. "auth_foo" -> "foo" for an auth provider)
353                 if item_name:find(name.."_", 1, true) == 1 then
354                         item_name = item_name:sub(#name+2);
355                 end
356                 item.name = item_name;
357         end
358         item._provided_by = self.name;
359         self:add_item(name.."-provider", item);
360 end
361
362 function api:send(stanza)
363         return core_post_stanza(hosts[self.host], stanza);
364 end
365
366 function api:broadcast(jids, stanza, iter)
367         for jid in (iter or it.values)(jids) do
368                 local new_stanza = st.clone(stanza);
369                 new_stanza.attr.to = jid;
370                 core_post_stanza(hosts[self.host], new_stanza);
371         end
372 end
373
374 function api:add_timer(delay, callback)
375         return timer.add_task(delay, function (t)
376                 if self.loaded == false then return; end
377                 return callback(t);
378         end);
379 end
380
381 local path_sep = package.config:sub(1,1);
382 function api:get_directory()
383         return self.path and (self.path:gsub("%"..path_sep.."[^"..path_sep.."]*$", "")) or nil;
384 end
385
386 function api:load_resource(path, mode)
387         path = resolve_relative_path(self:get_directory(), path);
388         return io.open(path, mode);
389 end
390
391 function api:open_store(name, store_type)
392         return require"core.storagemanager".open(self.host, name or self.name, store_type);
393 end
394
395 function api:measure(name, stat_type)
396         return measure(stat_type, "/"..self.host.."/mod_"..self.name.."/"..name);
397 end
398
399 function api:measure_object_event(events_object, event_name, stat_name)
400         local m = self:measure(stat_name or event_name, "duration");
401         local function handler(handlers, _event_name, _event_data)
402                 local finished = m();
403                 local ret = handlers(_event_name, _event_data);
404                 finished();
405                 return ret;
406         end
407         return self:hook_object_event(events_object, event_name, handler);
408 end
409
410 function api:measure_event(event_name, stat_name)
411         return self:measure_object_event((hosts[self.host] or prosody).events.wrappers, event_name, stat_name);
412 end
413
414 function api:measure_global_event(event_name, stat_name)
415         return self:measure_object_event(prosody.events.wrappers, event_name, stat_name);
416 end
417
418 return api;