server_status_monitor.js 90 KB

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