PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/scripts/mysql_stats.php

https://github.com/bohdan-s/librenms
PHP | 1247 lines | 1011 code | 52 blank | 184 comment | 117 complexity | 0445602dc36604be3fe5425ae4e9cb95 MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // MYSQL Check - FIXME
  3. // 1 UNKNOWN
  4. # ============================================================================
  5. # This is a script to retrieve information from a MySQL server for input to a
  6. # Cacti graphing process. It is hosted at
  7. # http://code.google.com/p/mysql-cacti-templates/.
  8. #
  9. # This program is copyright (c) 2007 Baron Schwartz. Feedback and improvements
  10. # are welcome.
  11. #
  12. # THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
  13. # WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
  14. # MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  15. #
  16. # This program is free software; you can redistribute it and/or modify it under
  17. # the terms of the GNU General Public License as published by the Free Software
  18. # Foundation, version 2.
  19. #
  20. # You should have received a copy of the GNU General Public License along with
  21. # this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  22. # Place, Suite 330, Boston, MA 02111-1307 USA.
  23. # ============================================================================
  24. # ============================================================================
  25. # To make this code testable, we need to prevent code from running when it is
  26. # included from the test script. The test script and this file have different
  27. # filenames, so we can compare them. In some cases $_SERVER['SCRIPT_FILENAME']
  28. # seems not to be defined, so we skip the check -- this check should certainly
  29. # pass in the test environment.
  30. # ============================================================================
  31. if (!array_key_exists('SCRIPT_FILENAME', $_SERVER)
  32. || basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME']) ) {
  33. # ============================================================================
  34. # CONFIGURATION
  35. # ============================================================================
  36. # Define MySQL connection constants in config.php. Arguments explicitly passed
  37. # in from Cacti will override these. However, if you leave them blank in Cacti
  38. # and set them here, you can make life easier. Instead of defining parameters
  39. # here, you can define them in another file named the same as this file, with a
  40. # .cnf extension.
  41. # ============================================================================
  42. # FIXME: why are these not taken from config.php?
  43. $mysql_user = 'observium';
  44. $mysql_pass = 'flobbleobservium';
  45. $mysql_host = 'localhost';
  46. $mysql_port = 3306;
  47. $mysql_ssl = FALSE; # Whether to use SSL to connect to MySQL.
  48. $heartbeat = ''; # db.tbl in case you use mk-heartbeat from Maatkit.
  49. $cache_dir = '/tmp'; # If set, this uses caching to avoid multiple calls.
  50. $poll_time = 300; # Adjust to match your polling interval.
  51. $chk_options = array (
  52. 'innodb' => true, # Do you want to check InnoDB statistics?
  53. 'master' => true, # Do you want to check binary logging?
  54. 'slave' => true, # Do you want to check slave status?
  55. 'procs' => true, # Do you want to check SHOW PROCESSLIST?
  56. );
  57. $use_ss = FALSE; # Whether to use the script server or not
  58. $debug = FALSE; # Define whether you want debugging behavior.
  59. $debug_log = FALSE; # If $debug_log is a filename, it'll be used.
  60. # ============================================================================
  61. # You should not need to change anything below this line.
  62. # ============================================================================
  63. $version = "1.1.7";
  64. # ============================================================================
  65. # Include settings from an external config file (issue 39).
  66. # ============================================================================
  67. if (file_exists(__FILE__ . '.cnf' ) ) {
  68. require(__FILE__ . '.cnf');
  69. }
  70. # Make this a happy little script even when there are errors.
  71. $no_http_headers = true;
  72. ini_set('implicit_flush', false); # No output, ever.
  73. if ($debug ) {
  74. ini_set('display_errors', true);
  75. ini_set('display_startup_errors', true);
  76. ini_set('error_reporting', 2147483647);
  77. }
  78. else {
  79. ini_set('error_reporting', E_ERROR);
  80. }
  81. ob_start(); # Catch all output such as notices of undefined array indexes.
  82. function error_handler($errno, $errstr, $errfile, $errline) {
  83. print("$errstr at $errfile line $errline\n");
  84. debug("$errstr at $errfile line $errline");
  85. }
  86. # ============================================================================
  87. # Set up the stuff we need to be called by the script server.
  88. # ============================================================================
  89. if ($use_ss ) {
  90. if (file_exists( dirname(__FILE__) . "/../include/global.php") ) {
  91. # See issue 5 for the reasoning behind this.
  92. debug("including " . dirname(__FILE__) . "/../include/global.php");
  93. include_once(dirname(__FILE__) . "/../include/global.php");
  94. }
  95. elseif (file_exists( dirname(__FILE__) . "/../include/config.php" ) ) {
  96. # Some Cacti installations don't have global.php.
  97. debug("including " . dirname(__FILE__) . "/../include/config.php");
  98. include_once(dirname(__FILE__) . "/../include/config.php");
  99. }
  100. }
  101. # ============================================================================
  102. # Make sure we can also be called as a script.
  103. # ============================================================================
  104. if (!isset($called_by_script_server)) {
  105. debug($_SERVER["argv"]);
  106. array_shift($_SERVER["argv"]); # Strip off this script's filename
  107. $options = parse_cmdline($_SERVER["argv"]);
  108. validate_options($options);
  109. $result = ss_get_mysql_stats($options);
  110. debug($result);
  111. if (!$debug ) {
  112. # Throw away the buffer, which ought to contain only errors.
  113. ob_end_clean();
  114. }
  115. else {
  116. ob_end_flush(); # In debugging mode, print out the errors.
  117. }
  118. # Split the result up and extract only the desired parts of it.
  119. $options['items'] = "";
  120. $wanted = explode(',', $options['items']);
  121. $output = array();
  122. foreach ( explode(' ', $result) as $item ) {
  123. if (in_array(substr($item, 0, 2), $wanted) ) {
  124. $output[] = $item;
  125. }
  126. list($short, $val) = explode(":", $item);
  127. echo(strtolower($short).":".strtolower($val)."\n");
  128. }
  129. debug(array("Final result", $output));
  130. print(implode(' ', $output));
  131. }
  132. # ============================================================================
  133. # End "if file was not included" section.
  134. # ============================================================================
  135. }
  136. # ============================================================================
  137. # Work around the lack of array_change_key_case in older PHP.
  138. # ============================================================================
  139. if (!function_exists('array_change_key_case') ) {
  140. function array_change_key_case($arr) {
  141. $res = array();
  142. foreach ( $arr as $key => $val ) {
  143. $res[strtolower($key)] = $val;
  144. }
  145. return $res;
  146. }
  147. }
  148. # ============================================================================
  149. # Validate that the command-line options are here and correct
  150. # ============================================================================
  151. function validate_options($options) {
  152. debug($options);
  153. $opts = array('items', 'user', 'pass', 'heartbeat', 'nocache', 'port');
  154. # Required command-line options
  155. foreach ( array() as $option ) {
  156. if (!isset($options[$option]) || !$options[$option] ) {
  157. usage("Required option --$option is missing");
  158. }
  159. }
  160. foreach ( $options as $key => $val ) {
  161. if (!in_array($key, $opts) ) {
  162. usage("Unknown option --$key");
  163. }
  164. }
  165. }
  166. # ============================================================================
  167. # Print out a brief usage summary
  168. # ============================================================================
  169. function usage($message) {
  170. global $mysql_host, $mysql_user, $mysql_pass, $mysql_port, $heartbeat;
  171. $usage = <<<EOF
  172. $message
  173. Usage: php ss_get_mysql_stats.php --host <host> --items <item,...> [OPTION]
  174. --host Hostname to connect to; use host:port syntax to specify a port
  175. Use :/path/to/socket if you want to connect via a UNIX socket
  176. --items Comma-separated list of the items whose data you want
  177. --user MySQL username; defaults to $mysql_user if not given
  178. --pass MySQL password; defaults to $mysql_pass if not given
  179. --heartbeat MySQL heartbeat table; defaults to '$heartbeat' (see mk-heartbeat)
  180. --nocache Do not cache results in a file
  181. --port MySQL port; defaults to $mysql_port if not given
  182. --mysql_ssl Add the MYSQL_CLIENT_SSL flag to mysql_connect() call
  183. EOF;
  184. die($usage);
  185. }
  186. # ============================================================================
  187. # Parse command-line arguments, in the format --arg value --arg value, and
  188. # return them as an array ( arg => value )
  189. # ============================================================================
  190. function parse_cmdline( $args ) {
  191. $result = array();
  192. $cur_arg = '';
  193. foreach ($args as $val) {
  194. if (strpos($val, '--') === 0 ) {
  195. if (strpos($val, '--no') === 0 ) {
  196. # It's an option without an argument, but it's a --nosomething so
  197. # it's OK.
  198. $result[substr($val, 2)] = 1;
  199. $cur_arg = '';
  200. }
  201. elseif ($cur_arg ) { # Maybe the last --arg was an option with no arg
  202. if ($cur_arg == '--user' || $cur_arg == '--pass' || $cur_arg == '--port' ) {
  203. # Special case because Cacti will pass these without an arg
  204. $cur_arg = '';
  205. }
  206. else {
  207. die("No arg: $cur_arg\n");
  208. }
  209. }
  210. else {
  211. $cur_arg = $val;
  212. }
  213. }
  214. else {
  215. $result[substr($cur_arg, 2)] = $val;
  216. $cur_arg = '';
  217. }
  218. }
  219. if ($cur_arg && ($cur_arg != '--user' && $cur_arg != '--pass' && $cur_arg != '--port') ) {
  220. die("No arg: $cur_arg\n");
  221. }
  222. debug($result);
  223. return $result;
  224. }
  225. # ============================================================================
  226. # This is the main function. Some parameters are filled in from defaults at the
  227. # top of this file.
  228. # ============================================================================
  229. function ss_get_mysql_stats( $options ) {
  230. # Process connection options and connect to MySQL.
  231. global $debug, $mysql_user, $mysql_pass, $heartbeat, $cache_dir, $poll_time,
  232. $chk_options, $mysql_host, $mysql_port, $mysql_ssl;
  233. # Connect to MySQL.
  234. $user = isset($options['user']) ? $options['user'] : $mysql_user;
  235. $pass = isset($options['pass']) ? $options['pass'] : $mysql_pass;
  236. $port = isset($options['port']) ? $options['port'] : $mysql_port;
  237. $host = isset($options['host']) ? $options['host'] : $mysql_host;
  238. $heartbeat = isset($options['heartbeat']) ? $options['heartbeat'] : $heartbeat;
  239. # If there is a port, or if it's a non-standard port, we add ":$port" to the
  240. # hostname.
  241. $host_str = $host
  242. . $port != 3306 ? ":$port" : '';
  243. debug(array('connecting to', $host_str, $user, $pass));
  244. if (!extension_loaded('mysql') ) {
  245. debug("The MySQL extension is not loaded");
  246. die("The MySQL extension is not loaded");
  247. }
  248. if ($mysql_ssl || (isset($options['mysql_ssl']) && $options['mysql_ssl']) ) {
  249. $conn = mysql_connect($host_str, $user, $pass, true, MYSQL_CLIENT_SSL);
  250. }
  251. else {
  252. $conn = mysql_connect($host_str, $user, $pass);
  253. }
  254. if (!$conn ) {
  255. die("MySQL: " . mysql_error());
  256. }
  257. $sanitized_host = str_replace(array(":", "/"), array("", "_"), $host);
  258. $cache_file = "$cache_dir/$sanitized_host-mysql_cacti_stats.txt"
  259. . $port != 3306 ? ":$port" : '';
  260. debug("Cache file is $cache_file");
  261. # First, check the cache.
  262. $fp = null;
  263. if (!isset($options['nocache']) ) {
  264. if ($fp = fopen($cache_file, 'a+') ) {
  265. $locked = flock($fp, 1); # LOCK_SH
  266. if ($locked ) {
  267. if (filesize($cache_file) > 0
  268. && filectime($cache_file) + ($poll_time/2) > time()
  269. && ($arr = file($cache_file))
  270. ) {# The cache file is good to use.
  271. debug("Using the cache file");
  272. fclose($fp);
  273. return $arr[0];
  274. }
  275. else {
  276. debug("The cache file seems too small or stale");
  277. # Escalate the lock to exclusive, so we can write to it.
  278. if (flock($fp, 2) ) { # LOCK_EX
  279. # We might have blocked while waiting for that LOCK_EX, and
  280. # another process ran and updated it. Let's see if we can just
  281. # return the data now:
  282. if (filesize($cache_file) > 0
  283. && filectime($cache_file) + ($poll_time/2) > time()
  284. && ($arr = file($cache_file))
  285. ) {# The cache file is good to use.
  286. debug("Using the cache file");
  287. fclose($fp);
  288. return $arr[0];
  289. }
  290. ftruncate($fp, 0); # Now it's ready for writing later.
  291. }
  292. }
  293. }
  294. else {
  295. debug("Couldn't lock the cache file, ignoring it.");
  296. $fp = null;
  297. }
  298. }
  299. }
  300. else {
  301. $fp = null;
  302. debug("Couldn't open the cache file");
  303. }
  304. # Set up variables.
  305. $status = array( # Holds the result of SHOW STATUS, SHOW INNODB STATUS, etc
  306. # Define some indexes so they don't cause errors with += operations.
  307. 'relay_log_space' => null,
  308. 'binary_log_space' => null,
  309. 'current_transactions' => null,
  310. 'locked_transactions' => null,
  311. 'active_transactions' => null,
  312. 'innodb_locked_tables' => null,
  313. 'innodb_tables_in_use' => null,
  314. 'innodb_lock_structs' => null,
  315. 'innodb_lock_wait_secs' => null,
  316. 'innodb_sem_waits' => null,
  317. 'innodb_sem_wait_time_ms'=> null,
  318. # Values for the 'state' column from SHOW PROCESSLIST (converted to
  319. # lowercase, with spaces replaced by underscores)
  320. 'State_closing_tables' => null,
  321. 'State_copying_to_tmp_table' => null,
  322. 'State_end' => null,
  323. 'State_freeing_items' => null,
  324. 'State_init' => null,
  325. 'State_locked' => null,
  326. 'State_login' => null,
  327. 'State_preparing' => null,
  328. 'State_reading_from_net' => null,
  329. 'State_sending_data' => null,
  330. 'State_sorting_result' => null,
  331. 'State_statistics' => null,
  332. 'State_updating' => null,
  333. 'State_writing_to_net' => null,
  334. 'State_none' => null,
  335. 'State_other' => null, # Everything not listed above
  336. );
  337. # Get SHOW STATUS and convert the name-value array into a simple
  338. # associative array.
  339. $result = run_query("SHOW /*!50002 GLOBAL */ STATUS", $conn);
  340. foreach ( $result as $row ) {
  341. $status[$row[0]] = $row[1];
  342. }
  343. # Get SHOW VARIABLES and do the same thing, adding it to the $status array.
  344. $result = run_query("SHOW VARIABLES", $conn);
  345. foreach ( $result as $row ) {
  346. $status[$row[0]] = $row[1];
  347. }
  348. # Get SHOW SLAVE STATUS, and add it to the $status array.
  349. if ($chk_options['slave'] ) {
  350. $result = run_query("SHOW SLAVE STATUS", $conn);
  351. $slave_status_rows_gotten = 0;
  352. foreach ( $result as $row ) {
  353. $slave_status_rows_gotten++;
  354. # Must lowercase keys because different MySQL versions have different
  355. # lettercase.
  356. $row = array_change_key_case($row, CASE_LOWER);
  357. $status['relay_log_space'] = $row['relay_log_space'];
  358. $status['slave_lag'] = $row['seconds_behind_master'];
  359. # Check replication heartbeat, if present.
  360. if ($heartbeat ) {
  361. $result2 = run_query(
  362. "SELECT GREATEST(0, UNIX_TIMESTAMP() - UNIX_TIMESTAMP(ts) - 1)"
  363. . " AS delay FROM $heartbeat WHERE id = 1", $conn);
  364. $slave_delay_rows_gotten = 0;
  365. foreach ( $result2 as $row2 ) {
  366. $slave_delay_rows_gotten++;
  367. if ($row2 && is_array($row2)
  368. && array_key_exists('delay', $row2) )
  369. {
  370. $status['slave_lag'] = $row2['delay'];
  371. }
  372. else {
  373. debug("Couldn't get slave lag from $heartbeat");
  374. }
  375. }
  376. if ($slave_delay_rows_gotten == 0 ) {
  377. debug("Got nothing from heartbeat query");
  378. }
  379. }
  380. # Scale slave_running and slave_stopped relative to the slave lag.
  381. $status['slave_running'] = ($row['slave_sql_running'] == 'Yes')
  382. ? $status['slave_lag'] : 0;
  383. $status['slave_stopped'] = ($row['slave_sql_running'] == 'Yes')
  384. ? 0 : $status['slave_lag'];
  385. }
  386. if ($slave_status_rows_gotten == 0 ) {
  387. debug("Got nothing from SHOW SLAVE STATUS");
  388. }
  389. }
  390. # Get SHOW MASTER STATUS, and add it to the $status array.
  391. if ($chk_options['master']
  392. && array_key_exists('log_bin', $status)
  393. && $status['log_bin'] == 'ON'
  394. ) { # See issue #8
  395. $binlogs = array(0);
  396. $result = run_query("SHOW MASTER LOGS", $conn);
  397. foreach ( $result as $row ) {
  398. $row = array_change_key_case($row, CASE_LOWER);
  399. # Older versions of MySQL may not have the File_size column in the
  400. # results of the command. Zero-size files indicate the user is
  401. # deleting binlogs manually from disk (bad user! bad!).
  402. if (array_key_exists('file_size', $row) && $row['file_size'] > 0 ) {
  403. $binlogs[] = $row['file_size'];
  404. }
  405. }
  406. if (count($binlogs)) {
  407. $status['binary_log_space'] = to_int(array_sum($binlogs));
  408. }
  409. }
  410. # Get SHOW PROCESSLIST and aggregate it by state, then add it to the array
  411. # too.
  412. if ($chk_options['procs'] ) {
  413. $result = run_query('SHOW PROCESSLIST', $conn);
  414. foreach ( $result as $row ) {
  415. $state = $row['State'];
  416. if (is_null($state) ) {
  417. $state = 'NULL';
  418. }
  419. if ($state == '' ) {
  420. $state = 'none';
  421. }
  422. $state = str_replace(' ', '_', strtolower($state));
  423. if (array_key_exists("State_$state", $status) ) {
  424. increment($status, "State_$state", 1);
  425. }
  426. else {
  427. increment($status, "State_other", 1);
  428. }
  429. }
  430. }
  431. # Get SHOW INNODB STATUS and extract the desired metrics from it, then add
  432. # those to the array too.
  433. if ($chk_options['innodb']
  434. && array_key_exists('have_innodb', $status)
  435. && $status['have_innodb'] == 'YES'
  436. ) {
  437. $result = run_query("SHOW /*!50000 ENGINE*/ INNODB STATUS", $conn);
  438. $istatus_text = $result[0]['Status'];
  439. $istatus_vals = get_innodb_array($istatus_text);
  440. # Override values from InnoDB parsing with values from SHOW STATUS,
  441. # because InnoDB status might not have everything and the SHOW STATUS is
  442. # to be preferred where possible.
  443. $overrides = array(
  444. 'Innodb_buffer_pool_pages_data' => 'database_pages',
  445. 'Innodb_buffer_pool_pages_dirty' => 'modified_pages',
  446. 'Innodb_buffer_pool_pages_free' => 'free_pages',
  447. 'Innodb_buffer_pool_pages_total' => 'pool_size',
  448. 'Innodb_data_fsyncs' => 'file_fsyncs',
  449. 'Innodb_data_pending_reads' => 'pending_normal_aio_reads',
  450. 'Innodb_data_pending_writes' => 'pending_normal_aio_writes',
  451. 'Innodb_os_log_pending_fsyncs' => 'pending_log_flushes',
  452. 'Innodb_pages_created' => 'pages_created',
  453. 'Innodb_pages_read' => 'pages_read',
  454. 'Innodb_pages_written' => 'pages_written',
  455. 'Innodb_rows_deleted' => 'rows_deleted',
  456. 'Innodb_rows_inserted' => 'rows_inserted',
  457. 'Innodb_rows_read' => 'rows_read',
  458. 'Innodb_rows_updated' => 'rows_updated',
  459. );
  460. # If the SHOW STATUS value exists, override...
  461. foreach ( $overrides as $key => $val ) {
  462. if (array_key_exists($key, $status) ) {
  463. debug("Override $key");
  464. $istatus_vals[$val] = $status[$key];
  465. }
  466. }
  467. # Now copy the values into $status.
  468. foreach ( $istatus_vals as $key => $val ) {
  469. $status[$key] = $istatus_vals[$key];
  470. }
  471. }
  472. # Make table_open_cache backwards-compatible (issue 63).
  473. if (array_key_exists('table_open_cache', $status) ) {
  474. $status['table_cache'] = $status['table_open_cache'];
  475. }
  476. # Compute how much of the key buffer is used and unflushed (issue 127).
  477. $status['Key_buf_bytes_used']
  478. = big_sub($status['key_buffer_size'],
  479. big_multiply($status['Key_blocks_unused'],
  480. $status['key_cache_block_size']));
  481. $status['Key_buf_bytes_unflushed']
  482. = big_multiply($status['Key_blocks_not_flushed'],
  483. $status['key_cache_block_size']);
  484. if (array_key_exists('unflushed_log', $status)
  485. && $status['unflushed_log']
  486. ) {
  487. # TODO: I'm not sure what the deal is here; need to debug this. But the
  488. # unflushed log bytes spikes a lot sometimes and it's impossible for it to
  489. # be more than the log buffer.
  490. debug("Unflushed log: $status[unflushed_log]");
  491. $status['unflushed_log']
  492. = max($status['unflushed_log'], $status['innodb_log_buffer_size']);
  493. }
  494. # Define the variables to output. I use shortened variable names so maybe
  495. # it'll all fit in 1024 bytes for Cactid and Spine's benefit. This list must
  496. # come right after the word MAGIC_VARS_DEFINITIONS. The Perl script parses
  497. # it and uses it as a Perl variable.
  498. $keys = array(
  499. 'Key_read_requests' => 'a0',
  500. 'Key_reads' => 'a1',
  501. 'Key_write_requests' => 'a2',
  502. 'Key_writes' => 'a3',
  503. 'history_list' => 'a4',
  504. 'innodb_transactions' => 'a5',
  505. 'read_views' => 'a6',
  506. 'current_transactions' => 'a7',
  507. 'locked_transactions' => 'a8',
  508. 'active_transactions' => 'a9',
  509. 'pool_size' => 'aa',
  510. 'free_pages' => 'ab',
  511. 'database_pages' => 'ac',
  512. 'modified_pages' => 'ad',
  513. 'pages_read' => 'ae',
  514. 'pages_created' => 'af',
  515. 'pages_written' => 'ag',
  516. 'file_fsyncs' => 'ah',
  517. 'file_reads' => 'ai',
  518. 'file_writes' => 'aj',
  519. 'log_writes' => 'ak',
  520. 'pending_aio_log_ios' => 'al',
  521. 'pending_aio_sync_ios' => 'am',
  522. 'pending_buf_pool_flushes' => 'an',
  523. 'pending_chkp_writes' => 'ao',
  524. 'pending_ibuf_aio_reads' => 'ap',
  525. 'pending_log_flushes' => 'aq',
  526. 'pending_log_writes' => 'ar',
  527. 'pending_normal_aio_reads' => 'as',
  528. 'pending_normal_aio_writes' => 'at',
  529. 'ibuf_inserts' => 'au',
  530. 'ibuf_merged' => 'av',
  531. 'ibuf_merges' => 'aw',
  532. 'spin_waits' => 'ax',
  533. 'spin_rounds' => 'ay',
  534. 'os_waits' => 'az',
  535. 'rows_inserted' => 'b0',
  536. 'rows_updated' => 'b1',
  537. 'rows_deleted' => 'b2',
  538. 'rows_read' => 'b3',
  539. 'Table_locks_waited' => 'b4',
  540. 'Table_locks_immediate' => 'b5',
  541. 'Slow_queries' => 'b6',
  542. 'Open_files' => 'b7',
  543. 'Open_tables' => 'b8',
  544. 'Opened_tables' => 'b9',
  545. 'innodb_open_files' => 'ba',
  546. 'open_files_limit' => 'bb',
  547. 'table_cache' => 'bc',
  548. 'Aborted_clients' => 'bd',
  549. 'Aborted_connects' => 'be',
  550. 'Max_used_connections' => 'bf',
  551. 'Slow_launch_threads' => 'bg',
  552. 'Threads_cached' => 'bh',
  553. 'Threads_connected' => 'bi',
  554. 'Threads_created' => 'bj',
  555. 'Threads_running' => 'bk',
  556. 'max_connections' => 'bl',
  557. 'thread_cache_size' => 'bm',
  558. 'Connections' => 'bn',
  559. 'slave_running' => 'bo',
  560. 'slave_stopped' => 'bp',
  561. 'Slave_retried_transactions' => 'bq',
  562. 'slave_lag' => 'br',
  563. 'Slave_open_temp_tables' => 'bs',
  564. 'Qcache_free_blocks' => 'bt',
  565. 'Qcache_free_memory' => 'bu',
  566. 'Qcache_hits' => 'bv',
  567. 'Qcache_inserts' => 'bw',
  568. 'Qcache_lowmem_prunes' => 'bx',
  569. 'Qcache_not_cached' => 'by',
  570. 'Qcache_queries_in_cache' => 'bz',
  571. 'Qcache_total_blocks' => 'c0',
  572. 'query_cache_size' => 'c1',
  573. 'Questions' => 'c2',
  574. 'Com_update' => 'c3',
  575. 'Com_insert' => 'c4',
  576. 'Com_select' => 'c5',
  577. 'Com_delete' => 'c6',
  578. 'Com_replace' => 'c7',
  579. 'Com_load' => 'c8',
  580. 'Com_update_multi' => 'c9',
  581. 'Com_insert_select' => 'ca',
  582. 'Com_delete_multi' => 'cb',
  583. 'Com_replace_select' => 'cc',
  584. 'Select_full_join' => 'cd',
  585. 'Select_full_range_join' => 'ce',
  586. 'Select_range' => 'cf',
  587. 'Select_range_check' => 'cg',
  588. 'Select_scan' => 'ch',
  589. 'Sort_merge_passes' => 'ci',
  590. 'Sort_range' => 'cj',
  591. 'Sort_rows' => 'ck',
  592. 'Sort_scan' => 'cl',
  593. 'Created_tmp_tables' => 'cm',
  594. 'Created_tmp_disk_tables' => 'cn',
  595. 'Created_tmp_files' => 'co',
  596. 'Bytes_sent' => 'cp',
  597. 'Bytes_received' => 'cq',
  598. 'innodb_log_buffer_size' => 'cr',
  599. 'unflushed_log' => 'cs',
  600. 'log_bytes_flushed' => 'ct',
  601. 'log_bytes_written' => 'cu',
  602. 'relay_log_space' => 'cv',
  603. 'binlog_cache_size' => 'cw',
  604. 'Binlog_cache_disk_use' => 'cx',
  605. 'Binlog_cache_use' => 'cy',
  606. 'binary_log_space' => 'cz',
  607. 'innodb_locked_tables' => 'd0',
  608. 'innodb_lock_structs' => 'd1',
  609. 'State_closing_tables' => 'd2',
  610. 'State_copying_to_tmp_table' => 'd3',
  611. 'State_end' => 'd4',
  612. 'State_freeing_items' => 'd5',
  613. 'State_init' => 'd6',
  614. 'State_locked' => 'd7',
  615. 'State_login' => 'd8',
  616. 'State_preparing' => 'd9',
  617. 'State_reading_from_net' => 'da',
  618. 'State_sending_data' => 'db',
  619. 'State_sorting_result' => 'dc',
  620. 'State_statistics' => 'dd',
  621. 'State_updating' => 'de',
  622. 'State_writing_to_net' => 'df',
  623. 'State_none' => 'dg',
  624. 'State_other' => 'dh',
  625. 'Handler_commit' => 'di',
  626. 'Handler_delete' => 'dj',
  627. 'Handler_discover' => 'dk',
  628. 'Handler_prepare' => 'dl',
  629. 'Handler_read_first' => 'dm',
  630. 'Handler_read_key' => 'dn',
  631. 'Handler_read_next' => 'do',
  632. 'Handler_read_prev' => 'dp',
  633. 'Handler_read_rnd' => 'dq',
  634. 'Handler_read_rnd_next' => 'dr',
  635. 'Handler_rollback' => 'ds',
  636. 'Handler_savepoint' => 'dt',
  637. 'Handler_savepoint_rollback' => 'du',
  638. 'Handler_update' => 'dv',
  639. 'Handler_write' => 'dw',
  640. # Some InnoDB stats added later...
  641. 'innodb_tables_in_use' => 'dx',
  642. 'innodb_lock_wait_secs' => 'dy',
  643. 'hash_index_cells_total' => 'dz',
  644. 'hash_index_cells_used' => 'e0',
  645. 'total_mem_alloc' => 'e1',
  646. 'additional_pool_alloc' => 'e2',
  647. 'uncheckpointed_bytes' => 'e3',
  648. 'ibuf_used_cells' => 'e4',
  649. 'ibuf_free_cells' => 'e5',
  650. 'ibuf_cell_count' => 'e6',
  651. 'adaptive_hash_memory' => 'e7',
  652. 'page_hash_memory' => 'e8',
  653. 'dictionary_cache_memory' => 'e9',
  654. 'file_system_memory' => 'ea',
  655. 'lock_system_memory' => 'eb',
  656. 'recovery_system_memory' => 'ec',
  657. 'thread_hash_memory' => 'ed',
  658. 'innodb_sem_waits' => 'ee',
  659. 'innodb_sem_wait_time_ms' => 'ef',
  660. 'Key_buf_bytes_unflushed' => 'eg',
  661. 'Key_buf_bytes_used' => 'eh',
  662. 'key_buffer_size' => 'ei',
  663. 'Innodb_row_lock_time' => 'ej',
  664. 'Innodb_row_lock_waits' => 'ek',
  665. );
  666. # Return the output.
  667. $output = array();
  668. foreach ($keys as $key => $short ) {
  669. # If the value isn't defined, return -1 which is lower than (most graphs')
  670. # minimum value of 0, so it'll be regarded as a missing value.
  671. $val = isset($status[$key]) ? $status[$key] : -1;
  672. $output[] = "$short:$val";
  673. }
  674. $result = implode(' ', $output);
  675. if ($fp ) {
  676. if (fwrite($fp, $result) === FALSE ) {
  677. die("Can't write '$cache_file'");
  678. }
  679. fclose($fp);
  680. }
  681. return $result;
  682. }
  683. # ============================================================================
  684. # Given INNODB STATUS text, returns a key-value array of the parsed text. Each
  685. # line shows a sample of the input for both standard InnoDB as you would find in
  686. # MySQL 5.0, and XtraDB or enhanced InnoDB from Percona if applicable. Note
  687. # that extra leading spaces are ignored due to trim().
  688. # ============================================================================
  689. function get_innodb_array($text) {
  690. $results = array(
  691. 'spin_waits' => array(),
  692. 'spin_rounds' => array(),
  693. 'os_waits' => array(),
  694. 'pending_normal_aio_reads' => null,
  695. 'pending_normal_aio_writes' => null,
  696. 'pending_ibuf_aio_reads' => null,
  697. 'pending_aio_log_ios' => null,
  698. 'pending_aio_sync_ios' => null,
  699. 'pending_log_flushes' => null,
  700. 'pending_buf_pool_flushes' => null,
  701. 'file_reads' => null,
  702. 'file_writes' => null,
  703. 'file_fsyncs' => null,
  704. 'ibuf_inserts' => null,
  705. 'ibuf_merged' => null,
  706. 'ibuf_merges' => null,
  707. 'log_bytes_written' => null,
  708. 'unflushed_log' => null,
  709. 'log_bytes_flushed' => null,
  710. 'pending_log_writes' => null,
  711. 'pending_chkp_writes' => null,
  712. 'log_writes' => null,
  713. 'pool_size' => null,
  714. 'free_pages' => null,
  715. 'database_pages' => null,
  716. 'modified_pages' => null,
  717. 'pages_read' => null,
  718. 'pages_created' => null,
  719. 'pages_written' => null,
  720. 'queries_inside' => null,
  721. 'queries_queued' => null,
  722. 'read_views' => null,
  723. 'rows_inserted' => null,
  724. 'rows_updated' => null,
  725. 'rows_deleted' => null,
  726. 'rows_read' => null,
  727. 'innodb_transactions' => null,
  728. 'unpurged_txns' => null,
  729. 'history_list' => null,
  730. 'current_transactions' => null,
  731. 'hash_index_cells_total' => null,
  732. 'hash_index_cells_used' => null,
  733. 'total_mem_alloc' => null,
  734. 'additional_pool_alloc' => null,
  735. 'last_checkpoint' => null,
  736. 'uncheckpointed_bytes' => null,
  737. 'ibuf_used_cells' => null,
  738. 'ibuf_free_cells' => null,
  739. 'ibuf_cell_count' => null,
  740. 'adaptive_hash_memory' => null,
  741. 'page_hash_memory' => null,
  742. 'dictionary_cache_memory' => null,
  743. 'file_system_memory' => null,
  744. 'lock_system_memory' => null,
  745. 'recovery_system_memory' => null,
  746. 'thread_hash_memory' => null,
  747. 'innodb_sem_waits' => null,
  748. 'innodb_sem_wait_time_ms' => null,
  749. );
  750. $txn_seen = FALSE;
  751. foreach ( explode("\n", $text) as $line ) {
  752. $line = trim($line);
  753. $row = preg_split('/ +/', $line);
  754. # SEMAPHORES
  755. if (strpos($line, 'Mutex spin waits') === 0 ) {
  756. # Mutex spin waits 79626940, rounds 157459864, OS waits 698719
  757. # Mutex spin waits 0, rounds 247280272495, OS waits 316513438
  758. $results['spin_waits'][] = to_int($row[3]);
  759. $results['spin_rounds'][] = to_int($row[5]);
  760. $results['os_waits'][] = to_int($row[8]);
  761. }
  762. elseif (strpos($line, 'RW-shared spins') === 0 ) {
  763. # RW-shared spins 3859028, OS waits 2100750; RW-excl spins 4641946, OS waits 1530310
  764. $results['spin_waits'][] = to_int($row[2]);
  765. $results['spin_waits'][] = to_int($row[8]);
  766. $results['os_waits'][] = to_int($row[5]);
  767. $results['os_waits'][] = to_int($row[11]);
  768. }
  769. elseif (strpos($line, 'seconds the semaphore:') > 0) {
  770. # --Thread 907205 has waited at handler/ha_innodb.cc line 7156 for 1.00 seconds the semaphore:
  771. increment($results, 'innodb_sem_waits', 1);
  772. increment($results,
  773. 'innodb_sem_wait_time_ms', to_int($row[9]) * 1000);
  774. }
  775. # TRANSACTIONS
  776. elseif (strpos($line, 'Trx id counter') === 0 ) {
  777. # The beginning of the TRANSACTIONS section: start counting
  778. # transactions
  779. # Trx id counter 0 1170664159
  780. # Trx id counter 861B144C
  781. $results['innodb_transactions'] = make_bigint($row[3], $row[4]);
  782. $txn_seen = TRUE;
  783. }
  784. elseif (strpos($line, 'Purge done for trx') === 0 ) {
  785. # Purge done for trx's n:o < 0 1170663853 undo n:o < 0 0
  786. # Purge done for trx's n:o < 861B135D undo n:o < 0
  787. $purged_to = make_bigint($row[6], $row[7] == 'undo' ? null : $row[7]);
  788. $results['unpurged_txns']
  789. = big_sub($results['innodb_transactions'], $purged_to);
  790. }
  791. elseif (strpos($line, 'History list length') === 0 ) {
  792. # History list length 132
  793. $results['history_list'] = to_int($row[3]);
  794. }
  795. elseif ($txn_seen && strpos($line, '---TRANSACTION') === 0 ) {
  796. # ---TRANSACTION 0, not started, process no 13510, OS thread id 1170446656
  797. increment($results, 'current_transactions', 1);
  798. if (strpos($line, 'ACTIVE') > 0 ) {
  799. increment($results, 'active_transactions', 1);
  800. }
  801. }
  802. elseif ($txn_seen && strpos($line, '------- TRX HAS BEEN') === 0 ) {
  803. # ------- TRX HAS BEEN WAITING 32 SEC FOR THIS LOCK TO BE GRANTED:
  804. increment($results, 'innodb_lock_wait_secs', to_int($row[5]));
  805. }
  806. elseif (strpos($line, 'read views open inside InnoDB') > 0 ) {
  807. # 1 read views open inside InnoDB
  808. $results['read_views'] = to_int($row[0]);
  809. }
  810. elseif (strpos($line, 'mysql tables in use') === 0 ) {
  811. # mysql tables in use 2, locked 2
  812. increment($results, 'innodb_tables_in_use', to_int($row[4]));
  813. increment($results, 'innodb_locked_tables', to_int($row[6]));
  814. }
  815. elseif ($txn_seen && strpos($line, 'lock struct(s)') > 0 ) {
  816. # 23 lock struct(s), heap size 3024, undo log entries 27
  817. # LOCK WAIT 12 lock struct(s), heap size 3024, undo log entries 5
  818. # LOCK WAIT 2 lock struct(s), heap size 368
  819. if (strpos($line, 'LOCK WAIT') === 0 ) {
  820. increment($results, 'innodb_lock_structs', to_int($row[2]));
  821. increment($results, 'locked_transactions', 1);
  822. }
  823. else {
  824. increment($results, 'innodb_lock_structs', to_int($row[0]));
  825. }
  826. }
  827. # FILE I/O
  828. elseif (strpos($line, ' OS file reads, ') > 0 ) {
  829. # 8782182 OS file reads, 15635445 OS file writes, 947800 OS fsyncs
  830. $results['file_reads'] = to_int($row[0]);
  831. $results['file_writes'] = to_int($row[4]);
  832. $results['file_fsyncs'] = to_int($row[8]);
  833. }
  834. elseif (strpos($line, 'Pending normal aio reads:') === 0 ) {
  835. # Pending normal aio reads: 0, aio writes: 0,
  836. $results['pending_normal_aio_reads'] = to_int($row[4]);
  837. $results['pending_normal_aio_writes'] = to_int($row[7]);
  838. }
  839. elseif (strpos($line, 'ibuf aio reads') === 0 ) {
  840. # ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0
  841. $results['pending_ibuf_aio_reads'] = to_int($row[3]);
  842. $results['pending_aio_log_ios'] = to_int($row[6]);
  843. $results['pending_aio_sync_ios'] = to_int($row[9]);
  844. }
  845. elseif (strpos($line, 'Pending flushes (fsync)') === 0 ) {
  846. # Pending flushes (fsync) log: 0; buffer pool: 0
  847. $results['pending_log_flushes'] = to_int($row[4]);
  848. $results['pending_buf_pool_flushes'] = to_int($row[7]);
  849. }
  850. # INSERT BUFFER AND ADAPTIVE HASH INDEX
  851. elseif (strpos($line, 'Ibuf for space 0: size ') === 0 ) {
  852. # Older InnoDB code seemed to be ready for an ibuf per tablespace. It
  853. # had two lines in the output. Newer has just one line, see below.
  854. # Ibuf for space 0: size 1, free list len 887, seg size 889, is not empty
  855. # Ibuf for space 0: size 1, free list len 887, seg size 889,
  856. $results['ibuf_used_cells'] = to_int($row[5]);
  857. $results['ibuf_free_cells'] = to_int($row[9]);
  858. $results['ibuf_cell_count'] = to_int($row[12]);
  859. }
  860. elseif (strpos($line, 'Ibuf: size ') === 0 ) {
  861. # Ibuf: size 1, free list len 4634, seg size 4636,
  862. $results['ibuf_used_cells'] = to_int($row[2]);
  863. $results['ibuf_free_cells'] = to_int($row[6]);
  864. $results['ibuf_cell_count'] = to_int($row[9]);
  865. }
  866. elseif (strpos($line, ' merged recs, ') > 0 ) {
  867. # 19817685 inserts, 19817684 merged recs, 3552620 merges
  868. $results['ibuf_inserts'] = to_int($row[0]);
  869. $results['ibuf_merged'] = to_int($row[2]);
  870. $results['ibuf_merges'] = to_int($row[5]);
  871. }
  872. elseif (strpos($line, 'Hash table size ') === 0 ) {
  873. # In some versions of InnoDB, the used cells is omitted.
  874. # Hash table size 4425293, used cells 4229064, ....
  875. # Hash table size 57374437, node heap has 72964 buffer(s) <-- no used cells
  876. $results['hash_index_cells_total'] = to_int($row[3]);
  877. $results['hash_index_cells_used']
  878. = strpos($line, 'used cells') > 0 ? to_int($row[6]) : '0';
  879. }
  880. # LOG
  881. elseif (strpos($line, " log i/o's done, ") > 0 ) {
  882. # 3430041 log i/o's done, 17.44 log i/o's/second
  883. # 520835887 log i/o's done, 17.28 log i/o's/second, 518724686 syncs, 2980893 checkpoints
  884. # TODO: graph syncs and checkpoints
  885. $results['log_writes'] = to_int($row[0]);
  886. }
  887. elseif (strpos($line, " pending log writes, ") > 0 ) {
  888. # 0 pending log writes, 0 pending chkp writes
  889. $results['pending_log_writes'] = to_int($row[0]);
  890. $results['pending_chkp_writes'] = to_int($row[4]);
  891. }
  892. elseif (strpos($line, "Log sequence number") === 0 ) {
  893. # This number is NOT printed in hex in InnoDB plugin.
  894. # Log sequence number 13093949495856 //plugin
  895. # Log sequence number 125 3934414864 //normal
  896. $results['log_bytes_written']
  897. = isset($row[4])
  898. ? make_bigint($row[3], $row[4])
  899. : to_int($row[3]);
  900. }
  901. elseif (strpos($line, "Log flushed up to") === 0 ) {
  902. # This number is NOT printed in hex in InnoDB plugin.
  903. # Log flushed up to 13093948219327
  904. # Log flushed up to 125 3934414864
  905. $results['log_bytes_flushed']
  906. = isset($row[5])
  907. ? make_bigint($row[4], $row[5])
  908. : to_int($row[4]);
  909. }
  910. elseif (strpos($line, "Last checkpoint at") === 0 ) {
  911. # Last checkpoint at 125 3934293461
  912. $results['last_checkpoint']
  913. = isset($row[4])
  914. ? make_bigint($row[3], $row[4])
  915. : to_int($row[3]);
  916. }
  917. # BUFFER POOL AND MEMORY
  918. elseif (strpos($line, "Total memory allocated") === 0 ) {
  919. # Total memory allocated 29642194944; in additional pool allocated 0
  920. $results['total_mem_alloc'] = to_int($row[3]);
  921. $results['additional_pool_alloc'] = to_int($row[8]);
  922. }
  923. elseif (strpos($line, 'Adaptive hash index ') === 0 ) {
  924. # Adaptive hash index 1538240664 (186998824 + 1351241840)
  925. $results['adaptive_hash_memory'] = to_int($row[3]);
  926. }
  927. elseif (strpos($line, 'Page hash ') === 0 ) {
  928. # Page hash 11688584
  929. $results['page_hash_memory'] = to_int($row[2]);
  930. }
  931. elseif (strpos($line, 'Dictionary cache ') === 0 ) {
  932. # Dictionary cache 145525560 (140250984 + 5274576)
  933. $results['dictionary_cache_memory'] = to_int($row[2]);
  934. }
  935. elseif (strpos($line, 'File system ') === 0 ) {
  936. # File system 313848 (82672 + 231176)
  937. $results['file_system_memory'] = to_int($row[2]);
  938. }
  939. elseif (strpos($line, 'Lock system ') === 0 ) {
  940. # Lock system 29232616 (29219368 + 13248)
  941. $results['lock_system_memory'] = to_int($row[2]);
  942. }
  943. elseif (strpos($line, 'Recovery system ') === 0 ) {
  944. # Recovery system 0 (0 + 0)
  945. $results['recovery_system_memory'] = to_int($row[2]);
  946. }
  947. elseif (strpos($line, 'Threads ') === 0 ) {
  948. # Threads 409336 (406936 + 2400)
  949. $results['thread_hash_memory'] = to_int($row[1]);
  950. }
  951. elseif (strpos($line, 'innodb_io_pattern ') === 0 ) {
  952. # innodb_io_pattern 0 (0 + 0)
  953. $results['innodb_io_pattern_memory'] = to_int($row[1]);
  954. }
  955. elseif (strpos($line, "Buffer pool size ") === 0 ) {
  956. # The " " after size is necessary to avoid matching the wrong line:
  957. # Buffer pool size 1769471
  958. # Buffer pool size, bytes 28991012864
  959. $results['pool_size'] = to_int($row[3]);
  960. }
  961. elseif (strpos($line, "Free buffers") === 0 ) {
  962. # Free buffers 0
  963. $results['free_pages'] = to_int($row[2]);
  964. }
  965. elseif (strpos($line, "Database pages") === 0 ) {
  966. # Database pages 1696503
  967. $results['database_pages'] = to_int($row[2]);
  968. }
  969. elseif (strpos($line, "Modified db pages") === 0 ) {
  970. # Modified db pages 160602
  971. $results['modified_pages'] = to_int($row[3]);
  972. }
  973. elseif (strpos($line, "Pages read ahead") === 0 ) {
  974. # Must do this BEFORE the next test, otherwise it'll get fooled by this
  975. # line from the new plugin (see samples/innodb-015.txt):
  976. # Pages read ahead 0.00/s, evicted without access 0.06/s
  977. # TODO: No-op for now, see issue 134.
  978. }
  979. elseif (strpos($line, "Pages read") === 0 ) {
  980. # Pages read 15240822, created 1770238, written 21705836
  981. $results['pages_read'] = to_int($row[2]);
  982. $results['pages_created'] = to_int($row[4]);
  983. $results['pages_written'] = to_int($row[6]);
  984. }
  985. # ROW OPERATIONS
  986. elseif (strpos($line, 'Number of rows inserted') === 0 ) {
  987. # Number of rows inserted 50678311, updated 66425915, deleted 20605903, read 454561562
  988. $results['rows_inserted'] = to_int($row[4]);
  989. $results['rows_updated'] = to_int($row[6]);
  990. $results['rows_deleted'] = to_int($row[8]);
  991. $results['rows_read'] = to_int($row[10]);
  992. }
  993. elseif (strpos($line, " queries inside InnoDB, ") > 0 ) {
  994. # 0 queries inside InnoDB, 0 queries in queue
  995. $results['queries_inside'] = to_int($row[0]);
  996. $results['queries_queued'] = to_int($row[4]);
  997. }
  998. }
  999. foreach ( array('spin_waits', 'spin_rounds', 'os_waits') as $key ) {
  1000. $results[$key] = to_int(array_sum($results[$key]));
  1001. }
  1002. $results['unflushed_log']
  1003. = big_sub($results['log_bytes_written'], $results['log_bytes_flushed']);
  1004. $results['uncheckpointed_bytes']
  1005. = big_sub($results['log_bytes_written'], $results['last_checkpoint']);
  1006. # foreach ($results as $key => $value) {
  1007. # echo(strtolower($key).":".strtolower($value)."\n");
  1008. # }
  1009. return $results;
  1010. }
  1011. # ============================================================================
  1012. # Returns a bigint from two ulint or a single hex number. This is tested in
  1013. # t/mysql_stats.php and copied, without tests, to ss_get_by_ssh.php.
  1014. # ============================================================================
  1015. function make_bigint ($hi, $lo = null) {
  1016. debug(array($hi, $lo));
  1017. if (is_null($lo) ) {
  1018. # Assume it is a hex string representation.
  1019. return base_convert($hi, 16, 10);
  1020. }
  1021. else {
  1022. $hi = $hi ? $hi : '0'; # Handle empty-string or whatnot
  1023. $lo = $lo ? $lo : '0';
  1024. return big_add(big_multiply($hi, 4294967296), $lo);
  1025. }
  1026. }
  1027. # ============================================================================
  1028. # Extracts the numbers from a string. You can't reliably do this by casting to
  1029. # an int, because numbers that are bigger than PHP's int (varies by platform)
  1030. # will be truncated. And you can't use sprintf(%u) either, because the maximum
  1031. # value that will return on some platforms is 4022289582. So this just handles
  1032. # them as a string instead. It extracts digits until it finds a non-digit and
  1033. # quits. This is tested in t/mysql_stats.php and copied, without tests, to
  1034. # ss_get_by_ssh.php.
  1035. # ============================================================================
  1036. function to_int ( $str ) {
  1037. debug($str);
  1038. global $debug;
  1039. preg_match('{(\d+)}', $str, $m);
  1040. if (isset($m[1]) ) {
  1041. return $m[1];
  1042. }
  1043. elseif ($debug ) {
  1044. print_r(debug_backtrace());
  1045. }
  1046. else {
  1047. return 0;
  1048. }
  1049. }
  1050. # ============================================================================
  1051. # Wrap mysql_query in error-handling, and instead of returning the result,
  1052. # return an array of arrays in the result.
  1053. # ============================================================================
  1054. function run_query($sql, $conn) {
  1055. global $debug;
  1056. debug($sql);
  1057. $result = @mysql_query($sql, $conn);
  1058. if ($debug ) {
  1059. $error = @mysql_error($conn);
  1060. if ($error ) {
  1061. debug(array($sql, $error));
  1062. die("SQLERR $error in $sql");
  1063. }
  1064. }
  1065. $array = array();
  1066. while ( $row = @mysql_fetch_array($result) ) {
  1067. $array[] = $row;
  1068. }
  1069. debug(array($sql, $array));
  1070. return $array;
  1071. }
  1072. # ============================================================================
  1073. # Safely increments a value that might be null.
  1074. # ============================================================================
  1075. function increment(&$arr, $key, $howmuch) {
  1076. debug(array($key, $howmuch));
  1077. if (array_key_exists($key, $arr) && isset($arr[$key]) ) {
  1078. $arr[$key] = big_add($arr[$key], $howmuch);
  1079. }
  1080. else {
  1081. $arr[$key] = $howmuch;
  1082. }
  1083. }
  1084. # ============================================================================
  1085. # Multiply two big integers together as accurately as possible with reasonable
  1086. # effort. This is tested in t/mysql_stats.php and copied, without tests, to
  1087. # ss_get_by_ssh.php. $force is for testability.
  1088. # ============================================================================
  1089. function big_multiply ($left, $right, $force = null) {
  1090. if (function_exists("gmp_mul") && (is_null($force) || $force == 'gmp') ) {
  1091. debug(array('gmp_mul', $left, $right));
  1092. return gmp_strval( gmp_mul( $left, $right ));
  1093. }
  1094. elseif (function_exists("bcmul") && (is_null($force) || $force == 'bc') ) {
  1095. debug(array('bcmul', $left, $right));
  1096. return bcmul( $left, $right );
  1097. }
  1098. else { # Or $force == 'something else'
  1099. debug(array('sprintf', $left, $right));
  1100. return sprintf("%.0f", $left * $right);
  1101. }
  1102. }
  1103. # ============================================================================
  1104. # Subtract two big integers as accurately as possible with reasonable effort.
  1105. # This is tested in t/mysql_stats.php and copied, without tests, to
  1106. # ss_get_by_ssh.php. $force is for testability.
  1107. # ============================================================================
  1108. function big_sub ($left, $right, $force = null) {
  1109. debug(array($left, $right));
  1110. if (is_null($left) ) { $left = 0; }
  1111. if (is_null($right) ) { $right = 0; }
  1112. if (function_exists("gmp_sub") && (is_null($force) || $force == 'gmp')) {
  1113. debug(array('gmp_sub', $left, $right));
  1114. return gmp_strval( gmp_sub( $left, $right ));
  1115. }
  1116. elseif (function_exists("bcsub") && (is_null($force) || $force == 'bc')) {
  1117. debug(array('bcsub', $left, $right));
  1118. return bcsub( $left, $right );
  1119. }
  1120. else { # Or $force == 'something else'
  1121. debug(array('to_int', $left, $right));
  1122. return to_int($left - $right);
  1123. }
  1124. }
  1125. # ============================================================================
  1126. # Add two big integers together as accurately as possible with reasonable
  1127. # effort. This is tested in t/mysql_stats.php and copied, without tests, to
  1128. # ss_get_by_ssh.php. $force is for testa

Large files files are truncated, but you can click here to view the full file