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').find('.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 && typeof presetCharts.cpu !== 'undefined') {
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').find('tr td').css('width', chartSize.width + 'px');
407 $('#chartGrid').find('.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').find('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').find('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').find('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 $('#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 var blob = new Blob([JSON.stringify(exportData)], {type: "application/octet-stream"});
574 var url = window.URL.createObjectURL(blob);
575 window.location.href = url;
576 window.URL.revokeObjectURL(url);
579 $('a[href="#importMonitorConfig"]').click(function (event) {
580 event.preventDefault();
581 $('#emptyDialog').dialog({title: PMA_messages.strImportDialogTitle});
582 $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ':<br/><form>' +
583 '<input type="file" name="file" id="import_file"> </form>');
587 dlgBtns[PMA_messages.strImport] = function () {
588 var input = $('#emptyDialog').find('#import_file')[0];
589 var reader = new FileReader();
591 reader.onerror = function(event) {
592 alert(PMA_messages.strFailedParsingConfig + "\n" + event.target.error.code);
594 reader.onload = function(e) {
596 var data = e.target.result;
598 // Try loading config
600 json = JSON.parse(data);
602 alert(PMA_messages.strFailedParsingConfig);
603 $('#emptyDialog').dialog('close');
607 // Basic check, is this a monitor config json?
608 if (!json || ! json.monitorCharts || ! json.monitorCharts) {
609 alert(PMA_messages.strFailedParsingConfig);
610 $('#emptyDialog').dialog('close');
614 // If json ok, try applying config
616 window.localStorage.monitorCharts = JSON.stringify(json.monitorCharts);
617 window.localStorage.monitorSettings = JSON.stringify(json.monitorSettings);
621 alert(PMA_messages.strFailedBuildingGrid);
622 // If an exception is thrown, load default again
623 if (isStorageSupported('localStorage')) {
624 window.localStorage.removeItem('monitorCharts');
625 window.localStorage.removeItem('monitorSettings');
630 $('#emptyDialog').dialog('close');
632 reader.readAsText(input.files[0]);
635 dlgBtns[PMA_messages.strCancel] = function () {
636 $(this).dialog('close');
639 $('#emptyDialog').dialog({
646 $('a[href="#clearMonitorConfig"]').click(function (event) {
647 event.preventDefault();
648 if (isStorageSupported('localStorage')) {
649 window.localStorage.removeItem('monitorCharts');
650 window.localStorage.removeItem('monitorSettings');
651 window.localStorage.removeItem('monitorVersion');
657 $('a[href="#pauseCharts"]').click(function (event) {
658 event.preventDefault();
659 runtime.redrawCharts = ! runtime.redrawCharts;
660 if (! runtime.redrawCharts) {
661 $(this).html(PMA_getImage('play.png') + PMA_messages.strResumeMonitor);
663 $(this).html(PMA_getImage('pause.png') + PMA_messages.strPauseMonitor);
664 if (! runtime.charts) {
666 $('a[href="#settingsPopup"]').show();
672 $('a[href="#monitorInstructionsDialog"]').click(function (event) {
673 event.preventDefault();
675 var $dialog = $('#monitorInstructionsDialog');
680 }).find('img.ajaxIcon').show();
682 var loadLogVars = function (getvars) {
683 var vars = { ajax_request: true, logging_vars: true };
685 $.extend(vars, getvars);
688 $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'), vars,
691 if (typeof data !== 'undefined' && data.success === true) {
692 logVars = data.message;
694 return serverResponseError();
696 var icon = PMA_getImage('s_success.png'), msg = '', str = '';
698 if (logVars.general_log == 'ON') {
699 if (logVars.slow_query_log == 'ON') {
700 msg = PMA_messages.strBothLogOn;
702 msg = PMA_messages.strGenLogOn;
706 if (msg.length === 0 && logVars.slow_query_log == 'ON') {
707 msg = PMA_messages.strSlowLogOn;
710 if (msg.length === 0) {
711 icon = PMA_getImage('s_error.png');
712 msg = PMA_messages.strBothLogOff;
715 str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">';
716 str += icon + msg + '<br />';
718 if (logVars.log_output != 'TABLE') {
719 str += PMA_getImage('s_error.png') + ' ' + PMA_messages.strLogOutNotTable + '<br />';
721 str += PMA_getImage('s_success.png') + ' ' + PMA_messages.strLogOutIsTable + '<br />';
724 if (logVars.slow_query_log == 'ON') {
725 if (logVars.long_query_time > 2) {
726 str += PMA_getImage('s_attention.png') + ' ';
727 str += PMA_sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
731 if (logVars.long_query_time < 2) {
732 str += PMA_getImage('s_success.png') + ' ';
733 str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time);
741 str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>';
742 str += '<div class="smallIndent">';
743 str += PMA_messages.strSettingsAppliedGlobal + '<br/>';
745 var varValue = 'TABLE';
746 if (logVars.log_output == 'TABLE') {
750 str += '- <a class="set" href="#log_output-' + varValue + '">';
751 str += PMA_sprintf(PMA_messages.strSetLogOutput, varValue);
752 str += ' </a><br />';
754 if (logVars.general_log != 'ON') {
755 str += '- <a class="set" href="#general_log-ON">';
756 str += PMA_sprintf(PMA_messages.strEnableVar, 'general_log');
757 str += ' </a><br />';
759 str += '- <a class="set" href="#general_log-OFF">';
760 str += PMA_sprintf(PMA_messages.strDisableVar, 'general_log');
761 str += ' </a><br />';
764 if (logVars.slow_query_log != 'ON') {
765 str += '- <a class="set" href="#slow_query_log-ON">';
766 str += PMA_sprintf(PMA_messages.strEnableVar, 'slow_query_log');
767 str += ' </a><br />';
769 str += '- <a class="set" href="#slow_query_log-OFF">';
770 str += PMA_sprintf(PMA_messages.strDisableVar, 'slow_query_log');
771 str += ' </a><br />';
775 if (logVars.long_query_time > 2) {
779 str += '- <a class="set" href="#long_query_time-' + varValue + '">';
780 str += PMA_sprintf(PMA_messages.setSetLongQueryTime, varValue);
781 str += ' </a><br />';
784 str += PMA_messages.strNoSuperUser + '<br/>';
789 $dialog.find('div.monitorUse').toggle(
790 logVars.log_output == 'TABLE' && (logVars.slow_query_log == 'ON' || logVars.general_log == 'ON')
793 $dialog.find('div.ajaxContent').html(str);
794 $dialog.find('img.ajaxIcon').hide();
795 $dialog.find('a.set').click(function () {
796 var nameValue = $(this).attr('href').split('-');
797 loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1]});
798 $dialog.find('img.ajaxIcon').show();
810 $('input[name="chartType"]').change(function () {
811 $('#chartVariableSettings').toggle(this.checked && this.value == 'variable');
812 var title = $('input[name="chartTitle"]').val();
813 if (title == PMA_messages.strChartTitle ||
814 title == $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
816 $('input[name="chartTitle"]')
817 .data('lastRadio', $(this).attr('id'))
818 .val($('label[for="' + $(this).attr('id') + '"]').text());
823 $('input[name="useDivisor"]').change(function () {
824 $('span.divisorInput').toggle(this.checked);
827 $('input[name="useUnit"]').change(function () {
828 $('span.unitInput').toggle(this.checked);
831 $('select[name="varChartList"]').change(function () {
832 if (this.selectedIndex !== 0) {
833 $('#variableInput').val(this.value);
837 $('a[href="#kibDivisor"]').click(function (event) {
838 event.preventDefault();
839 $('input[name="valueDivisor"]').val(1024);
840 $('input[name="valueUnit"]').val(PMA_messages.strKiB);
841 $('span.unitInput').toggle(true);
842 $('input[name="useUnit"]').prop('checked', true);
846 $('a[href="#mibDivisor"]').click(function (event) {
847 event.preventDefault();
848 $('input[name="valueDivisor"]').val(1024 * 1024);
849 $('input[name="valueUnit"]').val(PMA_messages.strMiB);
850 $('span.unitInput').toggle(true);
851 $('input[name="useUnit"]').prop('checked', true);
855 $('a[href="#submitClearSeries"]').click(function (event) {
856 event.preventDefault();
857 $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
859 $('#clearSeriesLink').hide();
862 $('a[href="#submitAddSeries"]').click(function (event) {
863 event.preventDefault();
864 if ($('#variableInput').val() === "") {
868 if (newChart === null) {
869 $('#seriesPreview').html('');
872 title: $('input[name="chartTitle"]').val(),
880 dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
881 display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
884 if (serie.dataPoints[0].name == 'Processes') {
885 serie.dataPoints[0].type = 'proc';
888 if ($('input[name="useDivisor"]').prop('checked')) {
889 serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
892 if ($('input[name="useUnit"]').prop('checked')) {
893 serie.unit = $('input[name="valueUnit"]').val();
896 var str = serie.display == 'differential' ? ', ' + PMA_messages.strDifferential : '';
897 str += serie.valueDivisor ? (', ' + PMA_sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
898 str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
901 label: $('#variableInput').val().replace(/_/g, " ")
903 newChart.series.push(newSeries);
904 $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '<br/>');
905 newChart.nodes.push(serie);
906 $('#variableInput').val('');
907 $('input[name="differentialValue"]').prop('checked', true);
908 $('input[name="useDivisor"]').prop('checked', false);
909 $('input[name="useUnit"]').prop('checked', false);
910 $('input[name="useDivisor"]').trigger('change');
911 $('input[name="useUnit"]').trigger('change');
912 $('select[name="varChartList"]').get(0).selectedIndex = 0;
914 $('#clearSeriesLink').show();
919 $("#variableInput").autocomplete({
920 source: variableNames
923 /* Initializes the monitor, called only once */
924 function initGrid() {
928 /* Apply default values & config */
929 if (isStorageSupported('localStorage')) {
930 if (typeof window.localStorage.monitorCharts !== 'undefined') {
931 runtime.charts = JSON.parse(window.localStorage.monitorCharts);
933 if (typeof window.localStorage.monitorSettings !== 'undefined') {
934 monitorSettings = JSON.parse(window.localStorage.monitorSettings);
937 $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);
939 if (runtime.charts !== null
940 && typeof window.localStorage.monitorVersion !== 'undefined'
941 && monitorProtocolVersion != window.localStorage.monitorVersion
943 $('#emptyDialog').dialog({title: PMA_messages.strIncompatibleMonitorConfig});
944 $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
947 dlgBtns[PMA_messages.strClose] = function () { $(this).dialog('close'); };
949 $('#emptyDialog').dialog({
956 if (runtime.charts === null) {
957 runtime.charts = defaultChartGrid;
959 if (monitorSettings === null) {
960 monitorSettings = defaultMonitorSettings;
963 $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
964 $('select[name="chartColumns"]').val(monitorSettings.columns);
966 if (monitorSettings.gridMaxPoints == 'auto') {
967 runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
969 runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
972 runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
973 runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
975 /* Calculate how much spacing there is between each chart */
976 $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
978 width: $('#chartGrid').find('td:nth-child(2)').offset().left -
979 $('#chartGrid').find('td:nth-child(1)').offset().left,
980 height: $('#chartGrid').find('tr:nth-child(2) td:nth-child(2)').offset().top -
981 $('#chartGrid').find('tr:nth-child(1) td:nth-child(1)').offset().top
983 $('#chartGrid').html('');
985 /* Add all charts - in correct order */
987 $.each(runtime.charts, function (key, value) {
991 for (i = 0; i < keys.length; i++) {
992 addChart(runtime.charts[keys[i]], true);
995 /* Fill in missing cells */
996 var numCharts = $('#chartGrid').find('.monitorChart').length;
997 var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
998 for (i = 0; i < numMissingCells; i++) {
999 $('#chartGrid').find('tr:last').append('<td></td>');
1002 // Empty cells should keep their size so you can drop onto them
1003 calculateChartSize();
1004 $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
1006 buildRequiredDataList();
1010 /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
1011 * data from each chart and restores it after the monitor is initialized again */
1012 function rebuildGrid() {
1014 if (runtime.charts) {
1016 $.each(runtime.charts, function (key, chartObj) {
1017 for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
1018 oldData[chartObj.nodes[i].dataPoint] = [];
1019 for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
1020 oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
1030 /* Calculactes the dynamic chart size that depends on the column width */
1031 function calculateChartSize() {
1033 if ($("body").height() > $(window).height()) { // has vertical scroll bar
1034 panelWidth = $('#logTable').innerWidth();
1036 panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
1039 var wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
1041 width: Math.floor(wdt),
1042 height: Math.floor(0.75 * wdt)
1046 /* Adds a chart to the chart grid */
1047 function addChart(chartObj, initialize) {
1051 title: escapeHtml(chartObj.title),
1055 background: 'rgba(0,0,0,0)'
1059 renderer: $.jqplot.DateAxisRenderer,
1061 formatString: '%H:%M:%S',
1088 if (settings.title === PMA_messages.strSystemCPUUsage ||
1089 settings.title === PMA_messages.strQueryCacheEfficiency
1091 settings.axes.yaxis.tickOptions = {
1092 formatString: "%d %%"
1094 } else if (settings.title === PMA_messages.strSystemMemory ||
1095 settings.title === PMA_messages.strSystemSwap
1097 settings.stackSeries = true;
1098 settings.axes.yaxis.tickOptions = {
1099 formatter: $.jqplot.byteFormatter(2) // MiB
1101 } else if (settings.title === PMA_messages.strTraffic) {
1102 settings.axes.yaxis.tickOptions = {
1103 formatter: $.jqplot.byteFormatter(1) // KiB
1105 } else if (settings.title === PMA_messages.strQuestions ||
1106 settings.title === PMA_messages.strConnections
1108 settings.axes.yaxis.tickOptions = {
1109 formatter: function (format, val) {
1110 if (Math.abs(val) >= 1000000) {
1111 return $.jqplot.sprintf("%.3g M", val / 1000000);
1112 } else if (Math.abs(val) >= 1000) {
1113 return $.jqplot.sprintf("%.3g k", val / 1000);
1115 return $.jqplot.sprintf("%d", val);
1121 settings.series = chartObj.series;
1123 if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
1124 var numCharts = $('#chartGrid').find('.monitorChart').length;
1126 if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
1127 $('#chartGrid').append('<tr></tr>');
1131 calculateChartSize();
1133 $('#chartGrid').find('tr:last').append(
1134 '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
1135 '<div class="ui-state-default monitorChart"' +
1136 ' id="gridchart' + runtime.chartAI + '"' +
1137 ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' +
1142 // Set series' data as [0,0], smooth lines won't plot with data array having null values.
1143 // also chart won't plot initially with no data and data comes on refreshChartGrid()
1145 for (i in chartObj.series) {
1146 series.push([[0, 0]]);
1149 var tempTooltipContentEditor = function (str, seriesIndex, pointIndex, plot) {
1151 // TODO: move style to theme CSS
1152 var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' +
1153 'opacity:0.95;filter:alpha(opacity=95);padding:5px;">';
1154 // x value i.e. time
1155 var timeValue = str.split(",")[0];
1157 tooltipHtml += 'Time: ' + timeValue;
1158 tooltipHtml += '<span style="font-weight:bold;">';
1159 // Add y values to the tooltip per series
1160 for (j in plot.series) {
1161 // get y value if present
1162 if (plot.series[j].data.length > pointIndex) {
1163 seriesValue = plot.series[j].data[pointIndex][1];
1167 var seriesLabel = plot.series[j].label;
1168 var seriesColor = plot.series[j].color;
1170 if (plot.series[0]._yaxis.tickOptions.formatter) {
1171 // using formatter function
1172 seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
1173 } else if (plot.series[0]._yaxis.tickOptions.formatString) {
1174 // using format string
1175 seriesValue = PMA_sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
1177 tooltipHtml += '<br /><span style="color:' + seriesColor + '">' +
1178 seriesLabel + ': ' + seriesValue + '</span>';
1180 tooltipHtml += '</span></div>';
1184 // set Tooltip for each series
1185 for (i in settings.series) {
1186 settings.series[i].highlighter = {
1188 tooltipContentEditor: tempTooltipContentEditor
1192 chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings);
1193 // remove [0,0] after plotting
1194 for (i in chartObj.chart.series) {
1195 chartObj.chart.series[i].data.shift();
1198 var $legend = $('<div />').css('padding', '0.5em');
1199 for (i in chartObj.chart.series) {
1201 $('<div />').append(
1205 background: chartObj.chart.seriesColors[i]
1206 }).addClass('floatleft')
1209 chartObj.chart.series[i].label
1210 ).addClass('floatleft')
1212 $('<div class="clearfloat">')
1213 ).addClass('floatleft')
1216 $('#gridchart' + runtime.chartAI)
1220 if (initialize !== true) {
1221 runtime.charts['c' + runtime.chartAI] = chartObj;
1222 buildRequiredDataList();
1225 // time span selection
1226 $('#gridchart' + runtime.chartAI).bind('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) {
1227 drawTimeSpan = true;
1228 selectionTimeDiff.push(datapos.xaxis);
1229 if ($('#selection_box').length) {
1230 $('#selection_box').remove();
1232 var selectionBox = $('<div id="selection_box" style="z-index:1000;height:205px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">');
1233 $(document.body).append(selectionBox);
1234 selectionStartX = ev.pageX;
1235 selectionStartY = ev.pageY;
1237 .attr({id: 'selection_box'})
1239 top: selectionStartY - gridpos.y,
1240 left: selectionStartX
1245 $('#gridchart' + runtime.chartAI).bind('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) {
1246 if (! drawTimeSpan || editMode) {
1250 selectionTimeDiff.push(datapos.xaxis);
1252 if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
1253 selectionTimeDiff = [];
1256 //get date from timestamp
1257 var min = new Date(Math.ceil(selectionTimeDiff[0]));
1258 var max = new Date(Math.ceil(selectionTimeDiff[1]));
1259 PMA_getLogAnalyseDialog(min, max);
1260 selectionTimeDiff = [];
1261 drawTimeSpan = false;
1264 $('#gridchart' + runtime.chartAI).bind('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) {
1265 if (! drawTimeSpan || editMode) {
1268 if (selectionStartX !== undefined) {
1271 width: Math.ceil(ev.pageX - selectionStartX)
1277 $('#gridchart' + runtime.chartAI).bind('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) {
1278 drawTimeSpan = false;
1281 $(document.body).mouseup(function () {
1282 if ($('#selection_box').length) {
1283 $('#selection_box').remove();
1287 // Edit, Print icon only in edit mode
1288 $('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
1293 function PMA_getLogAnalyseDialog(min, max) {
1294 var $logAnalyseDialog = $('#logAnalyseDialog');
1295 var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]');
1296 var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]');
1297 $dateStart.prop("readonly", true);
1298 $dateEnd.prop("readonly", true);
1302 dlgBtns[PMA_messages.strFromSlowLog] = function () {
1303 loadLog('slow', min, max);
1304 $(this).dialog("close");
1307 dlgBtns[PMA_messages.strFromGeneralLog] = function () {
1308 loadLog('general', min, max);
1309 $(this).dialog("close");
1312 $logAnalyseDialog.dialog({
1318 PMA_addDatepicker($dateStart, 'datetime', {
1319 showMillisec: false,
1320 showMicrosec: false,
1321 timeFormat: 'HH:mm:ss'
1323 PMA_addDatepicker($dateEnd, 'datetime', {
1324 showMillisec: false,
1325 showMicrosec: false,
1326 timeFormat: 'HH:mm:ss'
1328 $dateStart.datepicker('setDate', min);
1329 $dateEnd.datepicker('setDate', max);
1332 function loadLog(type, min, max) {
1333 var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min;
1334 var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max;
1340 removeVariables: $('#removeVariables').prop('checked'),
1341 limitTypes: $('#limitTypes').prop('checked')
1345 /* Called in regular intervals, this function updates the values of each chart in the grid */
1346 function refreshChartGrid() {
1347 /* Send to server */
1348 runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1352 requiredData: JSON.stringify(runtime.dataList),
1353 server: PMA_commonParams.get('server'),
1354 token: PMA_commonParams.get('token')
1355 }, function (data) {
1357 if (typeof data !== 'undefined' && data.success === true) {
1358 chartData = data.message;
1360 return serverResponseError();
1366 /* Update values in each graph */
1367 $.each(runtime.charts, function (orderKey, elem) {
1368 var key = elem.chartID;
1369 // If newly added chart, we have no data for it yet
1370 if (! chartData[key]) {
1375 for (var j = 0; j < elem.nodes.length; j++) {
1377 if (i === 0 && j === 0) {
1378 if (oldChartData === null) {
1379 diff = chartData.x - runtime.xmax;
1381 diff = parseInt(chartData.x - oldChartData.x, 10);
1384 runtime.xmin += diff;
1385 runtime.xmax += diff;
1388 //elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
1389 /* Calculate y value */
1391 // If transform function given, use it
1392 if (elem.nodes[j].transformFn) {
1393 value = chartValueTransform(
1394 elem.nodes[j].transformFn,
1396 // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
1398 oldChartData === null ||
1399 oldChartData[key] === null ||
1400 oldChartData[key] === undefined ? null : oldChartData[key][j]
1404 // Otherwise use original value and apply differential and divisor if given,
1405 // in this case we have only one data point per series - located at chartData[key][j][0]
1407 value = parseFloat(chartData[key][j][0].value);
1409 if (elem.nodes[j].display == 'differential') {
1410 if (oldChartData === null ||
1411 oldChartData[key] === null ||
1412 oldChartData[key] === undefined
1416 value -= oldChartData[key][j][0].value;
1419 if (elem.nodes[j].valueDivisor) {
1420 value = value / elem.nodes[j].valueDivisor;
1424 // Set y value, if defined
1425 if (value !== undefined) {
1426 elem.chart.series[j].data.push([chartData.x, value]);
1427 if (value > elem.maxYLabel) {
1428 elem.maxYLabel = value;
1429 } else if (elem.maxYLabel === 0) {
1430 elem.maxYLabel = 0.5;
1432 // free old data point values and update maxYLabel
1433 if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
1434 elem.chart.series[j].data[0][0] < runtime.xmin
1436 // check if the next freeable point is highest
1437 if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
1438 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1439 elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
1441 elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
1444 if (elem.title === PMA_messages.strSystemMemory ||
1445 elem.title === PMA_messages.strSystemSwap
1452 // update chart options
1453 // keep ticks number/positioning consistent while refreshrate changes
1454 var tickInterval = (runtime.xmax - runtime.xmin) / 5;
1455 elem.chart.axes.xaxis.ticks = [(runtime.xmax - tickInterval * 4),
1456 (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
1457 (runtime.xmax - tickInterval), runtime.xmax];
1459 if (elem.title !== PMA_messages.strSystemCPUUsage &&
1460 elem.title !== PMA_messages.strQueryCacheEfficiency &&
1461 elem.title !== PMA_messages.strSystemMemory &&
1462 elem.title !== PMA_messages.strSystemSwap
1464 elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
1465 elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
1466 } else if (elem.title === PMA_messages.strSystemMemory ||
1467 elem.title === PMA_messages.strSystemSwap
1469 elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
1470 elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
1474 if (runtime.redrawCharts) {
1475 elem.chart.replot();
1479 oldChartData = chartData;
1481 runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
1485 /* Function to get highest plotted point's y label, to scale the chart,
1486 * TODO: make jqplot's autoscale:true work here
1488 function getMaxYLabel(dataValues) {
1489 var maxY = dataValues[0][1];
1490 $.each(dataValues, function (k, v) {
1491 maxY = (v[1] > maxY) ? v[1] : maxY;
1496 /* Function that supplies special value transform functions for chart values */
1497 function chartValueTransform(name, cur, prev) {
1500 if (prev === null) {
1503 // cur and prev are datapoint arrays, but containing
1504 // only 1 element for cpu-linux
1508 var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
1509 var diff_idle = cur.idle - prev.idle;
1510 return 100 * (diff_total - diff_idle) / diff_total;
1512 // Query cache efficiency (%)
1514 if (prev === null) {
1517 // cur[0].value is Qcache_hits, cur[1].value is Com_select
1518 var diffQHits = cur[0].value - prev[0].value;
1519 // No NaN please :-)
1520 if (cur[1].value - prev[1].value === 0) {
1524 return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;
1526 // Query cache usage (%)
1528 if (cur[1].value === 0) {
1531 // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
1532 return 100 - cur[0].value / cur[1].value * 100;
1538 /* Build list of nodes that need to be retrieved from server.
1539 * It creates something like a stripped down version of the runtime.charts object.
1541 function buildRequiredDataList() {
1542 runtime.dataList = {};
1543 // Store an own id, because the property name is subject of reordering,
1544 // thus destroying our mapping with runtime.charts <=> runtime.dataList
1546 $.each(runtime.charts, function (key, chart) {
1547 runtime.dataList[chartID] = [];
1548 for (var i = 0, l = chart.nodes.length; i < l; i++) {
1549 runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
1551 runtime.charts[key].chartID = chartID;
1556 /* Loads the log table data, generates the table and handles the filters */
1557 function loadLogStatistics(opts) {
1559 var logRequest = null;
1561 if (! opts.removeVariables) {
1562 opts.removeVariables = false;
1564 if (! opts.limitTypes) {
1565 opts.limitTypes = false;
1568 $('#emptyDialog').dialog({title: PMA_messages.strAnalysingLogsTitle});
1569 $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
1570 ' <img class="ajaxIcon" src="' + pmaThemeImage +
1571 'ajax_clock_small.gif" alt="">');
1574 dlgBtns[PMA_messages.strCancelRequest] = function () {
1575 if (logRequest !== null) {
1579 $(this).dialog("close");
1582 $('#emptyDialog').dialog({
1589 logRequest = $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'),
1590 { ajax_request: true,
1593 time_start: Math.round(opts.start / 1000),
1594 time_end: Math.round(opts.end / 1000),
1595 removeVariables: opts.removeVariables,
1596 limitTypes: opts.limitTypes
1601 if (typeof data !== 'undefined' && data.success === true) {
1602 logData = data.message;
1604 return serverResponseError();
1607 if (logData.rows.length === 0) {
1608 $('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
1609 $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
1611 dlgBtns[PMA_messages.strClose] = function () {
1612 $(this).dialog("close");
1615 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1619 runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
1621 /* Show some stats in the dialog */
1622 $('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
1623 $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
1624 $.each(logData.sum, function (key, value) {
1625 key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
1626 if (key == 'Total') {
1627 key = '<b>' + key + '</b>';
1629 $('#emptyDialog').append(key + ': ' + value + '<br/>');
1632 /* Add filter options if more than a bunch of rows there to filter */
1633 if (logData.numRows > 12) {
1634 $('#logTable').prepend(
1635 '<fieldset id="logDataFilter">' +
1636 ' <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
1637 ' <div class="formelement">' +
1638 ' <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
1639 ' <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
1641 ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
1642 ' <div class="formelement">' +
1643 ' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
1644 ' <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
1649 $('#noWHEREData').change(function () {
1650 filterQueries(true);
1653 if (logData.numRows > 250) {
1654 $('#startFilterQueryText').click(filterQueries);
1656 $('#filterQueryText').keyup(filterQueries);
1661 dlgBtns[PMA_messages.strJumpToTable] = function () {
1662 $(this).dialog("close");
1663 $(document).scrollTop($('#logTable').offset().top);
1666 $('#emptyDialog').dialog("option", "buttons", dlgBtns);
1670 /* Handles the actions performed when the user uses any of the
1671 * log table filters which are the filter by name and grouping
1672 * with ignoring data in WHERE clauses
1674 * @param boolean Should be true when the users enabled or disabled
1675 * to group queries ignoring data in WHERE clauses
1677 function filterQueries(varFilterChange) {
1678 var cell, textFilter;
1679 var val = $('#filterQueryText').val();
1681 if (val.length === 0) {
1685 textFilter = new RegExp(val, 'i');
1686 $('#filterQueryText').removeClass('error');
1688 if (e instanceof SyntaxError) {
1689 $('#filterQueryText').addClass('error');
1695 var rowSum = 0, totalSum = 0, i = 0, q;
1696 var noVars = $('#noWHEREData').prop('checked');
1697 var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
1698 var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
1699 var filteredQueries = {}, filteredQueriesLines = {};
1700 var hide = false, rowData;
1701 var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
1702 var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
1703 var isSlowLog = opts.src == 'slow';
1704 var columnSums = {};
1706 // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
1707 var countRow = function (query, row) {
1708 var cells = row.match(/<td>(.*?)<\/td>/gi);
1709 if (!columnSums[query]) {
1710 columnSums[query] = [0, 0, 0, 0];
1713 // lock_time and query_time and displayed in timespan format
1714 columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
1715 columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
1716 // rows_examind and rows_sent are just numbers
1717 columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
1718 columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
1721 // We just assume the sql text is always in the second last column, and that the total count is right of it
1722 $('#logTable').find('table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
1724 // If query is a SELECT and user enabled or disabled to group
1725 // queries ignoring data in where statements, we
1726 // need to re-calculate the sums of each row
1727 if (varFilterChange && $t.html().match(/^SELECT/i)) {
1729 // Group on => Sum up identical columns, and hide all but 1
1731 q = $t.text().replace(equalsFilter, '$1=...$6').trim();
1732 q = q.replace(functionFilter, ' $1(...)');
1734 // Js does not specify a limit on property name length,
1735 // so we can abuse it as index :-)
1736 if (filteredQueries[q]) {
1737 filteredQueries[q] += parseInt($t.next().text(), 10);
1738 totalSum += parseInt($t.next().text(), 10);
1741 filteredQueries[q] = parseInt($t.next().text(), 10);
1742 filteredQueriesLines[q] = i;
1746 countRow(q, $t.parent().html());
1750 // Group off: Restore original columns
1752 rowData = $t.parent().data('query');
1754 $t.text(rowData[queryColumnName]);
1755 // Restore total count
1756 $t.next().text(rowData[sumColumnName]);
1757 // Restore slow log columns
1759 $t.parent().children('td:nth-child(3)').text(rowData.query_time);
1760 $t.parent().children('td:nth-child(4)').text(rowData.lock_time);
1761 $t.parent().children('td:nth-child(5)').text(rowData.rows_sent);
1762 $t.parent().children('td:nth-child(6)').text(rowData.rows_examined);
1767 // If not required to be hidden, do we need
1768 // to hide because of a not matching text filter?
1769 if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
1773 // Now display or hide this column
1775 $t.parent().css('display', 'none');
1777 totalSum += parseInt($t.next().text(), 10);
1779 $t.parent().css('display', '');
1786 // We finished summarizing counts => Update count values of all grouped entries
1787 if (varFilterChange) {
1789 var numCol, row, $table = $('#logTable').find('table tbody');
1790 $.each(filteredQueriesLines, function (key, value) {
1791 if (filteredQueries[key] <= 1) {
1795 row = $table.children('tr:nth-child(' + (value + 1) + ')');
1796 numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
1797 numCol.text(filteredQueries[key]);
1800 row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
1801 row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
1802 row.children('td:nth-child(5)').text(columnSums[key][2]);
1803 row.children('td:nth-child(6)').text(columnSums[key][3]);
1808 $('#logTable').find('table').trigger("update");
1809 setTimeout(function () {
1810 $('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
1814 // Display some stats at the bottom of the table
1815 $('#logTable').find('table tfoot tr')
1816 .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
1817 PMA_messages.strSumRows + ' ' + rowSum + '<span class="floatright">' +
1818 PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
1822 /* Turns a timespan (12:12:12) into a number */
1823 function timeToSec(timeStr) {
1824 var time = timeStr.split(':');
1825 return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
1828 /* Turns a number into a timespan (100 into 00:01:40) */
1829 function secToTime(timeInt) {
1830 var hours = Math.floor(timeInt / 3600);
1831 timeInt -= hours * 3600;
1832 var minutes = Math.floor(timeInt / 60);
1833 timeInt -= minutes * 60;
1836 hours = '0' + hours;
1839 minutes = '0' + minutes;
1842 timeInt = '0' + timeInt;
1845 return hours + ':' + minutes + ':' + timeInt;
1848 /* Constructs the log table out of the retrieved server data */
1849 function buildLogTable(data, groupInserts) {
1850 var rows = data.rows;
1852 var $table = $('<table class="sortable"></table>');
1853 var $tBody, $tRow, $tCell;
1855 $('#logTable').html($table);
1857 var tempPushKey = function (key, value) {
1861 var formatValue = function (name, value) {
1862 if (name == 'user_host') {
1863 return value.replace(/(\[.*?\])+/g, '');
1865 return escapeHtml(value);
1868 for (var i = 0, l = rows.length; i < l; i++) {
1870 $.each(rows[0], tempPushKey);
1871 $table.append('<thead>' +
1872 '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
1876 $table.append($tBody = $('<tbody></tbody>'));
1879 $tBody.append($tRow = $('<tr class="noclick"></tr>'));
1881 for (var j = 0, ll = cols.length; j < ll; j++) {
1882 // Assuming the query column is the second last
1883 if (j == cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
1884 $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
1885 $tCell.click(openQueryAnalyzer);
1887 $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
1890 $tRow.data('query', rows[i]);
1894 $table.append('<tfoot>' +
1895 '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
1896 ' ' + data.numRows + '<span class="floatright">' + PMA_messages.strTotal +
1897 '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
1899 // Append a tooltip to the count column, if there exist one
1900 if ($('#logTable').find('tr:first th:last').text().indexOf("#") > -1) {
1901 $('#logTable').find('tr:first th:last').append(' ' + PMA_getImage('b_help.png', '', {'class': 'qroupedQueryInfoIcon'}));
1903 var tooltipContent = PMA_messages.strCountColumnExplanation;
1905 tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
1909 $('img.qroupedQueryInfoIcon'),
1915 $('#logTable').find('table').tablesorter({
1916 sortList: [[cols.length - 1, 1]],
1917 widgets: ['fast-zebra']
1920 $('#logTable').find('table thead th')
1921 .append('<div class="sorticon"></div>');
1926 /* Opens the query analyzer dialog */
1927 function openQueryAnalyzer() {
1928 var rowData = $(this).parent().data('query');
1929 var query = rowData.argument || rowData.sql_text;
1931 if (codemirror_editor) {
1932 //TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
1933 //query = PMA_SQLPrettyPrint(query);
1934 codemirror_editor.setValue(query);
1935 // Codemirror is bugged, it doesn't refresh properly sometimes.
1936 // Following lines seem to fix that
1937 setTimeout(function () {
1938 codemirror_editor.refresh();
1942 $('#sqlquery').val(query);
1945 var profilingChart = null;
1948 dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
1949 loadQueryAnalysis(rowData);
1951 dlgBtns[PMA_messages.strClose] = function () {
1952 $(this).dialog('close');
1955 $('#queryAnalyzerDialog').dialog({
1960 close: function () {
1961 if (profilingChart !== null) {
1962 profilingChart.destroy();
1964 $('#queryAnalyzerDialog').find('div.placeHolder').html('');
1965 if (codemirror_editor) {
1966 codemirror_editor.setValue('');
1968 $('#sqlquery').val('');
1974 /* Loads and displays the analyzed query data */
1975 function loadQueryAnalysis(rowData) {
1976 var db = rowData.db || '';
1978 $('#queryAnalyzerDialog').find('div.placeHolder').html(
1979 PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
1980 pmaThemeImage + 'ajax_clock_small.gif" alt="">');
1982 $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
1984 query_analyzer: true,
1985 query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
1987 server: PMA_commonParams.get('server'),
1988 token: PMA_commonParams.get('token')
1989 }, function (data) {
1991 if (typeof data !== 'undefined' && data.success === true) {
1992 data = data.message;
1995 if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
1996 data.error = PMA_messages.strServerLogError;
1998 $('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="error">' + data.error + '</div>');
2002 // Float sux, I'll use table :(
2003 $('#queryAnalyzerDialog').find('div.placeHolder')
2004 .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
2006 var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
2007 if (data.explain.length > 1) {
2009 for (i = 0; i < data.explain.length; i++) {
2013 explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
2017 explain += '<p></p>';
2019 var tempExplain = function (key, value) {
2020 value = (value === null) ? 'null' : escapeHtml(value);
2022 if (key == 'type' && value.toLowerCase() == 'all') {
2023 value = '<span class="attention">' + value + '</span>';
2025 if (key == 'Extra') {
2026 value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
2028 explain += key + ': ' + value + '<br />';
2031 for (i = 0, l = data.explain.length; i < l; i++) {
2032 explain += '<div class="explain-' + i + '"' + (i > 0 ? 'style="display:none;"' : '') + '>';
2033 $.each(data.explain[i], tempExplain);
2034 explain += '</div>';
2037 explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
2039 $('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);
2041 $('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').click(function () {
2042 var id = $(this).attr('href').split('-')[1];
2043 $(this).parent().find('div[class*="explain"]').hide();
2044 $(this).parent().find('div[class*="explain-' + id + '"]').show();
2047 if (data.profiling) {
2049 var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
2053 for (i = 0, l = data.profiling.length; i < l; i++) {
2054 duration = parseFloat(data.profiling[i].duration);
2056 totalTime += duration;
2058 numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
2061 // Only put those values in the pie which are > 2%
2062 for (i = 0, l = data.profiling.length; i < l; i++) {
2063 duration = parseFloat(data.profiling[i].duration);
2065 if (duration / totalTime > 0.02) {
2066 chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
2068 otherTime += duration;
2072 if (otherTime > 0) {
2073 chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
2076 numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
2077 numberTable += '</tbody></table>';
2079 $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append(
2080 '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
2081 '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
2082 numberTable + ' <div id="queryProfiling"></div>');
2084 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').click(function () {
2085 $('#queryAnalyzerDialog').find('#queryProfiling').hide();
2086 $('#queryAnalyzerDialog').find('table.queryNums').show();
2090 $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').click(function () {
2091 $('#queryAnalyzerDialog').find('#queryProfiling').show();
2092 $('#queryAnalyzerDialog').find('table.queryNums').hide();
2096 profilingChart = PMA_createProfilingChart(
2101 //$('#queryProfiling').resizable();
2106 /* Saves the monitor to localstorage */
2107 function saveMonitor() {
2110 $.each(runtime.charts, function (key, elem) {
2112 gridCopy[key].nodes = elem.nodes;
2113 gridCopy[key].settings = elem.settings;
2114 gridCopy[key].title = elem.title;
2115 gridCopy[key].series = elem.series;
2116 gridCopy[key].maxYLabel = elem.maxYLabel;
2119 if (isStorageSupported('localStorage')) {
2120 window.localStorage.monitorCharts = JSON.stringify(gridCopy);
2121 window.localStorage.monitorSettings = JSON.stringify(monitorSettings);
2122 window.localStorage.monitorVersion = monitorProtocolVersion;
2125 $('a[href="#clearMonitorConfig"]').show();
2129 // Run the monitor once loaded
2130 AJAX.registerOnload('server_status_monitor.js', function () {
2131 $('a[href="#pauseCharts"]').trigger('click');
2134 function serverResponseError() {
2136 btns[PMA_messages.strReloadPage] = function () {
2137 window.location.reload();
2139 $('#emptyDialog').dialog({title: PMA_messages.strRefreshFailed});
2140 $('#emptyDialog').html(
2141 PMA_getImage('s_attention.png') +
2142 PMA_messages.strInvalidResponseExplanation
2144 $('#emptyDialog').dialog({ buttons: btns });
2147 /* Destroys all monitor related resources */
2148 function destroyGrid() {
2149 if (runtime.charts) {
2150 $.each(runtime.charts, function (key, value) {
2152 value.chart.destroy();
2158 runtime.refreshRequest.abort();
2161 clearTimeout(runtime.refreshTimeout);
2163 $('#chartGrid').html('');
2164 runtime.charts = null;
2165 runtime.chartAI = 0;
2166 monitorSettings = null; //TODO:this not global variable