Merge 0.9->0.10
[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                 changed_stats, stats_extra = {}, {};
32                 for stat_name, getter in pairs(stats.get_stats()) do
33                         local type, value, extra = getter();
34                         local old_value = latest_stats[stat_name];
35                         latest_stats[stat_name] = value;
36                         if value ~= old_value then
37                                 changed_stats[stat_name] = value;
38                         end
39                         if extra then
40                                 stats_extra[stat_name] = extra;
41                         end
42                 end
43                 mark_collection_done();
44                 local mark_processing_done = mark_processing_start();
45                 fire_event("stats-updated", { stats = latest_stats, changed_stats = changed_stats, stats_extra = stats_extra });
46                 mark_processing_done();
47                 return stats_interval;
48         end
49
50         timer.add_task(stats_interval, collect);
51 else
52         log("debug", "Statistics collection is disabled");
53         -- nop
54         function measure()
55                 return measure;
56         end
57         function collect()
58         end
59 end
60
61 return {
62         measure = measure;
63         collect = collect;
64         get_stats = function ()
65                 return latest_stats, changed_stats, stats_extra;
66         end;
67 };