monitor.js 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290
  1. "use strict";
  2. /**
  3. * @fileoverview Javascript functions used in server status monitor page
  4. * @name Server Status Monitor
  5. *
  6. * @requires jQuery
  7. * @requires jQueryUI
  8. * @requires js/functions.js
  9. */
  10. /* global isStorageSupported */
  11. // js/config.js
  12. /* global codeMirrorEditor:writable */
  13. // js/functions.js
  14. /* global firstDayOfCalendar, themeImagePath */
  15. // templates/javascript/variables.twig
  16. /* global variableNames */
  17. // templates/server/status/monitor/index.twig
  18. var runtime = {};
  19. var serverTimeDiff;
  20. var serverOs;
  21. var isSuperUser;
  22. var serverDbIsLocal;
  23. var chartSize;
  24. var monitorSettings;
  25. function serverResponseError() {
  26. var btns = {};
  27. btns[Messages.strReloadPage] = function () {
  28. window.location.reload();
  29. };
  30. $('#emptyDialog').dialog({
  31. title: Messages.strRefreshFailed
  32. });
  33. $('#emptyDialog').html(Functions.getImage('s_attention') + Messages.strInvalidResponseExplanation);
  34. $('#emptyDialog').dialog({
  35. buttons: btns
  36. });
  37. }
  38. /**
  39. * Destroys all monitor related resources
  40. */
  41. function destroyGrid() {
  42. if (runtime.charts) {
  43. $.each(runtime.charts, function (key, value) {
  44. try {
  45. value.chart.destroy();
  46. } catch (err) {// continue regardless of error
  47. }
  48. });
  49. }
  50. try {
  51. runtime.refreshRequest.abort();
  52. } catch (err) {// continue regardless of error
  53. }
  54. try {
  55. clearTimeout(runtime.refreshTimeout);
  56. } catch (err) {// continue regardless of error
  57. }
  58. $('#chartGrid').html('');
  59. runtime.charts = null;
  60. runtime.chartAI = 0;
  61. monitorSettings = null;
  62. }
  63. AJAX.registerOnload('server/status/monitor.js', function () {
  64. var $jsDataForm = $('#js_data');
  65. serverTimeDiff = new Date().getTime() - $jsDataForm.find('input[name=server_time]').val();
  66. serverOs = $jsDataForm.find('input[name=server_os]').val();
  67. isSuperUser = $jsDataForm.find('input[name=is_superuser]').val();
  68. serverDbIsLocal = $jsDataForm.find('input[name=server_db_isLocal]').val();
  69. });
  70. /**
  71. * Unbind all event handlers before tearing down a page
  72. */
  73. AJAX.registerTeardown('server/status/monitor.js', function () {
  74. $('#emptyDialog').remove();
  75. $('#addChartDialog').remove();
  76. $('a.popupLink').off('click');
  77. $('body').off('click');
  78. });
  79. /**
  80. * Popup behaviour
  81. */
  82. AJAX.registerOnload('server/status/monitor.js', function () {
  83. $('<div></div>').attr('id', 'emptyDialog').appendTo('#page_content');
  84. $('#addChartDialog').appendTo('#page_content');
  85. $('a.popupLink').on('click', function () {
  86. var $link = $(this);
  87. $('div.' + $link.attr('href').substr(1)).show().offset({
  88. top: $link.offset().top + $link.height() + 5,
  89. left: $link.offset().left
  90. }).addClass('openedPopup');
  91. return false;
  92. });
  93. $('body').on('click', function (event) {
  94. $('div.openedPopup').each(function () {
  95. var $cnt = $(this);
  96. var pos = $cnt.offset(); // Hide if the mouseclick is outside the popupcontent
  97. if (event.pageX < pos.left || event.pageY < pos.top || event.pageX > pos.left + $cnt.outerWidth() || event.pageY > pos.top + $cnt.outerHeight()) {
  98. $cnt.hide().removeClass('openedPopup');
  99. }
  100. });
  101. });
  102. });
  103. AJAX.registerTeardown('server/status/monitor.js', function () {
  104. $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').off('click');
  105. $('div.popupContent select[name="chartColumns"]').off('change');
  106. $('div.popupContent select[name="gridChartRefresh"]').off('change');
  107. $('a[href="#addNewChart"]').off('click');
  108. $('a[href="#exportMonitorConfig"]').off('click');
  109. $('a[href="#importMonitorConfig"]').off('click');
  110. $('a[href="#clearMonitorConfig"]').off('click');
  111. $('a[href="#pauseCharts"]').off('click');
  112. $('a[href="#monitorInstructionsDialog"]').off('click');
  113. $('input[name="chartType"]').off('click');
  114. $('input[name="useDivisor"]').off('click');
  115. $('input[name="useUnit"]').off('click');
  116. $('select[name="varChartList"]').off('click');
  117. $('a[href="#kibDivisor"]').off('click');
  118. $('a[href="#mibDivisor"]').off('click');
  119. $('a[href="#submitClearSeries"]').off('click');
  120. $('a[href="#submitAddSeries"]').off('click'); // $("input#variableInput").destroy();
  121. $('#chartPreset').off('click');
  122. $('#chartStatusVar').off('click');
  123. destroyGrid();
  124. });
  125. AJAX.registerOnload('server/status/monitor.js', function () {
  126. // Show tab links
  127. $('div.tabLinks').show();
  128. $('#loadingMonitorIcon').remove(); // Codemirror is loaded on demand so we might need to initialize it
  129. if (!codeMirrorEditor) {
  130. var $elm = $('#sqlquery');
  131. if ($elm.length > 0 && typeof CodeMirror !== 'undefined') {
  132. codeMirrorEditor = CodeMirror.fromTextArea($elm[0], {
  133. lineNumbers: true,
  134. matchBrackets: true,
  135. indentUnit: 4,
  136. mode: 'text/x-mysql',
  137. lineWrapping: true
  138. });
  139. }
  140. } // Timepicker is loaded on demand so we need to initialize
  141. // datetime fields from the 'load log' dialog
  142. $('#logAnalyseDialog').find('.datetimefield').each(function () {
  143. Functions.addDatepicker($(this));
  144. });
  145. /** ** Monitor charting implementation ****/
  146. /* Saves the previous ajax response for differential values */
  147. var oldChartData = null; // Holds about to be created chart
  148. var newChart = null;
  149. var chartSpacing; // Whenever the monitor object (runtime.charts) or the settings object
  150. // (monitorSettings) changes in a way incompatible to the previous version,
  151. // increase this number. It will reset the users monitor and settings object
  152. // in their localStorage to the default configuration
  153. var monitorProtocolVersion = '1.0'; // Runtime parameter of the monitor, is being fully set in initGrid()
  154. runtime = {
  155. // Holds all visible charts in the grid
  156. charts: null,
  157. // Stores the timeout handler so it can be cleared
  158. refreshTimeout: null,
  159. // Stores the GET request to refresh the charts
  160. refreshRequest: null,
  161. // Chart auto increment
  162. chartAI: 0,
  163. // To play/pause the monitor
  164. redrawCharts: false,
  165. // Object that contains a list of nodes that need to be retrieved
  166. // from the server for chart updates
  167. dataList: [],
  168. // Current max points per chart (needed for auto calculation)
  169. gridMaxPoints: 20,
  170. // displayed time frame
  171. xmin: -1,
  172. xmax: -1
  173. };
  174. monitorSettings = null;
  175. var defaultMonitorSettings = {
  176. columns: 3,
  177. chartSize: {
  178. width: 295,
  179. height: 250
  180. },
  181. // Max points in each chart. Settings it to 'auto' sets
  182. // gridMaxPoints to (chartwidth - 40) / 12
  183. gridMaxPoints: 'auto',
  184. /* Refresh rate of all grid charts in ms */
  185. gridRefresh: 5000
  186. }; // Allows drag and drop rearrange and print/edit icons on charts
  187. var editMode = false;
  188. /* List of preconfigured charts that the user may select */
  189. var presetCharts = {
  190. // Query cache efficiency
  191. 'qce': {
  192. title: Messages.strQueryCacheEfficiency,
  193. series: [{
  194. label: Messages.strQueryCacheEfficiency
  195. }],
  196. nodes: [{
  197. dataPoints: [{
  198. type: 'statusvar',
  199. name: 'Qcache_hits'
  200. }, {
  201. type: 'statusvar',
  202. name: 'Com_select'
  203. }],
  204. transformFn: 'qce'
  205. }],
  206. maxYLabel: 0
  207. },
  208. // Query cache usage
  209. 'qcu': {
  210. title: Messages.strQueryCacheUsage,
  211. series: [{
  212. label: Messages.strQueryCacheUsed
  213. }],
  214. nodes: [{
  215. dataPoints: [{
  216. type: 'statusvar',
  217. name: 'Qcache_free_memory'
  218. }, {
  219. type: 'servervar',
  220. name: 'query_cache_size'
  221. }],
  222. transformFn: 'qcu'
  223. }],
  224. maxYLabel: 0
  225. }
  226. }; // time span selection
  227. var selectionTimeDiff = [];
  228. var selectionStartX;
  229. var selectionStartY;
  230. var drawTimeSpan = false;
  231. /* Add OS specific system info charts to the preset chart list */
  232. switch (serverOs) {
  233. case 'WINNT':
  234. $.extend(presetCharts, {
  235. 'cpu': {
  236. title: Messages.strSystemCPUUsage,
  237. series: [{
  238. label: Messages.strAverageLoad
  239. }],
  240. nodes: [{
  241. dataPoints: [{
  242. type: 'cpu',
  243. name: 'loadavg'
  244. }]
  245. }],
  246. maxYLabel: 100
  247. },
  248. 'memory': {
  249. title: Messages.strSystemMemory,
  250. series: [{
  251. label: Messages.strTotalMemory,
  252. fill: true
  253. }, {
  254. dataType: 'memory',
  255. label: Messages.strUsedMemory,
  256. fill: true
  257. }],
  258. nodes: [{
  259. dataPoints: [{
  260. type: 'memory',
  261. name: 'MemTotal'
  262. }],
  263. valueDivisor: 1024
  264. }, {
  265. dataPoints: [{
  266. type: 'memory',
  267. name: 'MemUsed'
  268. }],
  269. valueDivisor: 1024
  270. }],
  271. maxYLabel: 0
  272. },
  273. 'swap': {
  274. title: Messages.strSystemSwap,
  275. series: [{
  276. label: Messages.strTotalSwap,
  277. fill: true
  278. }, {
  279. label: Messages.strUsedSwap,
  280. fill: true
  281. }],
  282. nodes: [{
  283. dataPoints: [{
  284. type: 'memory',
  285. name: 'SwapTotal'
  286. }]
  287. }, {
  288. dataPoints: [{
  289. type: 'memory',
  290. name: 'SwapUsed'
  291. }]
  292. }],
  293. maxYLabel: 0
  294. }
  295. });
  296. break;
  297. case 'Linux':
  298. $.extend(presetCharts, {
  299. 'cpu': {
  300. title: Messages.strSystemCPUUsage,
  301. series: [{
  302. label: Messages.strAverageLoad
  303. }],
  304. nodes: [{
  305. dataPoints: [{
  306. type: 'cpu',
  307. name: 'irrelevant'
  308. }],
  309. transformFn: 'cpu-linux'
  310. }],
  311. maxYLabel: 0
  312. },
  313. 'memory': {
  314. title: Messages.strSystemMemory,
  315. series: [{
  316. label: Messages.strBufferedMemory,
  317. fill: true
  318. }, {
  319. label: Messages.strUsedMemory,
  320. fill: true
  321. }, {
  322. label: Messages.strCachedMemory,
  323. fill: true
  324. }, {
  325. label: Messages.strFreeMemory,
  326. fill: true
  327. }],
  328. nodes: [{
  329. dataPoints: [{
  330. type: 'memory',
  331. name: 'Buffers'
  332. }],
  333. valueDivisor: 1024
  334. }, {
  335. dataPoints: [{
  336. type: 'memory',
  337. name: 'MemUsed'
  338. }],
  339. valueDivisor: 1024
  340. }, {
  341. dataPoints: [{
  342. type: 'memory',
  343. name: 'Cached'
  344. }],
  345. valueDivisor: 1024
  346. }, {
  347. dataPoints: [{
  348. type: 'memory',
  349. name: 'MemFree'
  350. }],
  351. valueDivisor: 1024
  352. }],
  353. maxYLabel: 0
  354. },
  355. 'swap': {
  356. title: Messages.strSystemSwap,
  357. series: [{
  358. label: Messages.strCachedSwap,
  359. fill: true
  360. }, {
  361. label: Messages.strUsedSwap,
  362. fill: true
  363. }, {
  364. label: Messages.strFreeSwap,
  365. fill: true
  366. }],
  367. nodes: [{
  368. dataPoints: [{
  369. type: 'memory',
  370. name: 'SwapCached'
  371. }],
  372. valueDivisor: 1024
  373. }, {
  374. dataPoints: [{
  375. type: 'memory',
  376. name: 'SwapUsed'
  377. }],
  378. valueDivisor: 1024
  379. }, {
  380. dataPoints: [{
  381. type: 'memory',
  382. name: 'SwapFree'
  383. }],
  384. valueDivisor: 1024
  385. }],
  386. maxYLabel: 0
  387. }
  388. });
  389. break;
  390. case 'SunOS':
  391. $.extend(presetCharts, {
  392. 'cpu': {
  393. title: Messages.strSystemCPUUsage,
  394. series: [{
  395. label: Messages.strAverageLoad
  396. }],
  397. nodes: [{
  398. dataPoints: [{
  399. type: 'cpu',
  400. name: 'loadavg'
  401. }]
  402. }],
  403. maxYLabel: 0
  404. },
  405. 'memory': {
  406. title: Messages.strSystemMemory,
  407. series: [{
  408. label: Messages.strUsedMemory,
  409. fill: true
  410. }, {
  411. label: Messages.strFreeMemory,
  412. fill: true
  413. }],
  414. nodes: [{
  415. dataPoints: [{
  416. type: 'memory',
  417. name: 'MemUsed'
  418. }],
  419. valueDivisor: 1024
  420. }, {
  421. dataPoints: [{
  422. type: 'memory',
  423. name: 'MemFree'
  424. }],
  425. valueDivisor: 1024
  426. }],
  427. maxYLabel: 0
  428. },
  429. 'swap': {
  430. title: Messages.strSystemSwap,
  431. series: [{
  432. label: Messages.strUsedSwap,
  433. fill: true
  434. }, {
  435. label: Messages.strFreeSwap,
  436. fill: true
  437. }],
  438. nodes: [{
  439. dataPoints: [{
  440. type: 'memory',
  441. name: 'SwapUsed'
  442. }],
  443. valueDivisor: 1024
  444. }, {
  445. dataPoints: [{
  446. type: 'memory',
  447. name: 'SwapFree'
  448. }],
  449. valueDivisor: 1024
  450. }],
  451. maxYLabel: 0
  452. }
  453. });
  454. break;
  455. } // Default setting for the chart grid
  456. var defaultChartGrid = {
  457. 'c0': {
  458. title: Messages.strQuestions,
  459. series: [{
  460. label: Messages.strQuestions
  461. }],
  462. nodes: [{
  463. dataPoints: [{
  464. type: 'statusvar',
  465. name: 'Questions'
  466. }],
  467. display: 'differential'
  468. }],
  469. maxYLabel: 0
  470. },
  471. 'c1': {
  472. title: Messages.strChartConnectionsTitle,
  473. series: [{
  474. label: Messages.strConnections
  475. }, {
  476. label: Messages.strProcesses
  477. }],
  478. nodes: [{
  479. dataPoints: [{
  480. type: 'statusvar',
  481. name: 'Connections'
  482. }],
  483. display: 'differential'
  484. }, {
  485. dataPoints: [{
  486. type: 'proc',
  487. name: 'processes'
  488. }]
  489. }],
  490. maxYLabel: 0
  491. },
  492. 'c2': {
  493. title: Messages.strTraffic,
  494. series: [{
  495. label: Messages.strBytesSent
  496. }, {
  497. label: Messages.strBytesReceived
  498. }],
  499. nodes: [{
  500. dataPoints: [{
  501. type: 'statusvar',
  502. name: 'Bytes_sent'
  503. }],
  504. display: 'differential',
  505. valueDivisor: 1024
  506. }, {
  507. dataPoints: [{
  508. type: 'statusvar',
  509. name: 'Bytes_received'
  510. }],
  511. display: 'differential',
  512. valueDivisor: 1024
  513. }],
  514. maxYLabel: 0
  515. }
  516. }; // Server is localhost => We can add cpu/memory/swap to the default chart
  517. if (serverDbIsLocal && typeof presetCharts.cpu !== 'undefined') {
  518. defaultChartGrid.c3 = presetCharts.cpu;
  519. defaultChartGrid.c4 = presetCharts.memory;
  520. defaultChartGrid.c5 = presetCharts.swap;
  521. }
  522. $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').on('click', function (event) {
  523. event.preventDefault();
  524. editMode = !editMode;
  525. if ($(this).attr('href') === '#endChartEditMode') {
  526. editMode = false;
  527. }
  528. $('a[href="#endChartEditMode"]').toggle(editMode);
  529. if (editMode) {
  530. // Close the settings popup
  531. $('div.popupContent').hide().removeClass('openedPopup');
  532. $('#chartGrid').sortableTable({
  533. ignoreRect: {
  534. top: 8,
  535. left: chartSize.width - 63,
  536. width: 54,
  537. height: 24
  538. }
  539. });
  540. } else {
  541. $('#chartGrid').sortableTable('destroy');
  542. }
  543. saveMonitor(); // Save settings
  544. return false;
  545. }); // global settings
  546. $('div.popupContent select[name="chartColumns"]').on('change', function () {
  547. monitorSettings.columns = parseInt(this.value, 10);
  548. calculateChartSize(); // Empty cells should keep their size so you can drop onto them
  549. $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
  550. $('#chartGrid').find('.monitorChart').css({
  551. width: chartSize.width + 'px',
  552. height: chartSize.height + 'px'
  553. });
  554. /* Reorder all charts that it fills all column cells */
  555. var numColumns;
  556. var $tr = $('#chartGrid').find('tr').first();
  557. var tempManageCols = function tempManageCols() {
  558. if (numColumns > monitorSettings.columns) {
  559. if ($tr.next().length === 0) {
  560. $tr.after('<tr></tr>');
  561. }
  562. $tr.next().prepend($(this));
  563. }
  564. numColumns++;
  565. };
  566. var tempAddCol = function tempAddCol() {
  567. if ($(this).next().length !== 0) {
  568. $(this).append($(this).next().find('td').first());
  569. }
  570. };
  571. while ($tr.length !== 0) {
  572. numColumns = 1; // To many cells in one row => put into next row
  573. $tr.find('td').each(tempManageCols); // To little cells in one row => for each cell to little,
  574. // move all cells backwards by 1
  575. if ($tr.next().length > 0) {
  576. var cnt = monitorSettings.columns - $tr.find('td').length;
  577. for (var i = 0; i < cnt; i++) {
  578. $tr.append($tr.next().find('td').first());
  579. $tr.nextAll().each(tempAddCol);
  580. }
  581. }
  582. $tr = $tr.next();
  583. }
  584. if (monitorSettings.gridMaxPoints === 'auto') {
  585. runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12);
  586. }
  587. runtime.xmin = new Date().getTime() - serverTimeDiff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
  588. runtime.xmax = new Date().getTime() - serverTimeDiff + monitorSettings.gridRefresh;
  589. if (editMode) {
  590. $('#chartGrid').sortableTable('refresh');
  591. }
  592. refreshChartGrid();
  593. saveMonitor(); // Save settings
  594. });
  595. $('div.popupContent select[name="gridChartRefresh"]').on('change', function () {
  596. monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000;
  597. clearTimeout(runtime.refreshTimeout);
  598. if (runtime.refreshRequest) {
  599. runtime.refreshRequest.abort();
  600. }
  601. runtime.xmin = new Date().getTime() - serverTimeDiff - runtime.gridMaxPoints * monitorSettings.gridRefresh; // fixing chart shift towards left on refresh rate change
  602. // runtime.xmax = new Date().getTime() - serverTimeDiff + monitorSettings.gridRefresh;
  603. runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
  604. saveMonitor(); // Save settings
  605. });
  606. $('a[href="#addNewChart"]').on('click', function (event) {
  607. event.preventDefault();
  608. var dlgButtons = {};
  609. dlgButtons[Messages.strAddChart] = function () {
  610. var type = $('input[name="chartType"]:checked').val();
  611. if (type === 'preset') {
  612. newChart = presetCharts[$('#addChartDialog').find('select[name="presetCharts"]').prop('value')];
  613. } else {
  614. // If user builds their own chart, it's being set/updated
  615. // each time they add a series
  616. // So here we only warn if they didn't add a series yet
  617. if (!newChart || !newChart.nodes || newChart.nodes.length === 0) {
  618. alert(Messages.strAddOneSeriesWarning);
  619. return;
  620. }
  621. }
  622. newChart.title = $('input[name="chartTitle"]').val(); // Add a cloned object to the chart grid
  623. addChart($.extend(true, {}, newChart));
  624. newChart = null;
  625. saveMonitor(); // Save settings
  626. $(this).dialog('close');
  627. };
  628. dlgButtons[Messages.strClose] = function () {
  629. newChart = null;
  630. $('span#clearSeriesLink').hide();
  631. $('#seriesPreview').html('');
  632. $(this).dialog('close');
  633. };
  634. var $presetList = $('#addChartDialog').find('select[name="presetCharts"]');
  635. if ($presetList.html().length === 0) {
  636. $.each(presetCharts, function (key, value) {
  637. $presetList.append('<option value="' + key + '">' + value.title + '</option>');
  638. });
  639. $presetList.on('change', function () {
  640. $('input[name="chartTitle"]').val($presetList.find(':selected').text());
  641. $('#chartPreset').prop('checked', true);
  642. });
  643. $('#chartPreset').on('click', function () {
  644. $('input[name="chartTitle"]').val($presetList.find(':selected').text());
  645. });
  646. $('#chartStatusVar').on('click', function () {
  647. $('input[name="chartTitle"]').val($('#chartSeries').find(':selected').text().replace(/_/g, ' '));
  648. });
  649. $('#chartSeries').on('change', function () {
  650. $('input[name="chartTitle"]').val($('#chartSeries').find(':selected').text().replace(/_/g, ' '));
  651. });
  652. }
  653. $('#addChartDialog').dialog({
  654. width: 'auto',
  655. height: 'auto',
  656. buttons: dlgButtons
  657. });
  658. $('#seriesPreview').html('<i>' + Messages.strNone + '</i>');
  659. return false;
  660. });
  661. $('a[href="#exportMonitorConfig"]').on('click', function (event) {
  662. event.preventDefault();
  663. var gridCopy = {};
  664. $.each(runtime.charts, function (key, elem) {
  665. gridCopy[key] = {};
  666. gridCopy[key].nodes = elem.nodes;
  667. gridCopy[key].series = elem.series;
  668. gridCopy[key].settings = elem.settings;
  669. gridCopy[key].title = elem.title;
  670. gridCopy[key].maxYLabel = elem.maxYLabel;
  671. });
  672. var exportData = {
  673. monitorCharts: gridCopy,
  674. monitorSettings: monitorSettings
  675. };
  676. var blob = new Blob([JSON.stringify(exportData)], {
  677. type: 'application/octet-stream'
  678. });
  679. var url = null;
  680. var fileName = 'monitor-config.json';
  681. if (window.navigator && window.navigator.msSaveOrOpenBlob) {
  682. window.navigator.msSaveOrOpenBlob(blob, fileName);
  683. } else {
  684. url = URL.createObjectURL(blob);
  685. window.location.href = url;
  686. }
  687. setTimeout(function () {
  688. // For some browsers it is necessary to delay revoking the ObjectURL
  689. if (url !== null) {
  690. window.URL.revokeObjectURL(url);
  691. }
  692. url = undefined;
  693. blob = undefined;
  694. }, 100);
  695. });
  696. $('a[href="#importMonitorConfig"]').on('click', function (event) {
  697. event.preventDefault();
  698. $('#emptyDialog').dialog({
  699. title: Messages.strImportDialogTitle
  700. });
  701. $('#emptyDialog').html(Messages.strImportDialogMessage + ':<br><form>' + '<input type="file" name="file" id="import_file"> </form>');
  702. var dlgBtns = {};
  703. dlgBtns[Messages.strImport] = function () {
  704. var input = $('#emptyDialog').find('#import_file')[0];
  705. var reader = new FileReader();
  706. reader.onerror = function (event) {
  707. alert(Messages.strFailedParsingConfig + '\n' + event.target.error.code);
  708. };
  709. reader.onload = function (e) {
  710. var data = e.target.result;
  711. var json = null; // Try loading config
  712. try {
  713. json = JSON.parse(data);
  714. } catch (err) {
  715. alert(Messages.strFailedParsingConfig);
  716. $('#emptyDialog').dialog('close');
  717. return;
  718. } // Basic check, is this a monitor config json?
  719. if (!json || !json.monitorCharts || !json.monitorCharts) {
  720. alert(Messages.strFailedParsingConfig);
  721. $('#emptyDialog').dialog('close');
  722. return;
  723. } // If json ok, try applying config
  724. try {
  725. if (isStorageSupported('localStorage')) {
  726. window.localStorage.monitorCharts = JSON.stringify(json.monitorCharts);
  727. window.localStorage.monitorSettings = JSON.stringify(json.monitorSettings);
  728. }
  729. rebuildGrid();
  730. } catch (err) {
  731. alert(Messages.strFailedBuildingGrid); // If an exception is thrown, load default again
  732. if (isStorageSupported('localStorage')) {
  733. window.localStorage.removeItem('monitorCharts');
  734. window.localStorage.removeItem('monitorSettings');
  735. }
  736. rebuildGrid();
  737. }
  738. $('#emptyDialog').dialog('close');
  739. };
  740. reader.readAsText(input.files[0]);
  741. };
  742. dlgBtns[Messages.strCancel] = function () {
  743. $(this).dialog('close');
  744. };
  745. $('#emptyDialog').dialog({
  746. width: 'auto',
  747. height: 'auto',
  748. buttons: dlgBtns
  749. });
  750. });
  751. $('a[href="#clearMonitorConfig"]').on('click', function (event) {
  752. event.preventDefault();
  753. if (isStorageSupported('localStorage')) {
  754. window.localStorage.removeItem('monitorCharts');
  755. window.localStorage.removeItem('monitorSettings');
  756. window.localStorage.removeItem('monitorVersion');
  757. }
  758. $(this).hide();
  759. rebuildGrid();
  760. });
  761. $('a[href="#pauseCharts"]').on('click', function (event) {
  762. event.preventDefault();
  763. runtime.redrawCharts = !runtime.redrawCharts;
  764. if (!runtime.redrawCharts) {
  765. $(this).html(Functions.getImage('play') + Messages.strResumeMonitor);
  766. } else {
  767. $(this).html(Functions.getImage('pause') + Messages.strPauseMonitor);
  768. if (!runtime.charts) {
  769. initGrid();
  770. $('a[href="#settingsPopup"]').show();
  771. }
  772. }
  773. return false;
  774. });
  775. $('a[href="#monitorInstructionsDialog"]').on('click', function (event) {
  776. event.preventDefault();
  777. var $dialog = $('#monitorInstructionsDialog');
  778. var dlgBtns = {};
  779. dlgBtns[Messages.strClose] = function () {
  780. $(this).dialog('close');
  781. };
  782. $dialog.dialog({
  783. width: '60%',
  784. height: 'auto',
  785. buttons: dlgBtns
  786. }).find('img.ajaxIcon').show();
  787. var loadLogVars = function loadLogVars(getvars) {
  788. var vars = {
  789. 'ajax_request': true,
  790. 'server': CommonParams.get('server')
  791. };
  792. if (getvars) {
  793. $.extend(vars, getvars);
  794. }
  795. $.post('index.php?route=/server/status/monitor/log-vars', vars, function (data) {
  796. var logVars;
  797. if (typeof data !== 'undefined' && data.success === true) {
  798. logVars = data.message;
  799. } else {
  800. return serverResponseError();
  801. }
  802. var icon = Functions.getImage('s_success');
  803. var msg = '';
  804. var str = '';
  805. if (logVars.general_log === 'ON') {
  806. if (logVars.slow_query_log === 'ON') {
  807. msg = Messages.strBothLogOn;
  808. } else {
  809. msg = Messages.strGenLogOn;
  810. }
  811. }
  812. if (msg.length === 0 && logVars.slow_query_log === 'ON') {
  813. msg = Messages.strSlowLogOn;
  814. }
  815. if (msg.length === 0) {
  816. icon = Functions.getImage('s_error');
  817. msg = Messages.strBothLogOff;
  818. }
  819. str = '<b>' + Messages.strCurrentSettings + '</b><br><div class="smallIndent">';
  820. str += icon + msg + '<br>';
  821. if (logVars.log_output !== 'TABLE') {
  822. str += Functions.getImage('s_error') + ' ' + Messages.strLogOutNotTable + '<br>';
  823. } else {
  824. str += Functions.getImage('s_success') + ' ' + Messages.strLogOutIsTable + '<br>';
  825. }
  826. if (logVars.slow_query_log === 'ON') {
  827. if (logVars.long_query_time > 2) {
  828. str += Functions.getImage('s_attention') + ' ';
  829. str += Functions.sprintf(Messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
  830. str += '<br>';
  831. }
  832. if (logVars.long_query_time < 2) {
  833. str += Functions.getImage('s_success') + ' ';
  834. str += Functions.sprintf(Messages.strLongQueryTimeSet, logVars.long_query_time);
  835. str += '<br>';
  836. }
  837. }
  838. str += '</div>';
  839. if (isSuperUser) {
  840. str += '<p></p><b>' + Messages.strChangeSettings + '</b>';
  841. str += '<div class="smallIndent">';
  842. str += Messages.strSettingsAppliedGlobal + '<br>';
  843. var varValue = 'TABLE';
  844. if (logVars.log_output === 'TABLE') {
  845. varValue = 'FILE';
  846. }
  847. str += '- <a class="set" href="#log_output-' + varValue + '">';
  848. str += Functions.sprintf(Messages.strSetLogOutput, varValue);
  849. str += ' </a><br>';
  850. if (logVars.general_log !== 'ON') {
  851. str += '- <a class="set" href="#general_log-ON">';
  852. str += Functions.sprintf(Messages.strEnableVar, 'general_log');
  853. str += ' </a><br>';
  854. } else {
  855. str += '- <a class="set" href="#general_log-OFF">';
  856. str += Functions.sprintf(Messages.strDisableVar, 'general_log');
  857. str += ' </a><br>';
  858. }
  859. if (logVars.slow_query_log !== 'ON') {
  860. str += '- <a class="set" href="#slow_query_log-ON">';
  861. str += Functions.sprintf(Messages.strEnableVar, 'slow_query_log');
  862. str += ' </a><br>';
  863. } else {
  864. str += '- <a class="set" href="#slow_query_log-OFF">';
  865. str += Functions.sprintf(Messages.strDisableVar, 'slow_query_log');
  866. str += ' </a><br>';
  867. }
  868. varValue = 5;
  869. if (logVars.long_query_time > 2) {
  870. varValue = 1;
  871. }
  872. str += '- <a class="set" href="#long_query_time-' + varValue + '">';
  873. str += Functions.sprintf(Messages.setSetLongQueryTime, varValue);
  874. str += ' </a><br>';
  875. } else {
  876. str += Messages.strNoSuperUser + '<br>';
  877. }
  878. str += '</div>';
  879. $dialog.find('div.monitorUse').toggle(logVars.log_output === 'TABLE' && (logVars.slow_query_log === 'ON' || logVars.general_log === 'ON'));
  880. $dialog.find('div.ajaxContent').html(str);
  881. $dialog.find('img.ajaxIcon').hide();
  882. $dialog.find('a.set').on('click', function () {
  883. var nameValue = $(this).attr('href').split('-');
  884. loadLogVars({
  885. varName: nameValue[0].substr(1),
  886. varValue: nameValue[1]
  887. });
  888. $dialog.find('img.ajaxIcon').show();
  889. });
  890. });
  891. };
  892. loadLogVars();
  893. return false;
  894. });
  895. $('input[name="chartType"]').on('change', function () {
  896. $('#chartVariableSettings').toggle(this.checked && this.value === 'variable');
  897. var title = $('input[name="chartTitle"]').val();
  898. if (title === Messages.strChartTitle || title === $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()) {
  899. $('input[name="chartTitle"]').data('lastRadio', $(this).attr('id')).val($('label[for="' + $(this).attr('id') + '"]').text());
  900. }
  901. });
  902. $('input[name="useDivisor"]').on('change', function () {
  903. $('span.divisorInput').toggle(this.checked);
  904. });
  905. $('input[name="useUnit"]').on('change', function () {
  906. $('span.unitInput').toggle(this.checked);
  907. });
  908. $('select[name="varChartList"]').on('change', function () {
  909. if (this.selectedIndex !== 0) {
  910. $('#variableInput').val(this.value);
  911. }
  912. });
  913. $('a[href="#kibDivisor"]').on('click', function (event) {
  914. event.preventDefault();
  915. $('input[name="valueDivisor"]').val(1024);
  916. $('input[name="valueUnit"]').val(Messages.strKiB);
  917. $('span.unitInput').toggle(true);
  918. $('input[name="useUnit"]').prop('checked', true);
  919. return false;
  920. });
  921. $('a[href="#mibDivisor"]').on('click', function (event) {
  922. event.preventDefault();
  923. $('input[name="valueDivisor"]').val(1024 * 1024);
  924. $('input[name="valueUnit"]').val(Messages.strMiB);
  925. $('span.unitInput').toggle(true);
  926. $('input[name="useUnit"]').prop('checked', true);
  927. return false;
  928. });
  929. $('a[href="#submitClearSeries"]').on('click', function (event) {
  930. event.preventDefault();
  931. $('#seriesPreview').html('<i>' + Messages.strNone + '</i>');
  932. newChart = null;
  933. $('#clearSeriesLink').hide();
  934. });
  935. $('a[href="#submitAddSeries"]').on('click', function (event) {
  936. event.preventDefault();
  937. if ($('#variableInput').val() === '') {
  938. return false;
  939. }
  940. if (newChart === null) {
  941. $('#seriesPreview').html('');
  942. newChart = {
  943. title: $('input[name="chartTitle"]').val(),
  944. nodes: [],
  945. series: [],
  946. maxYLabel: 0
  947. };
  948. }
  949. var serie = {
  950. dataPoints: [{
  951. type: 'statusvar',
  952. name: $('#variableInput').val()
  953. }],
  954. display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
  955. };
  956. if (serie.dataPoints[0].name === 'Processes') {
  957. serie.dataPoints[0].type = 'proc';
  958. }
  959. if ($('input[name="useDivisor"]').prop('checked')) {
  960. serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
  961. }
  962. if ($('input[name="useUnit"]').prop('checked')) {
  963. serie.unit = $('input[name="valueUnit"]').val();
  964. }
  965. var str = serie.display === 'differential' ? ', ' + Messages.strDifferential : '';
  966. str += serie.valueDivisor ? ', ' + Functions.sprintf(Messages.strDividedBy, serie.valueDivisor) : '';
  967. str += serie.unit ? ', ' + Messages.strUnit + ': ' + serie.unit : '';
  968. var newSeries = {
  969. label: $('#variableInput').val().replace(/_/g, ' ')
  970. };
  971. newChart.series.push(newSeries);
  972. $('#seriesPreview').append('- ' + Functions.escapeHtml(newSeries.label + str) + '<br>');
  973. newChart.nodes.push(serie);
  974. $('#variableInput').val('');
  975. $('input[name="differentialValue"]').prop('checked', true);
  976. $('input[name="useDivisor"]').prop('checked', false);
  977. $('input[name="useUnit"]').prop('checked', false);
  978. $('input[name="useDivisor"]').trigger('change');
  979. $('input[name="useUnit"]').trigger('change');
  980. $('select[name="varChartList"]').get(0).selectedIndex = 0;
  981. $('#clearSeriesLink').show();
  982. return false;
  983. });
  984. $('#variableInput').autocomplete({
  985. source: variableNames
  986. });
  987. /* Initializes the monitor, called only once */
  988. function initGrid() {
  989. var i;
  990. /* Apply default values & config */
  991. if (isStorageSupported('localStorage')) {
  992. if (typeof window.localStorage.monitorCharts !== 'undefined') {
  993. runtime.charts = JSON.parse(window.localStorage.monitorCharts);
  994. }
  995. if (typeof window.localStorage.monitorSettings !== 'undefined') {
  996. monitorSettings = JSON.parse(window.localStorage.monitorSettings);
  997. }
  998. $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
  999. if (runtime.charts !== null && typeof window.localStorage.monitorVersion !== 'undefined' && monitorProtocolVersion !== window.localStorage.monitorVersion) {
  1000. $('#emptyDialog').dialog({
  1001. title: Messages.strIncompatibleMonitorConfig
  1002. });
  1003. $('#emptyDialog').html(Messages.strIncompatibleMonitorConfigDescription);
  1004. var dlgBtns = {};
  1005. dlgBtns[Messages.strClose] = function () {
  1006. $(this).dialog('close');
  1007. };
  1008. $('#emptyDialog').dialog({
  1009. width: 400,
  1010. buttons: dlgBtns
  1011. });
  1012. }
  1013. }
  1014. if (runtime.charts === null) {
  1015. runtime.charts = defaultChartGrid;
  1016. }
  1017. if (monitorSettings === null) {
  1018. monitorSettings = defaultMonitorSettings;
  1019. }
  1020. $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
  1021. $('select[name="chartColumns"]').val(monitorSettings.columns);
  1022. if (monitorSettings.gridMaxPoints === 'auto') {
  1023. runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
  1024. } else {
  1025. runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
  1026. }
  1027. runtime.xmin = new Date().getTime() - serverTimeDiff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
  1028. runtime.xmax = new Date().getTime() - serverTimeDiff + monitorSettings.gridRefresh;
  1029. /* Calculate how much spacing there is between each chart */
  1030. $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
  1031. chartSpacing = {
  1032. width: $('#chartGrid').find('td').eq(1).offset().left - $('#chartGrid').find('td').eq(0).offset().left,
  1033. height: $('#chartGrid').find('tr').eq(1).find('td').eq(1).offset().top - $('#chartGrid').find('tr').eq(0).find('td').eq(0).offset().top
  1034. };
  1035. $('#chartGrid').html('');
  1036. /* Add all charts - in correct order */
  1037. var keys = [];
  1038. $.each(runtime.charts, function (key) {
  1039. keys.push(key);
  1040. });
  1041. keys.sort();
  1042. for (i = 0; i < keys.length; i++) {
  1043. addChart(runtime.charts[keys[i]], true);
  1044. }
  1045. /* Fill in missing cells */
  1046. var numCharts = $('#chartGrid').find('.monitorChart').length;
  1047. var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
  1048. for (i = 0; i < numMissingCells; i++) {
  1049. $('#chartGrid').find('tr').last().append('<td></td>');
  1050. } // Empty cells should keep their size so you can drop onto them
  1051. calculateChartSize();
  1052. $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
  1053. buildRequiredDataList();
  1054. refreshChartGrid();
  1055. }
  1056. /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
  1057. * data from each chart and restores it after the monitor is initialized again */
  1058. function rebuildGrid() {
  1059. var oldData = null;
  1060. if (runtime.charts) {
  1061. oldData = {};
  1062. $.each(runtime.charts, function (key, chartObj) {
  1063. for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
  1064. oldData[chartObj.nodes[i].dataPoint] = [];
  1065. for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
  1066. oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
  1067. }
  1068. }
  1069. });
  1070. }
  1071. destroyGrid();
  1072. initGrid();
  1073. }
  1074. /* Calculates the dynamic chart size that depends on the column width */
  1075. function calculateChartSize() {
  1076. var panelWidth;
  1077. if ($('body').height() > $(window).height()) {
  1078. // has vertical scroll bar
  1079. panelWidth = $('#logTable').innerWidth();
  1080. } else {
  1081. panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
  1082. }
  1083. var wdt = panelWidth;
  1084. var windowWidth = $(window).width();
  1085. if (windowWidth > 768) {
  1086. wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
  1087. }
  1088. chartSize = {
  1089. width: Math.floor(wdt),
  1090. height: Math.floor(0.75 * wdt)
  1091. };
  1092. }
  1093. /* Adds a chart to the chart grid */
  1094. function addChart(chartObj, initialize) {
  1095. var i;
  1096. var settings = {
  1097. title: Functions.escapeHtml(chartObj.title),
  1098. grid: {
  1099. drawBorder: false,
  1100. shadow: false,
  1101. background: 'rgba(0,0,0,0)'
  1102. },
  1103. axes: {
  1104. xaxis: {
  1105. renderer: $.jqplot.DateAxisRenderer,
  1106. tickOptions: {
  1107. formatString: '%H:%M:%S',
  1108. showGridline: false
  1109. },
  1110. min: runtime.xmin,
  1111. max: runtime.xmax
  1112. },
  1113. yaxis: {
  1114. min: 0,
  1115. max: 100,
  1116. tickInterval: 20
  1117. }
  1118. },
  1119. seriesDefaults: {
  1120. rendererOptions: {
  1121. smooth: true
  1122. },
  1123. showLine: true,
  1124. lineWidth: 2,
  1125. markerOptions: {
  1126. size: 6
  1127. }
  1128. },
  1129. highlighter: {
  1130. show: true
  1131. }
  1132. };
  1133. if (settings.title === Messages.strSystemCPUUsage || settings.title === Messages.strQueryCacheEfficiency) {
  1134. settings.axes.yaxis.tickOptions = {
  1135. formatString: '%d %%'
  1136. };
  1137. } else if (settings.title === Messages.strSystemMemory || settings.title === Messages.strSystemSwap) {
  1138. settings.stackSeries = true;
  1139. settings.axes.yaxis.tickOptions = {
  1140. formatter: $.jqplot.byteFormatter(2) // MiB
  1141. };
  1142. } else if (settings.title === Messages.strTraffic) {
  1143. settings.axes.yaxis.tickOptions = {
  1144. formatter: $.jqplot.byteFormatter(1) // KiB
  1145. };
  1146. } else if (settings.title === Messages.strQuestions || settings.title === Messages.strConnections) {
  1147. settings.axes.yaxis.tickOptions = {
  1148. formatter: function formatter(format, val) {
  1149. if (Math.abs(val) >= 1000000) {
  1150. return $.jqplot.sprintf('%.3g M', val / 1000000);
  1151. } else if (Math.abs(val) >= 1000) {
  1152. return $.jqplot.sprintf('%.3g k', val / 1000);
  1153. } else {
  1154. return $.jqplot.sprintf('%d', val);
  1155. }
  1156. }
  1157. };
  1158. }
  1159. settings.series = chartObj.series;
  1160. if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
  1161. var numCharts = $('#chartGrid').find('.monitorChart').length;
  1162. if (numCharts === 0 || numCharts % monitorSettings.columns === 0) {
  1163. $('#chartGrid').append('<tr></tr>');
  1164. }
  1165. if (!chartSize) {
  1166. calculateChartSize();
  1167. }
  1168. $('#chartGrid').find('tr').last().append('<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' + '<div class="ui-state-default monitorChart"' + ' id="gridchart' + runtime.chartAI + '"' + ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' + '</div></td>');
  1169. } // Set series' data as [0,0], smooth lines won't plot with data array having null values.
  1170. // also chart won't plot initially with no data and data comes on refreshChartGrid()
  1171. var series = [];
  1172. for (i in chartObj.series) {
  1173. series.push([[0, 0]]);
  1174. }
  1175. var tempTooltipContentEditor = function tempTooltipContentEditor(str, seriesIndex, pointIndex, plot) {
  1176. var j; // TODO: move style to theme CSS
  1177. var tooltipHtml = '<div id="tooltip_editor">'; // x value i.e. time
  1178. var timeValue = str.split(',')[0];
  1179. var seriesValue;
  1180. tooltipHtml += 'Time: ' + timeValue;
  1181. tooltipHtml += '<span id="tooltip_font">'; // Add y values to the tooltip per series
  1182. for (j in plot.series) {
  1183. // get y value if present
  1184. if (plot.series[j].data.length > pointIndex) {
  1185. seriesValue = plot.series[j].data[pointIndex][1];
  1186. } else {
  1187. return;
  1188. }
  1189. var seriesLabel = plot.series[j].label;
  1190. var seriesColor = plot.series[j].color; // format y value
  1191. if (plot.series[0]._yaxis.tickOptions.formatter) {
  1192. // eslint-disable-line no-underscore-dangle
  1193. // using formatter function
  1194. // eslint-disable-next-line no-underscore-dangle
  1195. seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
  1196. } else if (plot.series[0]._yaxis.tickOptions.formatString) {
  1197. // eslint-disable-line no-underscore-dangle
  1198. // using format string
  1199. // eslint-disable-next-line no-underscore-dangle
  1200. seriesValue = Functions.sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
  1201. }
  1202. tooltipHtml += '<br><span style="color:' + seriesColor + '">' + seriesLabel + ': ' + seriesValue + '</span>';
  1203. }
  1204. tooltipHtml += '</span></div>';
  1205. return tooltipHtml;
  1206. }; // set Tooltip for each series
  1207. for (i in settings.series) {
  1208. settings.series[i].highlighter = {
  1209. show: true,
  1210. tooltipContentEditor: tempTooltipContentEditor
  1211. };
  1212. }
  1213. chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings); // remove [0,0] after plotting
  1214. for (i in chartObj.chart.series) {
  1215. chartObj.chart.series[i].data.shift();
  1216. }
  1217. var $legend = $('<div></div>').css('padding', '0.5em');
  1218. for (i in chartObj.chart.series) {
  1219. $legend.append($('<div></div>').append($('<div>').css({
  1220. width: '1em',
  1221. height: '1em',
  1222. background: chartObj.chart.seriesColors[i]
  1223. }).addClass('floatleft')).append($('<div>').text(chartObj.chart.series[i].label).addClass('floatleft')).append($('<div class="clearfloat">')).addClass('floatleft'));
  1224. }
  1225. $('#gridchart' + runtime.chartAI).parent().append($legend);
  1226. if (initialize !== true) {
  1227. runtime.charts['c' + runtime.chartAI] = chartObj;
  1228. buildRequiredDataList();
  1229. } // time span selection
  1230. $('#gridchart' + runtime.chartAI).on('jqplotMouseDown', function (ev, gridpos, datapos) {
  1231. drawTimeSpan = true;
  1232. selectionTimeDiff.push(datapos.xaxis);
  1233. if ($('#selection_box').length) {
  1234. $('#selection_box').remove();
  1235. }
  1236. var selectionBox = $('<div id="selection_box" >');
  1237. $(document.body).append(selectionBox);
  1238. selectionStartX = ev.pageX;
  1239. selectionStartY = ev.pageY;
  1240. selectionBox.attr({
  1241. id: 'selection_box'
  1242. }).css({
  1243. top: selectionStartY - gridpos.y,
  1244. left: selectionStartX
  1245. }).fadeIn();
  1246. });
  1247. $('#gridchart' + runtime.chartAI).on('jqplotMouseUp', function (ev, gridpos, datapos) {
  1248. if (!drawTimeSpan || editMode) {
  1249. return;
  1250. }
  1251. selectionTimeDiff.push(datapos.xaxis);
  1252. if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
  1253. selectionTimeDiff = [];
  1254. return;
  1255. } // get date from timestamp
  1256. var min = new Date(Math.ceil(selectionTimeDiff[0]));
  1257. var max = new Date(Math.ceil(selectionTimeDiff[1]));
  1258. getLogAnalyseDialog(min, max);
  1259. selectionTimeDiff = [];
  1260. drawTimeSpan = false;
  1261. });
  1262. $('#gridchart' + runtime.chartAI).on('jqplotMouseMove', function (ev) {
  1263. if (!drawTimeSpan || editMode) {
  1264. return;
  1265. }
  1266. if (selectionStartX !== undefined) {
  1267. $('#selection_box').css({
  1268. width: Math.ceil(ev.pageX - selectionStartX)
  1269. }).fadeIn();
  1270. }
  1271. });
  1272. $('#gridchart' + runtime.chartAI).on('jqplotMouseLeave', function () {
  1273. drawTimeSpan = false;
  1274. });
  1275. $(document.body).on('mouseup', function () {
  1276. if ($('#selection_box').length) {
  1277. $('#selection_box').remove();
  1278. }
  1279. }); // Edit, Print icon only in edit mode
  1280. $('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
  1281. runtime.chartAI++;
  1282. }
  1283. function getLogAnalyseDialog(min, max) {
  1284. var $logAnalyseDialog = $('#logAnalyseDialog');
  1285. var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]');
  1286. var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]');
  1287. $dateStart.prop('readonly', true);
  1288. $dateEnd.prop('readonly', true);
  1289. var dlgBtns = {};
  1290. dlgBtns[Messages.strFromSlowLog] = function () {
  1291. loadLog('slow', min, max);
  1292. $(this).dialog('close');
  1293. };
  1294. dlgBtns[Messages.strFromGeneralLog] = function () {
  1295. loadLog('general', min, max);
  1296. $(this).dialog('close');
  1297. };
  1298. $logAnalyseDialog.dialog({
  1299. width: 'auto',
  1300. height: 'auto',
  1301. buttons: dlgBtns
  1302. });
  1303. Functions.addDatepicker($dateStart, 'datetime', {
  1304. showMillisec: false,
  1305. showMicrosec: false,
  1306. timeFormat: 'HH:mm:ss',
  1307. firstDay: firstDayOfCalendar
  1308. });
  1309. Functions.addDatepicker($dateEnd, 'datetime', {
  1310. showMillisec: false,
  1311. showMicrosec: false,
  1312. timeFormat: 'HH:mm:ss',
  1313. firstDay: firstDayOfCalendar
  1314. });
  1315. $dateStart.datepicker('setDate', min);
  1316. $dateEnd.datepicker('setDate', max);
  1317. }
  1318. function loadLog(type, min, max) {
  1319. var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min;
  1320. var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max;
  1321. loadLogStatistics({
  1322. src: type,
  1323. start: dateStart,
  1324. end: dateEnd,
  1325. removeVariables: $('#removeVariables').prop('checked'),
  1326. limitTypes: $('#limitTypes').prop('checked')
  1327. });
  1328. }
  1329. /* Called in regular intervals, this function updates the values of each chart in the grid */
  1330. function refreshChartGrid() {
  1331. /* Send to server */
  1332. runtime.refreshRequest = $.post('index.php?route=/server/status/monitor/chart', {
  1333. 'ajax_request': true,
  1334. 'requiredData': JSON.stringify(runtime.dataList),
  1335. 'server': CommonParams.get('server')
  1336. }, function (data) {
  1337. var chartData;
  1338. if (typeof data !== 'undefined' && data.success === true) {
  1339. chartData = data.message;
  1340. } else {
  1341. return serverResponseError();
  1342. }
  1343. var value;
  1344. var i = 0;
  1345. var diff;
  1346. var total;
  1347. /* Update values in each graph */
  1348. $.each(runtime.charts, function (orderKey, elem) {
  1349. var key = elem.chartID; // If newly added chart, we have no data for it yet
  1350. if (!chartData[key]) {
  1351. return;
  1352. } // Draw all series
  1353. total = 0;
  1354. for (var j = 0; j < elem.nodes.length; j++) {
  1355. // Update x-axis
  1356. if (i === 0 && j === 0) {
  1357. if (oldChartData === null) {
  1358. diff = chartData.x - runtime.xmax;
  1359. } else {
  1360. diff = parseInt(chartData.x - oldChartData.x, 10);
  1361. }
  1362. runtime.xmin += diff;
  1363. runtime.xmax += diff;
  1364. } // elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
  1365. /* Calculate y value */
  1366. // If transform function given, use it
  1367. if (elem.nodes[j].transformFn) {
  1368. value = chartValueTransform(elem.nodes[j].transformFn, chartData[key][j], // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
  1369. oldChartData === null || oldChartData[key] === null || oldChartData[key] === undefined ? null : oldChartData[key][j]); // Otherwise use original value and apply differential and divisor if given,
  1370. // in this case we have only one data point per series - located at chartData[key][j][0]
  1371. } else {
  1372. value = parseFloat(chartData[key][j][0].value);
  1373. if (elem.nodes[j].display === 'differential') {
  1374. if (oldChartData === null || oldChartData[key] === null || oldChartData[key] === undefined) {
  1375. continue;
  1376. }
  1377. value -= oldChartData[key][j][0].value;
  1378. }
  1379. if (elem.nodes[j].valueDivisor) {
  1380. value = value / elem.nodes[j].valueDivisor;
  1381. }
  1382. } // Set y value, if defined
  1383. if (value !== undefined) {
  1384. elem.chart.series[j].data.push([chartData.x, value]);
  1385. if (value > elem.maxYLabel) {
  1386. elem.maxYLabel = value;
  1387. } else if (elem.maxYLabel === 0) {
  1388. elem.maxYLabel = 0.5;
  1389. } // free old data point values and update maxYLabel
  1390. if (elem.chart.series[j].data.length > runtime.gridMaxPoints && elem.chart.series[j].data[0][0] < runtime.xmin) {
  1391. // check if the next freeable point is highest
  1392. if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
  1393. elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
  1394. elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
  1395. } else {
  1396. elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
  1397. }
  1398. }
  1399. if (elem.title === Messages.strSystemMemory || elem.title === Messages.strSystemSwap) {
  1400. total += value;
  1401. }
  1402. }
  1403. } // update chart options
  1404. // keep ticks number/positioning consistent while refreshrate changes
  1405. var tickInterval = (runtime.xmax - runtime.xmin) / 5;
  1406. elem.chart.axes.xaxis.ticks = [runtime.xmax - tickInterval * 4, runtime.xmax - tickInterval * 3, runtime.xmax - tickInterval * 2, runtime.xmax - tickInterval, runtime.xmax];
  1407. if (elem.title !== Messages.strSystemCPUUsage && elem.title !== Messages.strQueryCacheEfficiency && elem.title !== Messages.strSystemMemory && elem.title !== Messages.strSystemSwap) {
  1408. elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
  1409. elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
  1410. } else if (elem.title === Messages.strSystemMemory || elem.title === Messages.strSystemSwap) {
  1411. elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
  1412. elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
  1413. }
  1414. i++;
  1415. if (runtime.redrawCharts) {
  1416. elem.chart.replot();
  1417. }
  1418. });
  1419. oldChartData = chartData;
  1420. runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
  1421. });
  1422. }
  1423. /* Function to get highest plotted point's y label, to scale the chart,
  1424. * TODO: make jqplot's autoscale:true work here
  1425. */
  1426. function getMaxYLabel(dataValues) {
  1427. var maxY = dataValues[0][1];
  1428. $.each(dataValues, function (k, v) {
  1429. maxY = v[1] > maxY ? v[1] : maxY;
  1430. });
  1431. return maxY;
  1432. }
  1433. /* Function that supplies special value transform functions for chart values */
  1434. function chartValueTransform(name, cur, prev) {
  1435. switch (name) {
  1436. case 'cpu-linux':
  1437. if (prev === null) {
  1438. return undefined;
  1439. } // cur and prev are datapoint arrays, but containing
  1440. // only 1 element for cpu-linux
  1441. var newCur = cur[0];
  1442. var newPrev = prev[0];
  1443. var diffTotal = newCur.busy + newCur.idle - (newPrev.busy + newPrev.idle);
  1444. var diffIdle = newCur.idle - newPrev.idle;
  1445. return 100 * (diffTotal - diffIdle) / diffTotal;
  1446. // Query cache efficiency (%)
  1447. case 'qce':
  1448. if (prev === null) {
  1449. return undefined;
  1450. } // cur[0].value is Qcache_hits, cur[1].value is Com_select
  1451. var diffQHits = cur[0].value - prev[0].value; // No NaN please :-)
  1452. if (cur[1].value - prev[1].value === 0) {
  1453. return 0;
  1454. }
  1455. return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
  1456. // Query cache usage (%)
  1457. case 'qcu':
  1458. if (cur[1].value === 0) {
  1459. return 0;
  1460. } // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
  1461. return 100 - cur[0].value / cur[1].value * 100;
  1462. }
  1463. return undefined;
  1464. }
  1465. /* Build list of nodes that need to be retrieved from server.
  1466. * It creates something like a stripped down version of the runtime.charts object.
  1467. */
  1468. function buildRequiredDataList() {
  1469. runtime.dataList = {}; // Store an own id, because the property name is subject of reordering,
  1470. // thus destroying our mapping with runtime.charts <=> runtime.dataList
  1471. var chartID = 0;
  1472. $.each(runtime.charts, function (key, chart) {
  1473. runtime.dataList[chartID] = [];
  1474. for (var i = 0, l = chart.nodes.length; i < l; i++) {
  1475. runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
  1476. }
  1477. runtime.charts[key].chartID = chartID;
  1478. chartID++;
  1479. });
  1480. }
  1481. /* Loads the log table data, generates the table and handles the filters */
  1482. function loadLogStatistics(opts) {
  1483. var logRequest = null;
  1484. if (!opts.removeVariables) {
  1485. opts.removeVariables = false;
  1486. }
  1487. if (!opts.limitTypes) {
  1488. opts.limitTypes = false;
  1489. }
  1490. $('#emptyDialog').dialog({
  1491. title: Messages.strAnalysingLogsTitle
  1492. });
  1493. $('#emptyDialog').html(Messages.strAnalysingLogs + ' <img class="ajaxIcon" src="' + themeImagePath + 'ajax_clock_small.gif" alt="">');
  1494. var dlgBtns = {};
  1495. dlgBtns[Messages.strCancelRequest] = function () {
  1496. if (logRequest !== null) {
  1497. logRequest.abort();
  1498. }
  1499. $(this).dialog('close');
  1500. };
  1501. $('#emptyDialog').dialog({
  1502. width: 'auto',
  1503. height: 'auto',
  1504. buttons: dlgBtns
  1505. });
  1506. var url = 'index.php?route=/server/status/monitor/slow-log';
  1507. if (opts.src === 'general') {
  1508. url = 'index.php?route=/server/status/monitor/general-log';
  1509. }
  1510. logRequest = $.post(url, {
  1511. 'ajax_request': true,
  1512. 'time_start': Math.round(opts.start / 1000),
  1513. 'time_end': Math.round(opts.end / 1000),
  1514. 'removeVariables': opts.removeVariables,
  1515. 'limitTypes': opts.limitTypes,
  1516. 'server': CommonParams.get('server')
  1517. }, function (data) {
  1518. var logData;
  1519. var dlgBtns = {};
  1520. if (typeof data !== 'undefined' && data.success === true) {
  1521. logData = data.message;
  1522. } else {
  1523. return serverResponseError();
  1524. }
  1525. if (logData.rows.length === 0) {
  1526. $('#emptyDialog').dialog({
  1527. title: Messages.strNoDataFoundTitle
  1528. });
  1529. $('#emptyDialog').html('<p>' + Messages.strNoDataFound + '</p>');
  1530. dlgBtns[Messages.strClose] = function () {
  1531. $(this).dialog('close');
  1532. };
  1533. $('#emptyDialog').dialog('option', 'buttons', dlgBtns);
  1534. return;
  1535. }
  1536. runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
  1537. /* Show some stats in the dialog */
  1538. $('#emptyDialog').dialog({
  1539. title: Messages.strLoadingLogs
  1540. });
  1541. $('#emptyDialog').html('<p>' + Messages.strLogDataLoaded + '</p>');
  1542. $.each(logData.sum, function (key, value) {
  1543. var newKey = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
  1544. if (newKey === 'Total') {
  1545. newKey = '<b>' + newKey + '</b>';
  1546. }
  1547. $('#emptyDialog').append(newKey + ': ' + value + '<br>');
  1548. });
  1549. /* Add filter options if more than a bunch of rows there to filter */
  1550. if (logData.numRows > 12) {
  1551. $('#logTable').prepend('<fieldset id="logDataFilter">' + ' <legend>' + Messages.strFiltersForLogTable + '</legend>' + ' <div class="formelement">' + ' <label for="filterQueryText">' + Messages.strFilterByWordRegexp + '</label>' + ' <input name="filterQueryText" type="text" id="filterQueryText">' + ' </div>' + (logData.numRows > 250 ? ' <div class="formelement"><button class="btn btn-secondary" name="startFilterQueryText" id="startFilterQueryText">' + Messages.strFilter + '</button></div>' : '') + ' <div class="formelement">' + ' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1"> ' + ' <label for="noWHEREData"> ' + Messages.strIgnoreWhereAndGroup + '</label>' + ' </div' + '</fieldset>');
  1552. $('#noWHEREData').on('change', function () {
  1553. filterQueries(true);
  1554. });
  1555. if (logData.numRows > 250) {
  1556. $('#startFilterQueryText').on('click', filterQueries);
  1557. } else {
  1558. $('#filterQueryText').on('keyup', filterQueries);
  1559. }
  1560. }
  1561. dlgBtns[Messages.strJumpToTable] = function () {
  1562. $(this).dialog('close');
  1563. $(document).scrollTop($('#logTable').offset().top);
  1564. };
  1565. $('#emptyDialog').dialog('option', 'buttons', dlgBtns);
  1566. });
  1567. /* Handles the actions performed when the user uses any of the
  1568. * log table filters which are the filter by name and grouping
  1569. * with ignoring data in WHERE clauses
  1570. *
  1571. * @param boolean Should be true when the users enabled or disabled
  1572. * to group queries ignoring data in WHERE clauses
  1573. */
  1574. function filterQueries(varFilterChange) {
  1575. var textFilter;
  1576. var val = $('#filterQueryText').val();
  1577. if (val.length === 0) {
  1578. textFilter = null;
  1579. } else {
  1580. try {
  1581. textFilter = new RegExp(val, 'i');
  1582. $('#filterQueryText').removeClass('error');
  1583. } catch (e) {
  1584. if (e instanceof SyntaxError) {
  1585. $('#filterQueryText').addClass('error');
  1586. textFilter = null;
  1587. }
  1588. }
  1589. }
  1590. var rowSum = 0;
  1591. var totalSum = 0;
  1592. var i = 0;
  1593. var q;
  1594. var noVars = $('#noWHEREData').prop('checked');
  1595. var equalsFilter = /([^=]+)=(\d+|(('|"|).*?[^\\])\4((\s+)|$))/gi;
  1596. var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
  1597. var filteredQueries = {};
  1598. var filteredQueriesLines = {};
  1599. var hide = false;
  1600. var rowData;
  1601. var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
  1602. var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
  1603. var isSlowLog = opts.src === 'slow';
  1604. var columnSums = {}; // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
  1605. var countRow = function countRow(query, row) {
  1606. var cells = row.match(/<td>(.*?)<\/td>/gi);
  1607. if (!columnSums[query]) {
  1608. columnSums[query] = [0, 0, 0, 0];
  1609. } // lock_time and query_time and displayed in timespan format
  1610. columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
  1611. columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, '')); // rows_examind and rows_sent are just numbers
  1612. columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
  1613. columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
  1614. }; // We just assume the sql text is always in the second last column, and that the total count is right of it
  1615. $('#logTable').find('table tbody tr').children('td').eq(runtime.logDataCols.length - 2).each(function () {
  1616. var $t = $(this); // If query is a SELECT and user enabled or disabled to group
  1617. // queries ignoring data in where statements, we
  1618. // need to re-calculate the sums of each row
  1619. if (varFilterChange && $t.html().match(/^SELECT/i)) {
  1620. if (noVars) {
  1621. // Group on => Sum up identical columns, and hide all but 1
  1622. q = $t.text().replace(equalsFilter, '$1=...$6').trim();
  1623. q = q.replace(functionFilter, ' $1(...)'); // Js does not specify a limit on property name length,
  1624. // so we can abuse it as index :-)
  1625. if (filteredQueries[q]) {
  1626. filteredQueries[q] += parseInt($t.next().text(), 10);
  1627. totalSum += parseInt($t.next().text(), 10);
  1628. hide = true;
  1629. } else {
  1630. filteredQueries[q] = parseInt($t.next().text(), 10);
  1631. filteredQueriesLines[q] = i;
  1632. $t.text(q);
  1633. }
  1634. if (isSlowLog) {
  1635. countRow(q, $t.parent().html());
  1636. }
  1637. } else {
  1638. // Group off: Restore original columns
  1639. rowData = $t.parent().data('query'); // Restore SQL text
  1640. $t.text(rowData[queryColumnName]); // Restore total count
  1641. $t.next().text(rowData[sumColumnName]); // Restore slow log columns
  1642. if (isSlowLog) {
  1643. $t.parent().children('td').eq(2).text(rowData.query_time);
  1644. $t.parent().children('td').eq(3).text(rowData.lock_time);
  1645. $t.parent().children('td').eq(4).text(rowData.rows_sent);
  1646. $t.parent().children('td').eq(5).text(rowData.rows_examined);
  1647. }
  1648. }
  1649. } // If not required to be hidden, do we need
  1650. // to hide because of a not matching text filter?
  1651. if (!hide && textFilter !== null && !textFilter.exec($t.text())) {
  1652. hide = true;
  1653. } // Now display or hide this column
  1654. if (hide) {
  1655. $t.parent().css('display', 'none');
  1656. } else {
  1657. totalSum += parseInt($t.next().text(), 10);
  1658. rowSum++;
  1659. $t.parent().css('display', '');
  1660. }
  1661. hide = false;
  1662. i++;
  1663. }); // We finished summarizing counts => Update count values of all grouped entries
  1664. if (varFilterChange) {
  1665. if (noVars) {
  1666. var numCol;
  1667. var row;
  1668. var $table = $('#logTable').find('table tbody');
  1669. $.each(filteredQueriesLines, function (key, value) {
  1670. if (filteredQueries[key] <= 1) {
  1671. return;
  1672. }
  1673. row = $table.children('tr').eq(value);
  1674. numCol = row.children().eq(runtime.logDataCols.length - 1);
  1675. numCol.text(filteredQueries[key]);
  1676. if (isSlowLog) {
  1677. row.children('td').eq(2).text(secToTime(columnSums[key][0]));
  1678. row.children('td').eq(3).text(secToTime(columnSums[key][1]));
  1679. row.children('td').eq(4).text(columnSums[key][2]);
  1680. row.children('td').eq(5).text(columnSums[key][3]);
  1681. }
  1682. });
  1683. }
  1684. $('#logTable').find('table').trigger('update');
  1685. setTimeout(function () {
  1686. $('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
  1687. }, 0);
  1688. } // Display some stats at the bottom of the table
  1689. $('#logTable').find('table tfoot tr').html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' + Messages.strSumRows + ' ' + rowSum + '<span class="floatright">' + Messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
  1690. }
  1691. }
  1692. /* Turns a timespan (12:12:12) into a number */
  1693. function timeToSec(timeStr) {
  1694. var time = timeStr.split(':');
  1695. return parseInt(time[0], 10) * 3600 + parseInt(time[1], 10) * 60 + parseInt(time[2], 10);
  1696. }
  1697. /* Turns a number into a timespan (100 into 00:01:40) */
  1698. function secToTime(timeInt) {
  1699. var time = timeInt;
  1700. var hours = Math.floor(time / 3600);
  1701. time -= hours * 3600;
  1702. var minutes = Math.floor(time / 60);
  1703. time -= minutes * 60;
  1704. if (hours < 10) {
  1705. hours = '0' + hours;
  1706. }
  1707. if (minutes < 10) {
  1708. minutes = '0' + minutes;
  1709. }
  1710. if (time < 10) {
  1711. time = '0' + time;
  1712. }
  1713. return hours + ':' + minutes + ':' + time;
  1714. }
  1715. /* Constructs the log table out of the retrieved server data */
  1716. function buildLogTable(data, groupInserts) {
  1717. var rows = data.rows;
  1718. var cols = [];
  1719. var $table = $('<table class="pma-table sortable"></table>');
  1720. var $tBody;
  1721. var $tRow;
  1722. var $tCell;
  1723. $('#logTable').html($table);
  1724. var tempPushKey = function tempPushKey(key) {
  1725. cols.push(key);
  1726. };
  1727. var formatValue = function formatValue(name, value) {
  1728. if (name === 'user_host') {
  1729. return value.replace(/(\[.*?\])+/g, '');
  1730. }
  1731. return Functions.escapeHtml(value);
  1732. };
  1733. for (var i = 0, l = rows.length; i < l; i++) {
  1734. if (i === 0) {
  1735. $.each(rows[0], tempPushKey);
  1736. $table.append('<thead>' + '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' + '</thead>');
  1737. $table.append($tBody = $('<tbody></tbody>'));
  1738. }
  1739. $tBody.append($tRow = $('<tr class="noclick"></tr>'));
  1740. for (var j = 0, ll = cols.length; j < ll; j++) {
  1741. // Assuming the query column is the second last
  1742. if (j === cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
  1743. $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
  1744. $tCell.on('click', openQueryAnalyzer);
  1745. } else {
  1746. $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
  1747. }
  1748. $tRow.data('query', rows[i]);
  1749. }
  1750. }
  1751. $table.append('<tfoot>' + '<tr><th colspan="' + (cols.length - 1) + '">' + Messages.strSumRows + ' ' + data.numRows + '<span class="floatright">' + Messages.strTotal + '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>'); // Append a tooltip to the count column, if there exist one
  1752. if ($('#logTable').find('tr').first().find('th').last().text().indexOf('#') > -1) {
  1753. $('#logTable').find('tr').first().find('th').last().append('&nbsp;' + Functions.getImage('b_help', '', {
  1754. 'class': 'qroupedQueryInfoIcon'
  1755. }));
  1756. var tooltipContent = Messages.strCountColumnExplanation;
  1757. if (groupInserts) {
  1758. tooltipContent += '<p>' + Messages.strMoreCountColumnExplanation + '</p>';
  1759. }
  1760. Functions.tooltip($('img.qroupedQueryInfoIcon'), 'img', tooltipContent);
  1761. }
  1762. $('#logTable').find('table').tablesorter({
  1763. sortList: [[cols.length - 1, 1]],
  1764. widgets: ['fast-zebra']
  1765. });
  1766. $('#logTable').find('table thead th').append('<div class="sorticon"></div>');
  1767. return cols;
  1768. }
  1769. /* Opens the query analyzer dialog */
  1770. function openQueryAnalyzer() {
  1771. var rowData = $(this).parent().data('query');
  1772. var query = rowData.argument || rowData.sql_text;
  1773. if (codeMirrorEditor) {
  1774. // TODO: somehow Functions.sqlPrettyPrint messes up the query, needs be fixed
  1775. // query = Functions.sqlPrettyPrint(query);
  1776. codeMirrorEditor.setValue(query); // Codemirror is bugged, it doesn't refresh properly sometimes.
  1777. // Following lines seem to fix that
  1778. setTimeout(function () {
  1779. codeMirrorEditor.refresh();
  1780. }, 50);
  1781. } else {
  1782. $('#sqlquery').val(query);
  1783. }
  1784. var profilingChart = null;
  1785. var dlgBtns = {};
  1786. dlgBtns[Messages.strAnalyzeQuery] = function () {
  1787. profilingChart = loadQueryAnalysis(rowData);
  1788. };
  1789. dlgBtns[Messages.strClose] = function () {
  1790. $(this).dialog('close');
  1791. };
  1792. $('#queryAnalyzerDialog').dialog({
  1793. width: 'auto',
  1794. height: 'auto',
  1795. resizable: false,
  1796. buttons: dlgBtns,
  1797. close: function close() {
  1798. if (profilingChart !== null) {
  1799. profilingChart.destroy();
  1800. }
  1801. $('#queryAnalyzerDialog').find('div.placeHolder').html('');
  1802. if (codeMirrorEditor) {
  1803. codeMirrorEditor.setValue('');
  1804. } else {
  1805. $('#sqlquery').val('');
  1806. }
  1807. }
  1808. });
  1809. }
  1810. /* Loads and displays the analyzed query data */
  1811. function loadQueryAnalysis(rowData) {
  1812. var db = rowData.db || '';
  1813. var profilingChart = null;
  1814. $('#queryAnalyzerDialog').find('div.placeHolder').html(Messages.strAnalyzing + ' <img class="ajaxIcon" src="' + themeImagePath + 'ajax_clock_small.gif" alt="">');
  1815. $.post('index.php?route=/server/status/monitor/query', {
  1816. 'ajax_request': true,
  1817. 'query': codeMirrorEditor ? codeMirrorEditor.getValue() : $('#sqlquery').val(),
  1818. 'database': db,
  1819. 'server': CommonParams.get('server')
  1820. }, function (responseData) {
  1821. var data = responseData;
  1822. var i;
  1823. var l;
  1824. if (typeof data !== 'undefined' && data.success === true) {
  1825. data = data.message;
  1826. }
  1827. if (data.error) {
  1828. if (data.error.indexOf('1146') !== -1 || data.error.indexOf('1046') !== -1) {
  1829. data.error = Messages.strServerLogError;
  1830. }
  1831. $('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="alert alert-danger" role="alert">' + data.error + '</div>');
  1832. return;
  1833. }
  1834. var totalTime = 0; // Float sux, I'll use table :(
  1835. $('#queryAnalyzerDialog').find('div.placeHolder').html('<table class="pma-table" width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
  1836. var explain = '<b>' + Messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
  1837. if (data.explain.length > 1) {
  1838. explain += ' (';
  1839. for (i = 0; i < data.explain.length; i++) {
  1840. if (i > 0) {
  1841. explain += ', ';
  1842. }
  1843. explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
  1844. }
  1845. explain += ')';
  1846. }
  1847. explain += '<p></p>';
  1848. var tempExplain = function tempExplain(key, value) {
  1849. var newValue = value === null ? 'null' : Functions.escapeHtml(value);
  1850. if (key === 'type' && newValue.toLowerCase() === 'all') {
  1851. newValue = '<span class="attention">' + newValue + '</span>';
  1852. }
  1853. if (key === 'Extra') {
  1854. newValue = newValue.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
  1855. }
  1856. explain += key + ': ' + newValue + '<br>';
  1857. };
  1858. for (i = 0, l = data.explain.length; i < l; i++) {
  1859. explain += '<div class="explain-' + i + '"' + (i > 0 ? 'style="display:none;"' : '') + '>';
  1860. $.each(data.explain[i], tempExplain);
  1861. explain += '</div>';
  1862. }
  1863. explain += '<p><b>' + Messages.strAffectedRows + '</b> ' + data.affectedRows;
  1864. $('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);
  1865. $('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').on('click', function () {
  1866. var id = $(this).attr('href').split('-')[1];
  1867. $(this).parent().find('div[class*="explain"]').hide();
  1868. $(this).parent().find('div[class*="explain-' + id + '"]').show();
  1869. });
  1870. if (data.profiling) {
  1871. var chartData = [];
  1872. var numberTable = '<table class="pma-table queryNums"><thead><tr><th>' + Messages.strStatus + '</th><th>' + Messages.strTime + '</th></tr></thead><tbody>';
  1873. var duration;
  1874. var otherTime = 0;
  1875. for (i = 0, l = data.profiling.length; i < l; i++) {
  1876. duration = parseFloat(data.profiling[i].duration);
  1877. totalTime += duration;
  1878. numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + Functions.prettyProfilingNum(duration, 2) + '</td></tr>';
  1879. } // Only put those values in the pie which are > 2%
  1880. for (i = 0, l = data.profiling.length; i < l; i++) {
  1881. duration = parseFloat(data.profiling[i].duration);
  1882. if (duration / totalTime > 0.02) {
  1883. chartData.push([Functions.prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
  1884. } else {
  1885. otherTime += duration;
  1886. }
  1887. }
  1888. if (otherTime > 0) {
  1889. chartData.push([Functions.prettyProfilingNum(otherTime, 2) + ' ' + Messages.strOther, otherTime]);
  1890. }
  1891. numberTable += '<tr><td><b>' + Messages.strTotalTime + '</b></td><td>' + Functions.prettyProfilingNum(totalTime, 2) + '</td></tr>';
  1892. numberTable += '</tbody></table>';
  1893. $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append('<b>' + Messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' + '(<a href="#showNums">' + Messages.strTable + '</a>, <a href="#showChart">' + Messages.strChart + '</a>)<br>' + numberTable + ' <div id="queryProfiling"></div>');
  1894. $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').on('click', function () {
  1895. $('#queryAnalyzerDialog').find('#queryProfiling').hide();
  1896. $('#queryAnalyzerDialog').find('table.queryNums').show();
  1897. return false;
  1898. });
  1899. $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').on('click', function () {
  1900. $('#queryAnalyzerDialog').find('#queryProfiling').show();
  1901. $('#queryAnalyzerDialog').find('table.queryNums').hide();
  1902. return false;
  1903. });
  1904. profilingChart = Functions.createProfilingChart('queryProfiling', chartData);
  1905. }
  1906. });
  1907. return profilingChart;
  1908. }
  1909. /* Saves the monitor to localstorage */
  1910. function saveMonitor() {
  1911. var gridCopy = {};
  1912. $.each(runtime.charts, function (key, elem) {
  1913. gridCopy[key] = {};
  1914. gridCopy[key].nodes = elem.nodes;
  1915. gridCopy[key].settings = elem.settings;
  1916. gridCopy[key].title = elem.title;
  1917. gridCopy[key].series = elem.series;
  1918. gridCopy[key].maxYLabel = elem.maxYLabel;
  1919. });
  1920. if (isStorageSupported('localStorage')) {
  1921. window.localStorage.monitorCharts = JSON.stringify(gridCopy);
  1922. window.localStorage.monitorSettings = JSON.stringify(monitorSettings);
  1923. window.localStorage.monitorVersion = monitorProtocolVersion;
  1924. }
  1925. $('a[href="#clearMonitorConfig"]').show();
  1926. }
  1927. }); // Run the monitor once loaded
  1928. AJAX.registerOnload('server/status/monitor.js', function () {
  1929. $('a[href="#pauseCharts"]').trigger('click');
  1930. });