1 /* vim: set expandtab sw=4 ts=4 sts=4: */
8 AJAX.registerOnload('server_status_monitor.js', function () {
9 var $js_data_form = $('#js_data');
10 server_time_diff = new Date().getTime() - $js_data_form.find("input[name=server_time]").val();
11 server_os = $js_data_form.find("input[name=server_os]").val();
12 is_superuser = $js_data_form.find("input[name=is_superuser]").val();
13 server_db_isLocal = $js_data_form.find("input[name=server_db_isLocal]").val();
17 * Unbind all event handlers before tearing down a page
19 AJAX.registerTeardown('server_status_monitor.js', function () {
20 $('#emptyDialog').remove();
21 $('#addChartDialog').remove();
22 $('a.popupLink').unbind('click');
23 $('body').unbind('click');
28 AJAX.registerOnload('server_status_monitor.js', function () {
30 .attr('id', 'emptyDialog')
31 .appendTo('#page_content');
33 .appendTo('#page_content');
35 $('a.popupLink').click(function () {
37 $('div.' + $link.attr('href').substr(1))
39 .offset({ top: $link.offset().top + $link.height() + 5, left: $link.offset().left })
40 .addClass('openedPopup');
44 $('body').click(function (event) {
45 $('div.openedPopup').each(function () {
47 var pos = $cnt.offset();
48 // Hide if the mouseclick is outside the popupcontent
49 if (event.pageX < pos.left ||
50 event.pageY < pos.top ||
51 event.pageX > pos.left + $cnt.outerWidth() ||
52 event.pageY > pos.top + $cnt.outerHeight()
54 $cnt.hide().removeClass('openedPopup');
60 AJAX.registerTeardown('server_status_monitor.js', function () {
61 $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').unbind('click');
62 $('div.popupContent select[name="chartColumns"]').unbind('change');
63 $('div.popupContent select[name="gridChartRefresh"]').unbind('change');
64 $('a[href="#addNewChart"]').unbind('click');
65 $('a[href="#exportMonitorConfig"]').unbind('click');
66 $('a[href="#importMonitorConfig"]').unbind('click');
67 $('a[href="#clearMonitorConfig"]').unbind('click');
68 $('a[href="#pauseCharts"]').unbind('click');
69 $('a[href="#monitorInstructionsDialog"]').unbind('click');
70 $('input[name="chartType"]').unbind('click');
71 $('input[name="useDivisor"]').unbind('click');
72 $('input[name="useUnit"]').unbind('click');
73 $('select[name="varChartList"]').unbind('click');
74 $('a[href="#kibDivisor"]').unbind('click');
75 $('a[href="#mibDivisor"]').unbind('click');
76 $('a[href="#submitClearSeries"]').unbind('click');
77 $('a[href="#submitAddSeries"]').unbind('click');
78 // $("input#variableInput").destroy();
79 $('#chartPreset').unbind('click');
80 $('#chartStatusVar').unbind('click');
84 AJAX.registerOnload('server_status_monitor.js', function () {
86 $('div.tabLinks').show();
87 $('#loadingMonitorIcon').remove();
88 // Codemirror is loaded on demand so we might need to initialize it
89 if (! codemirror_editor) {
90 var $elm = $('#sqlquery');
91 if ($elm.length > 0 && typeof CodeMirror != 'undefined') {
92 codemirror_editor = CodeMirror.fromTextArea(
104 // Timepicker is loaded on demand so we need to initialize
105 // datetime fields from the 'load log' dialog
106 $('#logAnalyseDialog .datetimefield').each(function () {
107 PMA_addDatepicker($(this));
110 /**** Monitor charting implementation ****/
111 /* Saves the previous ajax response for differential values */
112 var oldChartData = null;
113 // Holds about to be created chart
117 // Whenever the monitor object (runtime.charts) or the settings object
118 // (monitorSettings) changes in a way incompatible to the previous version,
119 // increase this number. It will reset the users monitor and settings object
120 // in his localStorage to the default configuration
121 var monitorProtocolVersion = '1.0';
123 // Runtime parameter of the monitor, is being fully set in initGrid()
125 // Holds all visible charts in the grid
127 // Stores the timeout handler so it can be cleared
128 refreshTimeout: null,
129 // Stores the GET request to refresh the charts
130 refreshRequest: null,
131 // Chart auto increment
133 // To play/pause the monitor
135 // Object that contains a list of nodes that need to be retrieved
136 // from the server for chart updates
138 // Current max points per chart (needed for auto calculation)
140 // displayed time frame
144 var monitorSettings = null;
146 var defaultMonitorSettings = {
148 chartSize: { width: 295, height: 250 },
149 // Max points in each chart. Settings it to 'auto' sets
150 // gridMaxPoints to (chartwidth - 40) / 12
151 gridMaxPoints: 'auto',
152 /* Refresh rate of all grid charts in ms */
156 // Allows drag and drop rearrange and print/edit icons on charts
157 var editMode = false;
159 /* List of preconfigured charts that the user may select */
161 // Query cache efficiency
163 title: PMA_messages.strQueryCacheEfficiency,
165 label: PMA_messages.strQueryCacheEfficiency
168 dataPoints: [{type: 'statusvar', name: 'Qcache_hits'}, {type: 'statusvar', name: 'Com_select'}],
175 title: PMA_messages.strQueryCacheUsage,
177 label: PMA_messages.strQueryCacheUsed
180 dataPoints: [{type: 'statusvar', name: 'Qcache_free_memory'}, {type: 'servervar', name: 'query_cache_size'}],
187 // time span selection
188 var selectionTimeDiff = [];
189 var selectionStartX, selectionStartY, selectionEndX, selectionEndY;
190 var drawTimeSpan = false;
195 /* Add OS specific system info charts to the preset chart list */
198 $.extend(presetCharts, {
200 title: PMA_messages.strSystemCPUUsage,
202 label: PMA_messages.strAverageLoad
205 dataPoints: [{ type: 'cpu', name: 'loadavg'}]
211 title: PMA_messages.strSystemMemory,
213 label: PMA_messages.strTotalMemory,
217 label: PMA_messages.strUsedMemory,
220 nodes: [{ dataPoints: [{ type: 'memory', name: 'MemTotal' }], valueDivisor: 1024 },
221 { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }
227 title: PMA_messages.strSystemSwap,
229 label: PMA_messages.strTotalSwap,
232 label: PMA_messages.strUsedSwap,
235 nodes: [{ dataPoints: [{ type: 'memory', name: 'SwapTotal' }]},
236 { dataPoints: [{ type: 'memory', name: 'SwapUsed' }]}
244 $.extend(presetCharts, {
246 title: PMA_messages.strSystemCPUUsage,
248 label: PMA_messages.strAverageLoad
250 nodes: [{ dataPoints: [{ type: 'cpu', name: 'irrelevant' }], transformFn: 'cpu-linux'}],
254 title: PMA_messages.strSystemMemory,
256 { label: PMA_messages.strBufferedMemory, fill: true},
257 { label: PMA_messages.strUsedMemory, fill: true},
258 { label: PMA_messages.strCachedMemory, fill: true},
259 { label: PMA_messages.strFreeMemory, fill: true}
262 { dataPoints: [{ type: 'memory', name: 'Buffers' }], valueDivisor: 1024 },
263 { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
264 { dataPoints: [{ type: 'memory', name: 'Cached' }], valueDivisor: 1024 },
265 { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
270 title: PMA_messages.strSystemSwap,
272 { label: PMA_messages.strCachedSwap, fill: true},
273 { label: PMA_messages.strUsedSwap, fill: true},
274 { label: PMA_messages.strFreeSwap, fill: true}
277 { dataPoints: [{ type: 'memory', name: 'SwapCached' }], valueDivisor: 1024 },
278 { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
279 { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
287 $.extend(presetCharts, {
289 title: PMA_messages.strSystemCPUUsage,
291 label: PMA_messages.strAverageLoad
294 dataPoints: [{ type: 'cpu', name: 'loadavg'}]
299 title: PMA_messages.strSystemMemory,
301 { label: PMA_messages.strUsedMemory, fill: true },
302 { label: PMA_messages.strFreeMemory, fill: true }
305 { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
306 { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
311 title: PMA_messages.strSystemSwap,
313 { label: PMA_messages.strUsedSwap, fill: true },
314 { label: PMA_messages.strFreeSwap, fill: true }
317 { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
318 { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
326 // Default setting for the chart grid
327 var defaultChartGrid = {
329 title: PMA_messages.strQuestions,
331 {label: PMA_messages.strQuestions}
334 {dataPoints: [{ type: 'statusvar', name: 'Questions' }], display: 'differential' }
339 title: PMA_messages.strChartConnectionsTitle,
341 {label: PMA_messages.strConnections},
342 {label: PMA_messages.strProcesses}
345 {dataPoints: [{ type: 'statusvar', name: 'Connections' }], display: 'differential' },
346 {dataPoints: [{ type: 'proc', name: 'processes' }] }
351 title: PMA_messages.strTraffic,
353 {label: PMA_messages.strBytesSent},
354 {label: PMA_messages.strBytesReceived}
357 {dataPoints: [{ type: 'statusvar', name: 'Bytes_sent' }], display: 'differential', valueDivisor: 1024 },
358 {dataPoints: [{ type: 'statusvar', name: 'Bytes_received' }], display: 'differential', valueDivisor: 1024 }
364 // Server is localhost => We can add cpu/memory/swap to the default chart
365 if (server_db_isLocal) {
366 defaultChartGrid['c3'] = presetCharts['cpu'];
367 defaultChartGrid['c4'] = presetCharts['memory'];
368 defaultChartGrid['c5'] = presetCharts['swap'];
371 $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').click(function (event) {
372 event.preventDefault();
373 editMode = !editMode;
374 if ($(this).attr('href') == '#endChartEditMode') {
378 $('a[href="#endChartEditMode"]').toggle(editMode);
381 // Close the settings popup
382 $('div.popupContent').hide().removeClass('openedPopup');
384 $("#chartGrid").sortableTable({
387 left: chartSize.width - 63,
394 $("#chartGrid").sortableTable('destroy');
396 saveMonitor(); // Save settings
401 $('div.popupContent select[name="chartColumns"]').change(function () {
402 monitorSettings.columns = parseInt(this.value, 10);
404 calculateChartSize();
405 // Empty cells should keep their size so you can drop onto them
406 $('#chartGrid tr td').css('width', chartSize.width + 'px');
407 $('#chartGrid .monitorChart').css({
408 width: chartSize.width + 'px',
409 height: chartSize.height + 'px'
412 /* Reorder all charts that it fills all column cells */
414 var $tr = $('#chartGrid tr:first');
416 while ($tr.length !== 0) {
418 // To many cells in one row => put into next row
419 $tr.find('td').each(function () {
420 if (numColumns > monitorSettings.columns) {
421 if ($tr.next().length === 0) {
422 $tr.after('<tr></tr>');
424 $tr.next().prepend($(this));
429 // To little cells in one row => for each cell to little,
430 // move all cells backwards by 1
431 if ($tr.next().length > 0) {
432 var cnt = monitorSettings.columns - $tr.find('td').length;
433 for (var i = 0; i < cnt; i++) {
434 $tr.append($tr.next().find('td:first'));
435 $tr.nextAll().each(function () {
436 if ($(this).next().length !== 0) {
437 $(this).append($(this).next().find('td:first'));
447 if (monitorSettings.gridMaxPoints == 'auto') {
448 runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12);
451 runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
452 runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
455 $("#chartGrid").sortableTable('refresh');
459 saveMonitor(); // Save settings
462 $('div.popupContent select[name="gridChartRefresh"]').change(function () {
463 monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000;
464 clearTimeout(runtime.refreshTimeout);
466 if (runtime.refreshRequest) {
467 runtime.refreshRequest.abort();
470 runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
471 // fixing chart shift towards left on refresh rate change
472 //runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
473 runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
475 saveMonitor(); // Save settings
478 $('a[href="#addNewChart"]').click(function (event) {
479 event.preventDefault();
480 var dlgButtons = { };
482 dlgButtons[PMA_messages.strAddChart] = function () {
483 var type = $('input[name="chartType"]:checked').val();
485 if (type == 'preset') {
486 newChart = presetCharts[$('#addChartDialog select[name="presetCharts"]').prop('value')];
488 // If user builds his own chart, it's being set/updated
489 // each time he adds a series
490 // So here we only warn if he didn't add a series yet
491 if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) {
492 alert(PMA_messages.strAddOneSeriesWarning);
497 newChart.title = $('input[name="chartTitle"]').val();
498 // Add a cloned object to the chart grid
499 addChart($.extend(true, {}, newChart));
503 saveMonitor(); // Save settings
505 $(this).dialog("close");
508 dlgButtons[PMA_messages.strClose] = function () {
510 $('span#clearSeriesLink').hide();
511 $('#seriesPreview').html('');
512 $(this).dialog("close");
515 var $presetList = $('#addChartDialog select[name="presetCharts"]');
516 if ($presetList.html().length === 0) {
517 $.each(presetCharts, function (key, value) {
518 $presetList.append('<option value="' + key + '">' + value.title + '</option>');
520 $presetList.change(function () {
521 $('input[name="chartTitle"]').val(
522 $presetList.find(':selected').text()
524 $('#chartPreset').prop('checked', true);
526 $('#chartPreset').click(function () {
527 $('input[name="chartTitle"]').val(
528 $presetList.find(':selected').text()
531 $('#chartStatusVar').click(function () {
532 $('input[name="chartTitle"]').val(
533 $('#chartSeries').find(':selected').text().replace(/_/g, " ")
536 $('#chartSeries').change(function () {
537 $('input[name="chartTitle"]').val(
538 $('#chartSeries').find(':selected').text().replace(/_/g, " ")
543 $('#addChartDialog').dialog({
549 $('#addChartDialog #seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
554 $('a[href="#exportMonitorConfig"]').click(function (event) {
555 event.preventDefault();
557 $.each(runtime.charts, function (key, elem) {
559 gridCopy[key].nodes = elem.nodes;
560 gridCopy[key].settings = elem.settings;
561 gridCopy[key].title = elem.title;
564 monitorCharts: gridCopy,
565 monitorSettings: monitorSettings
568 "class": "disableAjax",
570 action: "file_echo.php?" + PMA_commonParams.get('common_query') + "&filename=1",
571 style: "display:none;"
576 name: "monitorconfig",
577 value: JSON.stringify(exportData)
585 $('a[href="#importMonitorConfig"]').click(function (event) {
586 event.preventDefault();
587 $('#emptyDialog').dialog({title: PMA_messages.strImportDialogTitle});
588 $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ':<br/><form action="file_echo.php?' + PMA_commonParams.get('common_query') + '&import=1" method="post" enctype="multipart/form-data">' +
589 '<input type="file" name="file"> <input type="hidden" name="import" value="1"> </form>');
593 dlgBtns[PMA_messages.strImport] = function () {
595 $('body').append($iframe = $('<iframe id="monitorConfigUpload" style="display:none;"></iframe>'));
596 var d = $iframe[0].contentWindow.document;
601 $iframe.load(function () {
604 // Try loading config
606 var data = $('body', $('iframe#monitorConfigUpload')[0].contentWindow.document).html();
607 // Chrome wraps around '<pre style="word-wrap: break-word; white-space: pre-wrap;">' to any text content -.-
608 json = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
610 alert(PMA_messages.strFailedParsingConfig);
611 $('#emptyDialog').dialog('close');
615 // Basic check, is this a monitor config json?
616 if (!json || ! json.monitorCharts || ! json.monitorCharts) {
617 alert(PMA_messages.strFailedParsingConfig);
618 $('#emptyDialog').dialog('close');
622 // If json ok, try applying config
624 window.localStorage['monitorCharts'] = JSON.stringify(json.monitorCharts);
625 window.localStorage['monitorSettings'] = JSON.stringify(json.monitorSettings);
628 alert(PMA_messages.strFailedBuildingGrid);
629 // If an exception is thrown, load default again
630 window.localStorage.removeItem('monitorCharts');
631 window.localStorage.removeItem('monitorSettings');
635 $('#emptyDialog').dialog('close');
638 $("body", d).append($form = $('#emptyDialog').find('form'));
640 $('#emptyDialog').append('<img class="ajaxIcon" src="' + pmaThemeImage + 'ajax_clock_small.gif" alt="">');
643 dlgBtns[PMA_messages.strCancel] = function () {
644 $(this).dialog('close');
648 $('#emptyDialog').dialog({
655 $('a[href="#clearMonitorConfig"]').click(function (event) {
656 event.preventDefault();
657 window.localStorage.removeItem('monitorCharts');
658 window.localStorage.removeItem('monitorSettings');
659 window.localStorage.removeItem('monitorVersion');
664 $('a[href="#pauseCharts"]').click(function (event) {
665 event.preventDefault();
666 runtime.redrawCharts = ! runtime.redrawCharts;
667 if (! runtime.redrawCharts) {
668 $(this).html(PMA_getImage('play.png') + ' ' + PMA_messages.strResumeMonitor);
670 $(this).html(PMA_getImage('pause.png') + ' ' + PMA_messages.strPauseMonitor);
671 if (! runtime.charts) {
673 $('a[href="#settingsPopup"]').show();
679 $('a[href="#monitorInstructionsDialog"]').click(function (event) {
680 event.preventDefault();
682 var $dialog = $('#monitorInstructionsDialog');
687 }).find('img.ajaxIcon').show();
689 var loadLogVars = function (getvars) {
690 var vars = { ajax_request: true, logging_vars: true };
692 $.extend(vars, getvars);
695 $.get('server_status_monitor.php?' + PMA_commonParams.get('common_query'), vars,
698 if (data.success === true) {
699 logVars = data.message;
701 return serverResponseError();
703 var icon = PMA_getImage('s_success.png'), msg = '', str = '';
705 if (logVars['general_log'] == 'ON') {
706 if (logVars['slow_query_log'] == 'ON') {
707 msg = PMA_messages.strBothLogOn;
709 msg = PMA_messages.strGenLogOn;
713 if (msg.length === 0 && logVars['slow_query_log'] == 'ON') {
714 msg = PMA_messages.strSlowLogOn;
717 if (msg.length === 0) {
718 icon = PMA_getImage('s_error.png');
719 msg = PMA_messages.strBothLogOff;
722 str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">';
723 str += icon + msg + '<br />';
725 if (logVars['log_output'] != 'TABLE') {
726 str += PMA_getImage('s_error.png') + ' ' + PMA_messages.strLogOutNotTable + '<br />';
728 str += PMA_getImage('s_success.png') + ' ' + PMA_messages.strLogOutIsTable + '<br />';
731 if (logVars['slow_query_log'] == 'ON') {
732 if (logVars['long_query_time'] > 2) {
733 str += PMA_getImage('s_attention.png') + ' ';
734 str += $.sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars['long_query_time']);
738 if (logVars['long_query_time'] < 2) {
739 str += PMA_getImage('s_success.png') + ' ';
740 str += $.sprintf(PMA_messages.strLongQueryTimeSet, logVars['long_query_time']);
748 str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>';
749 str += '<div class="smallIndent">';
750 str += PMA_messages.strSettingsAppliedGlobal + '<br/>';
752 var varValue = 'TABLE';
753 if (logVars['log_output'] == 'TABLE') {
757 str += '- <a class="set" href="#log_output-' + varValue + '">';
758 str += $.sprintf(PMA_messages.strSetLogOutput, varValue);
759 str += ' </a><br />';
761 if (logVars['general_log'] != 'ON') {
762 str += '- <a class="set" href="#general_log-ON">';
763 str += $.sprintf(PMA_messages.strEnableVar, 'general_log');
764 str += ' </a><br />';
766 str += '- <a class="set" href="#general_log-OFF">';
767 str += $.sprintf(PMA_messages.strDisableVar, 'general_log');
768 str += ' </a><br />';
771 if (logVars['slow_query_log'] != 'ON') {
772 str += '- <a class="set" href="#slow_query_log-ON">';
773 str += $.sprintf(PMA_messages.strEnableVar, 'slow_query_log');
774 str += ' </a><br />';
776 str += '- <a class="set" href="#slow_query_log-OFF">';
777 str += $.sprintf(PMA_messages.strDisableVar, 'slow_query_log');
778 str += ' </a><br />';
782 if (logVars['long_query_time'] > 2) {
786 str += '- <a class="set" href="#long_query_time-' + varValue + '">';
787 str += $.sprintf(PMA_messages.setSetLongQueryTime, varValue);
788 str += ' </a><br />';
791 str += PMA_messages.strNoSuperUser + '<br/>';
796 $dialog.find('div.monitorUse').toggle(
797 logVars['log_output'] == 'TABLE' && (logVars['slow_query_log'] == 'ON' || logVars['general_log'] == 'ON')
800 $dialog.find('div.ajaxContent').html(str);
801 $dialog.find('img.ajaxIcon').hide();
802 $dialog.find('a.set').click(function () {
803 var nameValue = $(this).attr('href').split('-');
804 loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1]});
805 $dialog.find('img.ajaxIcon').show();
817 $('input[name="chartType"]').change(function () {
818 $('#chartVariableSettings').toggle(this.checked && this.value == 'variable');
819 var title = $('input[name="chartTitle"]').val();
820 if (title == PMA_messages.strChartTitle ||
821 title == $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
823 $('input[name="chartTitle"]')
824 .data('lastRadio', $(this).attr('id'))
825 .val($('label[for="' + $(this).attr('id') + '"]').text());
830 $('input[name="useDivisor"]').change(function () {
831 $('span.divisorInput').toggle(this.checked);
834 $('input[name="useUnit"]').change(function () {
835 $('span.unitInput').toggle(this.checked);
838 $('select[name="varChartList"]').change(function () {
839 if (this.selectedIndex !== 0) {
840 $('#variableInput').val(this.value);
844 $('a[href="#kibDivisor"]').click(function (event) {
845 event.preventDefault();
846 $('input[name="valueDivisor"]').val(1024);
847 $('input[name="valueUnit"]').val(PMA_messages.strKiB);
848 $('span.unitInput').toggle(true);
849 $('input[name="useUnit"]').prop('checked', true);
853 $('a[href="#mibDivisor"]').click(function (event) {
854 event.preventDefault();
855 $('input[name="valueDivisor"]').val(1024 * 1024);
856 $('input[name="valueUnit"]').val(PMA_messages.strMiB);
857 $('span.unitInput').toggle(true);
858 $('input[name="useUnit"]').prop('checked', true);
862 $('a[href="#submitClearSeries"]').click(function (event) {
863 event.preventDefault();
864 $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
866 $('#clearSeriesLink').hide();
869 $('a[href="#submitAddSeries"]').click(function (event) {
870 event.preventDefault();
871 if ($('#variableInput').val() === "") {
875 if (newChart === null) {
876 $('#seriesPreview').html('');
879 title: $('input[name="chartTitle"]').val(),
887 dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
888 display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
891 if (serie.dataPoints[0].name == 'Processes') {
892 serie.dataPoints[0].type = 'proc';
895 if ($('input[name="useDivisor"]').prop('checked')) {
896 serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
899 if ($('input[name="useUnit"]').prop('checked')) {
900 serie.unit = $('input[name="valueUnit"]').val();
903 var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
904 str += serie.valueDivisor ? (', ' + $.sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
905 str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
908 label: $('#variableInput').val().replace(/_/g, " ")
910 newChart.series.push(newSeries);
911 $('#seriesPreview').append('- ' + newSeries.label + str + '<br/>');
912 newChart.nodes.push(serie);
913 $('#variableInput').val('');
914 $('input[name="differentialValue"]').prop('checked', true);
915 $('input[name="useDivisor"]').prop('checked', false);
916 $('input[name="useUnit"]').prop('checked', false);
917 $('input[name="useDivisor"]').trigger('change');
918 $('input[name="useUnit"]').trigger('change');
919 $('select[name="varChartList"]').get(0).selectedIndex = 0;
921 $('#clearSeriesLink').show();
926 $("#variableInput").autocomplete({
927 source: variableNames
930 /* Initializes the monitor, called only once */
931 function initGrid() {
935 /* Apply default values & config */
936 if (window.localStorage) {
937 if (window.localStorage['monitorCharts']) {
938 runtime.charts = $.parseJSON(window.localStorage['monitorCharts']);
940 if (window.localStorage['monitorSettings']) {
941 monitorSettings = $.parseJSON(window.localStorage['monitorSettings']);
944 $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
946 if (runtime.charts !== null && monitorProtocolVersion != window.localStorage['monitorVersion']) {
947 $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
948 $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
951 dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };
953 $('#emptyDialog').dialog({
960 if (runtime.charts === null) {
961 runtime.charts = defaultChartGrid;
963 if (monitorSettings === null) {
964 monitorSettings = defaultMonitorSettings;
967 $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
968 $('select[name="chartColumns"]').val(monitorSettings.columns);
970 if (monitorSettings.gridMaxPoints == 'auto') {
971 runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
973 runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
976 runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
977 runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
979 /* Calculate how much spacing there is between each chart */
980 $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
982 width: $('#chartGrid td:nth-child(2)').offset().left -
983 $('#chartGrid td:nth-child(1)').offset().left,
984 height: $('#chartGrid tr:nth-child(2) td:nth-child(2)').offset().top -
985 $('#chartGrid tr:nth-child(1) td:nth-child(1)').offset().top
987 $('#chartGrid').html('');
989 /* Add all charts - in correct order */
991 $.each(runtime.charts, function (key, value) {
995 for (i = 0; i < keys.length; i++) {
996 addChart(runtime.charts[keys[i]], true);
999 /* Fill in missing cells */
1000 var numCharts = $('#chartGrid .monitorChart').length;
1001 var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
1002 for (i = 0; i < numMissingCells; i++) {
1003 $('#chartGrid tr:last').append('<td></td>');
1006 // Empty cells should keep their size so you can drop onto them
1007 calculateChartSize();
1008 $('#chartGrid tr td').css('width', chartSize.width + 'px');
1010 buildRequiredDataList();
1014 /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
1015 * data from each chart and restores it after the monitor is initialized again */
1016 function rebuildGrid() {
1018 if (runtime.charts) {
1020 $.each(runtime.charts, function (key, chartObj) {
1021 for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
1022 oldData[chartObj.nodes[i].dataPoint] = [];
1023 for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
1024 oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
1034 /* Calculactes the dynamic chart size that depends on the column width */
1035 function calculateChartSize() {
1037 if ($("body").height() > $(window).height()) { // has vertical scroll bar
1038 panelWidth = $('#logTable').innerWidth();
1040 panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
1043 var wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
1045 width: Math.floor(wdt),
1046 height: Math.floor(0.75 * wdt)
1050 /* Adds a chart to the chart grid */
1051 function addChart(chartObj, initialize) {
1055 title: escapeHtml(chartObj.title),
1059 background: 'rgba(0,0,0,0)'
1063 renderer: $.jqplot.DateAxisRenderer,
1065 formatString: '%H:%M:%S',
1089 if (settings.title === PMA_messages.strSystemCPUUsage ||
1090 settings.title === PMA_messages.strQueryCacheEfficiency
1092 settings.axes.yaxis.tickOptions = {
1093 formatString: "%d %%"
1095 } else if (settings.title === PMA_messages.strSystemMemory ||
1096 settings.title === PMA_messages.strSystemSwap
1098 settings.stackSeries = true;
1099 settings.axes.yaxis.tickOptions = {
1100 formatter: $.jqplot.byteFormatter(2) // MiB
1102 } else if (settings.title === PMA_messages.strTraffic) {
1103 settings.axes.yaxis.tickOptions = {
1104 formatter: $.jqplot.byteFormatter(1) // KiB
1106 } else if (settings.title === PMA_messages.strQuestions ||
1107 settings.title === PMA_messages.strConnections
1109 settings.axes.yaxis.tickOptions = {
1110 formatter: function (format, val) {
1111 if (Math.abs(val) >= 1000000) {
1112 return $.jqplot.sprintf("%.3g M", val / 1000000);
1113 } else if (Math.abs(val) >= 1000) {
1114 return $.jqplot.sprintf("%.3g k", val / 1000);
1116 return $.jqplot.sprintf("%d", val);
1122 settings.series = chartObj.series;
1124 if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
1125 var numCharts = $('#chartGrid .monitorChart').length;
1127 if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
1128 $('#chartGrid').append('<tr></tr>');
1132 calculateChartSize();
1134 $('#chartGrid tr:last').append(
1135 '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
1136 '<div class="ui-state-default monitorChart"' +
1137 ' id="gridchart' + runtime.chartAI + '"' +
1138 ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' +
1143 // Set series' data as [0,0], smooth lines won't plot with data array having null values.
1144 // also chart won't plot initially with no data and data comes on refreshChartGrid()
1146 for (i in chartObj.series) {
1147 series.push([[0, 0]]);
1150 // set Tooltip for each series
1151 for (i in settings.series) {
1152 settings.series[i].highlighter = {
1154 tooltipContentEditor: function (str, seriesIndex, pointIndex, plot) {
1156 // TODO: move style to theme CSS
1157 var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' +
1158 'opacity:0.95;filter:alpha(opacity=95);padding:5px;">';
1159 // x value i.e. time
1160 var timeValue = str.split(",")[0];
1162 tooltipHtml += 'Time: ' + timeValue;
1163 tooltipHtml += '<span style="font-weight:bold;">';
1164 // Add y values to the tooltip per series
1165 for (j in plot.series) {
1166 // get y value if present
1167 if (plot.series[j].data.length > pointIndex) {
1168 seriesValue = plot.series[j].data[pointIndex][1];
1172 var seriesLabel = plot.series[j].label;
1173 var seriesColor = plot.series[j].color;
1175 if (plot.series[0]._yaxis.tickOptions.formatter) {
1176 // using formatter function
1177 seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
1178 } else if (plot.series[0]._yaxis.tickOptions.formatString) {
1179 // using format string
1180 seriesValue = $.sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
1182 tooltipHtml += '<br /><span style="color:' + seriesColor + '">' +
1183 seriesLabel + ': ' + seriesValue + '</span>';
1185 tooltipHtml += '</span></div>';
1191 chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings);
1192 // remove [0,0] after plotting
1193 for (i in chartObj.chart.series) {
1194 chartObj.chart.series[i].data.shift();
1197 var $legend = $('<div />').css('padding', '0.5em');
1198 for (i in chartObj.chart.series) {
1200 $('<div />').append(
1204 background: chartObj.chart.seriesColors[i]
1205 }).addClass('floatleft')
1208 chartObj.chart.series[i].label
1209 ).addClass('floatleft')
1211 $('<div class="clearfloat">')
1212 ).addClass('floatleft')
1215 $('#gridchart' + runtime.chartAI)
1219 if (initialize !== true) {
1220 runtime.charts['c' + runtime.chartAI] = chartObj;
1221 buildRequiredDataList();
1224 // time span selection
1225 $('#gridchart' + runtime.chartAI).bind('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) {
1226 drawTimeSpan = true;
1227 selectionTimeDiff.push(datapos.xaxis);
1228 if ($('#selection_box').length) {
1229 $('#selection_box').remove();
1231 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;">');
1232 $(document.body).append(selectionBox);
1233 selectionStartX = ev.pageX;
1234 selectionStartY = ev.pageY;
1236 .attr({id: 'selection_box'})
1238 top: selectionStartY - gridpos.y,
1239 left: selectionStartX
1244 $('#gridchart' + runtime.chartAI).bind('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) {
1245 if (! drawTimeSpan || editMode) {
1249 selectionTimeDiff.push(datapos.xaxis);
1251 if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
1252 selectionTimeDiff = [];
1255 //get date from timestamp
1256 var min = new Date(Math.ceil(selectionTimeDiff[0]));
1257 var max = new Date(Math.ceil(selectionTimeDiff[1]));
1258 PMA_getLogAnalyseDialog(min, max);
1259 selectionTimeDiff = [];
1260 drawTimeSpan = false;
1263 $('#gridchart' + runtime.chartAI).bind('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) {
1264 if (! drawTimeSpan || editMode) {
1267 if (selectionStartX !== undefined) {
1270 width: Math.ceil(ev.pageX - selectionStartX)
1276 $('#gridchart' + runtime.chartAI).bind('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) {
1277 drawTimeSpan = false;
1280 $(document.body).mouseup(function () {
1281 if ($('#selection_box').length) {
1282 selectionBox.remove();
1286 // Edit, Print icon only in edit mode
1287 $('#chartGrid div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
1292 function PMA_getLogAnalyseDialog(min, max) {
1293 var $dateStart = $('#logAnalyseDialog input[name="dateStart"]');
1294 var $dateEnd = $('#logAnalyseDialog input[name="dateEnd"]');
1295 $dateStart.prop("readonly", true);
1296 $dateEnd.prop("readonly", true);
1300 dlgBtns[PMA_messages.strFromSlowLog] = function () {
1301 loadLog('slow', min, max);
1302 $(this).dialog("close");
1305 dlgBtns[PMA_messages.strFromGeneralLog] = function () {
1306 loadLog('general', min, max);
1307 $(this).dialog("close");
1310 $('#logAnalyseDialog').dialog({
1316 PMA_addDatepicker($dateStart, 'datetime', {
1317 showMillisec: false,
1318 showMicrosec: false,
1319 timeFormat: 'HH:mm:ss'
1321 PMA_addDatepicker($dateEnd, 'datetime', {
1322 showMillisec: false,
1323 showMicrosec: false,
1324 timeFormat: 'HH:mm:ss'
1326 $('#logAnalyseDialog input[name="dateStart"]').datepicker('setDate', min);
1327 $('#logAnalyseDialog input[name="dateEnd"]').datepicker('setDate', max);
1330 function loadLog(type, min, max) {
1331 var dateStart = Date.parse($('#logAnalyseDialog input[name="dateStart"]').datepicker('getDate')) || min;
1332 var dateEnd = Date.parse($('#logAnalyseDialog input[name="dateEnd"]').datepicker('getDate')) || max;
1338 removeVariables: $('#removeVariables').prop('checked'),
1339 limitTypes: $('#limitTypes').prop('checked')
1343 /* Called in regular intervalls, this function updates the values of each chart in the grid */
1344 function refreshChartGrid() {
1345 /* Send to server */
1346 runtime.refreshRequest = $.post('server_status_monitor.php?' + PMA_commonParams.get('common_query'), {
1350 requiredData: JSON.stringify(runtime.dataList)
1351 }, function (data) {
1353 if (data.success === true) {
1354 chartData = data.message;
1356 return serverResponseError();
1362 /* Update values in each graph */
1363 $.each(runtime.charts, function (orderKey, elem) {
1364 var key = elem.chartID;
1365 // If newly added chart, we have no data for it yet
1366 if (! chartData[key]) {
1371 for (var j = 0; j < elem.nodes.length; j++) {
1373 if (i === 0 && j === 0) {
1374 if (oldChartData === null) {
1375 diff = chartData.x - runtime.xmax;
1377 diff = parseInt(chartData.x - oldChartData.x, 10);
1380 runtime.xmin += diff;
1381 runtime.xmax += diff;
1384 //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
1385 /* Calculate y value */
1387 // If transform function given, use it
1388 if (elem.nodes[j].transformFn) {
1389 value = chartValueTransform(
1390 elem.nodes[j].transformFn,
1392 // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
1394 oldChartData === null ||
1395 oldChartData[key] === null ||
1396 oldChartData[key] === undefined ? null : oldChartData[key][j]
1400 // Otherwise use original value and apply differential and divisor if given,
1401 // in this case we have only one data point per series - located at chartData[key][j][0]
1403 value = parseFloat(chartData[key][j][0].value);
1405 if (elem.nodes[j].display == 'differential') {
1406 if (oldChartData === null ||
1407 oldChartData[key] === null ||
1408 oldChartData[key] === undefined
1412 value -= oldChartData[key][j][0].value;
1415 if (elem.nodes[j].valueDivisor) {
1416 value = value / elem.nodes[j].valueDivisor;
1420 // Set y value, if defined
1421 if (value !== undefined) {
1422 elem.chart.series[j].data.push([chartData.x, value]);
1423 if (value > elem.maxYLabel) {
1424 elem.maxYLabel = value;
1425 } else if (elem.maxYLabel === 0) {
1426 elem.maxYLabel = 0.5;
1428 // free old data point values and update maxYLabel
1429 if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
1430 elem.chart.series[j].data[0][0] < runtime.xmin
1432 // check if the next freeable point is highest
1433 if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
1434 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1435 elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
1437 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1440 if (elem.title === PMA_messages.strSystemMemory ||
1441 elem.title === PMA_messages.strSystemSwap
1448 // update chart options
1449 // keep ticks number/positioning consistent while refreshrate changes
1450 var tickInterval = (runtime.xmax - runtime.xmin) / 5;
1451 elem.chart['axes']['xaxis'].ticks = [(runtime.xmax - tickInterval * 4),
1452 (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
1453 (runtime.xmax - tickInterval), runtime.xmax];
1455 if (elem.title !== PMA_messages.strSystemCPUUsage &&
1456 elem.title !== PMA_messages.strQueryCacheEfficiency &&
1457 elem.title !== PMA_messages.strSystemMemory &&
1458 elem.title !== PMA_messages.strSystemSwap
1460 elem.chart['axes']['yaxis']['max'] = Math.ceil(elem.maxYLabel * 1.1);
1461 elem.chart['axes']['yaxis']['tickInterval'] = Math.ceil(elem.maxYLabel * 1.1 / 5);
1462 } else if (elem.title === PMA_messages.strSystemMemory ||
1463 elem.title === PMA_messages.strSystemSwap
1465 elem.chart['axes']['yaxis']['max'] = Math.ceil(total * 1.1 / 100) * 100;
1466 elem.chart['axes']['yaxis']['tickInterval'] = Math.ceil(total * 1.1 / 5);
1470 if (runtime.redrawCharts) {
1471 elem.chart.replot();
1475 oldChartData = chartData;
1477 runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
1481 /* Function to get highest plotted point's y label, to scale the chart,
1482 * TODO: make jqplot's autoscale:true work here
1484 function getMaxYLabel(dataValues) {
1485 var maxY = dataValues[0][1];
1486 $.each(dataValues, function (k, v) {
1487 maxY = (v[1] > maxY) ? v[1] : maxY;
1492 /* Function that supplies special value transform functions for chart values */
1493 function chartValueTransform(name, cur, prev) {
1496 if (prev === null) {
1499 // cur and prev are datapoint arrays, but containing
1500 // only 1 element for cpu-linux
1504 var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
1505 var diff_idle = cur.idle - prev.idle;
1506 return 100 * (diff_total - diff_idle) / diff_total;
1508 // Query cache efficiency (%)
1510 if (prev === null) {
1513 // cur[0].value is Qcache_hits, cur[1].value is Com_select
1514 var diffQHits = cur[0].value - prev[0].value;
1515 // No NaN please :-)
1516 if (cur[1].value - prev[1].value === 0) {
1520 return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
1522 // Query cache usage (%)
1524 if (cur[1].value === 0) {
1527 // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
1528 return 100 - cur[0].value / cur[1].value * 100;
1534 /* Build list of nodes that need to be retrieved from server.
1535 * It creates something like a stripped down version of the runtime.charts object.
1537 function buildRequiredDataList() {
1538 runtime.dataList = {};
1539 // Store an own id, because the property name is subject of reordering,
1540 // thus destroying our mapping with runtime.charts <=> runtime.dataList
1542 $.each(runtime.charts, function (key, chart) {
1543 runtime.dataList[chartID] = [];
1544 for (var i = 0, l = chart.nodes.length; i < l; i++) {
1545 runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
1547 runtime.charts[key].chartID = chartID;
1552 /* Loads the log table data, generates the table and handles the filters */
1553 function loadLogStatistics(opts) {
1555 var logRequest = null;
1557 if (! opts.removeVariables) {
1558 opts.removeVariables = false;
1560 if (! opts.limitTypes) {
1561 opts.limitTypes = false;
1564 $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle});
1565 $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
1566 ' <img class="ajaxIcon" src="' + pmaThemeImage +
1567 'ajax_clock_small.gif" alt="">');
1570 dlgBtns[PMA_messages.strCancelRequest] = function () {
1571 if (logRequest !== null) {
1575 $(this).dialog("close");
1578 $('#emptyDialog').dialog({
1585 logRequest = $.get('server_status_monitor.php?' + PMA_commonParams.get('common_query'),
1586 { ajax_request: true,
1589 time_start: Math.round(opts.start / 1000),
1590 time_end: Math.round(opts.end / 1000),
1591 removeVariables: opts.removeVariables,
1592 limitTypes: opts.limitTypes
1597 if (data.success === true) {
1598 logData = data.message;
1600 return serverResponseError();
1603 if (logData.rows.length !== 0) {
1604 runtime.logDataCols = buildLogTable(logData);
1606 /* Show some stats in the dialog */
1607 $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
1608 $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
1609 $.each(logData.sum, function (key, value) {
1610 key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
1611 if (key == 'Total') {
1612 key = '<b>' + key + '</b>';
1614 $('#emptyDialog').append(key + ': ' + value + '<br/>');
1617 /* Add filter options if more than a bunch of rows there to filter */
1618 if (logData.numRows > 12) {
1619 $('#logTable').prepend(
1620 '<fieldset id="logDataFilter">' +
1621 ' <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
1622 ' <div class="formelement">' +
1623 ' <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
1624 ' <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1626 ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
1627 ' <div class="formelement">' +
1628 ' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1629 ' <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
1634 $('#logTable #noWHEREData').change(function () {
1635 filterQueries(true);
1638 if (logData.numRows > 250) {
1639 $('#logTable #startFilterQueryText').click(filterQueries);
1641 $('#logTable #filterQueryText').keyup(filterQueries);
1646 dlgBtns[PMA_messages.strJumpToTable] = function () {
1647 $(this).dialog("close");
1648 $(document).scrollTop($('#logTable').offset().top);
1651 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1654 $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
1655 $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
1657 dlgBtns[PMA_messages.strClose] = function () {
1658 $(this).dialog("close");
1661 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1666 /* Handles the actions performed when the user uses any of the
1667 * log table filters which are the filter by name and grouping
1668 * with ignoring data in WHERE clauses
1670 * @param boolean Should be true when the users enabled or disabled
1671 * to group queries ignoring data in WHERE clauses
1673 function filterQueries(varFilterChange) {
1674 var odd_row = false, cell, textFilter;
1675 var val = $('#logTable #filterQueryText').val();
1677 if (val.length === 0) {
1680 textFilter = new RegExp(val, 'i');
1683 var rowSum = 0, totalSum = 0, i = 0, q;
1684 var noVars = $('#logTable #noWHEREData').prop('checked');
1685 var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1686 var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
1687 var filteredQueries = {}, filteredQueriesLines = {};
1688 var hide = false, rowData;
1689 var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
1690 var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
1691 var isSlowLog = opts.src == 'slow';
1692 var columnSums = {};
1694 // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
1695 var countRow = function (query, row) {
1696 var cells = row.match(/<td>(.*?)<\/td>/gi);
1697 if (!columnSums[query]) {
1698 columnSums[query] = [0, 0, 0, 0];
1701 // lock_time and query_time and displayed in timespan format
1702 columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
1703 columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
1704 // rows_examind and rows_sent are just numbers
1705 columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
1706 columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
1709 // We just assume the sql text is always in the second last column, and that the total count is right of it
1710 $('#logTable table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
1712 // If query is a SELECT and user enabled or disabled to group
1713 // queries ignoring data in where statements, we
1714 // need to re-calculate the sums of each row
1715 if (varFilterChange && $t.html().match(/^SELECT/i)) {
1717 // Group on => Sum up identical columns, and hide all but 1
1719 q = $t.text().replace(equalsFilter, '$1=...$6').trim();
1720 q = q.replace(functionFilter, ' $1(...)');
1722 // Js does not specify a limit on property name length,
1723 // so we can abuse it as index :-)
1724 if (filteredQueries[q]) {
1725 filteredQueries[q] += parseInt($t.next().text(), 10);
1726 totalSum += parseInt($t.next().text(), 10);
1729 filteredQueries[q] = parseInt($t.next().text(), 10);
1730 filteredQueriesLines[q] = i;
1734 countRow(q, $t.parent().html());
1738 // Group off: Restore original columns
1740 rowData = $t.parent().data('query');
1742 $t.text(rowData[queryColumnName]);
1743 // Restore total count
1744 $t.next().text(rowData[sumColumnName]);
1745 // Restore slow log columns
1747 $t.parent().children('td:nth-child(3)').text(rowData['query_time']);
1748 $t.parent().children('td:nth-child(4)').text(rowData['lock_time']);
1749 $t.parent().children('td:nth-child(5)').text(rowData['rows_sent']);
1750 $t.parent().children('td:nth-child(6)').text(rowData['rows_examined']);
1755 // If not required to be hidden, do we need
1756 // to hide because of a not matching text filter?
1757 if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
1761 // Now display or hide this column
1763 $t.parent().css('display', 'none');
1765 totalSum += parseInt($t.next().text(), 10);
1768 odd_row = ! odd_row;
1769 $t.parent().css('display', '');
1771 $t.parent().addClass('odd');
1772 $t.parent().removeClass('even');
1774 $t.parent().addClass('even');
1775 $t.parent().removeClass('odd');
1783 // We finished summarizing counts => Update count values of all grouped entries
1784 if (varFilterChange) {
1786 var numCol, row, $table = $('#logTable table tbody');
1787 $.each(filteredQueriesLines, function (key, value) {
1788 if (filteredQueries[key] <= 1) {
1792 row = $table.children('tr:nth-child(' + (value + 1) + ')');
1793 numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
1794 numCol.text(filteredQueries[key]);
1797 row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
1798 row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
1799 row.children('td:nth-child(5)').text(columnSums[key][2]);
1800 row.children('td:nth-child(6)').text(columnSums[key][3]);
1805 $('#logTable table').trigger("update");
1806 setTimeout(function () {
1807 $('#logTable table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
1811 // Display some stats at the bottom of the table
1812 $('#logTable table tfoot tr')
1813 .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
1814 PMA_messages.strSumRows + ' ' + rowSum + '<span style="float:right">' +
1815 PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
1819 /* Turns a timespan (12:12:12) into a number */
1820 function timeToSec(timeStr) {
1821 var time = timeStr.split(':');
1822 return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
1825 /* Turns a number into a timespan (100 into 00:01:40) */
1826 function secToTime(timeInt) {
1827 var hours = Math.floor(timeInt / 3600);
1828 timeInt -= hours * 3600;
1829 var minutes = Math.floor(timeInt / 60);
1830 timeInt -= minutes * 60;
1833 hours = '0' + hours;
1836 minutes = '0' + minutes;
1839 timeInt = '0' + timeInt;
1842 return hours + ':' + minutes + ':' + timeInt;
1845 /* Constructs the log table out of the retrieved server data */
1846 function buildLogTable(data) {
1847 var rows = data.rows;
1849 var $table = $('<table class="sortable"></table>');
1850 var $tBody, $tRow, $tCell;
1852 $('#logTable').html($table);
1854 var formatValue = function (name, value) {
1855 if (name == 'user_host') {
1856 return value.replace(/(\[.*?\])+/g, '');
1861 for (var i = 0, l = rows.length; i < l; i++) {
1863 $.each(rows[0], function (key, value) {
1866 $table.append('<thead>' +
1867 '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
1871 $table.append($tBody = $('<tbody></tbody>'));
1874 $tBody.append($tRow = $('<tr class="noclick"></tr>'));
1876 for (var j = 0, ll = cols.length; j < ll; j++) {
1877 // Assuming the query column is the second last
1878 if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
1879 $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
1880 $tCell.click(openQueryAnalyzer);
1882 $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
1885 $tRow.data('query', rows[i]);
1889 $table.append('<tfoot>' +
1890 '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
1891 ' ' + data.numRows + '<span style="float:right">' + PMA_messages.strTotal +
1892 '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
1894 // Append a tooltip to the count column, if there exist one
1895 if ($('#logTable th:last').html() == '#') {
1896 $('#logTable th:last').append(' ' + PMA_getImage('b_docs.png', '', {'class': 'qroupedQueryInfoIcon'}));
1898 var tooltipContent = PMA_messages.strCountColumnExplanation;
1900 tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
1904 $('img.qroupedQueryInfoIcon'),
1910 $('#logTable table').tablesorter({
1911 sortList: [[cols.length - 1, 1]],
1912 widgets: ['fast-zebra']
1915 $('#logTable table thead th')
1916 .append('<img class="icon sortableIcon" src="themes/dot.gif" alt="">');
1921 /* Opens the query analyzer dialog */
1922 function openQueryAnalyzer() {
1923 var rowData = $(this).parent().data('query');
1924 var query = rowData.argument || rowData.sql_text;
1926 if (codemirror_editor) {
1927 //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
1928 //query = PMA_SQLPrettyPrint(query);
1929 codemirror_editor.setValue(query);
1930 // Codemirror is bugged, it doesn't refresh properly sometimes.
1931 // Following lines seem to fix that
1932 setTimeout(function () {
1933 codemirror_editor.refresh();
1937 $('#sqlquery').val(query);
1940 var profilingChart = null;
1943 dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
1944 loadQueryAnalysis(rowData);
1946 dlgBtns[PMA_messages.strClose] = function () {
1947 $(this).dialog('close');
1950 $('#queryAnalyzerDialog').dialog({
1955 close: function () {
1956 if (profilingChart !== null) {
1957 profilingChart.destroy();
1959 $('#queryAnalyzerDialog div.placeHolder').html('');
1960 if (codemirror_editor) {
1961 codemirror_editor.setValue('');
1963 $('#sqlquery').val('');
1969 /* Loads and displays the analyzed query data */
1970 function loadQueryAnalysis(rowData) {
1971 var db = rowData.db || '';
1973 $('#queryAnalyzerDialog div.placeHolder').html(
1974 PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
1975 pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1977 $.post('server_status_monitor.php?' + PMA_commonParams.get('common_query'), {
1979 query_analyzer: true,
1980 query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
1982 }, function (data) {
1984 if (data.success === true) {
1985 data = data.message;
1988 if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
1989 data.error = PMA_messages['strServerLogError'];
1991 $('#queryAnalyzerDialog div.placeHolder').html('<div class="error">' + data.error + '</div>');
1995 // Float sux, I'll use table :(
1996 $('#queryAnalyzerDialog div.placeHolder')
1997 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
1999 var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
2000 if (data.explain.length > 1) {
2002 for (i = 0; i < data.explain.length; i++) {
2006 explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
2010 explain += '<p></p>';
2011 for (i = 0, l = data.explain.length; i < l; i++) {
2012 explain += '<div class="explain-' + i + '"' + (i > 0 ? 'style="display:none;"' : '') + '>';
2013 $.each(data.explain[i], function (key, value) {
2014 value = (value === null) ? 'null' : value;
2016 if (key == 'type' && value.toLowerCase() == 'all') {
2017 value = '<span class="attention">' + value + '</span>';
2019 if (key == 'Extra') {
2020 value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
2022 explain += key + ': ' + value + '<br />';
2024 explain += '</div>';
2027 explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
2029 $('#queryAnalyzerDialog div.placeHolder td.explain').append(explain);
2031 $('#queryAnalyzerDialog div.placeHolder a[href*="#showExplain"]').click(function () {
2032 var id = $(this).attr('href').split('-')[1];
2033 $(this).parent().find('div[class*="explain"]').hide();
2034 $(this).parent().find('div[class*="explain-' + id + '"]').show();
2037 if (data.profiling) {
2039 var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
2043 for (i = 0, l = data.profiling.length; i < l; i++) {
2044 duration = parseFloat(data.profiling[i].duration);
2046 totalTime += duration;
2048 numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
2051 // Only put those values in the pie which are > 2%
2052 for (i = 0, l = data.profiling.length; i < l; i++) {
2053 duration = parseFloat(data.profiling[i].duration);
2055 if (duration / totalTime > 0.02) {
2056 chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
2058 otherTime += duration;
2062 if (otherTime > 0) {
2063 chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
2066 numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
2067 numberTable += '</tbody></table>';
2069 $('#queryAnalyzerDialog div.placeHolder td.chart').append(
2070 '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
2071 '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
2072 numberTable + ' <div id="queryProfiling"></div>');
2074 $('#queryAnalyzerDialog div.placeHolder a[href="#showNums"]').click(function () {
2075 $('#queryAnalyzerDialog #queryProfiling').hide();
2076 $('#queryAnalyzerDialog table.queryNums').show();
2080 $('#queryAnalyzerDialog div.placeHolder a[href="#showChart"]').click(function () {
2081 $('#queryAnalyzerDialog #queryProfiling').show();
2082 $('#queryAnalyzerDialog table.queryNums').hide();
2086 profilingChart = PMA_createProfilingChartJqplot(
2091 //$('#queryProfiling').resizable();
2096 /* Saves the monitor to localstorage */
2097 function saveMonitor() {
2100 $.each(runtime.charts, function (key, elem) {
2102 gridCopy[key].nodes = elem.nodes;
2103 gridCopy[key].settings = elem.settings;
2104 gridCopy[key].title = elem.title;
2105 gridCopy[key].series = elem.series;
2106 gridCopy[key].maxYLabel = elem.maxYLabel;
2109 if (window.localStorage) {
2110 window.localStorage['monitorCharts'] = JSON.stringify(gridCopy);
2111 window.localStorage['monitorSettings'] = JSON.stringify(monitorSettings);
2112 window.localStorage['monitorVersion'] = monitorProtocolVersion;
2115 $('a[href="#clearMonitorConfig"]').show();
2119 // Run the monitor once loaded
2120 AJAX.registerOnload('server_status_monitor.js', function () {
2121 $('a[href="#pauseCharts"]').trigger('click');
2124 function serverResponseError() {
2126 btns[PMA_messages.strReloadPage] = function () {
2127 window.location.reload();
2129 $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed});
2130 $('#emptyDialog').html(
2131 PMA_getImage('s_attention.png') +
2132 PMA_messages.strInvalidResponseExplanation
2134 $('#emptyDialog').dialog({ buttons: btns });
2137 /* Destroys all monitor related resources */
2138 function destroyGrid() {
2139 if (runtime.charts) {
2140 $.each(runtime.charts, function (key, value) {
2142 value.chart.destroy();
2148 runtime.refreshRequest.abort();
2151 clearTimeout(runtime.refreshTimeout);
2153 $('#chartGrid').html('');
2154 runtime.charts = null;
2155 runtime.chartAI = 0;
2156 monitorSettings = null; //TODO:this not global variable