2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Server status monitor feature
9 require_once 'libraries/common.inc.php';
10 require_once 'libraries/server_common.inc.php';
11 require_once 'libraries/ServerStatusData.class.php';
13 $server_master_status = false;
14 $server_slave_status = false;
16 include_once 'libraries/replication.inc.php';
17 include_once 'libraries/replication_gui.lib.php';
23 if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) {
24 // Send with correct charset
25 header('Content-Type: text/html; charset=UTF-8');
27 // real-time charting data
28 if (isset($_REQUEST['chart_data'])) {
29 switch($_REQUEST['type']) {
30 case 'chartgrid': // Data for the monitor
31 $ret = json_decode($_REQUEST['requiredData'], true);
32 $statusVars = array();
33 $serverVars = array();
34 $sysinfo = $cpuload = $memory = 0;
37 /* Accumulate all required variables and data */
39 foreach ($ret as $chart_id => $chartNodes) {
40 // For each data series
41 foreach ($chartNodes as $node_id => $nodeDataPoints) {
42 // For each data point in the series (usually just 1)
43 foreach ($nodeDataPoints as $point_id => $dataPoint) {
44 $pName = $dataPoint['name'];
46 switch ($dataPoint['type']) {
47 /* We only collect the status and server variables here to
48 * read them all in one query,
49 * and only afterwards assign them.
50 * Also do some white list filtering on the names
53 if (! preg_match('/[^a-zA-Z_]+/', $pName)) {
54 $serverVars[] = $pName;
59 if (! preg_match('/[^a-zA-Z_]+/', $pName)) {
60 $statusVars[] = $pName;
65 $result = PMA_DBI_query('SHOW PROCESSLIST');
66 $ret[$chart_id][$node_id][$point_id]['value']
67 = PMA_DBI_num_rows($result);
72 include_once 'libraries/sysinfo.lib.php';
73 $sysinfo = PMA_getSysInfo();
76 $cpuload = $sysinfo->loadavg();
79 if (PMA_getSysInfoOs() == 'Linux') {
80 $ret[$chart_id][$node_id][$point_id]['idle']
82 $ret[$chart_id][$node_id][$point_id]['busy']
85 $ret[$chart_id][$node_id][$point_id]['value']
86 = $cpuload['loadavg'];
93 include_once 'libraries/sysinfo.lib.php';
94 $sysinfo = PMA_getSysInfo();
97 $memory = $sysinfo->memory();
100 $ret[$chart_id][$node_id][$point_id]['value']
108 // Retrieve all required status variables
109 if (count($statusVars)) {
110 $statusVarValues = PMA_DBI_fetch_result(
111 "SHOW GLOBAL STATUS WHERE Variable_name='"
112 . implode("' OR Variable_name='", $statusVars) . "'",
117 $statusVarValues = array();
120 // Retrieve all required server variables
121 if (count($serverVars)) {
122 $serverVarValues = PMA_DBI_fetch_result(
123 "SHOW GLOBAL VARIABLES WHERE Variable_name='"
124 . implode("' OR Variable_name='", $serverVars) . "'",
129 $serverVarValues = array();
132 // ...and now assign them
133 foreach ($ret as $chart_id => $chartNodes) {
134 foreach ($chartNodes as $node_id => $nodeDataPoints) {
135 foreach ($nodeDataPoints as $point_id => $dataPoint) {
136 switch($dataPoint['type']) {
138 $ret[$chart_id][$node_id][$point_id]['value']
139 = $statusVarValues[$dataPoint['name']];
142 $ret[$chart_id][$node_id][$point_id]['value']
143 = $serverVarValues[$dataPoint['name']];
150 $ret['x'] = microtime(true) * 1000;
152 PMA_Response
::getInstance()->addJSON('message', $ret);
157 if (isset($_REQUEST['log_data'])) {
158 if (PMA_MYSQL_INT_VERSION
< 50106) {
159 // Table logging is only available since 5.1.6
163 $start = intval($_REQUEST['time_start']);
164 $end = intval($_REQUEST['time_end']);
166 if ($_REQUEST['type'] == 'slow') {
167 $q = 'SELECT start_time, user_host, ';
168 $q .= 'Sec_to_Time(Sum(Time_to_Sec(query_time))) as query_time, ';
169 $q .= 'Sec_to_Time(Sum(Time_to_Sec(lock_time))) as lock_time, ';
170 $q .= 'SUM(rows_sent) AS rows_sent, ';
171 $q .= 'SUM(rows_examined) AS rows_examined, db, sql_text, ';
172 $q .= 'COUNT(sql_text) AS \'#\' ';
173 $q .= 'FROM `mysql`.`slow_log` ';
174 $q .= 'WHERE start_time > FROM_UNIXTIME(' . $start . ') ';
175 $q .= 'AND start_time < FROM_UNIXTIME(' . $end . ') GROUP BY sql_text';
177 $result = PMA_DBI_try_query($q);
179 $return = array('rows' => array(), 'sum' => array());
182 while ($row = PMA_DBI_fetch_assoc($result)) {
184 substr($row['sql_text'], 0, strpos($row['sql_text'], ' '))
190 //Cut off big inserts and updates, but append byte count instead
191 if (strlen($row['sql_text']) > 220) {
192 $implode_sql_text = implode(
194 PMA_Util
::formatByteDown(
195 strlen($row['sql_text']), 2, 2
198 $row['sql_text'] = substr($row['sql_text'], 0, 200)
199 . '... [' . $implode_sql_text . ']';
206 if (! isset($return['sum'][$type])) {
207 $return['sum'][$type] = 0;
209 $return['sum'][$type] +
= $row['#'];
210 $return['rows'][] = $row;
213 $return['sum']['TOTAL'] = array_sum($return['sum']);
214 $return['numRows'] = count($return['rows']);
216 PMA_DBI_free_result($result);
218 PMA_Response
::getInstance()->addJSON('message', $return);
222 if ($_REQUEST['type'] == 'general') {
224 if (isset($_REQUEST['limitTypes']) && $_REQUEST['limitTypes']) {
226 = 'AND argument REGEXP \'^(INSERT|SELECT|UPDATE|DELETE)\' ';
229 $q = 'SELECT TIME(event_time) as event_time, user_host, thread_id, ';
230 $q .= 'server_id, argument, count(argument) as \'#\' ';
231 $q .= 'FROM `mysql`.`general_log` ';
232 $q .= 'WHERE command_type=\'Query\' ';
233 $q .= 'AND event_time > FROM_UNIXTIME(' . $start . ') ';
234 $q .= 'AND event_time < FROM_UNIXTIME(' . $end . ') ';
235 $q .= $limitTypes . 'GROUP by argument'; // HAVING count > 1';
237 $result = PMA_DBI_try_query($q);
239 $return = array('rows' => array(), 'sum' => array());
241 $insertTables = array();
242 $insertTablesFirst = -1;
244 $removeVars = isset($_REQUEST['removeVariables'])
245 && $_REQUEST['removeVariables'];
247 while ($row = PMA_DBI_fetch_assoc($result)) {
248 preg_match('/^(\w+)\s/', $row['argument'], $match);
249 $type = strtolower($match[1]);
251 if (! isset($return['sum'][$type])) {
252 $return['sum'][$type] = 0;
254 $return['sum'][$type] +
= $row['#'];
258 // Group inserts if selected
261 '/^INSERT INTO (`|\'|"|)([^\s\\1]+)\\1/i',
262 $row['argument'], $matches
265 $insertTables[$matches[2]]++
;
266 if ($insertTables[$matches[2]] > 1) {
267 $return['rows'][$insertTablesFirst]['#']
268 = $insertTables[$matches[2]];
270 // Add a ... to the end of this query to indicate that
271 // there's been other queries
272 $temp = $return['rows'][$insertTablesFirst]['argument'];
273 if ($temp[strlen($temp) - 1] != '.') {
274 $return['rows'][$insertTablesFirst]['argument']
278 // Group this value, thus do not add to the result list
281 $insertTablesFirst = $i;
282 $insertTables[$matches[2]] +
= $row['#'] - 1;
288 // Cut off big inserts and updates,
289 // but append byte count therefor
290 if (strlen($row['argument']) > 220) {
291 $row['argument'] = substr($row['argument'], 0, 200)
295 PMA_Util
::formatByteDown(
296 strlen($row['argument']),
309 $return['rows'][] = $row;
313 $return['sum']['TOTAL'] = array_sum($return['sum']);
314 $return['numRows'] = count($return['rows']);
316 PMA_DBI_free_result($result);
318 PMA_Response
::getInstance()->addJSON('message', $return);
323 if (isset($_REQUEST['logging_vars'])) {
324 if (isset($_REQUEST['varName']) && isset($_REQUEST['varValue'])) {
325 $value = PMA_Util
::sqlAddSlashes($_REQUEST['varValue']);
326 if (! is_numeric($value)) {
327 $value="'" . $value . "'";
330 if (! preg_match("/[^a-zA-Z0-9_]+/", $_REQUEST['varName'])) {
332 'SET GLOBAL ' . $_REQUEST['varName'] . ' = ' . $value
338 $loggingVars = PMA_DBI_fetch_result(
339 'SHOW GLOBAL VARIABLES WHERE Variable_name IN'
340 . ' ("general_log","slow_query_log","long_query_time","log_output")',
344 PMA_Response
::getInstance()->addJSON('message', $loggingVars);
348 if (isset($_REQUEST['query_analyzer'])) {
351 if (strlen($_REQUEST['database'])) {
352 PMA_DBI_select_db($_REQUEST['database']);
355 if ($profiling = PMA_Util
::profilingSupported()) {
356 PMA_DBI_query('SET PROFILING=1;');
359 // Do not cache query
360 $query = preg_replace(
366 $result = PMA_DBI_try_query($query);
367 $return['affectedRows'] = $GLOBALS['cached_affected_rows'];
369 $result = PMA_DBI_try_query('EXPLAIN ' . $query);
370 while ($row = PMA_DBI_fetch_assoc($result)) {
371 $return['explain'][] = $row;
374 // In case an error happened
375 $return['error'] = PMA_DBI_getError();
377 PMA_DBI_free_result($result);
380 $return['profiling'] = array();
381 $result = PMA_DBI_try_query(
382 'SELECT seq,state,duration FROM INFORMATION_SCHEMA.PROFILING'
383 . ' WHERE QUERY_ID=1 ORDER BY seq'
385 while ($row = PMA_DBI_fetch_assoc($result)) {
386 $return['profiling'][]= $row;
388 PMA_DBI_free_result($result);
391 PMA_Response
::getInstance()->addJSON('message', $return);
399 $header = $response->getHeader();
400 $scripts = $header->getScripts();
401 $scripts->addFile('jquery/jquery.tablesorter.js');
402 $scripts->addFile('jquery/jquery.json-2.4.js');
403 $scripts->addFile('jquery/jquery.sortableTable.js');
404 $scripts->addFile('jquery/jquery-ui-timepicker-addon.js');
405 /* < IE 9 doesn't support canvas natively */
406 if (PMA_USR_BROWSER_AGENT
== 'IE' && PMA_USR_BROWSER_VER
< 9) {
407 $scripts->addFile('jqplot/excanvas.js');
409 $scripts->addFile('canvg/canvg.js');
411 $scripts->addFile('jqplot/jquery.jqplot.js');
412 $scripts->addFile('jqplot/plugins/jqplot.pieRenderer.js');
413 $scripts->addFile('jqplot/plugins/jqplot.canvasTextRenderer.js');
414 $scripts->addFile('jqplot/plugins/jqplot.canvasAxisLabelRenderer.js');
415 $scripts->addFile('jqplot/plugins/jqplot.dateAxisRenderer.js');
416 $scripts->addFile('jqplot/plugins/jqplot.highlighter.js');
417 $scripts->addFile('jqplot/plugins/jqplot.cursor.js');
418 $scripts->addFile('jqplot/plugins/jqplot.byteFormatter.js');
419 $scripts->addFile('date.js');
421 $scripts->addFile('server_status_monitor.js');
422 $scripts->addFile('server_status_sorter.js');
428 $ServerStatusData = new PMA_ServerStatusData();
431 * Define some data needed on the client side
433 $input = '<input type="hidden" name="%s" value="%s" />';
434 $form = '<form id="js_data" class="hide">';
435 $form .= sprintf($input, 'server_time', microtime(true) * 1000);
436 $form .= sprintf($input, 'server_os', PHP_OS
);
437 $form .= sprintf($input, 'is_superuser', PMA_isSuperuser());
438 $form .= sprintf($input, 'server_db_isLocal', $ServerStatusData->db_isLocal
);
441 * Define some links used on client side
443 $links = '<div id="profiling_docu" class="hide">';
444 $links .= PMA_Util
::showMySQLDocu('general-thread-states', 'general-thread-states');
446 $links .= '<div id="explain_docu" class="hide">';
447 $links .= PMA_Util
::showMySQLDocu('explain-output', 'explain-output');
453 $response->addHTML('<div>');
454 $response->addHTML($ServerStatusData->getMenuHtml());
455 $response->addHTML(getPrintMonitorHtml($ServerStatusData));
456 $response->addHTML($form);
457 $response->addHTML($links);
458 $response->addHTML('</div>');
462 * Prints html with monitor
464 * @param object $ServerStatusData An instance of the PMA_ServerStatusData class
468 function getPrintMonitorHtml($ServerStatusData)
470 $retval = '<div class="tabLinks">';
471 $retval .= '<a href="#pauseCharts">';
472 $retval .= PMA_Util
::getImage('play.png') . __('Start Monitor');
474 $retval .= '<a href="#settingsPopup" class="popupLink">';
475 $retval .= PMA_Util
::getImage('s_cog.png') . __('Settings');
478 $retval .= '<a href="#monitorInstructionsDialog">';
479 $retval .= PMA_Util
::getImage('b_help.png') . __('Instructions/Setup');
481 $retval .= '<a href="#endChartEditMode" style="display:none;">';
482 $retval .= PMA_Util
::getImage('s_okay.png');
483 $retval .= __('Done dragging (rearranging) charts');
487 $retval .= '<div class="popupContent settingsPopup">';
488 $retval .= '<a href="#addNewChart">';
489 $retval .= PMA_Util
::getImage('b_chart.png') . __('Add chart');
491 $retval .= '<a href="#rearrangeCharts">';
492 $retval .= PMA_Util
::getImage('b_tblops.png') . __('Enable charts dragging');
494 $retval .= '<div class="clearfloat paddingtop"></div>';
495 $retval .= '<div class="floatleft">';
496 $retval .= __('Refresh rate') . '<br />';
497 $retval .= PMA_getRefreshList(
500 Array(2, 3, 4, 5, 10, 20, 40, 60, 120, 300, 600, 1200)
504 $retval .= '<div class="floatleft">';
505 $retval .= __('Chart columns');
507 $retval .= '<select name="chartColumns">';
508 $retval .= '<option>1</option>';
509 $retval .= '<option>2</option>';
510 $retval .= '<option>3</option>';
511 $retval .= '<option>4</option>';
512 $retval .= '<option>5</option>';
513 $retval .= '<option>6</option>';
514 $retval .= '<option>7</option>';
515 $retval .= '<option>8</option>';
516 $retval .= '<option>9</option>';
517 $retval .= '<option>10</option>';
518 $retval .= '</select>';
520 $retval .= '<div class="clearfloat paddingtop">';
521 $retval .= '<b>' . __('Chart arrangement') . '</b> ';
522 $retval .= PMA_Util
::showHint(
524 'The arrangement of the charts is stored to the browsers local storage. '
525 . 'You may want to export it if you have a complicated set up.'
529 $retval .= '<a class="ajax" href="#importMonitorConfig">';
530 $retval .= __('Import');
532 $retval .= ' ';
533 $retval .= '<a class="disableAjax" href="#exportMonitorConfig">';
534 $retval .= __('Export');
536 $retval .= ' ';
537 $retval .= '<a href="#clearMonitorConfig">';
538 $retval .= __('Reset to default');
543 $retval .= '<div id="monitorInstructionsDialog" title="';
544 $retval .= __('Monitor Instructions') . '" style="display:none;">';
546 'The phpMyAdmin Monitor can assist you in optimizing the server'
547 . ' configuration and track down time intensive queries. For the latter you'
548 . ' will need to set log_output to \'TABLE\' and have either the'
549 . ' slow_query_log or general_log enabled. Note however, that the'
550 . ' general_log produces a lot of data and increases server load'
554 if (PMA_MYSQL_INT_VERSION
< 50106) {
556 $retval .= PMA_Util
::getImage('s_attention.png');
558 'Unfortunately your Database server does not support logging to table,'
559 . ' which is a requirement for analyzing the database logs with'
560 . ' phpMyAdmin. Logging to table is supported by MySQL 5.1.6 and'
561 . ' onwards. You may still use the server charting features however.'
565 $retval .= '<p></p>';
566 $retval .= '<img class="ajaxIcon" src="';
567 $retval .= $GLOBALS['pmaThemeImage'] . 'ajax_clock_small.gif"';
568 $retval .= ' alt="' . __('Loading') . '" />';
569 $retval .= '<div class="ajaxContent"></div>';
570 $retval .= '<div class="monitorUse" style="display:none;">';
571 $retval .= '<p></p>';
572 $retval .= '<strong>';
573 $retval .= __('Using the monitor:');
574 $retval .= '</strong><p>';
576 'Your browser will refresh all displayed charts in a regular interval.'
577 . ' You may add charts and change the refresh rate under \'Settings\','
578 . ' or remove any chart using the cog icon on each respective chart.'
580 $retval .= '</p><p>';
582 'To display queries from the logs, select the relevant time span on any'
583 . ' chart by holding down the left mouse button and panning over the'
584 . ' chart. Once confirmed, this will load a table of grouped queries,'
585 . ' there you may click on any occuring SELECT statements to further'
590 $retval .= PMA_Util
::getImage('s_attention.png');
591 $retval .= '<strong>';
592 $retval .= __('Please note:');
593 $retval .= '</strong><br />';
595 'Enabling the general_log may increase the server load by'
596 . ' 5-15%. Also be aware that generating statistics from the logs is a'
597 . ' load intensive task, so it is advisable to select only a small time'
598 . ' span and to disable the general_log and empty its table once'
599 . ' monitoring is not required any more.'
606 $retval .= '<div id="addChartDialog" title="' . __('Add chart') . '" style="display:none;">';
607 $retval .= '<div id="tabGridVariables">';
608 $retval .= '<p><input type="text" name="chartTitle" value="' . __('Chart Title') . '" /></p>';
609 $retval .= '<input type="radio" name="chartType" value="preset" id="chartPreset" />';
610 $retval .= '<label for="chartPreset">' . __('Preset chart') . '</label>';
611 $retval .= '<select name="presetCharts"></select><br/>';
612 $retval .= '<input type="radio" name="chartType" value="variable" id="chartStatusVar" checked="checked" />';
613 $retval .= '<label for="chartStatusVar">';
614 $retval .= __('Status variable(s)');
615 $retval .= '</label><br/>';
616 $retval .= '<div id="chartVariableSettings">';
617 $retval .= '<label for="chartSeries">' . __('Select series:') . '</label><br />';
618 $retval .= '<select id="chartSeries" name="varChartList" size="1">';
619 $retval .= '<option>' . __('Commonly monitored') . '</option>';
620 $retval .= '<option>Processes</option>';
621 $retval .= '<option>Questions</option>';
622 $retval .= '<option>Connections</option>';
623 $retval .= '<option>Bytes_sent</option>';
624 $retval .= '<option>Bytes_received</option>';
625 $retval .= '<option>Threads_connected</option>';
626 $retval .= '<option>Created_tmp_disk_tables</option>';
627 $retval .= '<option>Handler_read_first</option>';
628 $retval .= '<option>Innodb_buffer_pool_wait_free</option>';
629 $retval .= '<option>Key_reads</option>';
630 $retval .= '<option>Open_tables</option>';
631 $retval .= '<option>Select_full_join</option>';
632 $retval .= '<option>Slow_queries</option>';
633 $retval .= '</select><br />';
634 $retval .= '<label for="variableInput">';
635 $retval .= __('or type variable name:');
636 $retval .= ' </label>';
637 $retval .= '<input type="text" name="variableInput" id="variableInput" />';
638 $retval .= '<p></p>';
639 $retval .= '<input type="checkbox" name="differentialValue"';
640 $retval .= ' id="differentialValue" value="differential" checked="checked" />';
641 $retval .= '<label for="differentialValue">';
642 $retval .= __('Display as differential value');
643 $retval .= '</label><br />';
644 $retval .= '<input type="checkbox" id="useDivisor" name="useDivisor" value="1" />';
645 $retval .= '<label for="useDivisor">' . __('Apply a divisor') . '</label>';
646 $retval .= '<span class="divisorInput" style="display:none;">';
647 $retval .= '<input type="text" name="valueDivisor" size="4" value="1" />';
648 $retval .= '(<a href="#kibDivisor">' . __('KiB') . '</a>, ';
649 $retval .= '<a href="#mibDivisor">' . __('MiB') . '</a>)';
650 $retval .= '</span><br />';
651 $retval .= '<input type="checkbox" id="useUnit" name="useUnit" value="1" />';
652 $retval .= '<label for="useUnit">';
653 $retval .= __('Append unit to data values');
654 $retval .= '</label>';
655 $retval .= '<span class="unitInput" style="display:none;">';
656 $retval .= '<input type="text" name="valueUnit" size="4" value="" />';
657 $retval .= '</span>';
659 $retval .= '<a href="#submitAddSeries"><b>' . __('Add this series') . '</b></a>';
660 $retval .= '<span id="clearSeriesLink" style="display:none;">';
661 $retval .= ' | <a href="#submitClearSeries">' . __('Clear series') . '</a>';
662 $retval .= '</span>';
664 $retval .= __('Series in Chart:');
666 $retval .= '<span id="seriesPreview">';
667 $retval .= '<i>' . __('None') . '</i>';
668 $retval .= '</span>';
674 $retval .= '<div id="logAnalyseDialog" title="';
675 $retval .= __('Log statistics') . '" style="display:none;">';
676 $retval .= '<p>' . __('Selected time range:');
677 $retval .= '<input type="text" name="dateStart" class="datetimefield" value="" /> - ';
678 $retval .= '<input type="text" name="dateEnd" class="datetimefield" value="" />';
680 $retval .= '<input type="checkbox" id="limitTypes" value="1" checked="checked" />';
681 $retval .= '<label for="limitTypes">';
682 $retval .= __('Only retrieve SELECT,INSERT,UPDATE and DELETE Statements');
683 $retval .= '</label>';
685 $retval .= '<input type="checkbox" id="removeVariables" value="1" checked="checked" />';
686 $retval .= '<label for="removeVariables">';
687 $retval .= __('Remove variable data in INSERT statements for better grouping');
688 $retval .= '</label>';
690 $retval .= __('Choose from which log you want the statistics to be generated from.');
693 $retval .= __('Results are grouped by query text.');
696 $retval .= '<div id="queryAnalyzerDialog" title="';
697 $retval .= __('Query analyzer') . '" style="display:none;">';
698 $retval .= '<textarea id="sqlquery"> </textarea>';
699 $retval .= '<p></p>';
700 $retval .= '<div class="placeHolder"></div>';
704 $retval .= '<table class="clearfloat" id="chartGrid"></table>';
705 $retval .= '<div id="logTable">';
709 $retval .= '<script type="text/javascript">';
710 $retval .= 'variableNames = [ ';
712 foreach ($ServerStatusData->status
as $name=>$value) {
713 if (is_numeric($value)) {
717 $retval .= "'" . $name . "'";
721 $retval .= '</script>';
727 * Builds a <select> list for refresh rates
729 * @param string $name Name of select
730 * @param int $defaultRate Currently chosen rate
731 * @param array $refreshRates List of refresh rates
735 function PMA_getRefreshList($name,
737 $refreshRates = Array(1, 2, 5, 10, 20, 40, 60, 120, 300, 600)
739 $return = '<select name="' . $name . '" id="id_' . $name
740 . '" class="refreshRate">';
741 foreach ($refreshRates as $rate) {
742 $selected = ($rate == $defaultRate)?
' selected="selected"':'';
743 $return .= '<option value="' . $rate . '"' . $selected . '>';
745 $return .= sprintf(_ngettext('%d second', '%d seconds', $rate), $rate);
748 $return .= sprintf(_ngettext('%d minute', '%d minutes', $rate), $rate);
750 $return .= '</option>';
752 $return .= '</select>';