Mercurial > prosody-modules
comparison mod_http_stats_stream/mod_http_stats_stream.lua @ 2432:47a6f01231b2
mod_http_stats_stream: Sends statistics from statsmanager over an HTTP event stream
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Wed, 04 Jan 2017 09:18:34 +0100 |
| parents | |
| children | fd054689a64c |
comparison
equal
deleted
inserted
replaced
| 2431:623e23190c3e | 2432:47a6f01231b2 |
|---|---|
| 1 local statsman = require "core.statsmanager"; | |
| 2 local json = require "util.json"; | |
| 3 | |
| 4 local sessions = {}; | |
| 5 | |
| 6 local function updates_client_closed(response) | |
| 7 module:log("debug", "Streamstats client closed"); | |
| 8 sessions[response] = nil; | |
| 9 end | |
| 10 | |
| 11 local function get_updates(event) | |
| 12 local request, response = event.request, event.response; | |
| 13 | |
| 14 response.on_destroy = updates_client_closed; | |
| 15 | |
| 16 response.conn:write(table.concat({ | |
| 17 "HTTP/1.1 200 OK"; | |
| 18 "Content-Type: text/event-stream"; | |
| 19 "X-Accel-Buffering: no"; -- For nginx maybe? | |
| 20 ""; | |
| 21 "event: stats-full"; | |
| 22 "data: "..json.encode(statsman.get_stats()); | |
| 23 ""; | |
| 24 ""; | |
| 25 }, "\r\n")); | |
| 26 | |
| 27 sessions[response] = request; | |
| 28 return true; | |
| 29 end | |
| 30 | |
| 31 | |
| 32 module:hook_global("stats-updated", function (event) | |
| 33 local data = table.concat({ | |
| 34 "event: stats-updated"; | |
| 35 "data: "..json.encode(event.changed_stats); | |
| 36 ""; | |
| 37 ""; | |
| 38 }, "\r\n") | |
| 39 for response in pairs(sessions) do | |
| 40 response.conn:write(data); | |
| 41 end | |
| 42 end); | |
| 43 | |
| 44 | |
| 45 module:depends("http"); | |
| 46 module:provides("http", { | |
| 47 route = { | |
| 48 GET = get_updates; | |
| 49 } | |
| 50 }); |
