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

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