You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stats.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. The MIT License (MIT)
  3. Copyright (C) 2017 Vsevolod Stakhov <vsevolod@highsecure.ru>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /* global d3:false */
  21. define(["jquery", "d3pie"],
  22. function ($, D3Pie) {
  23. "use strict";
  24. // @ ms to date
  25. function msToTime(seconds) {
  26. if (!Number.isFinite(seconds)) return "???";
  27. /* eslint-disable no-bitwise */
  28. var years = seconds / 31536000 >> 0; // 3600*24*365
  29. var months = seconds % 31536000 / 2628000 >> 0; // 3600*24*365/12
  30. var days = seconds % 31536000 % 2628000 / 86400 >> 0; // 24*3600
  31. var hours = seconds % 31536000 % 2628000 % 86400 / 3600 >> 0;
  32. var minutes = seconds % 31536000 % 2628000 % 86400 % 3600 / 60 >> 0;
  33. /* eslint-enable no-bitwise */
  34. var out = null;
  35. if (years > 0) {
  36. if (months > 0) {
  37. out = years + "yr " + months + "mth";
  38. } else {
  39. out = years + "yr " + days + "d";
  40. }
  41. } else if (months > 0) {
  42. out = months + "mth " + days + "d";
  43. } else if (days > 0) {
  44. out = days + "d " + hours + "hr";
  45. } else if (hours > 0) {
  46. out = hours + "hr " + minutes + "min";
  47. } else {
  48. out = minutes + "min";
  49. }
  50. return out;
  51. }
  52. function displayStatWidgets(checked_server) {
  53. var servers = JSON.parse(sessionStorage.getItem("Credentials"));
  54. var data = {};
  55. if (servers && servers[checked_server]) {
  56. data = servers[checked_server].data;
  57. }
  58. var stat_w = [];
  59. $("#statWidgets").empty().hide();
  60. $.each(data, function (i, item) {
  61. var widgetsOrder = ["scanned", "no action", "greylist", "add header", "rewrite subject", "reject", "learned"];
  62. function widget(k, v, cls) {
  63. var c = (typeof cls === "undefined") ? "" : cls;
  64. var titleAtt = d3.format(",")(v) + " " + k;
  65. return '<div class="card stat-box d-inline-block text-center shadow-sm mr-3 px-3">' +
  66. '<div class="widget overflow-hidden p-2' + c + '" title="' + titleAtt +
  67. '"><strong class="d-block mt-2 mb-1 font-weight-bold">' +
  68. d3.format(".3~s")(v) + "</strong>" + k + "</div></div>";
  69. }
  70. if (i === "auth" || i === "error") return; // Skip to the next iteration
  71. if (i === "uptime" || i === "version") {
  72. var cls = "border-right ";
  73. var val = item;
  74. if (i === "uptime") {
  75. cls = "";
  76. val = msToTime(item);
  77. }
  78. $('<div class="' + cls + 'float-left px-3"><strong class="d-block mt-2 mb-1 font-weight-bold">' +
  79. val + "</strong>" + i + "</div>")
  80. .appendTo("#statWidgets");
  81. } else if (i === "actions") {
  82. $.each(item, function (action, count) {
  83. stat_w[widgetsOrder.indexOf(action)] = widget(action, count);
  84. });
  85. } else {
  86. stat_w[widgetsOrder.indexOf(i)] = widget(i, item, " text-capitalize");
  87. }
  88. });
  89. $.each(stat_w, function (i, item) {
  90. $(item).appendTo("#statWidgets");
  91. });
  92. $("#statWidgets > div:not(.stat-box)")
  93. .wrapAll('<div class="card stat-box text-center shadow-sm float-right">' +
  94. '<div class="widget overflow-hidden p-2 text-capitalize"></div></div>');
  95. $("#statWidgets").find("div.float-right").appendTo("#statWidgets");
  96. $("#statWidgets").show();
  97. $("#clusterTable tbody").empty();
  98. $("#selSrv").empty();
  99. $.each(servers, function (key, val) {
  100. var row_class = "danger";
  101. var glyph_status = "fas fa-times";
  102. var version = "???";
  103. var uptime = "???";
  104. var short_id = "???";
  105. let scan_times = {
  106. data: "???",
  107. title: ""
  108. };
  109. if (val.status) {
  110. row_class = "success";
  111. glyph_status = "fas fa-check";
  112. if (Number.isFinite(val.data.uptime)) {
  113. uptime = msToTime(val.data.uptime);
  114. }
  115. if ("version" in val.data) {
  116. version = val.data.version;
  117. }
  118. if (key === "All SERVERS") {
  119. short_id = "";
  120. scan_times.data = "";
  121. } else {
  122. if ("config_id" in val.data) {
  123. short_id = val.data.config_id.substring(0, 8);
  124. }
  125. if ("scan_times" in val.data) {
  126. const [min, max] = d3.extent(val.data.scan_times);
  127. if (max) {
  128. const f = d3.format(".3f");
  129. scan_times = {
  130. data: "<small>" + f(min) + "/</small>" + f(d3.mean(val.data.scan_times)) + "<small>/" + f(max) + "</small>",
  131. title: ' title="min/avg/max"'
  132. };
  133. } else {
  134. scan_times = {
  135. data: "-",
  136. title: ' title="Have not scanned anything yet"'
  137. };
  138. }
  139. }
  140. }
  141. }
  142. $("#clusterTable tbody").append('<tr class="' + row_class + '">' +
  143. '<td class="align-middle"><input type="radio" class="form-check m-auto" name="clusterName" value="' + key + '"></td>' +
  144. "<td>" + key + "</td>" +
  145. "<td>" + val.host + "</td>" +
  146. '<td class="text-center"><span class="icon"><i class="' + glyph_status + '"></i></span></td>' +
  147. '<td class="text-center"' + scan_times.title + ">" + scan_times.data + "</td>" +
  148. '<td class="text-right' +
  149. ((Number.isFinite(val.data.uptime) && val.data.uptime < 3600)
  150. ? ' warning" title="Has been restarted within the last hour"'
  151. : "") +
  152. '">' + uptime + "</td>" +
  153. "<td>" + version + "</td>" +
  154. "<td>" + short_id + "</td></tr>");
  155. $("#selSrv").append($('<option value="' + key + '">' + key + "</option>"));
  156. if (checked_server === key) {
  157. $('#clusterTable tbody [value="' + key + '"]').prop("checked", true);
  158. $('#selSrv [value="' + key + '"]').prop("selected", true);
  159. } else if (!val.status) {
  160. $('#clusterTable tbody [value="' + key + '"]').prop("disabled", true);
  161. $('#selSrv [value="' + key + '"]').prop("disabled", true);
  162. }
  163. });
  164. function addStatfiles(server, statfiles) {
  165. $.each(statfiles, function (i, statfile) {
  166. var cls = "";
  167. switch (statfile.symbol) {
  168. case "BAYES_SPAM":
  169. cls = "symbol-positive";
  170. break;
  171. case "BAYES_HAM":
  172. cls = "symbol-negative";
  173. break;
  174. default:
  175. }
  176. $("#bayesTable tbody").append("<tr>" +
  177. (i === 0 ? '<td rowspan="' + statfiles.length + '">' + server + "</td>" : "") +
  178. '<td class="' + cls + '">' + statfile.symbol + "</td>" +
  179. '<td class="' + cls + '">' + statfile.type + "</td>" +
  180. '<td class="text-right ' + cls + '">' + statfile.revision + "</td>" +
  181. '<td class="text-right ' + cls + '">' + statfile.users + "</td></tr>");
  182. });
  183. }
  184. function addFuzzyStorage(server, storages) {
  185. var i = 0;
  186. $.each(storages, function (storage, hashes) {
  187. $("#fuzzyTable tbody").append("<tr>" +
  188. (i === 0 ? '<td rowspan="' + Object.keys(storages).length + '">' + server + "</td>" : "") +
  189. "<td>" + storage + "</td>" +
  190. '<td class="text-right">' + hashes + "</td></tr>");
  191. i++;
  192. });
  193. }
  194. $("#bayesTable tbody, #fuzzyTable tbody").empty();
  195. if (checked_server === "All SERVERS") {
  196. $.each(servers, function (server, val) {
  197. if (server !== "All SERVERS") {
  198. addStatfiles(server, val.data.statfiles);
  199. addFuzzyStorage(server, val.data.fuzzy_hashes);
  200. }
  201. });
  202. } else {
  203. addStatfiles(checked_server, data.statfiles);
  204. addFuzzyStorage(checked_server, data.fuzzy_hashes);
  205. }
  206. }
  207. function getChart(rspamd, graphs, checked_server) {
  208. if (!graphs.chart) {
  209. graphs.chart = new D3Pie("chart", {
  210. labels: {
  211. inner: {
  212. offset: 0
  213. },
  214. outer: {
  215. collideHeight: 18,
  216. }
  217. },
  218. size: {
  219. pieInnerRadius: "50%"
  220. },
  221. title: "Rspamd filter stats",
  222. total: {
  223. enabled: true,
  224. label: "Scanned"
  225. }
  226. });
  227. }
  228. var data = [];
  229. var creds = JSON.parse(sessionStorage.getItem("Credentials"));
  230. // Controller doesn't return the 'actions' object until at least one message is scanned
  231. if (creds && creds[checked_server] && creds[checked_server].data.scanned) {
  232. var actions = creds[checked_server].data.actions;
  233. ["no action", "soft reject", "add header", "rewrite subject", "greylist", "reject"]
  234. .forEach(function (action) {
  235. data.push({
  236. color: rspamd.chartLegend.find(function (item) { return item.label === action; }).color,
  237. label: action,
  238. value: actions[action]
  239. });
  240. });
  241. }
  242. graphs.chart.data(data);
  243. }
  244. // Public API
  245. var ui = {
  246. statWidgets: function (rspamd, graphs, checked_server) {
  247. rspamd.query("stat", {
  248. success: function (neighbours_status) {
  249. var neighbours_sum = {
  250. version: neighbours_status[0].data.version,
  251. uptime: 0,
  252. scanned: 0,
  253. learned: 0,
  254. actions: {
  255. "no action": 0,
  256. "add header": 0,
  257. "rewrite subject": 0,
  258. "greylist": 0,
  259. "reject": 0,
  260. "soft reject": 0,
  261. }
  262. };
  263. var status_count = 0;
  264. var promises = [];
  265. var to_Credentials = {
  266. "All SERVERS": {
  267. name: "All SERVERS",
  268. url: "",
  269. host: "",
  270. checked: true,
  271. status: true
  272. }
  273. };
  274. function process_node_stat(e) {
  275. var data = neighbours_status[e].data;
  276. // Controller doesn't return the 'actions' object until at least one message is scanned
  277. if (data.scanned) {
  278. for (var action in neighbours_sum.actions) {
  279. if ({}.hasOwnProperty.call(neighbours_sum.actions, action)) {
  280. neighbours_sum.actions[action] += data.actions[action];
  281. }
  282. }
  283. }
  284. ["learned", "scanned", "uptime"].forEach(function (p) {
  285. neighbours_sum[p] += data[p];
  286. });
  287. status_count++;
  288. }
  289. // Get config_id, version and uptime using /auth query for Rspamd 2.5 and earlier
  290. function get_legacy_stat(e) {
  291. var alerted = "alerted_stats_legacy_" + neighbours_status[e].name;
  292. promises.push($.ajax({
  293. url: neighbours_status[e].url + "auth",
  294. headers: {Password:rspamd.getPassword()},
  295. success: function (data) {
  296. sessionStorage.removeItem(alerted);
  297. ["config_id", "version", "uptime"].forEach(function (p) {
  298. neighbours_status[e].data[p] = data[p];
  299. });
  300. process_node_stat(e);
  301. },
  302. error: function (jqXHR, textStatus, errorThrown) {
  303. if (!(alerted in sessionStorage)) {
  304. sessionStorage.setItem(alerted, true);
  305. rspamd.alertMessage("alert-error", neighbours_status[e].name + " > " +
  306. "Cannot receive legacy stats data" + (errorThrown ? ": " + errorThrown : ""));
  307. }
  308. process_node_stat(e);
  309. }
  310. }));
  311. }
  312. for (var e in neighbours_status) {
  313. if ({}.hasOwnProperty.call(neighbours_status, e)) {
  314. to_Credentials[neighbours_status[e].name] = neighbours_status[e];
  315. if (neighbours_status[e].status === true) {
  316. // Remove alert status
  317. sessionStorage.removeItem("alerted_stats_" + neighbours_status[e].name);
  318. if ({}.hasOwnProperty.call(neighbours_status[e].data, "version")) {
  319. process_node_stat(e);
  320. } else {
  321. get_legacy_stat(e);
  322. }
  323. }
  324. }
  325. }
  326. setTimeout(function () {
  327. $.when.apply($, promises).always(function () {
  328. neighbours_sum.uptime = Math.floor(neighbours_sum.uptime / status_count);
  329. to_Credentials["All SERVERS"].data = neighbours_sum;
  330. sessionStorage.setItem("Credentials", JSON.stringify(to_Credentials));
  331. displayStatWidgets(checked_server);
  332. getChart(rspamd, graphs, checked_server);
  333. });
  334. }, promises.length ? 100 : 0);
  335. },
  336. complete: function () { $("#refresh").removeAttr("disabled").removeClass("disabled"); },
  337. errorMessage: "Cannot receive stats data",
  338. errorOnceId: "alerted_stats_",
  339. server: "All SERVERS"
  340. });
  341. },
  342. };
  343. return ui;
  344. }
  345. );