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');
417 var tempManageCols = function () {
418 if (numColumns > monitorSettings.columns) {
419 if ($tr.next().length === 0) {
420 $tr.after('<tr></tr>');
422 $tr.next().prepend($(this));
427 var tempAddCol = function () {
428 if ($(this).next().length !== 0) {
429 $(this).append($(this).next().find('td:first'));
433 while ($tr.length !== 0) {
435 // To many cells in one row => put into next row
436 $tr.find('td').each(tempManageCols);
438 // To little cells in one row => for each cell to little,
439 // move all cells backwards by 1
440 if ($tr.next().length > 0) {
441 var cnt = monitorSettings.columns - $tr.find('td').length;
442 for (var i = 0; i < cnt; i++) {
443 $tr.append($tr.next().find('td:first'));
444 $tr.nextAll().each(tempAddCol);
452 if (monitorSettings.gridMaxPoints == 'auto') {
453 runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12);
456 runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
457 runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
460 $("#chartGrid").sortableTable('refresh');
464 saveMonitor(); // Save settings
467 $('div.popupContent select[name="gridChartRefresh"]').change(function () {
468 monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000;
469 clearTimeout(runtime.refreshTimeout);
471 if (runtime.refreshRequest) {
472 runtime.refreshRequest.abort();
475 runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
476 // fixing chart shift towards left on refresh rate change
477 //runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
478 runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
480 saveMonitor(); // Save settings
483 $('a[href="#addNewChart"]').click(function (event) {
484 event.preventDefault();
485 var dlgButtons = { };
487 dlgButtons[PMA_messages.strAddChart] = function () {
488 var type = $('input[name="chartType"]:checked').val();
490 if (type == 'preset') {
491 newChart = presetCharts[$('#addChartDialog select[name="presetCharts"]').prop('value')];
493 // If user builds his own chart, it's being set/updated
494 // each time he adds a series
495 // So here we only warn if he didn't add a series yet
496 if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) {
497 alert(PMA_messages.strAddOneSeriesWarning);
502 newChart.title = $('input[name="chartTitle"]').val();
503 // Add a cloned object to the chart grid
504 addChart($.extend(true, {}, newChart));
508 saveMonitor(); // Save settings
510 $(this).dialog("close");
513 dlgButtons[PMA_messages.strClose] = function () {
515 $('span#clearSeriesLink').hide();
516 $('#seriesPreview').html('');
517 $(this).dialog("close");
520 var $presetList = $('#addChartDialog select[name="presetCharts"]');
521 if ($presetList.html().length === 0) {
522 $.each(presetCharts, function (key, value) {
523 $presetList.append('<option value="' + key + '">' + value.title + '</option>');
525 $presetList.change(function () {
526 $('input[name="chartTitle"]').val(
527 $presetList.find(':selected').text()
529 $('#chartPreset').prop('checked', true);
531 $('#chartPreset').click(function () {
532 $('input[name="chartTitle"]').val(
533 $presetList.find(':selected').text()
536 $('#chartStatusVar').click(function () {
537 $('input[name="chartTitle"]').val(
538 $('#chartSeries').find(':selected').text().replace(/_/g, " ")
541 $('#chartSeries').change(function () {
542 $('input[name="chartTitle"]').val(
543 $('#chartSeries').find(':selected').text().replace(/_/g, " ")
548 $('#addChartDialog').dialog({
554 $('#addChartDialog #seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
559 $('a[href="#exportMonitorConfig"]').click(function (event) {
560 event.preventDefault();
562 $.each(runtime.charts, function (key, elem) {
564 gridCopy[key].nodes = elem.nodes;
565 gridCopy[key].settings = elem.settings;
566 gridCopy[key].title = elem.title;
569 monitorCharts: gridCopy,
570 monitorSettings: monitorSettings
573 "class": "disableAjax",
575 action: "file_echo.php" + PMA_commonParams.get('common_query') + "&filename=1",
576 style: "display:none;"
581 name: "monitorconfig",
582 value: JSON.stringify(exportData)
590 $('a[href="#importMonitorConfig"]').click(function (event) {
591 event.preventDefault();
592 $('#emptyDialog').dialog({title: PMA_messages.strImportDialogTitle});
593 $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ':<br/><form action="file_echo.php' + PMA_commonParams.get('common_query') + '&import=1" method="post" enctype="multipart/form-data">' +
594 '<input type="file" name="file"> <input type="hidden" name="import" value="1"> </form>');
598 dlgBtns[PMA_messages.strImport] = function () {
600 $('body').append($iframe = $('<iframe id="monitorConfigUpload" style="display:none;"></iframe>'));
601 var d = $iframe[0].contentWindow.document;
606 $iframe.load(function () {
609 // Try loading config
611 var data = $('body', $('iframe#monitorConfigUpload')[0].contentWindow.document).html();
612 // Chrome wraps around '<pre style="word-wrap: break-word; white-space: pre-wrap;">' to any text content -.-
613 json = $.parseJSON(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
615 alert(PMA_messages.strFailedParsingConfig);
616 $('#emptyDialog').dialog('close');
620 // Basic check, is this a monitor config json?
621 if (!json || ! json.monitorCharts || ! json.monitorCharts) {
622 alert(PMA_messages.strFailedParsingConfig);
623 $('#emptyDialog').dialog('close');
627 // If json ok, try applying config
629 window.localStorage.monitorCharts = JSON.stringify(json.monitorCharts);
630 window.localStorage.monitorSettings = JSON.stringify(json.monitorSettings);
633 alert(PMA_messages.strFailedBuildingGrid);
634 // If an exception is thrown, load default again
635 window.localStorage.removeItem('monitorCharts');
636 window.localStorage.removeItem('monitorSettings');
640 $('#emptyDialog').dialog('close');
643 $("body", d).append($form = $('#emptyDialog').find('form'));
645 $('#emptyDialog').append('<img class="ajaxIcon" src="' + pmaThemeImage + 'ajax_clock_small.gif" alt="">');
648 dlgBtns[PMA_messages.strCancel] = function () {
649 $(this).dialog('close');
653 $('#emptyDialog').dialog({
660 $('a[href="#clearMonitorConfig"]').click(function (event) {
661 event.preventDefault();
662 window.localStorage.removeItem('monitorCharts');
663 window.localStorage.removeItem('monitorSettings');
664 window.localStorage.removeItem('monitorVersion');
669 $('a[href="#pauseCharts"]').click(function (event) {
670 event.preventDefault();
671 runtime.redrawCharts = ! runtime.redrawCharts;
672 if (! runtime.redrawCharts) {
673 $(this).html(PMA_getImage('play.png') + PMA_messages.strResumeMonitor);
675 $(this).html(PMA_getImage('pause.png') + PMA_messages.strPauseMonitor);
676 if (! runtime.charts) {
678 $('a[href="#settingsPopup"]').show();
684 $('a[href="#monitorInstructionsDialog"]').click(function (event) {
685 event.preventDefault();
687 var $dialog = $('#monitorInstructionsDialog');
692 }).find('img.ajaxIcon').show();
694 var loadLogVars = function (getvars) {
695 var vars = { ajax_request: true, logging_vars: true };
697 $.extend(vars, getvars);
700 $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'), vars,
703 if (typeof data !== 'undefined' && data.success === true) {
704 logVars = data.message;
706 return serverResponseError();
708 var icon = PMA_getImage('s_success.png'), msg = '', str = '';
710 if (logVars.general_log == 'ON') {
711 if (logVars.slow_query_log == 'ON') {
712 msg = PMA_messages.strBothLogOn;
714 msg = PMA_messages.strGenLogOn;
718 if (msg.length === 0 && logVars.slow_query_log == 'ON') {
719 msg = PMA_messages.strSlowLogOn;
722 if (msg.length === 0) {
723 icon = PMA_getImage('s_error.png');
724 msg = PMA_messages.strBothLogOff;
727 str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">';
728 str += icon + msg + '<br />';
730 if (logVars.log_output != 'TABLE') {
731 str += PMA_getImage('s_error.png') + ' ' + PMA_messages.strLogOutNotTable + '<br />';
733 str += PMA_getImage('s_success.png') + ' ' + PMA_messages.strLogOutIsTable + '<br />';
736 if (logVars.slow_query_log == 'ON') {
737 if (logVars.long_query_time > 2) {
738 str += PMA_getImage('s_attention.png') + ' ';
739 str += PMA_sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
743 if (logVars.long_query_time < 2) {
744 str += PMA_getImage('s_success.png') + ' ';
745 str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time);
753 str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>';
754 str += '<div class="smallIndent">';
755 str += PMA_messages.strSettingsAppliedGlobal + '<br/>';
757 var varValue = 'TABLE';
758 if (logVars.log_output == 'TABLE') {
762 str += '- <a class="set" href="#log_output-' + varValue + '">';
763 str += PMA_sprintf(PMA_messages.strSetLogOutput, varValue);
764 str += ' </a><br />';
766 if (logVars.general_log != 'ON') {
767 str += '- <a class="set" href="#general_log-ON">';
768 str += PMA_sprintf(PMA_messages.strEnableVar, 'general_log');
769 str += ' </a><br />';
771 str += '- <a class="set" href="#general_log-OFF">';
772 str += PMA_sprintf(PMA_messages.strDisableVar, 'general_log');
773 str += ' </a><br />';
776 if (logVars.slow_query_log != 'ON') {
777 str += '- <a class="set" href="#slow_query_log-ON">';
778 str += PMA_sprintf(PMA_messages.strEnableVar, 'slow_query_log');
779 str += ' </a><br />';
781 str += '- <a class="set" href="#slow_query_log-OFF">';
782 str += PMA_sprintf(PMA_messages.strDisableVar, 'slow_query_log');
783 str += ' </a><br />';
787 if (logVars.long_query_time > 2) {
791 str += '- <a class="set" href="#long_query_time-' + varValue + '">';
792 str += PMA_sprintf(PMA_messages.setSetLongQueryTime, varValue);
793 str += ' </a><br />';
796 str += PMA_messages.strNoSuperUser + '<br/>';
801 $dialog.find('div.monitorUse').toggle(
802 logVars.log_output == 'TABLE' && (logVars.slow_query_log == 'ON' || logVars.general_log == 'ON')
805 $dialog.find('div.ajaxContent').html(str);
806 $dialog.find('img.ajaxIcon').hide();
807 $dialog.find('a.set').click(function () {
808 var nameValue = $(this).attr('href').split('-');
809 loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1]});
810 $dialog.find('img.ajaxIcon').show();
822 $('input[name="chartType"]').change(function () {
823 $('#chartVariableSettings').toggle(this.checked && this.value == 'variable');
824 var title = $('input[name="chartTitle"]').val();
825 if (title == PMA_messages.strChartTitle ||
826 title == $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
828 $('input[name="chartTitle"]')
829 .data('lastRadio', $(this).attr('id'))
830 .val($('label[for="' + $(this).attr('id') + '"]').text());
835 $('input[name="useDivisor"]').change(function () {
836 $('span.divisorInput').toggle(this.checked);
839 $('input[name="useUnit"]').change(function () {
840 $('span.unitInput').toggle(this.checked);
843 $('select[name="varChartList"]').change(function () {
844 if (this.selectedIndex !== 0) {
845 $('#variableInput').val(this.value);
849 $('a[href="#kibDivisor"]').click(function (event) {
850 event.preventDefault();
851 $('input[name="valueDivisor"]').val(1024);
852 $('input[name="valueUnit"]').val(PMA_messages.strKiB);
853 $('span.unitInput').toggle(true);
854 $('input[name="useUnit"]').prop('checked', true);
858 $('a[href="#mibDivisor"]').click(function (event) {
859 event.preventDefault();
860 $('input[name="valueDivisor"]').val(1024 * 1024);
861 $('input[name="valueUnit"]').val(PMA_messages.strMiB);
862 $('span.unitInput').toggle(true);
863 $('input[name="useUnit"]').prop('checked', true);
867 $('a[href="#submitClearSeries"]').click(function (event) {
868 event.preventDefault();
869 $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
871 $('#clearSeriesLink').hide();
874 $('a[href="#submitAddSeries"]').click(function (event) {
875 event.preventDefault();
876 if ($('#variableInput').val() === "") {
880 if (newChart === null) {
881 $('#seriesPreview').html('');
884 title: $('input[name="chartTitle"]').val(),
892 dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
893 display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
896 if (serie.dataPoints[0].name == 'Processes') {
897 serie.dataPoints[0].type = 'proc';
900 if ($('input[name="useDivisor"]').prop('checked')) {
901 serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
904 if ($('input[name="useUnit"]').prop('checked')) {
905 serie.unit = $('input[name="valueUnit"]').val();
908 var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
909 str += serie.valueDivisor ? (', ' + PMA_sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
910 str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
913 label: $('#variableInput').val().replace(/_/g, " ")
915 newChart.series.push(newSeries);
916 $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '<br/>');
917 newChart.nodes.push(serie);
918 $('#variableInput').val('');
919 $('input[name="differentialValue"]').prop('checked', true);
920 $('input[name="useDivisor"]').prop('checked', false);
921 $('input[name="useUnit"]').prop('checked', false);
922 $('input[name="useDivisor"]').trigger('change');
923 $('input[name="useUnit"]').trigger('change');
924 $('select[name="varChartList"]').get(0).selectedIndex = 0;
926 $('#clearSeriesLink').show();
931 $("#variableInput").autocomplete({
932 source: variableNames
935 /* Initializes the monitor, called only once */
936 function initGrid() {
940 /* Apply default values & config */
941 if (window.localStorage) {
942 if (window.localStorage.monitorCharts) {
943 runtime.charts = $.parseJSON(window.localStorage.monitorCharts);
945 if (window.localStorage.monitorSettings) {
946 monitorSettings = $.parseJSON(window.localStorage.monitorSettings);
949 $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
951 if (runtime.charts !== null && monitorProtocolVersion != window.localStorage.monitorVersion) {
952 $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
953 $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
956 dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };
958 $('#emptyDialog').dialog({
965 if (runtime.charts === null) {
966 runtime.charts = defaultChartGrid;
968 if (monitorSettings === null) {
969 monitorSettings = defaultMonitorSettings;
972 $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
973 $('select[name="chartColumns"]').val(monitorSettings.columns);
975 if (monitorSettings.gridMaxPoints == 'auto') {
976 runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
978 runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
981 runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
982 runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
984 /* Calculate how much spacing there is between each chart */
985 $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
987 width: $('#chartGrid td:nth-child(2)').offset().left -
988 $('#chartGrid td:nth-child(1)').offset().left,
989 height: $('#chartGrid tr:nth-child(2) td:nth-child(2)').offset().top -
990 $('#chartGrid tr:nth-child(1) td:nth-child(1)').offset().top
992 $('#chartGrid').html('');
994 /* Add all charts - in correct order */
996 $.each(runtime.charts, function (key, value) {
1000 for (i = 0; i < keys.length; i++) {
1001 addChart(runtime.charts[keys[i]], true);
1004 /* Fill in missing cells */
1005 var numCharts = $('#chartGrid .monitorChart').length;
1006 var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
1007 for (i = 0; i < numMissingCells; i++) {
1008 $('#chartGrid tr:last').append('<td></td>');
1011 // Empty cells should keep their size so you can drop onto them
1012 calculateChartSize();
1013 $('#chartGrid tr td').css('width', chartSize.width + 'px');
1015 buildRequiredDataList();
1019 /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
1020 * data from each chart and restores it after the monitor is initialized again */
1021 function rebuildGrid() {
1023 if (runtime.charts) {
1025 $.each(runtime.charts, function (key, chartObj) {
1026 for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
1027 oldData[chartObj.nodes[i].dataPoint] = [];
1028 for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
1029 oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
1039 /* Calculactes the dynamic chart size that depends on the column width */
1040 function calculateChartSize() {
1042 if ($("body").height() > $(window).height()) { // has vertical scroll bar
1043 panelWidth = $('#logTable').innerWidth();
1045 panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
1048 var wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
1050 width: Math.floor(wdt),
1051 height: Math.floor(0.75 * wdt)
1055 /* Adds a chart to the chart grid */
1056 function addChart(chartObj, initialize) {
1060 title: escapeHtml(chartObj.title),
1064 background: 'rgba(0,0,0,0)'
1068 renderer: $.jqplot.DateAxisRenderer,
1070 formatString: '%H:%M:%S',
1097 if (settings.title === PMA_messages.strSystemCPUUsage ||
1098 settings.title === PMA_messages.strQueryCacheEfficiency
1100 settings.axes.yaxis.tickOptions = {
1101 formatString: "%d %%"
1103 } else if (settings.title === PMA_messages.strSystemMemory ||
1104 settings.title === PMA_messages.strSystemSwap
1106 settings.stackSeries = true;
1107 settings.axes.yaxis.tickOptions = {
1108 formatter: $.jqplot.byteFormatter(2) // MiB
1110 } else if (settings.title === PMA_messages.strTraffic) {
1111 settings.axes.yaxis.tickOptions = {
1112 formatter: $.jqplot.byteFormatter(1) // KiB
1114 } else if (settings.title === PMA_messages.strQuestions ||
1115 settings.title === PMA_messages.strConnections
1117 settings.axes.yaxis.tickOptions = {
1118 formatter: function (format, val) {
1119 if (Math.abs(val) >= 1000000) {
1120 return $.jqplot.sprintf("%.3g M", val / 1000000);
1121 } else if (Math.abs(val) >= 1000) {
1122 return $.jqplot.sprintf("%.3g k", val / 1000);
1124 return $.jqplot.sprintf("%d", val);
1130 settings.series = chartObj.series;
1132 if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
1133 var numCharts = $('#chartGrid .monitorChart').length;
1135 if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
1136 $('#chartGrid').append('<tr></tr>');
1140 calculateChartSize();
1142 $('#chartGrid tr:last').append(
1143 '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
1144 '<div class="ui-state-default monitorChart"' +
1145 ' id="gridchart' + runtime.chartAI + '"' +
1146 ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' +
1151 // Set series' data as [0,0], smooth lines won't plot with data array having null values.
1152 // also chart won't plot initially with no data and data comes on refreshChartGrid()
1154 for (i in chartObj.series) {
1155 series.push([[0, 0]]);
1158 var tempTooltipContentEditor = function (str, seriesIndex, pointIndex, plot) {
1160 // TODO: move style to theme CSS
1161 var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' +
1162 'opacity:0.95;filter:alpha(opacity=95);padding:5px;">';
1163 // x value i.e. time
1164 var timeValue = str.split(",")[0];
1166 tooltipHtml += 'Time: ' + timeValue;
1167 tooltipHtml += '<span style="font-weight:bold;">';
1168 // Add y values to the tooltip per series
1169 for (j in plot.series) {
1170 // get y value if present
1171 if (plot.series[j].data.length > pointIndex) {
1172 seriesValue = plot.series[j].data[pointIndex][1];
1176 var seriesLabel = plot.series[j].label;
1177 var seriesColor = plot.series[j].color;
1179 if (plot.series[0]._yaxis.tickOptions.formatter) {
1180 // using formatter function
1181 seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
1182 } else if (plot.series[0]._yaxis.tickOptions.formatString) {
1183 // using format string
1184 seriesValue = PMA_sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
1186 tooltipHtml += '<br /><span style="color:' + seriesColor + '">' +
1187 seriesLabel + ': ' + seriesValue + '</span>';
1189 tooltipHtml += '</span></div>';
1193 // set Tooltip for each series
1194 for (i in settings.series) {
1195 settings.series[i].highlighter = {
1197 tooltipContentEditor: tempTooltipContentEditor
1201 chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings);
1202 // remove [0,0] after plotting
1203 for (i in chartObj.chart.series) {
1204 chartObj.chart.series[i].data.shift();
1207 var $legend = $('<div />').css('padding', '0.5em');
1208 for (i in chartObj.chart.series) {
1210 $('<div />').append(
1214 background: chartObj.chart.seriesColors[i]
1215 }).addClass('floatleft')
1218 chartObj.chart.series[i].label
1219 ).addClass('floatleft')
1221 $('<div class="clearfloat">')
1222 ).addClass('floatleft')
1225 $('#gridchart' + runtime.chartAI)
1229 if (initialize !== true) {
1230 runtime.charts['c' + runtime.chartAI] = chartObj;
1231 buildRequiredDataList();
1234 // time span selection
1235 $('#gridchart' + runtime.chartAI).bind('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) {
1236 drawTimeSpan = true;
1237 selectionTimeDiff.push(datapos.xaxis);
1238 if ($('#selection_box').length) {
1239 $('#selection_box').remove();
1241 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;">');
1242 $(document.body).append(selectionBox);
1243 selectionStartX = ev.pageX;
1244 selectionStartY = ev.pageY;
1246 .attr({id: 'selection_box'})
1248 top: selectionStartY - gridpos.y,
1249 left: selectionStartX
1254 $('#gridchart' + runtime.chartAI).bind('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) {
1255 if (! drawTimeSpan || editMode) {
1259 selectionTimeDiff.push(datapos.xaxis);
1261 if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
1262 selectionTimeDiff = [];
1265 //get date from timestamp
1266 var min = new Date(Math.ceil(selectionTimeDiff[0]));
1267 var max = new Date(Math.ceil(selectionTimeDiff[1]));
1268 PMA_getLogAnalyseDialog(min, max);
1269 selectionTimeDiff = [];
1270 drawTimeSpan = false;
1273 $('#gridchart' + runtime.chartAI).bind('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) {
1274 if (! drawTimeSpan || editMode) {
1277 if (selectionStartX !== undefined) {
1280 width: Math.ceil(ev.pageX - selectionStartX)
1286 $('#gridchart' + runtime.chartAI).bind('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) {
1287 drawTimeSpan = false;
1290 $(document.body).mouseup(function () {
1291 if ($('#selection_box').length) {
1292 selectionBox.remove();
1296 // Edit, Print icon only in edit mode
1297 $('#chartGrid div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
1302 function PMA_getLogAnalyseDialog(min, max) {
1303 var $dateStart = $('#logAnalyseDialog input[name="dateStart"]');
1304 var $dateEnd = $('#logAnalyseDialog input[name="dateEnd"]');
1305 $dateStart.prop("readonly", true);
1306 $dateEnd.prop("readonly", true);
1310 dlgBtns[PMA_messages.strFromSlowLog] = function () {
1311 loadLog('slow', min, max);
1312 $(this).dialog("close");
1315 dlgBtns[PMA_messages.strFromGeneralLog] = function () {
1316 loadLog('general', min, max);
1317 $(this).dialog("close");
1320 $('#logAnalyseDialog').dialog({
1326 PMA_addDatepicker($dateStart, 'datetime', {
1327 showMillisec: false,
1328 showMicrosec: false,
1329 timeFormat: 'HH:mm:ss'
1331 PMA_addDatepicker($dateEnd, 'datetime', {
1332 showMillisec: false,
1333 showMicrosec: false,
1334 timeFormat: 'HH:mm:ss'
1336 $('#logAnalyseDialog input[name="dateStart"]').datepicker('setDate', min);
1337 $('#logAnalyseDialog input[name="dateEnd"]').datepicker('setDate', max);
1340 function loadLog(type, min, max) {
1341 var dateStart = Date.parse($('#logAnalyseDialog input[name="dateStart"]').datepicker('getDate')) || min;
1342 var dateEnd = Date.parse($('#logAnalyseDialog input[name="dateEnd"]').datepicker('getDate')) || max;
1348 removeVariables: $('#removeVariables').prop('checked'),
1349 limitTypes: $('#limitTypes').prop('checked')
1353 /* Called in regular intervalls, this function updates the values of each chart in the grid */
1354 function refreshChartGrid() {
1355 /* Send to server */
1356 runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1360 requiredData: JSON.stringify(runtime.dataList)
1361 }, function (data) {
1363 if (typeof data !== 'undefined' && data.success === true) {
1364 chartData = data.message;
1366 return serverResponseError();
1372 /* Update values in each graph */
1373 $.each(runtime.charts, function (orderKey, elem) {
1374 var key = elem.chartID;
1375 // If newly added chart, we have no data for it yet
1376 if (! chartData[key]) {
1381 for (var j = 0; j < elem.nodes.length; j++) {
1383 if (i === 0 && j === 0) {
1384 if (oldChartData === null) {
1385 diff = chartData.x - runtime.xmax;
1387 diff = parseInt(chartData.x - oldChartData.x, 10);
1390 runtime.xmin += diff;
1391 runtime.xmax += diff;
1394 //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
1395 /* Calculate y value */
1397 // If transform function given, use it
1398 if (elem.nodes[j].transformFn) {
1399 value = chartValueTransform(
1400 elem.nodes[j].transformFn,
1402 // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
1404 oldChartData === null ||
1405 oldChartData[key] === null ||
1406 oldChartData[key] === undefined ? null : oldChartData[key][j]
1410 // Otherwise use original value and apply differential and divisor if given,
1411 // in this case we have only one data point per series - located at chartData[key][j][0]
1413 value = parseFloat(chartData[key][j][0].value);
1415 if (elem.nodes[j].display == 'differential') {
1416 if (oldChartData === null ||
1417 oldChartData[key] === null ||
1418 oldChartData[key] === undefined
1422 value -= oldChartData[key][j][0].value;
1425 if (elem.nodes[j].valueDivisor) {
1426 value = value / elem.nodes[j].valueDivisor;
1430 // Set y value, if defined
1431 if (value !== undefined) {
1432 elem.chart.series[j].data.push([chartData.x, value]);
1433 if (value > elem.maxYLabel) {
1434 elem.maxYLabel = value;
1435 } else if (elem.maxYLabel === 0) {
1436 elem.maxYLabel = 0.5;
1438 // free old data point values and update maxYLabel
1439 if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
1440 elem.chart.series[j].data[0][0] < runtime.xmin
1442 // check if the next freeable point is highest
1443 if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
1444 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1445 elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
1447 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1450 if (elem.title === PMA_messages.strSystemMemory ||
1451 elem.title === PMA_messages.strSystemSwap
1458 // update chart options
1459 // keep ticks number/positioning consistent while refreshrate changes
1460 var tickInterval = (runtime.xmax - runtime.xmin) / 5;
1461 elem.chart.axes.xaxis.ticks = [(runtime.xmax - tickInterval * 4),
1462 (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
1463 (runtime.xmax - tickInterval), runtime.xmax];
1465 if (elem.title !== PMA_messages.strSystemCPUUsage &&
1466 elem.title !== PMA_messages.strQueryCacheEfficiency &&
1467 elem.title !== PMA_messages.strSystemMemory &&
1468 elem.title !== PMA_messages.strSystemSwap
1470 elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
1471 elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
1472 } else if (elem.title === PMA_messages.strSystemMemory ||
1473 elem.title === PMA_messages.strSystemSwap
1475 elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
1476 elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
1480 if (runtime.redrawCharts) {
1481 elem.chart.replot();
1485 oldChartData = chartData;
1487 runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
1491 /* Function to get highest plotted point's y label, to scale the chart,
1492 * TODO: make jqplot's autoscale:true work here
1494 function getMaxYLabel(dataValues) {
1495 var maxY = dataValues[0][1];
1496 $.each(dataValues, function (k, v) {
1497 maxY = (v[1] > maxY) ? v[1] : maxY;
1502 /* Function that supplies special value transform functions for chart values */
1503 function chartValueTransform(name, cur, prev) {
1506 if (prev === null) {
1509 // cur and prev are datapoint arrays, but containing
1510 // only 1 element for cpu-linux
1514 var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
1515 var diff_idle = cur.idle - prev.idle;
1516 return 100 * (diff_total - diff_idle) / diff_total;
1518 // Query cache efficiency (%)
1520 if (prev === null) {
1523 // cur[0].value is Qcache_hits, cur[1].value is Com_select
1524 var diffQHits = cur[0].value - prev[0].value;
1525 // No NaN please :-)
1526 if (cur[1].value - prev[1].value === 0) {
1530 return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
1532 // Query cache usage (%)
1534 if (cur[1].value === 0) {
1537 // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
1538 return 100 - cur[0].value / cur[1].value * 100;
1544 /* Build list of nodes that need to be retrieved from server.
1545 * It creates something like a stripped down version of the runtime.charts object.
1547 function buildRequiredDataList() {
1548 runtime.dataList = {};
1549 // Store an own id, because the property name is subject of reordering,
1550 // thus destroying our mapping with runtime.charts <=> runtime.dataList
1552 $.each(runtime.charts, function (key, chart) {
1553 runtime.dataList[chartID] = [];
1554 for (var i = 0, l = chart.nodes.length; i < l; i++) {
1555 runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
1557 runtime.charts[key].chartID = chartID;
1562 /* Loads the log table data, generates the table and handles the filters */
1563 function loadLogStatistics(opts) {
1565 var logRequest = null;
1567 if (! opts.removeVariables) {
1568 opts.removeVariables = false;
1570 if (! opts.limitTypes) {
1571 opts.limitTypes = false;
1574 $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle});
1575 $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
1576 ' <img class="ajaxIcon" src="' + pmaThemeImage +
1577 'ajax_clock_small.gif" alt="">');
1580 dlgBtns[PMA_messages.strCancelRequest] = function () {
1581 if (logRequest !== null) {
1585 $(this).dialog("close");
1588 $('#emptyDialog').dialog({
1595 logRequest = $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'),
1596 { ajax_request: true,
1599 time_start: Math.round(opts.start / 1000),
1600 time_end: Math.round(opts.end / 1000),
1601 removeVariables: opts.removeVariables,
1602 limitTypes: opts.limitTypes
1607 if (typeof data !== 'undefined' && data.success === true) {
1608 logData = data.message;
1610 return serverResponseError();
1613 if (logData.rows.length !== 0) {
1614 runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
1616 /* Show some stats in the dialog */
1617 $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
1618 $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
1619 $.each(logData.sum, function (key, value) {
1620 key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
1621 if (key == 'Total') {
1622 key = '<b>' + key + '</b>';
1624 $('#emptyDialog').append(key + ': ' + value + '<br/>');
1627 /* Add filter options if more than a bunch of rows there to filter */
1628 if (logData.numRows > 12) {
1629 $('#logTable').prepend(
1630 '<fieldset id="logDataFilter">' +
1631 ' <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
1632 ' <div class="formelement">' +
1633 ' <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
1634 ' <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1636 ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
1637 ' <div class="formelement">' +
1638 ' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1639 ' <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
1644 $('#logTable #noWHEREData').change(function () {
1645 filterQueries(true);
1648 if (logData.numRows > 250) {
1649 $('#logTable #startFilterQueryText').click(filterQueries);
1651 $('#logTable #filterQueryText').keyup(filterQueries);
1656 dlgBtns[PMA_messages.strJumpToTable] = function () {
1657 $(this).dialog("close");
1658 $(document).scrollTop($('#logTable').offset().top);
1661 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1664 $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
1665 $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
1667 dlgBtns[PMA_messages.strClose] = function () {
1668 $(this).dialog("close");
1671 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1676 /* Handles the actions performed when the user uses any of the
1677 * log table filters which are the filter by name and grouping
1678 * with ignoring data in WHERE clauses
1680 * @param boolean Should be true when the users enabled or disabled
1681 * to group queries ignoring data in WHERE clauses
1683 function filterQueries(varFilterChange) {
1684 var odd_row = false, cell, textFilter;
1685 var val = $('#logTable #filterQueryText').val();
1687 if (val.length === 0) {
1690 textFilter = new RegExp(val, 'i');
1693 var rowSum = 0, totalSum = 0, i = 0, q;
1694 var noVars = $('#logTable #noWHEREData').prop('checked');
1695 var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1696 var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
1697 var filteredQueries = {}, filteredQueriesLines = {};
1698 var hide = false, rowData;
1699 var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
1700 var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
1701 var isSlowLog = opts.src == 'slow';
1702 var columnSums = {};
1704 // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
1705 var countRow = function (query, row) {
1706 var cells = row.match(/<td>(.*?)<\/td>/gi);
1707 if (!columnSums[query]) {
1708 columnSums[query] = [0, 0, 0, 0];
1711 // lock_time and query_time and displayed in timespan format
1712 columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
1713 columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
1714 // rows_examind and rows_sent are just numbers
1715 columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
1716 columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
1719 // We just assume the sql text is always in the second last column, and that the total count is right of it
1720 $('#logTable table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
1722 // If query is a SELECT and user enabled or disabled to group
1723 // queries ignoring data in where statements, we
1724 // need to re-calculate the sums of each row
1725 if (varFilterChange && $t.html().match(/^SELECT/i)) {
1727 // Group on => Sum up identical columns, and hide all but 1
1729 q = $t.text().replace(equalsFilter, '$1=...$6').trim();
1730 q = q.replace(functionFilter, ' $1(...)');
1732 // Js does not specify a limit on property name length,
1733 // so we can abuse it as index :-)
1734 if (filteredQueries[q]) {
1735 filteredQueries[q] += parseInt($t.next().text(), 10);
1736 totalSum += parseInt($t.next().text(), 10);
1739 filteredQueries[q] = parseInt($t.next().text(), 10);
1740 filteredQueriesLines[q] = i;
1744 countRow(q, $t.parent().html());
1748 // Group off: Restore original columns
1750 rowData = $t.parent().data('query');
1752 $t.text(rowData[queryColumnName]);
1753 // Restore total count
1754 $t.next().text(rowData[sumColumnName]);
1755 // Restore slow log columns
1757 $t.parent().children('td:nth-child(3)').text(rowData.query_time);
1758 $t.parent().children('td:nth-child(4)').text(rowData.lock_time);
1759 $t.parent().children('td:nth-child(5)').text(rowData.rows_sent);
1760 $t.parent().children('td:nth-child(6)').text(rowData.rows_examined);
1765 // If not required to be hidden, do we need
1766 // to hide because of a not matching text filter?
1767 if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
1771 // Now display or hide this column
1773 $t.parent().css('display', 'none');
1775 totalSum += parseInt($t.next().text(), 10);
1778 odd_row = ! odd_row;
1779 $t.parent().css('display', '');
1781 $t.parent().addClass('odd');
1782 $t.parent().removeClass('even');
1784 $t.parent().addClass('even');
1785 $t.parent().removeClass('odd');
1793 // We finished summarizing counts => Update count values of all grouped entries
1794 if (varFilterChange) {
1796 var numCol, row, $table = $('#logTable table tbody');
1797 $.each(filteredQueriesLines, function (key, value) {
1798 if (filteredQueries[key] <= 1) {
1802 row = $table.children('tr:nth-child(' + (value + 1) + ')');
1803 numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
1804 numCol.text(filteredQueries[key]);
1807 row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
1808 row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
1809 row.children('td:nth-child(5)').text(columnSums[key][2]);
1810 row.children('td:nth-child(6)').text(columnSums[key][3]);
1815 $('#logTable table').trigger("update");
1816 setTimeout(function () {
1817 $('#logTable table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
1821 // Display some stats at the bottom of the table
1822 $('#logTable table tfoot tr')
1823 .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
1824 PMA_messages.strSumRows + ' ' + rowSum + '<span style="float:right">' +
1825 PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
1829 /* Turns a timespan (12:12:12) into a number */
1830 function timeToSec(timeStr) {
1831 var time = timeStr.split(':');
1832 return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
1835 /* Turns a number into a timespan (100 into 00:01:40) */
1836 function secToTime(timeInt) {
1837 var hours = Math.floor(timeInt / 3600);
1838 timeInt -= hours * 3600;
1839 var minutes = Math.floor(timeInt / 60);
1840 timeInt -= minutes * 60;
1843 hours = '0' + hours;
1846 minutes = '0' + minutes;
1849 timeInt = '0' + timeInt;
1852 return hours + ':' + minutes + ':' + timeInt;
1855 /* Constructs the log table out of the retrieved server data */
1856 function buildLogTable(data, groupInserts) {
1857 var rows = data.rows;
1859 var $table = $('<table class="sortable"></table>');
1860 var $tBody, $tRow, $tCell;
1862 $('#logTable').html($table);
1864 var tempPushKey = function (key, value) {
1868 var formatValue = function (name, value) {
1869 if (name == 'user_host') {
1870 return value.replace(/(\[.*?\])+/g, '');
1872 return escapeHtml(value);
1875 for (var i = 0, l = rows.length; i < l; i++) {
1877 $.each(rows[0], tempPushKey);
1878 $table.append('<thead>' +
1879 '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
1883 $table.append($tBody = $('<tbody></tbody>'));
1886 $tBody.append($tRow = $('<tr class="noclick"></tr>'));
1888 for (var j = 0, ll = cols.length; j < ll; j++) {
1889 // Assuming the query column is the second last
1890 if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
1891 $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
1892 $tCell.click(openQueryAnalyzer);
1894 $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
1897 $tRow.data('query', rows[i]);
1901 $table.append('<tfoot>' +
1902 '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
1903 ' ' + data.numRows + '<span style="float:right">' + PMA_messages.strTotal +
1904 '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
1906 // Append a tooltip to the count column, if there exist one
1907 if ($('#logTable tr:first th:last').text().indexOf("#") > -1) {
1908 $('#logTable tr:first th:last').append(' ' + PMA_getImage('b_help.png', '', {'class': 'qroupedQueryInfoIcon'}));
1910 var tooltipContent = PMA_messages.strCountColumnExplanation;
1912 tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
1916 $('img.qroupedQueryInfoIcon'),
1922 $('#logTable table').tablesorter({
1923 sortList: [[cols.length - 1, 1]],
1924 widgets: ['fast-zebra']
1927 $('#logTable table thead th')
1928 .append('<div class="sorticon"></div>');
1933 /* Opens the query analyzer dialog */
1934 function openQueryAnalyzer() {
1935 var rowData = $(this).parent().data('query');
1936 var query = rowData.argument || rowData.sql_text;
1938 if (codemirror_editor) {
1939 //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
1940 //query = PMA_SQLPrettyPrint(query);
1941 codemirror_editor.setValue(query);
1942 // Codemirror is bugged, it doesn't refresh properly sometimes.
1943 // Following lines seem to fix that
1944 setTimeout(function () {
1945 codemirror_editor.refresh();
1949 $('#sqlquery').val(query);
1952 var profilingChart = null;
1955 dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
1956 loadQueryAnalysis(rowData);
1958 dlgBtns[PMA_messages.strClose] = function () {
1959 $(this).dialog('close');
1962 $('#queryAnalyzerDialog').dialog({
1967 close: function () {
1968 if (profilingChart !== null) {
1969 profilingChart.destroy();
1971 $('#queryAnalyzerDialog div.placeHolder').html('');
1972 if (codemirror_editor) {
1973 codemirror_editor.setValue('');
1975 $('#sqlquery').val('');
1981 /* Loads and displays the analyzed query data */
1982 function loadQueryAnalysis(rowData) {
1983 var db = rowData.db || '';
1985 $('#queryAnalyzerDialog div.placeHolder').html(
1986 PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
1987 pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1989 $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1991 query_analyzer: true,
1992 query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
1994 }, function (data) {
1996 if (typeof data !== 'undefined' && data.success === true) {
1997 data = data.message;
2000 if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
2001 data.error = PMA_messages.strServerLogError;
2003 $('#queryAnalyzerDialog div.placeHolder').html('<div class="error">' + data.error + '</div>');
2007 // Float sux, I'll use table :(
2008 $('#queryAnalyzerDialog div.placeHolder')
2009 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
2011 var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
2012 if (data.explain.length > 1) {
2014 for (i = 0; i < data.explain.length; i++) {
2018 explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
2022 explain += '<p></p>';
2024 var tempExplain = function (key, value) {
2025 value = (value === null) ? 'null' : escapeHtml(value);
2027 if (key == 'type' && value.toLowerCase() == 'all') {
2028 value = '<span class="attention">' + value + '</span>';
2030 if (key == 'Extra') {
2031 value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
2033 explain += key + ': ' + value + '<br />';
2036 for (i = 0, l = data.explain.length; i < l; i++) {
2037 explain += '<div class="explain-' + i + '"' + (i > 0 ? 'style="display:none;"' : '') + '>';
2038 $.each(data.explain[i], tempExplain);
2039 explain += '</div>';
2042 explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
2044 $('#queryAnalyzerDialog div.placeHolder td.explain').append(explain);
2046 $('#queryAnalyzerDialog div.placeHolder a[href*="#showExplain"]').click(function () {
2047 var id = $(this).attr('href').split('-')[1];
2048 $(this).parent().find('div[class*="explain"]').hide();
2049 $(this).parent().find('div[class*="explain-' + id + '"]').show();
2052 if (data.profiling) {
2054 var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
2058 for (i = 0, l = data.profiling.length; i < l; i++) {
2059 duration = parseFloat(data.profiling[i].duration);
2061 totalTime += duration;
2063 numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
2066 // Only put those values in the pie which are > 2%
2067 for (i = 0, l = data.profiling.length; i < l; i++) {
2068 duration = parseFloat(data.profiling[i].duration);
2070 if (duration / totalTime > 0.02) {
2071 chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
2073 otherTime += duration;
2077 if (otherTime > 0) {
2078 chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
2081 numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
2082 numberTable += '</tbody></table>';
2084 $('#queryAnalyzerDialog div.placeHolder td.chart').append(
2085 '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
2086 '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
2087 numberTable + ' <div id="queryProfiling"></div>');
2089 $('#queryAnalyzerDialog div.placeHolder a[href="#showNums"]').click(function () {
2090 $('#queryAnalyzerDialog #queryProfiling').hide();
2091 $('#queryAnalyzerDialog table.queryNums').show();
2095 $('#queryAnalyzerDialog div.placeHolder a[href="#showChart"]').click(function () {
2096 $('#queryAnalyzerDialog #queryProfiling').show();
2097 $('#queryAnalyzerDialog table.queryNums').hide();
2101 profilingChart = PMA_createProfilingChartJqplot(
2106 //$('#queryProfiling').resizable();
2111 /* Saves the monitor to localstorage */
2112 function saveMonitor() {
2115 $.each(runtime.charts, function (key, elem) {
2117 gridCopy[key].nodes = elem.nodes;
2118 gridCopy[key].settings = elem.settings;
2119 gridCopy[key].title = elem.title;
2120 gridCopy[key].series = elem.series;
2121 gridCopy[key].maxYLabel = elem.maxYLabel;
2124 if (window.localStorage) {
2125 window.localStorage.monitorCharts = JSON.stringify(gridCopy);
2126 window.localStorage.monitorSettings = JSON.stringify(monitorSettings);
2127 window.localStorage.monitorVersion = monitorProtocolVersion;
2130 $('a[href="#clearMonitorConfig"]').show();
2134 // Run the monitor once loaded
2135 AJAX.registerOnload('server_status_monitor.js', function () {
2136 $('a[href="#pauseCharts"]').trigger('click');
2139 function serverResponseError() {
2141 btns[PMA_messages.strReloadPage] = function () {
2142 window.location.reload();
2144 $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed});
2145 $('#emptyDialog').html(
2146 PMA_getImage('s_attention.png') +
2147 PMA_messages.strInvalidResponseExplanation
2149 $('#emptyDialog').dialog({ buttons: btns });
2152 /* Destroys all monitor related resources */
2153 function destroyGrid() {
2154 if (runtime.charts) {
2155 $.each(runtime.charts, function (key, value) {
2157 value.chart.destroy();
2163 runtime.refreshRequest.abort();
2166 clearTimeout(runtime.refreshTimeout);
2168 $('#chartGrid').html('');
2169 runtime.charts = null;
2170 runtime.chartAI = 0;
2171 monitorSettings = null; //TODO:this not global variable