High Performance MySQL Tuning Script v1.3.0

Skapad 3 år sedan, skriven i Perl, med 252 visningar.
URL http://kod.perl.se/view/9069b8e8 Bädda in
Ladda hem koden eller visa koden i råformatVisa bredare version
  1. #!/usr/bin/perl -w
  2. # mysqltuner.pl - Version 1.3.0
  3. # High Performance MySQL Tuning Script
  4. # Copyright (C) 2006-2014 Major Hayden - major@mhtx.net
  5. #
  6. # For the latest updates, please visit http://mysqltuner.com/
  7. # Git repository available at http://github.com/major/MySQLTuner-perl
  8. #
  9. # This program is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program.  If not, see <http://www.gnu.org/licenses/>.
  21. #
  22. # This project would not be possible without help from:
  23. #   Matthew Montgomery     Paul Kehrer          Dave Burgess
  24. #   Jonathan Hinds         Mike Jackson         Nils Breunese
  25. #   Shawn Ashlee           Luuk Vosslamber      Ville Skytta
  26. #   Trent Hornibrook       Jason Gill           Mark Imbriaco
  27. #   Greg Eden              Aubin Galinotti      Giovanni Bechis
  28. #   Bill Bradford          Ryan Novosielski     Michael Scheidell
  29. #   Blair Christensen      Hans du Plooy        Victor Trac
  30. #   Everett Barnes         Tom Krouper          Gary Barrueto
  31. #   Simon Greenaway        Adam Stein           Isart Montane
  32. #   Baptiste M.            Cole Turner
  33. #
  34. # Inspired by Matthew Montgomery's tuning-primer.sh script:
  35. # http://forge.mysql.com/projects/view.php?id=44
  36. #
  37. use strict;
  38. use warnings;
  39. use diagnostics;
  40. use File::Spec;
  41. use Getopt::Long;
  42.  
  43. # Set up a few variables for use in the script
  44. my $tunerversion = "1.4.0";
  45. my (@adjvars, @generalrec);
  46.  
  47. # Set defaults
  48. my %opt = (
  49.                 "nobad"                 => 0,
  50.                 "nogood"                => 0,
  51.                 "noinfo"                => 0,
  52.                 "nocolor"               => 0,
  53.                 "forcemem"              => 0,
  54.                 "forceswap"     => 0,
  55.                 "host"                  => 0,
  56.                 "socket"                => 0,
  57.                 "port"                  => 0,
  58.                 "user"                  => 0,
  59.                 "pass"                  => 0,
  60.                 "skipsize"              => 0,
  61.                 "checkversion"  => 0,
  62.                 "buffers"               => 0,
  63.         );
  64.  
  65. # Gather the options from the command line
  66. GetOptions(\%opt,
  67.                 'nobad',
  68.                 'nogood',
  69.                 'noinfo',
  70.                 'nocolor',
  71.                 'forcemem=i',
  72.                 'forceswap=i',
  73.                 'host=s',
  74.                 'socket=s',
  75.                 'port=i',
  76.                 'user=s',
  77.                 'pass=s',
  78.                 'skipsize',
  79.                 'checkversion',
  80.                 'mysqladmin=s',
  81.                 'help',
  82.                 'buffers',
  83.         );
  84.  
  85. if (defined $opt{'help'} && $opt{'help'} == 1) { usage(); }
  86.  
  87. sub usage {
  88.         # Shown with --help option passed
  89.         print "\n".
  90.                 "   MySQLTuner $tunerversion - MySQL High Performance Tuning Script\n".
  91.                 "   Bug reports, feature requests, and downloads at http://mysqltuner.com/\n".
  92.                 "   Maintained by Major Hayden (major\@mhtx.net) - Licensed under GPL\n".
  93.                 "\n".
  94.                 "   Important Usage Guidelines:\n".
  95.                 "      To run the script with the default options, run the script without arguments\n".
  96.                 "      Allow MySQL server to run for at least 24-48 hours before trusting suggestions\n".
  97.                 "      Some routines may require root level privileges (script will provide warnings)\n".
  98.                 "      You must provide the remote server's total memory when connecting to other servers\n".
  99.                 "\n".
  100.                 "   Connection and Authentication\n".
  101.                 "      --host <hostname>    Connect to a remote host to perform tests (default: localhost)\n".
  102.                 "      --socket <socket>    Use a different socket for a local connection\n".
  103.                 "      --port <port>        Port to use for connection (default: 3306)\n".
  104.                 "      --user <username>    Username to use for authentication\n".
  105.                 "      --pass <password>    Password to use for authentication\n".
  106.                 "      --mysqladmin <path>  Path to a custom mysqladmin executable\n".
  107.                 "\n".
  108.                 "   Performance and Reporting Options\n".
  109.                 "      --skipsize           Don't enumerate tables and their types/sizes (default: on)\n".
  110.                 "                             (Recommended for servers with many tables)\n".
  111.                 "      --checkversion       Check for updates to MySQLTuner (default: don't check)\n".
  112.                 "      --forcemem <size>    Amount of RAM installed in megabytes\n".
  113.                 "      --forceswap <size>   Amount of swap memory configured in megabytes\n".
  114.                 "\n".
  115.                 "   Output Options:\n".
  116.                 "      --nogood             Remove OK responses\n".
  117.                 "      --nobad              Remove negative/suggestion responses\n".
  118.                 "      --noinfo             Remove informational responses\n".
  119.                 "      --nocolor            Don't print output in color\n".
  120.                 "      --buffers            Print global and per-thread buffer values\n".
  121.                 "\n";
  122.         exit;
  123. }
  124.  
  125. my $devnull = File::Spec->devnull();
  126.  
  127. # Setting up the colors for the print styles
  128. my $good = ($opt{nocolor} == 0)? "[\e[0;32mOK\e[0m]" : "[OK]" ;
  129. my $bad = ($opt{nocolor} == 0)? "[\e[0;31m!!\e[0m]" : "[!!]" ;
  130. my $info = ($opt{nocolor} == 0)? "[\e[0;34m--\e[0m]" : "[--]" ;
  131.  
  132. # Functions that handle the print styles
  133. sub goodprint { print $good." ".$_[0] unless ($opt{nogood} == 1); }
  134. sub infoprint { print $info." ".$_[0] unless ($opt{noinfo} == 1); }
  135. sub badprint { print $bad." ".$_[0] unless ($opt{nobad} == 1); }
  136. sub redwrap { return ($opt{nocolor} == 0)? "\e[0;31m".$_[0]."\e[0m" : $_[0] ; }
  137. sub greenwrap { return ($opt{nocolor} == 0)? "\e[0;32m".$_[0]."\e[0m" : $_[0] ; }
  138.  
  139. # Calculates the parameter passed in bytes, and then rounds it to one decimal place
  140. sub hr_bytes {
  141.         my $num = shift;
  142.         if ($num >= (1024**3)) { #GB
  143.                 return sprintf("%.1f",($num/(1024**3)))."G";
  144.         } elsif ($num >= (1024**2)) { #MB
  145.                 return sprintf("%.1f",($num/(1024**2)))."M";
  146.         } elsif ($num >= 1024) { #KB
  147.                 return sprintf("%.1f",($num/1024))."K";
  148.         } else {
  149.                 return $num."B";
  150.         }
  151. }
  152.  
  153. # Calculates the parameter passed in bytes, and then rounds it to the nearest integer
  154. sub hr_bytes_rnd {
  155.         my $num = shift;
  156.         if ($num >= (1024**3)) { #GB
  157.                 return int(($num/(1024**3)))."G";
  158.         } elsif ($num >= (1024**2)) { #MB
  159.                 return int(($num/(1024**2)))."M";
  160.         } elsif ($num >= 1024) { #KB
  161.                 return int(($num/1024))."K";
  162.         } else {
  163.                 return $num."B";
  164.         }
  165. }
  166.  
  167. # Calculates the parameter passed to the nearest power of 1000, then rounds it to the nearest integer
  168. sub hr_num {
  169.         my $num = shift;
  170.         if ($num >= (1000**3)) { # Billions
  171.                 return int(($num/(1000**3)))."B";
  172.         } elsif ($num >= (1000**2)) { # Millions
  173.                 return int(($num/(1000**2)))."M";
  174.         } elsif ($num >= 1000) { # Thousands
  175.                 return int(($num/1000))."K";
  176.         } else {
  177.                 return $num;
  178.         }
  179. }
  180.  
  181. # Calculates uptime to display in a more attractive form
  182. sub pretty_uptime {
  183.         my $uptime = shift;
  184.         my $seconds = $uptime % 60;
  185.         my $minutes = int(($uptime % 3600) / 60);
  186.         my $hours = int(($uptime % 86400) / (3600));
  187.         my $days = int($uptime / (86400));
  188.         my $uptimestring;
  189.         if ($days > 0) {
  190.                 $uptimestring = "${days}d ${hours}h ${minutes}m ${seconds}s";
  191.         } elsif ($hours > 0) {
  192.                 $uptimestring = "${hours}h ${minutes}m ${seconds}s";
  193.         } elsif ($minutes > 0) {
  194.                 $uptimestring = "${minutes}m ${seconds}s";
  195.         } else {
  196.                 $uptimestring = "${seconds}s";
  197.         }
  198.         return $uptimestring;
  199. }
  200.  
  201. # Retrieves the memory installed on this machine
  202. my ($physical_memory,$swap_memory,$duflags);
  203. sub os_setup {
  204.         sub memerror {
  205.                 badprint "Unable to determine total memory/swap; use '--forcemem' and '--forceswap'\n";
  206.                 exit;
  207.         }
  208.         my $os = `uname`;
  209.         $duflags = ($os =~ /Linux/) ? '-b' : '';
  210.         if ($opt{'forcemem'} > 0) {
  211.                 $physical_memory = $opt{'forcemem'} * 1048576;
  212.                 infoprint "Assuming $opt{'forcemem'} MB of physical memory\n";
  213.                 if ($opt{'forceswap'} > 0) {
  214.                         $swap_memory = $opt{'forceswap'} * 1048576;
  215.                         infoprint "Assuming $opt{'forceswap'} MB of swap space\n";
  216.                 } else {
  217.                         $swap_memory = 0;
  218.                         badprint "Assuming 0 MB of swap space (use --forceswap to specify)\n";
  219.                 }
  220.         } else {
  221.                 if ($os =~ /Linux/) {
  222.                         $physical_memory = `free -b | grep Mem | awk '{print \$2}'` or memerror;
  223.                         $swap_memory = `free -b | grep Swap | awk '{print \$2}'` or memerror;
  224.                 } elsif ($os =~ /Darwin/) {
  225.                         $physical_memory = `sysctl -n hw.memsize` or memerror;
  226.                         $swap_memory = `sysctl -n vm.swapusage | awk '{print \$3}' | sed 's/\..*\$//'` or memerror;
  227.                 } elsif ($os =~ /NetBSD|OpenBSD|FreeBSD/) {
  228.                         $physical_memory = `sysctl -n hw.physmem` or memerror;
  229.                         if ($physical_memory < 0) {
  230.                                 $physical_memory = `sysctl -n hw.physmem64` or memerror;
  231.                         }
  232.                         $swap_memory = `swapctl -l | grep '^/' | awk '{ s+= \$2 } END { print s }'` or memerror;
  233.                 } elsif ($os =~ /BSD/) {
  234.                         $physical_memory = `sysctl -n hw.realmem` or memerror;
  235.                         $swap_memory = `swapinfo | grep '^/' | awk '{ s+= \$2 } END { print s }'`;
  236.                 } elsif ($os =~ /SunOS/) {
  237.                         $physical_memory = `/usr/sbin/prtconf | grep Memory | cut -f 3 -d ' '` or memerror;
  238.                         chomp($physical_memory);
  239.                         $physical_memory = $physical_memory*1024*1024;
  240.                 } elsif ($os =~ /AIX/) {
  241.                         $physical_memory = `lsattr -El sys0 | grep realmem | awk '{print \$2}'` or memerror;
  242.                         chomp($physical_memory);
  243.                         $physical_memory = $physical_memory*1024;
  244.                         $swap_memory = `lsps -as | awk -F"(MB| +)" '/MB /{print \$2}'` or memerror;
  245.                         chomp($swap_memory);
  246.                         $swap_memory = $swap_memory*1024*1024;
  247.                 }
  248.         }
  249.         chomp($physical_memory);
  250. }
  251.  
  252. # Checks to see if a MySQL login is possible
  253. my ($mysqllogin,$doremote,$remotestring);
  254. sub mysql_setup {
  255.         $doremote = 0;
  256.         $remotestring = '';
  257.         my $mysqladmincmd;
  258.     if ($opt{mysqladmin}) {
  259.             $mysqladmincmd = $opt{mysqladmin};
  260.     } else {
  261.                 $mysqladmincmd = `which mysqladmin`;
  262.     }
  263.     chomp($mysqladmincmd);
  264.     if (! -e $mysqladmincmd && $opt{mysqladmin}) {
  265.                 badprint "Unable to find the mysqladmin command you specified: ".$mysqladmincmd."\n";
  266.                 exit;
  267.         } elsif (! -e $mysqladmincmd) {
  268.         badprint "Couldn't find mysqladmin in your \$PATH. Is MySQL installed?\n";
  269.                 exit;
  270.         }
  271.  
  272.  
  273.         # Are we being asked to connect via a socket?
  274.         if ($opt{socket} ne 0) {
  275.                 $remotestring = " -S $opt{socket}";
  276.         }
  277.         # Are we being asked to connect to a remote server?
  278.         if ($opt{host} ne 0) {
  279.                 chomp($opt{host});
  280.                 $opt{port} = ($opt{port} eq 0)? 3306 : $opt{port} ;
  281.                 # If we're doing a remote connection, but forcemem wasn't specified, we need to exit
  282.                 if ($opt{'forcemem'} eq 0) {
  283.                         badprint "The --forcemem option is required for remote connections\n";
  284.                         exit;
  285.                 }
  286.                 infoprint "Performing tests on $opt{host}:$opt{port}\n";
  287.                 $remotestring = " -h $opt{host} -P $opt{port}";
  288.                 $doremote = 1;
  289.         }
  290.         # Did we already get a username and password passed on the command line?
  291.         if ($opt{user} ne 0 and $opt{pass} ne 0) {
  292.                 $mysqllogin = "-u $opt{user} -p'$opt{pass}'".$remotestring;
  293.                 my $loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
  294.                 if ($loginstatus =~ /mysqld is alive/) {
  295.                         goodprint "Logged in using credentials passed on the command line\n";
  296.                         return 1;
  297.                 } else {
  298.                         badprint "Attempted to use login credentials, but they were invalid\n";
  299.                         exit 0;
  300.                 }
  301.         }
  302.         my $svcprop = `which svcprop 2>/dev/null`;
  303.         if (substr($svcprop, 0, 1) =~ "/") {
  304.                 # We are on solaris
  305.                 (my $mysql_login = `svcprop -p quickbackup/username svc:/network/mysql-quickbackup:default`) =~ s/\s+$//;
  306.                 (my $mysql_pass = `svcprop -p quickbackup/password svc:/network/mysql-quickbackup:default`) =~ s/\s+$//;
  307.                 if ( substr($mysql_login, 0, 7) ne "svcprop" ) {
  308.                         # mysql-quickbackup is installed
  309.                         $mysqllogin = "-u $mysql_login -p$mysql_pass";
  310.                         my $loginstatus = `mysqladmin $mysqllogin ping 2>&1`;
  311.                         if ($loginstatus =~ /mysqld is alive/) {
  312.                                 goodprint "Logged in using credentials from mysql-quickbackup.\n";
  313.                                 return 1;
  314.                         } else {
  315.                                 badprint "Attempted to use login credentials from mysql-quickbackup, but they failed.\n";
  316.                                 exit 0;
  317.                         }
  318.                 }
  319.         } elsif ( -r "/etc/psa/.psa.shadow" and $doremote == 0 ) {
  320.                 # It's a Plesk box, use the available credentials
  321.                 $mysqllogin = "-u admin -p`cat /etc/psa/.psa.shadow`";
  322.                 my $loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
  323.                 unless ($loginstatus =~ /mysqld is alive/) {
  324.                         badprint "Attempted to use login credentials from Plesk, but they failed.\n";
  325.                         exit 0;
  326.                 }
  327.         } elsif ( -r "/usr/local/directadmin/conf/mysql.conf" and $doremote == 0 ){
  328.                 # It's a DirectAdmin box, use the available credentials
  329.                 my $mysqluser=`cat /usr/local/directadmin/conf/mysql.conf | egrep '^user=.*'`;
  330.                 my $mysqlpass=`cat /usr/local/directadmin/conf/mysql.conf | egrep '^passwd=.*'`;
  331.  
  332.                 $mysqluser =~ s/user=//;
  333.                 $mysqluser =~ s/[\r\n]//;
  334.                 $mysqlpass =~ s/passwd=//;
  335.                 $mysqlpass =~ s/[\r\n]//;
  336.                
  337.                 $mysqllogin = "-u $mysqluser -p$mysqlpass";
  338.                
  339.                 my $loginstatus = `mysqladmin ping $mysqllogin 2>&1`;
  340.                 unless ($loginstatus =~ /mysqld is alive/) {
  341.                         badprint "Attempted to use login credentials from DirectAdmin, but they failed.\n";
  342.                         exit 0;
  343.                 }
  344.         } elsif ( -r "/etc/mysql/debian.cnf" and $doremote == 0 ){
  345.                 # We have a debian maintenance account, use it
  346.                 $mysqllogin = "--defaults-file=/etc/mysql/debian.cnf";
  347.                 my $loginstatus = `$mysqladmincmd $mysqllogin ping 2>&1`;
  348.                 if ($loginstatus =~ /mysqld is alive/) {
  349.                         goodprint "Logged in using credentials from debian maintenance account.\n";
  350.                         return 1;
  351.                 } else {
  352.                         badprint "Attempted to use login credentials from debian maintenance account, but they failed.\n";
  353.                         exit 0;
  354.                 }
  355.         } else {
  356.                 # It's not Plesk or debian, we should try a login
  357.                 my $loginstatus = `$mysqladmincmd $remotestring ping 2>&1`;
  358.                 if ($loginstatus =~ /mysqld is alive/) {
  359.                         # Login went just fine
  360.                         $mysqllogin = " $remotestring ";
  361.                         # Did this go well because of a .my.cnf file or is there no password set?
  362.                         my $userpath = `printenv HOME`;
  363.                         if (length($userpath) > 0) {
  364.                                 chomp($userpath);
  365.                         }
  366.                         unless ( -e "${userpath}/.my.cnf" ) {
  367.                                 badprint "Successfully authenticated with no password - SECURITY RISK!\n";
  368.                         }
  369.                         return 1;
  370.                 } else {
  371.                         print STDERR "Please enter your MySQL administrative login: ";
  372.                         my $name = <>;
  373.                         print STDERR "Please enter your MySQL administrative password: ";
  374.                         system("stty -echo >$devnull 2>&1");
  375.                         my $password = <>;
  376.                         system("stty echo >$devnull 2>&1");
  377.                         chomp($password);
  378.                         chomp($name);
  379.                         $mysqllogin = "-u $name";
  380.                         if (length($password) > 0) {
  381.                                 $mysqllogin .= " -p'$password'";
  382.                         }
  383.                         $mysqllogin .= $remotestring;
  384.                         my $loginstatus = `$mysqladmincmd ping $mysqllogin 2>&1`;
  385.                         if ($loginstatus =~ /mysqld is alive/) {
  386.                                 print STDERR "\n";
  387.                                 if (! length($password)) {
  388.                                         # Did this go well because of a .my.cnf file or is there no password set?
  389.                                         my $userpath = `ls -d ~`;
  390.                                         chomp($userpath);
  391.                                         unless ( -e "$userpath/.my.cnf" ) {
  392.                                                 badprint "Successfully authenticated with no password - SECURITY RISK!\n";
  393.                                         }
  394.                                 }
  395.                                 return 1;
  396.                         } else {
  397.                                 print "\n".$bad." Attempted to use login credentials, but they were invalid.\n";
  398.                                 exit 0;
  399.                         }
  400.                         exit 0;
  401.                 }
  402.         }
  403. }
  404.  
  405. # Populates all of the variable and status hashes
  406. my (%mystat,%myvar,$dummyselect);
  407. sub get_all_vars {
  408.         # We need to initiate at least one query so that our data is useable
  409.         $dummyselect = `mysql $mysqllogin -Bse "SELECT VERSION();"`;
  410.         my @mysqlvarlist = `mysql $mysqllogin -Bse "SHOW /*!50000 GLOBAL */ VARIABLES;"`;
  411.         foreach my $line (@mysqlvarlist) {
  412.                 $line =~ /([a-zA-Z_]*)\s*(.*)/;
  413.                 $myvar{$1} = $2;
  414.         }
  415.         my @mysqlstatlist = `mysql $mysqllogin -Bse "SHOW /*!50000 GLOBAL */ STATUS;"`;
  416.         foreach my $line (@mysqlstatlist) {
  417.                 $line =~ /([a-zA-Z_]*)\s*(.*)/;
  418.                 $mystat{$1} = $2;
  419.         }
  420.         # Workaround for MySQL bug #59393 wrt. ignore-builtin-innodb
  421.         if (($myvar{'ignore_builtin_innodb'} || "") eq "ON") {
  422.                 $myvar{'have_innodb'} = "NO";
  423.         }
  424.         # have_* for engines is deprecated and will be removed in MySQL 5.6;
  425.         # check SHOW ENGINES and set corresponding old style variables.
  426.         # Also works around MySQL bug #59393 wrt. skip-innodb
  427.         my @mysqlenginelist = `mysql $mysqllogin -Bse "SHOW ENGINES;" 2>$devnull`;
  428.         foreach my $line (@mysqlenginelist) {
  429.                 if ($line =~ /^([a-zA-Z_]+)\s+(\S+)/) {
  430.                         my $engine = lc($1);
  431.                         if ($engine eq "federated" || $engine eq "blackhole") {
  432.                                 $engine .= "_engine";
  433.                         } elsif ($engine eq "berkeleydb") {
  434.                                 $engine = "bdb";
  435.                         }
  436.                         my $val = ($2 eq "DEFAULT") ? "YES" : $2;
  437.                         $myvar{"have_$engine"} = $val;
  438.                 }
  439.         }
  440. }
  441.  
  442. sub security_recommendations {
  443.         print "\n-------- Security Recommendations  -------------------------------------------\n";
  444.         my @mysqlstatlist = `mysql $mysqllogin -Bse "SELECT CONCAT(user, '\@', host) FROM mysql.user WHERE password = '' OR password IS NULL;"`;
  445.         if (@mysqlstatlist) {
  446.                 foreach my $line (sort @mysqlstatlist) {
  447.                         chomp($line);
  448.                         badprint "User '".$line."' has no password set.\n";
  449.                 }
  450.         } else {
  451.                 goodprint "All database users have passwords assigned\n";
  452.         }
  453. }
  454.  
  455. sub get_replication_status {
  456.         my $slave_status = `mysql $mysqllogin -Bse "show slave status\\G"`;
  457.         my ($io_running) = ($slave_status =~ /slave_io_running\S*\s+(\S+)/i);
  458.         my ($sql_running) = ($slave_status =~ /slave_sql_running\S*\s+(\S+)/i);
  459.         if ($io_running eq 'Yes' && $sql_running eq 'Yes') {
  460.                 if ($myvar{'read_only'} eq 'OFF') {
  461.                         badprint "This replication slave is running with the read_only option disabled.";
  462.                 } else {
  463.                         goodprint "This replication slave is running with the read_only option enabled.";
  464.                 }
  465.         }
  466. }
  467.  
  468. # Checks for supported or EOL'ed MySQL versions
  469. my ($mysqlvermajor,$mysqlverminor);
  470. sub validate_mysql_version {
  471.         ($mysqlvermajor,$mysqlverminor) = $myvar{'version'} =~ /(\d+)\.(\d+)/;
  472.         if (!mysql_version_ge(5)) {
  473.                 badprint "Your MySQL version ".$myvar{'version'}." is EOL software!  Upgrade soon!\n";
  474.         } elsif (mysql_version_ge(6)) {
  475.                 badprint "Currently running unsupported MySQL version ".$myvar{'version'}."\n";
  476.         } else {
  477.                 goodprint "Currently running supported MySQL version ".$myvar{'version'}."\n";
  478.         }
  479. }
  480.  
  481. # Checks if MySQL version is greater than equal to (major, minor)
  482. sub mysql_version_ge {
  483.         my ($maj, $min) = @_;
  484.         return $mysqlvermajor > $maj || ($mysqlvermajor == $maj && $mysqlverminor >= ($min || 0));
  485. }
  486.  
  487. # Checks for 32-bit boxes with more than 2GB of RAM
  488. my ($arch);
  489. sub check_architecture {
  490.         if ($doremote eq 1) { return; }
  491.         if (`uname` =~ /SunOS/ && `isainfo -b` =~ /64/) {
  492.                 $arch = 64;
  493.                 goodprint "Operating on 64-bit architecture\n";
  494.         } elsif (`uname` !~ /SunOS/ && `uname -m` =~ /64/) {
  495.                 $arch = 64;
  496.                 goodprint "Operating on 64-bit architecture\n";
  497.         } elsif (`uname` =~ /AIX/ && `bootinfo -K` =~ /64/) {
  498.                 $arch = 64;
  499.                 goodprint "Operating on 64-bit architecture\n";
  500.         } elsif (`uname` =~ /NetBSD|OpenBSD/ && `sysctl -b hw.machine` =~ /64/) {
  501.                 $arch = 64;
  502.                 goodprint "Operating on 64-bit architecture\n";
  503.         } elsif (`uname` =~ /FreeBSD/ && `sysctl -b hw.machine_arch` =~ /64/) {
  504.                 $arch = 64;
  505.                 goodprint "Operating on 64-bit architecture\n";
  506.         } elsif (`uname` =~ /Darwin/ && `uname -m` =~ /Power Macintosh/) {
  507.                 # Darwin box.local 9.8.0 Darwin Kernel Version 9.8.0: Wed Jul 15 16:57:01 PDT 2009; root:xnu1228.15.4~1/RELEASE_PPC Power Macintosh
  508.                 $arch = 64;
  509.                 goodprint "Operating on 64-bit architecture\n";
  510.         } elsif (`uname` =~ /Darwin/ && `uname -m` =~ /x86_64/) {
  511.                 # Darwin gibas.local 12.3.0 Darwin Kernel Version 12.3.0: Sun Jan  6 22:37:10 PST 2013; root:xnu-2050.22.13~1/RELEASE_X86_64 x86_64
  512.                 $arch = 64;
  513.                 goodprint "Operating on 64-bit architecture\n";
  514.         } else {
  515.                 $arch = 32;
  516.                 if ($physical_memory > 2147483648) {
  517.                         badprint "Switch to 64-bit OS - MySQL cannot currently use all of your RAM\n";
  518.                 } else {
  519.                         goodprint "Operating on 32-bit architecture with less than 2GB RAM\n";
  520.                 }
  521.         }
  522. }
  523.  
  524. # Start up a ton of storage engine counts/statistics
  525. my (%enginestats,%enginecount,$fragtables);
  526. sub check_storage_engines {
  527.         if ($opt{skipsize} eq 1) {
  528.                 print "\n-------- Storage Engine Statistics -------------------------------------------\n";
  529.                 infoprint "Skipped due to --skipsize option\n";
  530.                 return;
  531.         }
  532.         print "\n-------- Storage Engine Statistics -------------------------------------------\n";
  533.         infoprint "Status: ";
  534.         my $engines;
  535.         if (mysql_version_ge(5, 1)) {
  536.                 my @engineresults = `mysql $mysqllogin -Bse "SELECT ENGINE,SUPPORT FROM information_schema.ENGINES WHERE ENGINE NOT IN ('performance_schema','MyISAM','MERGE','MEMORY') ORDER BY ENGINE ASC"`;
  537.                 foreach my $line (@engineresults) {
  538.                         my ($engine,$engineenabled);
  539.                         ($engine,$engineenabled) = $line =~ /([a-zA-Z_]*)\s+([a-zA-Z]+)/;
  540.                         $engines .= ($engineenabled eq "YES" || $engineenabled eq "DEFAULT") ? greenwrap "+".$engine." " : redwrap "-".$engine." ";
  541.                 }
  542.         } else {
  543.                 $engines .= (defined $myvar{'have_archive'} && $myvar{'have_archive'} eq "YES")? greenwrap "+Archive " : redwrap "-Archive " ;
  544.                 $engines .= (defined $myvar{'have_bdb'} && $myvar{'have_bdb'} eq "YES")? greenwrap "+BDB " : redwrap "-BDB " ;
  545.                 $engines .= (defined $myvar{'have_federated_engine'} && $myvar{'have_federated_engine'} eq "YES")? greenwrap "+Federated " : redwrap "-Federated " ;
  546.                 $engines .= (defined $myvar{'have_innodb'} && $myvar{'have_innodb'} eq "YES")? greenwrap "+InnoDB " : redwrap "-InnoDB " ;
  547.                 $engines .= (defined $myvar{'have_isam'} && $myvar{'have_isam'} eq "YES")? greenwrap "+ISAM " : redwrap "-ISAM " ;
  548.                 $engines .= (defined $myvar{'have_ndbcluster'} && $myvar{'have_ndbcluster'} eq "YES")? greenwrap "+NDBCluster " : redwrap "-NDBCluster " ;
  549.         }
  550.         print "$engines\n";
  551.         if (mysql_version_ge(5)) {
  552.                 # MySQL 5 servers can have table sizes calculated quickly from information schema
  553.                 my @templist = `mysql $mysqllogin -Bse "SELECT ENGINE,SUM(DATA_LENGTH),COUNT(ENGINE) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','mysql') AND ENGINE IS NOT NULL GROUP BY ENGINE ORDER BY ENGINE ASC;"`;
  554.                 foreach my $line (@templist) {
  555.                         my ($engine,$size,$count);
  556.                         ($engine,$size,$count) = $line =~ /([a-zA-Z_]*)\s+(\d+)\s+(\d+)/;
  557.                         if (!defined($size)) { next; }
  558.                         $enginestats{$engine} = $size;
  559.                         $enginecount{$engine} = $count;
  560.                 }
  561.                 $fragtables = `mysql $mysqllogin -Bse "SELECT COUNT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','mysql') AND Data_free > 0 AND NOT ENGINE='MEMORY';"`;
  562.                 chomp($fragtables);
  563.         } else {
  564.                 # MySQL < 5 servers take a lot of work to get table sizes
  565.                 my @tblist;
  566.                 # Now we build a database list, and loop through it to get storage engine stats for tables
  567.                 my @dblist = `mysql $mysqllogin -Bse "SHOW DATABASES"`;
  568.                 foreach my $db (@dblist) {
  569.                         chomp($db);
  570.                         if ($db eq "information_schema") { next; }
  571.                         my @ixs = (1, 6, 9);
  572.                         if (!mysql_version_ge(4, 1)) {
  573.                                 # MySQL 3.23/4.0 keeps Data_Length in the 5th (0-based) column
  574.                                 @ixs = (1, 5, 8);
  575.                         }
  576.                         push(@tblist, map { [ (split)[@ixs] ] } `mysql $mysqllogin -Bse "SHOW TABLE STATUS FROM \\\`$db\\\`"`);
  577.                 }
  578.                 # Parse through the table list to generate storage engine counts/statistics
  579.                 $fragtables = 0;
  580.                 foreach my $tbl (@tblist) {
  581.                         my ($engine, $size, $datafree) = @$tbl;
  582.                         if (defined $enginestats{$engine}) {
  583.                                 $enginestats{$engine} += $size;
  584.                                 $enginecount{$engine} += 1;
  585.                         } else {
  586.                                 $enginestats{$engine} = $size;
  587.                                 $enginecount{$engine} = 1;
  588.                         }
  589.                         if ($datafree > 0) {
  590.                                 $fragtables++;
  591.                         }
  592.                 }
  593.         }
  594.         while (my ($engine,$size) = each(%enginestats)) {
  595.                 infoprint "Data in $engine tables: ".hr_bytes_rnd($size)." (Tables: ".$enginecount{$engine}.")"."\n";
  596.         }
  597.         # If the storage engine isn't being used, recommend it to be disabled
  598.         if (!defined $enginestats{'InnoDB'} && defined $myvar{'have_innodb'} && $myvar{'have_innodb'} eq "YES") {
  599.                 badprint "InnoDB is enabled but isn't being used\n";
  600.                 push(@generalrec,"Add skip-innodb to MySQL configuration to disable InnoDB");
  601.         }
  602.         if (!defined $enginestats{'BerkeleyDB'} && defined $myvar{'have_bdb'} && $myvar{'have_bdb'} eq "YES") {
  603.                 badprint "BDB is enabled but isn't being used\n";
  604.                 push(@generalrec,"Add skip-bdb to MySQL configuration to disable BDB");
  605.         }
  606.         if (!defined $enginestats{'ISAM'} && defined $myvar{'have_isam'} && $myvar{'have_isam'} eq "YES") {
  607.                 badprint "ISAM is enabled but isn't being used\n";
  608.                 push(@generalrec,"Add skip-isam to MySQL configuration to disable ISAM (MySQL > 4.1.0)");
  609.         }
  610.         # Fragmented tables
  611.         if ($fragtables > 0) {
  612.                 badprint "Total fragmented tables: $fragtables\n";
  613.                 push(@generalrec,"Run OPTIMIZE TABLE to defragment tables for better performance");
  614.         } else {
  615.                 goodprint "Total fragmented tables: $fragtables\n";
  616.         }
  617.  
  618.        
  619.         # Auto increments
  620.         my %tblist;
  621.         # Find the maximum integer
  622.         my $maxint = `mysql $mysqllogin -Bse "SELECT ~0"`;
  623.        
  624.         # Now we build a database list, and loop through it to get storage engine stats for tables
  625.         my @dblist = `mysql $mysqllogin -Bse "SHOW DATABASES"`;
  626.         foreach my $db (@dblist) {
  627.                 chomp($db);
  628.                
  629.                 if(!$tblist{$db})
  630.                 {
  631.                         $tblist{$db} = ();
  632.                 }
  633.                
  634.                 if ($db eq "information_schema") { next; }
  635.                 my @ia = (0, 10);
  636.                 if (!mysql_version_ge(4, 1)) {
  637.                         # MySQL 3.23/4.0 keeps Data_Length in the 5th (0-based) column
  638.                         @ia = (0, 9);
  639.                 }
  640.                 push(@{$tblist{$db}}, map { [ (split)[@ia] ] } `mysql $mysqllogin -Bse "SHOW TABLE STATUS FROM \\\`$db\\\`"`);
  641.         }
  642.        
  643.         my @dbnames = keys %tblist;
  644.        
  645.         foreach my $db (@dbnames) {
  646.                 foreach my $tbl (@{$tblist{$db}}) {
  647.                         my ($name, $autoincrement) = @$tbl;
  648.                        
  649.                         if ($autoincrement =~ /^\d+?$/) {
  650.                                 my $percent = ($autoincrement / $maxint) * 100;
  651.                                 if($percent >= 75) {
  652.                                         badprint "Table '$db.$name' has an autoincrement value near max capacity ($percent%)\n";
  653.                                 }
  654.                         }
  655.                 }
  656.         }
  657.  
  658. }
  659.  
  660. my %mycalc;
  661. sub calculations {
  662.         if ($mystat{'Questions'} < 1) {
  663.                 badprint "Your server has not answered any queries - cannot continue...";
  664.                 exit 0;
  665.         }
  666.         # Per-thread memory
  667.         if (mysql_version_ge(4)) {
  668.                 $mycalc{'per_thread_buffers'} = $myvar{'read_buffer_size'} + $myvar{'read_rnd_buffer_size'} + $myvar{'sort_buffer_size'} + $myvar{'thread_stack'} + $myvar{'join_buffer_size'};
  669.         } else {
  670.                 $mycalc{'per_thread_buffers'} = $myvar{'record_buffer'} + $myvar{'record_rnd_buffer'} + $myvar{'sort_buffer'} + $myvar{'thread_stack'} + $myvar{'join_buffer_size'};
  671.         }
  672.         $mycalc{'total_per_thread_buffers'} = $mycalc{'per_thread_buffers'} * $myvar{'max_connections'};
  673.         $mycalc{'max_total_per_thread_buffers'} = $mycalc{'per_thread_buffers'} * $mystat{'Max_used_connections'};
  674.  
  675.         # Server-wide memory
  676.         $mycalc{'max_tmp_table_size'} = ($myvar{'tmp_table_size'} > $myvar{'max_heap_table_size'}) ? $myvar{'max_heap_table_size'} : $myvar{'tmp_table_size'} ;
  677.         $mycalc{'server_buffers'} = $myvar{'key_buffer_size'} + $mycalc{'max_tmp_table_size'};
  678.         $mycalc{'server_buffers'} += (defined $myvar{'innodb_buffer_pool_size'}) ? $myvar{'innodb_buffer_pool_size'} : 0 ;
  679.         $mycalc{'server_buffers'} += (defined $myvar{'innodb_additional_mem_pool_size'}) ? $myvar{'innodb_additional_mem_pool_size'} : 0 ;
  680.         $mycalc{'server_buffers'} += (defined $myvar{'innodb_log_buffer_size'}) ? $myvar{'innodb_log_buffer_size'} : 0 ;
  681.         $mycalc{'server_buffers'} += (defined $myvar{'query_cache_size'}) ? $myvar{'query_cache_size'} : 0 ;
  682.  
  683.         # Global memory
  684.         $mycalc{'max_used_memory'} = $mycalc{'server_buffers'} + $mycalc{"max_total_per_thread_buffers"};
  685.         $mycalc{'total_possible_used_memory'} = $mycalc{'server_buffers'} + $mycalc{'total_per_thread_buffers'};
  686.         $mycalc{'pct_physical_memory'} = int(($mycalc{'total_possible_used_memory'} * 100) / $physical_memory);
  687.  
  688.         # Slow queries
  689.         $mycalc{'pct_slow_queries'} = int(($mystat{'Slow_queries'}/$mystat{'Questions'}) * 100);
  690.  
  691.         # Connections
  692.         $mycalc{'pct_connections_used'} = int(($mystat{'Max_used_connections'}/$myvar{'max_connections'}) * 100);
  693.         $mycalc{'pct_connections_used'} = ($mycalc{'pct_connections_used'} > 100) ? 100 : $mycalc{'pct_connections_used'} ;
  694.  
  695.         # Key buffers
  696.         if (mysql_version_ge(4, 1) && $myvar{'key_buffer_size'} > 0) {
  697.                 $mycalc{'pct_key_buffer_used'} = sprintf("%.1f",(1 - (($mystat{'Key_blocks_unused'} * $myvar{'key_cache_block_size'}) / $myvar{'key_buffer_size'})) * 100);
  698.         } else {
  699.                 $mycalc{'pct_key_buffer_used'} = 0;
  700.         }
  701.         if ($mystat{'Key_read_requests'} > 0) {
  702.                 $mycalc{'pct_keys_from_mem'} = sprintf("%.1f",(100 - (($mystat{'Key_reads'} / $mystat{'Key_read_requests'}) * 100)));
  703.         } else {
  704.             $mycalc{'pct_keys_from_mem'} = 0;
  705.         }
  706.         if ($doremote eq 0 and !mysql_version_ge(5)) {
  707.                 my $size = 0;
  708.                 $size += (split)[0] for `find $myvar{'datadir'} -name "*.MYI" 2>&1 | xargs du -L $duflags 2>&1`;
  709.                 $mycalc{'total_myisam_indexes'} = $size;
  710.         } elsif (mysql_version_ge(5)) {
  711.                 $mycalc{'total_myisam_indexes'} = `mysql $mysqllogin -Bse "SELECT IFNULL(SUM(INDEX_LENGTH),0) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema') AND ENGINE = 'MyISAM';"`;
  712.         }
  713.         if (defined $mycalc{'total_myisam_indexes'} and $mycalc{'total_myisam_indexes'} == 0) {
  714.                 $mycalc{'total_myisam_indexes'} = "fail";
  715.         } elsif (defined $mycalc{'total_myisam_indexes'}) {
  716.                 chomp($mycalc{'total_myisam_indexes'});
  717.         }
  718.  
  719.         # Query cache
  720.         if (mysql_version_ge(4)) {
  721.                 $mycalc{'query_cache_efficiency'} = sprintf("%.1f",($mystat{'Qcache_hits'} / ($mystat{'Com_select'} + $mystat{'Qcache_hits'})) * 100);
  722.                 if ($myvar{'query_cache_size'}) {
  723.                         $mycalc{'pct_query_cache_used'} = sprintf("%.1f",100 - ($mystat{'Qcache_free_memory'} / $myvar{'query_cache_size'}) * 100);
  724.                 }
  725.         if ($mystat{'Qcache_lowmem_prunes'} == 0) {
  726.                         $mycalc{'query_cache_prunes_per_day'} = 0;
  727.                 } else {
  728.                         $mycalc{'query_cache_prunes_per_day'} = int($mystat{'Qcache_lowmem_prunes'} / ($mystat{'Uptime'}/86400));
  729.                 }
  730.         }
  731.  
  732.         # Sorting
  733.         $mycalc{'total_sorts'} = $mystat{'Sort_scan'} + $mystat{'Sort_range'};
  734.         if ($mycalc{'total_sorts'} > 0) {
  735.                 $mycalc{'pct_temp_sort_table'} = int(($mystat{'Sort_merge_passes'} / $mycalc{'total_sorts'}) * 100);
  736.         }
  737.  
  738.         # Joins
  739.         $mycalc{'joins_without_indexes'} = $mystat{'Select_range_check'} + $mystat{'Select_full_join'};
  740.         $mycalc{'joins_without_indexes_per_day'} = int($mycalc{'joins_without_indexes'} / ($mystat{'Uptime'}/86400));
  741.  
  742.         # Temporary tables
  743.         if ($mystat{'Created_tmp_tables'} > 0) {
  744.                 if ($mystat{'Created_tmp_disk_tables'} > 0) {
  745.                         $mycalc{'pct_temp_disk'} = int(($mystat{'Created_tmp_disk_tables'} / $mystat{'Created_tmp_tables'}) * 100);
  746.                 } else {
  747.                         $mycalc{'pct_temp_disk'} = 0;
  748.                 }
  749.         }
  750.  
  751.         # Table cache
  752.         if ($mystat{'Opened_tables'} > 0) {
  753.                 $mycalc{'table_cache_hit_rate'} = int($mystat{'Open_tables'}*100/$mystat{'Opened_tables'});
  754.         } else {
  755.                 $mycalc{'table_cache_hit_rate'} = 100;
  756.         }
  757.  
  758.         # Open files
  759.         if ($myvar{'open_files_limit'} > 0) {
  760.                 $mycalc{'pct_files_open'} = int($mystat{'Open_files'}*100/$myvar{'open_files_limit'});
  761.         }
  762.  
  763.         # Table locks
  764.         if ($mystat{'Table_locks_immediate'} > 0) {
  765.                 if ($mystat{'Table_locks_waited'} == 0) {
  766.                         $mycalc{'pct_table_locks_immediate'} = 100;
  767.                 } else {
  768.                         $mycalc{'pct_table_locks_immediate'} = int($mystat{'Table_locks_immediate'}*100/($mystat{'Table_locks_waited'} + $mystat{'Table_locks_immediate'}));
  769.                 }
  770.         }
  771.  
  772.         # Thread cache
  773.         $mycalc{'thread_cache_hit_rate'} = int(100 - (($mystat{'Threads_created'} / $mystat{'Connections'}) * 100));
  774.  
  775.         # Other
  776.         if ($mystat{'Connections'} > 0) {
  777.                 $mycalc{'pct_aborted_connections'} = int(($mystat{'Aborted_connects'}/$mystat{'Connections'}) * 100);
  778.         }
  779.         if ($mystat{'Questions'} > 0) {
  780.                 $mycalc{'total_reads'} = $mystat{'Com_select'};
  781.                 $mycalc{'total_writes'} = $mystat{'Com_delete'} + $mystat{'Com_insert'} + $mystat{'Com_update'} + $mystat{'Com_replace'};
  782.                 if ($mycalc{'total_reads'} == 0) {
  783.                         $mycalc{'pct_reads'} = 0;
  784.                         $mycalc{'pct_writes'} = 100;
  785.                 } else {
  786.                         $mycalc{'pct_reads'} = int(($mycalc{'total_reads'}/($mycalc{'total_reads'}+$mycalc{'total_writes'})) * 100);
  787.                         $mycalc{'pct_writes'} = 100-$mycalc{'pct_reads'};
  788.                 }
  789.         }
  790.  
  791.         # InnoDB
  792.         if ($myvar{'have_innodb'} eq "YES") {
  793.                 $mycalc{'innodb_log_size_pct'} = ($myvar{'innodb_log_file_size'} * 100 / $myvar{'innodb_buffer_pool_size'});
  794.         }
  795. }
  796.  
  797. sub mysql_stats {
  798.         print "\n-------- Performance Metrics -------------------------------------------------\n";
  799.         # Show uptime, queries per second, connections, traffic stats
  800.         my $qps;
  801.         if ($mystat{'Uptime'} > 0) { $qps = sprintf("%.3f",$mystat{'Questions'}/$mystat{'Uptime'}); }
  802.         if ($mystat{'Uptime'} < 86400) { push(@generalrec,"MySQL started within last 24 hours - recommendations may be inaccurate"); }
  803.         infoprint "Up for: ".pretty_uptime($mystat{'Uptime'})." (".hr_num($mystat{'Questions'}).
  804.                 " q [".hr_num($qps)." qps], ".hr_num($mystat{'Connections'})." conn,".
  805.                 " TX: ".hr_num($mystat{'Bytes_sent'}).", RX: ".hr_num($mystat{'Bytes_received'}).")\n";
  806.         infoprint "Reads / Writes: ".$mycalc{'pct_reads'}."% / ".$mycalc{'pct_writes'}."%\n";
  807.  
  808.         # Memory usage
  809.         infoprint "Total buffers: ".hr_bytes($mycalc{'server_buffers'})." global + ".hr_bytes($mycalc{'per_thread_buffers'})." per thread ($myvar{'max_connections'} max threads)\n";
  810.        
  811.         if ($opt{buffers} ne 0) {
  812.                 infoprint "Global Buffers\n";
  813.                 infoprint " +-- Key Buffer: " . hr_bytes($myvar{'key_buffer_size'}) . "\n";
  814.                 infoprint " +-- Max Tmp Table: ".hr_bytes($mycalc{'max_tmp_table_size'})."\n";
  815.                
  816.                 if (defined $myvar{'innodb_buffer_pool_size'}) {
  817.                         infoprint " +-- InnoDB Buffer Pool: " . hr_bytes($myvar{'innodb_buffer_pool_size'}) . "\n";
  818.                 }
  819.                 if (defined $myvar{'innodb_additional_mem_pool_size'}) {
  820.                         infoprint " +-- InnoDB Additional Mem Pool: " . hr_bytes($myvar{'innodb_additional_mem_pool_size'}) . "\n";
  821.                 }
  822.                 if (defined $myvar{'innodb_log_buffer_size'}) {
  823.                         infoprint " +-- InnoDB Log Buffer: " . hr_bytes($myvar{'innodb_log_buffer_size'}) . "\n";
  824.                 }
  825.                 if (defined $myvar{'query_cache_size'}) {
  826.                         infoprint " +-- Query Cache: " . hr_bytes($myvar{'query_cache_size'}) . "\n";
  827.                 }
  828.                
  829.                 infoprint "Per Thread Buffers\n";
  830.                 infoprint " +-- Read Buffer: " . hr_bytes($myvar{'read_buffer_size'}) . "\n";
  831.                 infoprint " +-- Read RND Buffer: " . hr_bytes($myvar{'read_rnd_buffer_size'}) . "\n";
  832.                 infoprint " +-- Sort Buffer: " . hr_bytes($myvar{'sort_buffer_size'}) . "\n";
  833.                 infoprint " +-- Thread stack: " . hr_bytes($myvar{'thread_stack'}) . "\n";
  834.                 infoprint " +-- Join Buffer: " . hr_bytes($myvar{'join_buffer_size'}) . "\n";
  835.         }      
  836.  
  837.         if ($arch && $arch == 32 && $mycalc{'total_possible_used_memory'} > 2*1024*1024*1024) {
  838.                 badprint "Allocating > 2GB RAM on 32-bit systems can cause system instability\n";
  839.                 badprint "Maximum possible memory usage: ".hr_bytes($mycalc{'total_possible_used_memory'})." ($mycalc{'pct_physical_memory'}% of installed RAM)\n";
  840.         } elsif ($mycalc{'pct_physical_memory'} > 85) {
  841.                 badprint "Maximum possible memory usage: ".hr_bytes($mycalc{'total_possible_used_memory'})." ($mycalc{'pct_physical_memory'}% of installed RAM)\n";
  842.                 push(@generalrec,"Reduce your overall MySQL memory footprint for system stability");
  843.         } else {
  844.                 goodprint "Maximum possible memory usage: ".hr_bytes($mycalc{'total_possible_used_memory'})." ($mycalc{'pct_physical_memory'}% of installed RAM)\n";
  845.         }
  846.  
  847.         # Slow queries
  848.         if ($mycalc{'pct_slow_queries'} > 5) {
  849.                 badprint "Slow queries: $mycalc{'pct_slow_queries'}% (".hr_num($mystat{'Slow_queries'})."/".hr_num($mystat{'Questions'}).")\n";
  850.         } else {
  851.                 goodprint "Slow queries: $mycalc{'pct_slow_queries'}% (".hr_num($mystat{'Slow_queries'})."/".hr_num($mystat{'Questions'}).")\n";
  852.         }
  853.         if ($myvar{'long_query_time'} > 10) { push(@adjvars,"long_query_time (<= 10)"); }
  854.         if (defined($myvar{'log_slow_queries'})) {
  855.                 if ($myvar{'log_slow_queries'} eq "OFF") { push(@generalrec,"Enable the slow query log to troubleshoot bad queries"); }
  856.         }
  857.  
  858.         # Connections
  859.         if ($mycalc{'pct_connections_used'} > 85) {
  860.                 badprint "Highest connection usage: $mycalc{'pct_connections_used'}%  ($mystat{'Max_used_connections'}/$myvar{'max_connections'})\n";
  861.                 push(@adjvars,"max_connections (> ".$myvar{'max_connections'}.")");
  862.                 push(@adjvars,"wait_timeout (< ".$myvar{'wait_timeout'}.")","interactive_timeout (< ".$myvar{'interactive_timeout'}.")");
  863.                 push(@generalrec,"Reduce or eliminate persistent connections to reduce connection usage")
  864.         } else {
  865.                 goodprint "Highest usage of available connections: $mycalc{'pct_connections_used'}% ($mystat{'Max_used_connections'}/$myvar{'max_connections'})\n";
  866.         }
  867.  
  868.         # Key buffer
  869.         if (!defined($mycalc{'total_myisam_indexes'}) and $doremote == 1) {
  870.                 push(@generalrec,"Unable to calculate MyISAM indexes on remote MySQL server < 5.0.0");
  871.         } elsif ($mycalc{'total_myisam_indexes'} =~ /^fail$/) {
  872.                 badprint "Cannot calculate MyISAM index size - re-run script as root user\n";
  873.         } elsif ($mycalc{'total_myisam_indexes'} == "0") {
  874.                 badprint "None of your MyISAM tables are indexed - add indexes immediately\n";
  875.         } else {
  876.                 if ($myvar{'key_buffer_size'} < $mycalc{'total_myisam_indexes'} && $mycalc{'pct_keys_from_mem'} < 95) {
  877.                         badprint "Key buffer size / total MyISAM indexes: ".hr_bytes($myvar{'key_buffer_size'})."/".hr_bytes($mycalc{'total_myisam_indexes'})."\n";
  878.                         push(@adjvars,"key_buffer_size (> ".hr_bytes($mycalc{'total_myisam_indexes'}).")");
  879.                 } else {
  880.                         goodprint "Key buffer size / total MyISAM indexes: ".hr_bytes($myvar{'key_buffer_size'})."/".hr_bytes($mycalc{'total_myisam_indexes'})."\n";
  881.                 }
  882.                 if ($mystat{'Key_read_requests'} > 0) {
  883.                         if ($mycalc{'pct_keys_from_mem'} < 95) {
  884.                                 badprint "Key buffer hit rate: $mycalc{'pct_keys_from_mem'}% (".hr_num($mystat{'Key_read_requests'})." cached / ".hr_num($mystat{'Key_reads'})." reads)\n";
  885.                         } else {
  886.                                 goodprint "Key buffer hit rate: $mycalc{'pct_keys_from_mem'}% (".hr_num($mystat{'Key_read_requests'})." cached / ".hr_num($mystat{'Key_reads'})." reads)\n";
  887.                         }
  888.                 } else {
  889.                         # No queries have run that would use keys
  890.                 }
  891.         }
  892.  
  893.         # Query cache
  894.         if (!mysql_version_ge(4)) {
  895.                 # MySQL versions < 4.01 don't support query caching
  896.                 push(@generalrec,"Upgrade MySQL to version 4+ to utilize query caching");
  897.         } elsif ($myvar{'query_cache_size'} < 1) {
  898.                 badprint "Query cache is disabled\n";
  899.                 push(@adjvars,"query_cache_size (>= 8M)");
  900.         } elsif ($myvar{'query_cache_type'} eq "OFF") {
  901.                 badprint "Query cache is disabled\n";
  902.                 push(@adjvars,"query_cache_type (=1)");
  903.         } elsif ($mystat{'Com_select'} == 0) {
  904.                 badprint "Query cache cannot be analyzed - no SELECT statements executed\n";
  905.         } else {
  906.                 if ($mycalc{'query_cache_efficiency'} < 20) {
  907.                         badprint "Query cache efficiency: $mycalc{'query_cache_efficiency'}% (".hr_num($mystat{'Qcache_hits'})." cached / ".hr_num($mystat{'Qcache_hits'}+$mystat{'Com_select'})." selects)\n";
  908.                         push(@adjvars,"query_cache_limit (> ".hr_bytes_rnd($myvar{'query_cache_limit'}).", or use smaller result sets)");
  909.                 } else {
  910.                         goodprint "Query cache efficiency: $mycalc{'query_cache_efficiency'}% (".hr_num($mystat{'Qcache_hits'})." cached / ".hr_num($mystat{'Qcache_hits'}+$mystat{'Com_select'})." selects)\n";
  911.                 }
  912.                 if ($mycalc{'query_cache_prunes_per_day'} > 98) {
  913.                         badprint "Query cache prunes per day: $mycalc{'query_cache_prunes_per_day'}\n";
  914.                         if ($myvar{'query_cache_size'} > 128*1024*1024) {
  915.                             push(@generalrec,"Increasing the query_cache size over 128M may reduce performance");
  916.                         push(@adjvars,"query_cache_size (> ".hr_bytes_rnd($myvar{'query_cache_size'}).") [see warning above]");
  917.                         } else {
  918.                         push(@adjvars,"query_cache_size (> ".hr_bytes_rnd($myvar{'query_cache_size'}).")");
  919.                         }
  920.                 } else {
  921.                         goodprint "Query cache prunes per day: $mycalc{'query_cache_prunes_per_day'}\n";
  922.                 }
  923.         }
  924.  
  925.         # Sorting
  926.         if ($mycalc{'total_sorts'} == 0) {
  927.                 # For the sake of space, we will be quiet here
  928.                 # No sorts have run yet
  929.         } elsif ($mycalc{'pct_temp_sort_table'} > 10) {
  930.                 badprint "Sorts requiring temporary tables: $mycalc{'pct_temp_sort_table'}% (".hr_num($mystat{'Sort_merge_passes'})." temp sorts / ".hr_num($mycalc{'total_sorts'})." sorts)\n";
  931.                 push(@adjvars,"sort_buffer_size (> ".hr_bytes_rnd($myvar{'sort_buffer_size'}).")");
  932.                 push(@adjvars,"read_rnd_buffer_size (> ".hr_bytes_rnd($myvar{'read_rnd_buffer_size'}).")");
  933.         } else {
  934.                 goodprint "Sorts requiring temporary tables: $mycalc{'pct_temp_sort_table'}% (".hr_num($mystat{'Sort_merge_passes'})." temp sorts / ".hr_num($mycalc{'total_sorts'})." sorts)\n";
  935.         }
  936.  
  937.         # Joins
  938.         if ($mycalc{'joins_without_indexes_per_day'} > 250) {
  939.                 badprint "Joins performed without indexes: $mycalc{'joins_without_indexes'}\n";
  940.                 push(@adjvars,"join_buffer_size (> ".hr_bytes($myvar{'join_buffer_size'}).", or always use indexes with joins)");
  941.                 push(@generalrec,"Adjust your join queries to always utilize indexes");
  942.         } else {
  943.                 # For the sake of space, we will be quiet here
  944.                 # No joins have run without indexes
  945.         }
  946.  
  947.         # Temporary tables
  948.         if ($mystat{'Created_tmp_tables'} > 0) {
  949.                 if ($mycalc{'pct_temp_disk'} > 25 && $mycalc{'max_tmp_table_size'} < 256*1024*1024) {
  950.                         badprint "Temporary tables created on disk: $mycalc{'pct_temp_disk'}% (".hr_num($mystat{'Created_tmp_disk_tables'})." on disk / ".hr_num($mystat{'Created_tmp_tables'})." total)\n";
  951.                         push(@adjvars,"tmp_table_size (> ".hr_bytes_rnd($myvar{'tmp_table_size'}).")");
  952.                         push(@adjvars,"max_heap_table_size (> ".hr_bytes_rnd($myvar{'max_heap_table_size'}).")");
  953.                         push(@generalrec,"When making adjustments, make tmp_table_size/max_heap_table_size equal");
  954.                         push(@generalrec,"Reduce your SELECT DISTINCT queries without LIMIT clauses");
  955.                 } elsif ($mycalc{'pct_temp_disk'} > 25 && $mycalc{'max_tmp_table_size'} >= 256) {
  956.                         badprint "Temporary tables created on disk: $mycalc{'pct_temp_disk'}% (".hr_num($mystat{'Created_tmp_disk_tables'})." on disk / ".hr_num($mystat{'Created_tmp_tables'})." total)\n";
  957.                         push(@generalrec,"Temporary table size is already large - reduce result set size");
  958.                         push(@generalrec,"Reduce your SELECT DISTINCT queries without LIMIT clauses");
  959.                 } else {
  960.                         goodprint "Temporary tables created on disk: $mycalc{'pct_temp_disk'}% (".hr_num($mystat{'Created_tmp_disk_tables'})." on disk / ".hr_num($mystat{'Created_tmp_tables'})." total)\n";
  961.                 }
  962.         } else {
  963.                 # For the sake of space, we will be quiet here
  964.                 # No temporary tables have been created
  965.         }
  966.  
  967.         # Thread cache
  968.         if ($myvar{'thread_cache_size'} eq 0) {
  969.                 badprint "Thread cache is disabled\n";
  970.                 push(@generalrec,"Set thread_cache_size to 4 as a starting value");
  971.                 push(@adjvars,"thread_cache_size (start at 4)");
  972.         } else {
  973.                 if ($mycalc{'thread_cache_hit_rate'} <= 50) {
  974.                         badprint "Thread cache hit rate: $mycalc{'thread_cache_hit_rate'}% (".hr_num($mystat{'Threads_created'})." created / ".hr_num($mystat{'Connections'})." connections)\n";
  975.                         push(@adjvars,"thread_cache_size (> $myvar{'thread_cache_size'})");
  976.                 } else {
  977.                         goodprint "Thread cache hit rate: $mycalc{'thread_cache_hit_rate'}% (".hr_num($mystat{'Threads_created'})." created / ".hr_num($mystat{'Connections'})." connections)\n";
  978.                 }
  979.         }
  980.  
  981.         # Table cache
  982.         my $table_cache_var = "";
  983.         if ($mystat{'Open_tables'} > 0) {
  984.                 if ($mycalc{'table_cache_hit_rate'} < 20) {
  985.                         badprint "Table cache hit rate: $mycalc{'table_cache_hit_rate'}% (".hr_num($mystat{'Open_tables'})." open / ".hr_num($mystat{'Opened_tables'})." opened)\n";
  986.                         if (mysql_version_ge(5, 1)) {
  987.                                 $table_cache_var = "table_open_cache";
  988.                         } else {
  989.                                 $table_cache_var = "table_cache";
  990.                         }
  991.                         push(@adjvars,$table_cache_var." (> ".$myvar{$table_cache_var}.")");
  992.                         push(@generalrec,"Increase ".$table_cache_var." gradually to avoid file descriptor limits");
  993.                         push(@generalrec,"Read this before increasing ".$table_cache_var." over 64: http://bit.ly/1mi7c4C");
  994.                 } else {
  995.                         goodprint "Table cache hit rate: $mycalc{'table_cache_hit_rate'}% (".hr_num($mystat{'Open_tables'})." open / ".hr_num($mystat{'Opened_tables'})." opened)\n";
  996.                 }
  997.         }
  998.  
  999.         # Open files
  1000.         if (defined $mycalc{'pct_files_open'}) {
  1001.                 if ($mycalc{'pct_files_open'} > 85) {
  1002.                         badprint "Open file limit used: $mycalc{'pct_files_open'}% (".hr_num($mystat{'Open_files'})."/".hr_num($myvar{'open_files_limit'}).")\n";
  1003.                         push(@adjvars,"open_files_limit (> ".$myvar{'open_files_limit'}.")");
  1004.                 } else {
  1005.                         goodprint "Open file limit used: $mycalc{'pct_files_open'}% (".hr_num($mystat{'Open_files'})."/".hr_num($myvar{'open_files_limit'}).")\n";
  1006.                 }
  1007.         }
  1008.  
  1009.         # Table locks
  1010.         if (defined $mycalc{'pct_table_locks_immediate'}) {
  1011.                 if ($mycalc{'pct_table_locks_immediate'} < 95) {
  1012.                         badprint "Table locks acquired immediately: $mycalc{'pct_table_locks_immediate'}%\n";
  1013.                         push(@generalrec,"Optimize queries and/or use InnoDB to reduce lock wait");
  1014.                 } else {
  1015.                         goodprint "Table locks acquired immediately: $mycalc{'pct_table_locks_immediate'}% (".hr_num($mystat{'Table_locks_immediate'})." immediate / ".hr_num($mystat{'Table_locks_waited'}+$mystat{'Table_locks_immediate'})." locks)\n";
  1016.                 }
  1017.         }
  1018.  
  1019.         # Performance options
  1020.         if (!mysql_version_ge(4, 1)) {
  1021.                 push(@generalrec,"Upgrade to MySQL 4.1+ to use concurrent MyISAM inserts");
  1022.         } elsif ($myvar{'concurrent_insert'} eq "OFF") {
  1023.                 push(@generalrec,"Enable concurrent_insert by setting it to 'ON'");
  1024.         } elsif ($myvar{'concurrent_insert'} eq 0) {
  1025.                 push(@generalrec,"Enable concurrent_insert by setting it to 1");
  1026.         }
  1027.         if ($mycalc{'pct_aborted_connections'} > 5) {
  1028.                 badprint "Connections aborted: ".$mycalc{'pct_aborted_connections'}."%\n";
  1029.                 push(@generalrec,"Your applications are not closing MySQL connections properly");
  1030.         }
  1031.  
  1032.         # InnoDB
  1033.         if (defined $myvar{'have_innodb'} && $myvar{'have_innodb'} eq "YES" && defined $enginestats{'InnoDB'}) {
  1034.                 if ($myvar{'innodb_buffer_pool_size'} > $enginestats{'InnoDB'}) {
  1035.                         goodprint "InnoDB buffer pool / data size: ".hr_bytes($myvar{'innodb_buffer_pool_size'})."/".hr_bytes($enginestats{'InnoDB'})."\n";
  1036.                 } else {
  1037.                         badprint "InnoDB  buffer pool / data size: ".hr_bytes($myvar{'innodb_buffer_pool_size'})."/".hr_bytes($enginestats{'InnoDB'})."\n";
  1038.                         push(@adjvars,"innodb_buffer_pool_size (>= ".hr_bytes_rnd($enginestats{'InnoDB'}).")");
  1039.                 }
  1040.             if (defined $mystat{'Innodb_log_waits'} && $mystat{'Innodb_log_waits'} > 0) {
  1041.                     badprint "InnoDB log waits: ".$mystat{'Innodb_log_waits'};
  1042.                 push(@adjvars,"innodb_log_buffer_size (>= ".hr_bytes_rnd($myvar{'innodb_log_buffer_size'}).")");
  1043.         } else {
  1044.                 goodprint "InnoDB log waits: ".$mystat{'Innodb_log_waits'};
  1045.         }
  1046.         }
  1047. }
  1048.  
  1049. # Take the two recommendation arrays and display them at the end of the output
  1050. sub make_recommendations {
  1051.         print "\n-------- Recommendations -----------------------------------------------------\n";
  1052.         if (@generalrec > 0) {
  1053.                 print "General recommendations:\n";
  1054.                 foreach (@generalrec) { print "    ".$_."\n"; }
  1055.         }
  1056.         if (@adjvars > 0) {
  1057.                 print "Variables to adjust:\n";
  1058.                 if ($mycalc{'pct_physical_memory'} > 90) {
  1059.                         print "  *** MySQL's maximum memory usage is dangerously high ***\n".
  1060.                                   "  *** Add RAM before increasing MySQL buffer variables ***\n";
  1061.                 }
  1062.                 foreach (@adjvars) { print "    ".$_."\n"; }
  1063.         }
  1064.         if (@generalrec == 0 && @adjvars ==0) {
  1065.                 print "No additional performance recommendations are available.\n"
  1066.         }
  1067.         print "\n";
  1068. }
  1069.  
  1070. # ---------------------------------------------------------------------------
  1071. # BEGIN 'MAIN'
  1072. # ---------------------------------------------------------------------------
  1073. print   "\n >>  MySQLTuner $tunerversion - Major Hayden <major\@mhtx.net>\n".
  1074.                 " >>  Bug reports, feature requests, and downloads at http://mysqltuner.com/\n".
  1075.                 " >>  Run with '--help' for additional options and output filtering\n";
  1076. mysql_setup;                            # Gotta login first
  1077. os_setup;                               # Set up some OS variables
  1078. get_all_vars;                           # Toss variables/status into hashes
  1079. validate_mysql_version;                 # Check current MySQL version
  1080. check_architecture;                     # Suggest 64-bit upgrade
  1081. check_storage_engines;                  # Show enabled storage engines
  1082. security_recommendations;               # Display some security recommendations
  1083. calculations;                           # Calculate everything we need
  1084. mysql_stats;                            # Print the server stats
  1085. make_recommendations;                   # Make recommendations based on stats
  1086. # ---------------------------------------------------------------------------
  1087. # END 'MAIN'
  1088. # ---------------------------------------------------------------------------
  1089.  
  1090. # Local variables:
  1091. # indent-tabs-mode: t
  1092. # cperl-indent-level: 8
  1093. # perl-indent-level: 8
  1094. # End:

Svara på "High Performance MySQL Tuning Script v1.3.0"

Här kan du skriva ett svar till kodsnutten ovan