PageRenderTime 364ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/scripts/agent-local/mysql

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

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