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');
420 $scripts->addFile('server_status_monitor.js');
421 $scripts->addFile('server_status_sorter.js');
427 $ServerStatusData = new PMA_ServerStatusData();
430 * Define some data needed on the client side
432 $input = '<input type="hidden" name="%s" value="%s" />';
433 $form = '<form id="js_data" class="hide">';
434 $form .= sprintf($input, 'server_time', microtime(true) * 1000);
435 $form .= sprintf($input, 'server_os', PHP_OS
);
436 $form .= sprintf($input, 'is_superuser', PMA_isSuperuser());
437 $form .= sprintf($input, 'server_db_isLocal', $ServerStatusData->db_isLocal
);
440 * Define some links used on client side
442 $links = '<div id="profiling_docu" class="hide">';
443 $links .= PMA_Util
::showMySQLDocu('general-thread-states', 'general-thread-states');
445 $links .= '<div id="explain_docu" class="hide">';
446 $links .= PMA_Util
::showMySQLDocu('explain-output', 'explain-output');
452 $response->addHTML('<div>');
453 $response->addHTML($ServerStatusData->getMenuHtml());
454 $response->addHTML(getPrintMonitorHtml($ServerStatusData));
455 $response->addHTML($form);
456 $response->addHTML($links);
457 $response->addHTML('</div>');
461 * Prints html with monitor
463 * @param object $ServerStatusData An instance of the PMA_ServerStatusData class
467 function getPrintMonitorHtml($ServerStatusData)
469 $retval = '<div class="tabLinks">';
470 $retval .= '<a href="#pauseCharts">';
471 $retval .= PMA_Util
::getImage('play.png') . __('Start Monitor');
473 $retval .= '<a href="#settingsPopup" class="popupLink">';
474 $retval .= PMA_Util
::getImage('s_cog.png') . __('Settings');
477 $retval .= '<a href="#monitorInstructionsDialog">';
478 $retval .= PMA_Util
::getImage('b_help.png') . __('Instructions/Setup');
480 $retval .= '<a href="#endChartEditMode" style="display:none;">';
481 $retval .= PMA_Util
::getImage('s_okay.png');
482 $retval .= __('Done dragging (rearranging) charts');
486 $retval .= '<div class="popupContent settingsPopup">';
487 $retval .= '<a href="#addNewChart">';
488 $retval .= PMA_Util
::getImage('b_chart.png') . __('Add chart');
490 $retval .= '<a href="#rearrangeCharts">';
491 $retval .= PMA_Util
::getImage('b_tblops.png') . __('Enable charts dragging');
493 $retval .= '<div class="clearfloat paddingtop"></div>';
494 $retval .= '<div class="floatleft">';
495 $retval .= __('Refresh rate') . '<br />';
496 $retval .= PMA_getRefreshList(
499 Array(2, 3, 4, 5, 10, 20, 40, 60, 120, 300, 600, 1200)
503 $retval .= '<div class="floatleft">';
504 $retval .= __('Chart columns');
506 $retval .= '<select name="chartColumns">';
507 $retval .= '<option>1</option>';
508 $retval .= '<option>2</option>';
509 $retval .= '<option>3</option>';
510 $retval .= '<option>4</option>';
511 $retval .= '<option>5</option>';
512 $retval .= '<option>6</option>';
513 $retval .= '<option>7</option>';
514 $retval .= '<option>8</option>';
515 $retval .= '<option>9</option>';
516 $retval .= '<option>10</option>';
517 $retval .= '</select>';
519 $retval .= '<div class="clearfloat paddingtop">';
520 $retval .= '<b>' . __('Chart arrangement') . '</b> ';
521 $retval .= PMA_Util
::showHint(
523 'The arrangement of the charts is stored to the browsers local storage. '
524 . 'You may want to export it if you have a complicated set up.'
528 $retval .= '<a class="ajax" href="#importMonitorConfig">';
529 $retval .= __('Import');
531 $retval .= ' ';
532 $retval .= '<a class="disableAjax" href="#exportMonitorConfig">';
533 $retval .= __('Export');
535 $retval .= ' ';
536 $retval .= '<a href="#clearMonitorConfig">';
537 $retval .= __('Reset to default');
542 $retval .= '<div id="monitorInstructionsDialog" title="';
543 $retval .= __('Monitor Instructions') . '" style="display:none;">';
545 'The phpMyAdmin Monitor can assist you in optimizing the server'
546 . ' configuration and track down time intensive queries. For the latter you'
547 . ' will need to set log_output to \'TABLE\' and have either the'
548 . ' slow_query_log or general_log enabled. Note however, that the'
549 . ' general_log produces a lot of data and increases server load'
553 if (PMA_MYSQL_INT_VERSION
< 50106) {
555 $retval .= PMA_Util
::getImage('s_attention.png');
557 'Unfortunately your Database server does not support logging to table,'
558 . ' which is a requirement for analyzing the database logs with'
559 . ' phpMyAdmin. Logging to table is supported by MySQL 5.1.6 and'
560 . ' onwards. You may still use the server charting features however.'
564 $retval .= '<p></p>';
565 $retval .= '<img class="ajaxIcon" src="';
566 $retval .= $GLOBALS['pmaThemeImage'] . 'ajax_clock_small.gif"';
567 $retval .= ' alt="' . __('Loading') . '" />';
568 $retval .= '<div class="ajaxContent"></div>';
569 $retval .= '<div class="monitorUse" style="display:none;">';
570 $retval .= '<p></p>';
571 $retval .= '<strong>';
572 $retval .= __('Using the monitor:');
573 $retval .= '</strong><p>';
575 'Your browser will refresh all displayed charts in a regular interval.'
576 . ' You may add charts and change the refresh rate under \'Settings\','
577 . ' or remove any chart using the cog icon on each respective chart.'
579 $retval .= '</p><p>';
581 'To display queries from the logs, select the relevant time span on any'
582 . ' chart by holding down the left mouse button and panning over the'
583 . ' chart. Once confirmed, this will load a table of grouped queries,'
584 . ' there you may click on any occuring SELECT statements to further'
589 $retval .= PMA_Util
::getImage('s_attention.png');
590 $retval .= '<strong>';
591 $retval .= __('Please note:');
592 $retval .= '</strong><br />';
594 'Enabling the general_log may increase the server load by'
595 . ' 5-15%. Also be aware that generating statistics from the logs is a'
596 . ' load intensive task, so it is advisable to select only a small time'
597 . ' span and to disable the general_log and empty its table once'
598 . ' monitoring is not required any more.'
605 $retval .= '<div id="addChartDialog" title="' . __('Add chart') . '" style="display:none;">';
606 $retval .= '<div id="tabGridVariables">';
607 $retval .= '<p><input type="text" name="chartTitle" value="' . __('Chart Title') . '" /></p>';
608 $retval .= '<input type="radio" name="chartType" value="preset" id="chartPreset" />';
609 $retval .= '<label for="chartPreset">' . __('Preset chart') . '</label>';
610 $retval .= '<select name="presetCharts"></select><br/>';
611 $retval .= '<input type="radio" name="chartType" value="variable" id="chartStatusVar" checked="checked" />';
612 $retval .= '<label for="chartStatusVar">';
613 $retval .= __('Status variable(s)');
614 $retval .= '</label><br/>';
615 $retval .= '<div id="chartVariableSettings">';
616 $retval .= '<label for="chartSeries">' . __('Select series:') . '</label><br />';
617 $retval .= '<select id="chartSeries" name="varChartList" size="1">';
618 $retval .= '<option>' . __('Commonly monitored') . '</option>';
619 $retval .= '<option>Processes</option>';
620 $retval .= '<option>Questions</option>';
621 $retval .= '<option>Connections</option>';
622 $retval .= '<option>Bytes_sent</option>';
623 $retval .= '<option>Bytes_received</option>';
624 $retval .= '<option>Threads_connected</option>';
625 $retval .= '<option>Created_tmp_disk_tables</option>';
626 $retval .= '<option>Handler_read_first</option>';
627 $retval .= '<option>Innodb_buffer_pool_wait_free</option>';
628 $retval .= '<option>Key_reads</option>';
629 $retval .= '<option>Open_tables</option>';
630 $retval .= '<option>Select_full_join</option>';
631 $retval .= '<option>Slow_queries</option>';
632 $retval .= '</select><br />';
633 $retval .= '<label for="variableInput">';
634 $retval .= __('or type variable name:');
635 $retval .= ' </label>';
636 $retval .= '<input type="text" name="variableInput" id="variableInput" />';
637 $retval .= '<p></p>';
638 $retval .= '<input type="checkbox" name="differentialValue"';
639 $retval .= ' id="differentialValue" value="differential" checked="checked" />';
640 $retval .= '<label for="differentialValue">';
641 $retval .= __('Display as differential value');
642 $retval .= '</label><br />';
643 $retval .= '<input type="checkbox" id="useDivisor" name="useDivisor" value="1" />';
644 $retval .= '<label for="useDivisor">' . __('Apply a divisor') . '</label>';
645 $retval .= '<span class="divisorInput" style="display:none;">';
646 $retval .= '<input type="text" name="valueDivisor" size="4" value="1" />';
647 $retval .= '(<a href="#kibDivisor">' . __('KiB') . '</a>, ';
648 $retval .= '<a href="#mibDivisor">' . __('MiB') . '</a>)';
649 $retval .= '</span><br />';
650 $retval .= '<input type="checkbox" id="useUnit" name="useUnit" value="1" />';
651 $retval .= '<label for="useUnit">';
652 $retval .= __('Append unit to data values');
653 $retval .= '</label>';
654 $retval .= '<span class="unitInput" style="display:none;">';
655 $retval .= '<input type="text" name="valueUnit" size="4" value="" />';
656 $retval .= '</span>';
658 $retval .= '<a href="#submitAddSeries"><b>' . __('Add this series') . '</b></a>';
659 $retval .= '<span id="clearSeriesLink" style="display:none;">';
660 $retval .= ' | <a href="#submitClearSeries">' . __('Clear series') . '</a>';
661 $retval .= '</span>';
663 $retval .= __('Series in Chart:');
665 $retval .= '<span id="seriesPreview">';
666 $retval .= '<i>' . __('None') . '</i>';
667 $retval .= '</span>';
673 $retval .= '<div id="logAnalyseDialog" title="';
674 $retval .= __('Log statistics') . '" style="display:none;">';
675 $retval .= '<p>' . __('Selected time range:');
676 $retval .= '<input type="text" name="dateStart" class="datetimefield" value="" /> - ';
677 $retval .= '<input type="text" name="dateEnd" class="datetimefield" value="" />';
679 $retval .= '<input type="checkbox" id="limitTypes" value="1" checked="checked" />';
680 $retval .= '<label for="limitTypes">';
681 $retval .= __('Only retrieve SELECT,INSERT,UPDATE and DELETE Statements');
682 $retval .= '</label>';
684 $retval .= '<input type="checkbox" id="removeVariables" value="1" checked="checked" />';
685 $retval .= '<label for="removeVariables">';
686 $retval .= __('Remove variable data in INSERT statements for better grouping');
687 $retval .= '</label>';
689 $retval .= __('Choose from which log you want the statistics to be generated from.');
692 $retval .= __('Results are grouped by query text.');
695 $retval .= '<div id="queryAnalyzerDialog" title="';
696 $retval .= __('Query analyzer') . '" style="display:none;">';
697 $retval .= '<textarea id="sqlquery"> </textarea>';
698 $retval .= '<p></p>';
699 $retval .= '<div class="placeHolder"></div>';
703 $retval .= '<table class="clearfloat" id="chartGrid"></table>';
704 $retval .= '<div id="logTable">';
708 $retval .= '<script type="text/javascript">';
709 $retval .= 'variableNames = [ ';
711 foreach ($ServerStatusData->status
as $name=>$value) {
712 if (is_numeric($value)) {
716 $retval .= "'" . $name . "'";
720 $retval .= '</script>';
726 * Builds a <select> list for refresh rates
728 * @param string $name Name of select
729 * @param int $defaultRate Currently chosen rate
730 * @param array $refreshRates List of refresh rates
734 function PMA_getRefreshList($name,
736 $refreshRates = Array(1, 2, 5, 10, 20, 40, 60, 120, 300, 600)
738 $return = '<select name="' . $name . '" id="id_' . $name
739 . '" class="refreshRate">';
740 foreach ($refreshRates as $rate) {
741 $selected = ($rate == $defaultRate)?
' selected="selected"':'';
742 $return .= '<option value="' . $rate . '"' . $selected . '>';
744 $return .= sprintf(_ngettext('%d second', '%d seconds', $rate), $rate);
747 $return .= sprintf(_ngettext('%d minute', '%d minutes', $rate), $rate);
749 $return .= '</option>';
751 $return .= '</select>';