mysqldumpslow.pl 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #!/usr/bin/perl
  2. # Copyright (c) 2000, 2021, Oracle and/or its affiliates.
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2.0,
  6. # as published by the Free Software Foundation.
  7. #
  8. # This program is also distributed with certain software (including
  9. # but not limited to OpenSSL) that is licensed under separate terms,
  10. # as designated in a particular file or component or in included license
  11. # documentation. The authors of MySQL hereby grant you an additional
  12. # permission to link the program and your derivative works with the
  13. # separately licensed software that they have included with MySQL.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License, version 2.0, for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License
  21. # along with this program; if not, write to the Free Software
  22. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  23. # mysqldumpslow - parse and summarize the MySQL slow query log
  24. use strict;
  25. use Getopt::Long;
  26. # t=time, l=lock time, r=rows
  27. # at, al, and ar are the corresponding averages
  28. my %opt = (
  29. s => 'at',
  30. h => '*',
  31. );
  32. GetOptions(\%opt,
  33. 'v|verbose+',# verbose
  34. 'help+', # write usage info
  35. 'd|debug+', # debug
  36. 's=s', # what to sort by (al, at, ar, c, t, l, r)
  37. 'r!', # reverse the sort order (largest last instead of first)
  38. 't=i', # just show the top n queries
  39. 'a!', # don't abstract all numbers to N and strings to 'S'
  40. 'n=i', # abstract numbers with at least n digits within names
  41. 'g=s', # grep: only consider stmts that include this string
  42. 'h=s', # hostname of db server for *-slow.log filename (can be wildcard)
  43. 'i=s', # name of server instance (if using mysql.server startup script)
  44. 'l!', # don't subtract lock time from total time
  45. ) or usage("bad option");
  46. $opt{'help'} and usage();
  47. unless (@ARGV) {
  48. my $defaults = `my_print_defaults mysqld`;
  49. my $basedir = ($defaults =~ m/--basedir=(.*)/)[0]
  50. or die "Can't determine basedir from 'my_print_defaults mysqld' output: $defaults";
  51. warn "basedir=$basedir\n" if $opt{v};
  52. my $datadir = ($defaults =~ m/--datadir=(.*)/)[0];
  53. my $slowlog = ($defaults =~ m/--slow-query-log-file=(.*)/)[0];
  54. if (!$datadir or $opt{i}) {
  55. # determine the datadir from the instances section of /etc/my.cnf, if any
  56. my $instances = `my_print_defaults instances`;
  57. die "Can't determine datadir from 'my_print_defaults mysqld' output: $defaults"
  58. unless $instances;
  59. my @instances = ($instances =~ m/^--(\w+)-/mg);
  60. die "No -i 'instance_name' specified to select among known instances: @instances.\n"
  61. unless $opt{i};
  62. die "Instance '$opt{i}' is unknown (known instances: @instances)\n"
  63. unless grep { $_ eq $opt{i} } @instances;
  64. $datadir = ($instances =~ m/--$opt{i}-datadir=(.*)/)[0]
  65. or die "Can't determine --$opt{i}-datadir from 'my_print_defaults instances' output: $instances";
  66. warn "datadir=$datadir\n" if $opt{v};
  67. }
  68. if ( -f $slowlog ) {
  69. @ARGV = ($slowlog);
  70. die "Can't find '$slowlog'\n" unless @ARGV;
  71. } else {
  72. @ARGV = <$datadir/$opt{h}-slow.log>;
  73. die "Can't find '$datadir/$opt{h}-slow.log'\n" unless @ARGV;
  74. }
  75. }
  76. warn "\nReading mysql slow query log from @ARGV\n";
  77. my @pending;
  78. my %stmt;
  79. $/ = ";\n#"; # read entire statements using paragraph mode
  80. while ( defined($_ = shift @pending) or defined($_ = <>) ) {
  81. warn "[[$_]]\n" if $opt{d}; # show raw paragraph being read
  82. my @chunks = split /^\/.*Version.*started with[\000-\377]*?Time.*Id.*Command.*Argument.*\n/m;
  83. if (@chunks > 1) {
  84. unshift @pending, map { length($_) ? $_ : () } @chunks;
  85. warn "<<".join(">>\n<<",@chunks).">>" if $opt{d};
  86. next;
  87. }
  88. s/^#? Time: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+(Z|[+-]\d{2}:\d{2}).*\n//;
  89. my ($user,$host,$dummy,$thread_id) = s/^#? User\@Host:\s+(\S+)\s+\@\s+(\S+)\s+\S+(\s+Id:\s+(\d+))?.*\n// ? ($1,$2,$3,$4) : ('','','','','');
  90. s/^# Query_time: ([0-9.]+)\s+Lock_time: ([0-9.]+)\s+Rows_sent: ([0-9.]+).*\n//;
  91. my ($t, $l, $r) = ($1, $2, $3);
  92. $t -= $l unless $opt{l};
  93. # remove fluff that mysqld writes to log when it (re)starts:
  94. s!^/.*Version.*started with:.*\n!!mg;
  95. s!^Tcp port: \d+ Unix socket: \S+\n!!mg;
  96. s!^Time.*Id.*Command.*Argument.*\n!!mg;
  97. s/^use \w+;\n//; # not consistently added
  98. s/^SET timestamp=\d+;\n//;
  99. s/^[ ]*\n//mg; # delete blank lines
  100. s/^[ ]*/ /mg; # normalize leading whitespace
  101. s/\s*;\s*(#\s*)?$//; # remove trailing semicolon(+newline-hash)
  102. next if $opt{g} and !m/$opt{g}/io;
  103. unless ($opt{a}) {
  104. s/\b\d+\b/N/g;
  105. s/\b0x[0-9A-Fa-f]+\b/N/g;
  106. s/''/'S'/g;
  107. s/""/"S"/g;
  108. s/(\\')//g;
  109. s/(\\")//g;
  110. s/'[^']+'/'S'/g;
  111. s/"[^"]+"/"S"/g;
  112. # -n=8: turn log_20001231 into log_NNNNNNNN
  113. s/([a-z_]+)(\d{$opt{n},})/$1.('N' x length($2))/ieg if $opt{n};
  114. # abbreviate massive "in (...)" statements and similar
  115. s!(([NS],){100,})!sprintf("$2,{repeated %d times}",length($1)/2)!eg;
  116. }
  117. my $s = $stmt{$_} ||= { users=>{}, hosts=>{} };
  118. $s->{c} += 1;
  119. $s->{t} += $t;
  120. $s->{l} += $l;
  121. $s->{r} += $r;
  122. $s->{users}->{$user}++ if $user;
  123. $s->{hosts}->{$host}++ if $host;
  124. warn "{{$_}}\n\n" if $opt{d}; # show processed statement string
  125. }
  126. foreach (keys %stmt) {
  127. my $v = $stmt{$_} || die;
  128. my ($c, $t, $l, $r) = @{ $v }{qw(c t l r)};
  129. $v->{at} = $t / $c;
  130. $v->{al} = $l / $c;
  131. $v->{ar} = $r / $c;
  132. }
  133. my @sorted = sort { $stmt{$b}->{$opt{s}} <=> $stmt{$a}->{$opt{s}} } keys %stmt;
  134. @sorted = @sorted[0 .. $opt{t}-1] if $opt{t};
  135. @sorted = reverse @sorted if $opt{r};
  136. foreach (@sorted) {
  137. my $v = $stmt{$_} || die;
  138. my ($c, $t,$at, $l,$al, $r,$ar) = @{ $v }{qw(c t at l al r ar)};
  139. my @users = keys %{$v->{users}};
  140. my $user = (@users==1) ? $users[0] : sprintf "%dusers",scalar @users;
  141. my @hosts = keys %{$v->{hosts}};
  142. my $host = (@hosts==1) ? $hosts[0] : sprintf "%dhosts",scalar @hosts;
  143. printf "Count: %d Time=%.2fs (%ds) Lock=%.2fs (%ds) Rows=%.1f (%d), $user\@$host\n%s\n\n",
  144. $c, $at,$t, $al,$l, $ar,$r, $_;
  145. }
  146. sub usage {
  147. my $str= shift;
  148. my $text= <<HERE;
  149. Usage: mysqldumpslow [ OPTS... ] [ LOGS... ]
  150. Parse and summarize the MySQL slow query log. Options are
  151. --verbose verbose
  152. --debug debug
  153. --help write this text to standard output
  154. -v verbose
  155. -d debug
  156. -s ORDER what to sort by (al, at, ar, c, l, r, t), 'at' is default
  157. al: average lock time
  158. ar: average rows sent
  159. at: average query time
  160. c: count
  161. l: lock time
  162. r: rows sent
  163. t: query time
  164. -r reverse the sort order (largest last instead of first)
  165. -t NUM just show the top n queries
  166. -a don't abstract all numbers to N and strings to 'S'
  167. -n NUM abstract numbers with at least n digits within names
  168. -g PATTERN grep: only consider stmts that include this string
  169. -h HOSTNAME hostname of db server for *-slow.log filename (can be wildcard),
  170. default is '*', i.e. match all
  171. -i NAME name of server instance (if using mysql.server startup script)
  172. -l don't subtract lock time from total time
  173. HERE
  174. if ($str) {
  175. print STDERR "ERROR: $str\n\n";
  176. print STDERR $text;
  177. exit 1;
  178. } else {
  179. print $text;
  180. exit 0;
  181. }
  182. }