Merge 0.10->trunk
[prosody.git] / core / statsmanager.lua
1
2 local stats = require "util.statistics".new();
3 local config = require "core.configmanager";
4 local log = require "util.logger".init("stats");
5 local timer = require "util.timer";
6 local fire_event = prosody.events.fire_event;
7
8 local stats_config = config.get("*", "statistics_interval");
9 local stats_interval = tonumber(stats_config);
10 if stats_config and not stats_interval then
11         log("error", "Invalid 'statistics_interval' setting, statistics will be disabled");
12 end
13
14 local measure, collect;
15 local latest_stats = {};
16 local changed_stats = {};
17 local stats_extra = {};
18
19 if stats_interval then
20         log("debug", "Statistics collection is enabled every %d seconds", stats_interval);
21         function measure(type, name)
22                 local f = assert(stats[type], "unknown stat type: "..type);
23                 return f(name);
24         end
25
26         local mark_collection_start = measure("times", "stats.collection");
27         local mark_processing_start = measure("times", "stats.processing");
28
29         function collect()
30                 local mark_collection_done = mark_collection_start();
31                 fire_event("stats-update");
32                 changed_stats, stats_extra = {}, {};
33                 for stat_name, getter in pairs(stats.get_stats()) do
34                         local type, value, extra = getter();
35                         local old_value = latest_stats[stat_name];
36                         latest_stats[stat_name] = value;
37                         if value ~= old_value then
38                                 changed_stats[stat_name] = value;
39                         end
40                         if extra then
41                                 stats_extra[stat_name] = extra;
42                         end
43                 end
44                 mark_collection_done();
45                 local mark_processing_done = mark_processing_start();
46                 fire_event("stats-updated", { stats = latest_stats, changed_stats = changed_stats, stats_extra = stats_extra });
47                 mark_processing_done();
48                 return stats_interval;
49         end
50
51         timer.add_task(stats_interval, collect);
52         prosody.events.add_handler("server-started", function () collect() end, -1);
53 else
54         log("debug", "Statistics collection is disabled");
55         -- nop
56         function measure()
57                 return measure;
58         end
59         function collect()
60         end
61 end
62
63 return {
64         measure = measure;
65         collect = collect;
66         get_stats = function ()
67                 return latest_stats, changed_stats, stats_extra;
68         end;
69         get = function (name)
70                 return latest_stats[name], stats_extra[name];
71         end;
72 };