#!/usr/bin/perl -w # # $Id: mytop,v 1.9 2002/10/27 06:49:33 jzawodn Exp $ =pod =head1 NAME mytop - display MySQL server performance info like `top' =cut ## most of the POD is at the bottom of the file use 5.005; use strict; use DBI; use Getopt::Long; $main::VERSION = "1.2"; $|++; $0 = 'mytop'; my $WIN = ($^O eq 'MSWin32') ? 1 : 0; ## Test for color support. eval { require Term::ANSIColor; }; my $HAS_COLOR = $@ ? 0 : 1; $HAS_COLOR = 0 if $WIN; ## Test of Time::HiRes support eval { require Time::HiRes }; my $HAS_TIME = $@ ? 0 : 1; my $debug = 0; ## Try to lower our priority (which, who, pri) setpriority(0,0,10) unless $WIN; ## Prototypes sub Clear(); sub GetData(); sub GetQPS(); sub FullQueryInfo($); sub Explain($); sub PrintTable(@); sub PrintHelp(); sub Sum(@); sub commify($); sub Hashes($); sub Execute($); ## Default Config Values my %config = ( delay => 5, host => 'localhost', db => 'test', user => 'root', pass => '', port => 3306, socket => '', batchmode => 0, header => 1, color => 1, idle => 1, mode => 'top', sort => 0, ); my %qcache = (); ## The query cache--used for full query info support. my %dbcache = (); ## The db cache. This should be merged at some point. my $num_q; ## Queries counter for computing qps my $num_qc; ## Query cach hits counter for qchps my $CLEAR = $WIN ? '': `clear`; ## Term::ReadKey values my $RM_RESET = 0; my $RM_NOBLKRD = 3; ## using 4 traps Ctrl-C :-( ## Read the user's config file, if it exists. my $config = "$ENV{HOME}/.mytop"; if (-e $config) { if (open CFG, "<$config") { while () { next if /^\s*$/; ## skip blanks next if /^\s*#/; ## skip comments chomp; if (/(\S+)\s*=\s*(\S+)/) { $config{lc $1} = $2 if exists $config{lc $1}; } } close CFG; } } ## Command-line args. use vars qw($opt_foo); Getopt::Long::Configure('no_ignore_case', 'bundling'); GetOptions( "color!" => \$config{color}, "user|u=s" => \$config{user}, "pass|password|p=s" => \$config{pass}, "database|db|d=s" => \$config{db}, "host|h=s" => \$config{host}, "port|P=i" => \$config{port}, "socket|S=s" => \$config{socket}, "delay|s=i" => \$config{delay}, "batch|batchmode|b" => \$config{batchmode}, "header!" => \$config{header}, "idle|i" => \$config{idle}, ); ## User may have put the port with the host. if ($config{host} =~ s/:(\d+)$//) { $config{port} = $1; } ## Don't use Term::ReadKey unless running interactively. if (not $config{batchmode}) { require Term::ReadKey; Term::ReadKey->import(); } ## User may want to disable color. if ($HAS_COLOR and not $config{color}) { $HAS_COLOR = 0; } if ($HAS_COLOR) { import Term::ANSIColor ':constants'; } else { *RESET = sub { }; *YELLOW = sub { }; *RED = sub { }; *GREEN = sub { }; *BLUE = sub { }; *WHITE = sub { }; *BOLD = sub { }; } my $RESET = RESET() || ''; my $YELLOW = YELLOW() || ''; my $RED = RED() || ''; my $GREEN = GREEN() || ''; my $BLUE = BLUE() || ''; my $WHITE = WHITE() || ''; my $BOLD = BOLD() || ''; ## Connect my $dsn; ## Socket takes precedence. $dsn ="DBI:mysql:database=$config{db};"; if ($config{socket} and -S $config{socket}) { $dsn .= "mysql_socket=$config{socket}"; } else { $dsn .= "host=$config{host};port=$config{port}"; } my $dbh = DBI->connect($dsn, $config{user}, $config{pass}, { PrintError => 0 }); if (not ref $dbh) { my $Error = <{Variable_name} eq "version") { $db_version = $_->{Value}; next; } if ($_->{Variable_name} eq "have_query_cache") { if ($_->{Value} eq 'YES') { $have_query_cache = 1; } else { $have_query_cache = 0; } next; } } ######################################################################### ## ## The main loop ## ######################################################################### ReadMode($RM_NOBLKRD) unless $config{batchmode}; while (1) { my $key; if ($config{mode} eq 'top') { Clear() unless $config{batchmode}; GetData(); last if $config{batchmode}; $key = ReadKey($config{delay}); next unless $key; } elsif ($config{mode} eq 'qps') { GetQPS(); $key = ReadKey(1); next unless $key; if ($key =~ /q/i) { $config{mode} = 'top'; } next; } ## ## keystroke command processing (if we get this far) ## ## q - quit if ($key eq 'q') { ReadMode($RM_RESET); print "\n"; exit; } ## m - mode swtich to qps if ($key eq 'm') { $config{mode} = 'qps'; Clear() unless $config{batchmode}; print "Queries Per Second [hit q to exit this mode]\n"; next; } ## s - seconds of delay if ($key eq 's') { ReadMode($RM_RESET); print RED(), "Seconds of Delay: ", RESET(); my $secs = ReadLine(0); if ($secs =~ /^\s*(\d+)/) { $config{delay} = $1; if ($config{delay} < 1) { $config{delay} = 1; } } ReadMode($RM_NOBLKRD); next; } ## u - username based filter if ($key eq 'u') { ReadMode($RM_RESET); print RED(), "Which user (blank for all): ", RESET(); my $user = ReadLine(0); chomp $user; $config{filter_user} = $user ? $user : undef; ReadMode($RM_NOBLKRD); next; } ## d - database name based filter if ($key eq 'd') { ReadMode($RM_RESET); print RED(), "Which database (blank for all): ", RESET(); my $db = ReadLine(0); chomp $db; $config{filter_db} = $db ? $db : undef; ReadMode($RM_NOBLKRD); next; } ## h - hostname based filter if ($key eq 'h') { ReadMode($RM_RESET); print RED(), "Which hostname (blank for all): ", RESET(); my $host = ReadLine(0); chomp $host; $config{filter_host} = $host ? $host : undef; ReadMode($RM_NOBLKRD); next; } ## F - remove all filters if ($key eq 'F') { $config{filter_host} = undef; $config{filter_db} = undef; $config{filter_user} = undef; print RED(), "-- display unfiltered --", RESET(); sleep 2; next; } ## p - pause if ($key eq 'p') { print RED(), "-- paused. press any key to resume --", RESET(); ReadKey(0); next; } ## i - idle toggle if ($key =~ /i/) { if ($config{idle}) { $config{idle} = 0; $config{sort} = 1; print RED(), "-- idle (sleeping) processed filtered --", RESET(); sleep 2; } else { $config{idle} = 1; $config{sort} = 0; print RED(), "-- idle (sleeping) processed unfiltered --", RESET(); sleep 2; } } ## o - sort order if ($key =~ /o/) { if ($config{sort}) { $config{sort} = 0; print RED(), "-- sort order reversed --", RESET(); sleep 2; } else { $config{sort} = 1; print RED(), "-- sort order reversed --", RESET(); sleep 2; } } ## ? - help if ($key eq '?') { Clear(); PrintHelp(); ReadKey(0); next; } ## k - kill if ($key =~ /k/) { ReadMode($RM_RESET); print RED(), "Thread id to kill: ", RESET(); my $id = ReadLine(0); $id =~ s/\s//g; if ($id =~ /^\d+$/) { Execute("KILL $id"); } else { print RED(), "-- invalid thread id --", RESET(); sleep 2; } ReadMode($RM_NOBLKRD); next; } ## f - full info if ($key =~ /f/) { ReadMode($RM_RESET); print RED(), "Full query for which thread id: ", RESET(); my $id = ReadLine(0); chomp $id; FullQueryInfo($id); ReadMode($RM_NOBLKRD); print RED(), "-- paused. press any key to resume or (e) to explain --", RESET(); my $key = ReadKey(0); if ($key eq 'e') { Explain($id); print RED(), "-- paused. press any key to resume --", RESET(); ReadKey(0); } next; } ## e - explain if ($key =~ /e/) { ReadMode($RM_RESET); print RED(), "Explain which query (id): ", RESET(); my $id = ReadLine(0); chomp $id; Explain($id); ReadMode($RM_NOBLKRD); print RED(), "-- paused. press any key to resume --", RESET(); ReadKey(0); next; } ## r - reset status counters if ($key =~ /r/) { Execute("FLUSH STATUS"); print RED(), "-- counters reset --", RESET(); sleep 2; next; } ## H - header toggle if ($key eq 'H') { if ($config{header}) { $config{header} = 0; } else { $config{header}++; } } ## # - magic debug key if ($key eq '#') { $debug = 1; } } ReadMode($RM_RESET) unless $config{batchmode}; exit; ####################################################################### sub Clear() { if (not $WIN) { print "$CLEAR" } else { print "\n" x 90; ## dumb hack for now. Anyone know how to ## clear the screen in dos window on a Win32 ## system?? } } my $last_time; sub GetData() { ## Get terminal info my $now_time; %qcache = (); ## recycle memory %dbcache = (); my ($width, $height, $wpx, $hpx, $lines_left); if (not $config{batchmode}) { ($width, $height, $wpx, $hpx) = GetTerminalSize(); $lines_left = $height - 2; } else { $height = 999_999; ## I hope you don't have more than that! $lines_left = 999_999; $width = 80; } ## ## Header stuff. ## if ($config{header}) { my @recs = Hashes("show status"); my %S; ## if the server died or we lost connectivity if (not @recs) { ReadMode($RM_RESET); exit 1; } ## get high-res or low-res time if ($HAS_TIME) { $now_time = Time::HiRes::gettimeofday(); } else { $now_time = time; } foreach my $ref (@recs) { my $key = $ref->{Variable_name}; my $val = $ref->{Value}; $S{$key} = $val; } ## Stash away the number of queries. my $now_queries_per_sec; if (defined $last_time and $last_time != $now_time) { my $q_delta = $S{Questions} - $num_q; my $t_delta = $now_time - $last_time; $now_queries_per_sec = sprintf "%.2f", $q_delta / $t_delta; } $num_q = $S{Questions}; ## Compute Key Cache Hit Stats $S{Key_read_requests} ||= 1; ## can't divide by zero next my $cache_hits_percent = (100-($S{Key_reads}/$S{Key_read_requests}) * 100); $cache_hits_percent = sprintf("%2.2f",$cache_hits_percent); ## Query Cache info ## ## mysql> show status like 'qcache%'; ## +-------------------------+----------+ ## | Variable_name | Value | ## +-------------------------+----------+ ## | Qcache_queries_in_cache | 81 | ## | Qcache_inserts | 4961668 | ## | Qcache_hits | 1374170 | ## | Qcache_not_cached | 5656249 | ## | Qcache_free_memory | 33164800 | ## | Qcache_free_blocks | 2 | ## | Qcache_total_blocks | 168 | ## +-------------------------+----------+ my $query_cache_hits = 0; my $query_cache_hits_per_sec = 0; my $now_query_cache_hits_per_sec = 0; if ($have_query_cache) { $query_cache_hits = $S{Qcache_hits}; $query_cache_hits_per_sec = $S{Qcache_hits} / $S{Uptime}; if (defined $last_time and $last_time != $now_time) { my $q_delta = $S{Qcache_hits} - $num_qc; my $t_delta = $now_time - $last_time; $now_query_cache_hits_per_sec = sprintf "%.2f", $q_delta / $t_delta; } } $num_qc = $S{Qcache_hits}; $last_time = $now_time; ## Server Uptime in meaningful terms... my $time = $S{Uptime}; my ($d,$h,$m,$s) = (0, 0, 0, 0); $d += int($time / (60*60*24)); $time -= $d * (60*60*24); $h += int($time / (60*60)); $time -= $h * (60*60); $m += int($time / (60)); $time -= $m * (60); $s += int($time); my $uptime = sprintf("%d+%02d:%02d:%02d", $d, $h, $m, $s); ## Queries per second... my $avg_queries_per_sec = sprintf("%.2f", $S{Questions} / $S{Uptime}); my $num_queries = $S{Questions}; my @t = localtime(time); my $current_time = sprintf "[%02d:%02d:%02d]", $t[2], $t[1], $t[0]; my $host_width = 52; my $up_width = $width - $host_width; print RESET(); printf "%-${host_width}s%${up_width}s\n", "MySQL on $config{host} ($db_version)", "up $uptime $current_time"; $lines_left--; printf " Queries Total: %-13s ", commify($num_queries); printf "Avg/Sec: %-4.2f ", $avg_queries_per_sec; printf "Now/Sec: %-4.2f ", $now_queries_per_sec if defined $now_queries_per_sec; printf "Slow: %s\n", commify($S{Slow_queries}); $lines_left--; if ($have_query_cache) { printf " Cache Hits : %-13s ", commify($query_cache_hits); printf "Avg/Sec: %-4.2f ", $query_cache_hits_per_sec; printf "Now/Sec: %-4.2f ", $now_query_cache_hits_per_sec; printf "Ratio: %-2.2f%%", (($query_cache_hits / $num_queries) * 100); printf "\n"; $lines_left--; } printf " Threads Total: %-5s Active: %-5s Cached: %-5s\n", commify($S{Threads_connected}), commify($S{Threads_running}), commify($S{Threads_cached}); $lines_left--; printf " Key Efficiency: %2.2f%% Bytes in: %s Bytes out: %s\n\n", $cache_hits_percent, commify($S{Bytes_received}), commify($S{Bytes_sent}); $lines_left--; } ## ## Threads ## #my $sz = $width - 52; my @sz = (8, 9, 15, 10, 9, 6); my $used = scalar(@sz) + Sum(@sz); my $free = $width - $used; print BOLD(); printf "%8s %9s %15s %10s %9s %6s %-${free}s\n", 'Id','User','Host/IP','DB','Time', 'Cmd', 'Query or State'; print RESET(); ## Id User Host DB printf "%8s %9s %15s %10s %9s %6s %-${free}s\n", '--','----','-------','--','----', '---', '----------'; $lines_left -= 2; my $proc_cmd = "show full processlist"; my @data = Hashes($proc_cmd); foreach my $thread (@data) { last if not $lines_left; ## Drop Domain Name (unless it looks like an IP address) if ($thread->{Host} !~ /^(\d{1,3}\.){3}(\d{1,3})$/) { $thread->{Host} =~ s/^([^.]+).*/$1/; } ## Fix possible undefs $thread->{db} ||= ''; $thread->{Info} ||= ''; $thread->{Time} ||= 0 ; $thread->{Id} ||= 0 ; $thread->{User} ||= ''; $thread->{Command} ||= ''; $thread->{Host} ||= ''; ## Normalize spaces $thread->{Info} =~ s/[\n\r]//g; $thread->{Info} =~ s/\s+/ /g; $thread->{Info} =~ s/^\s*//; ## stow it in the cache $qcache{$thread->{Id}} = $thread->{Info}; $dbcache{$thread->{Id}} = $thread->{db}; } ## Sort by idle time (closest thing to CPU usage I can think of). my @sorted; if (not $config{sort}) { @sorted = sort { $a->{Time} <=> $b->{Time} } @data } else { @sorted = sort { $b->{Time} <=> $a->{Time} } @data } foreach my $thread (@sorted) { ## Check to see if we can skip out. next if (($thread->{Command} eq "Sleep") and (not $config{idle})); next if (($thread->{Command} eq "Binlog Dump") and (not $config{idle})); next if (defined $config{filter_user} and $thread->{User} ne $config{filter_user} ); next if (defined $config{filter_db} and $thread->{db} ne $config{filter_db} ); next if (defined $config{filter_host} and $thread->{Host} ne $config{filter_host} ); ## Otherwise, print. my $smInfo; if ($thread->{Info}) { $smInfo = substr $thread->{Info}, 0, $free; } elsif ($thread->{State}) { $smInfo = substr $thread->{State}, 0, $free; } else { $smInfo = ""; } if ($HAS_COLOR) { print YELLOW() if $thread->{Command} eq 'Query'; print WHITE() if $thread->{Command} eq 'Sleep'; print GREEN() if $thread->{Command} eq 'Connect'; } printf "%8d %9.9s %15.15s %10.10s %9d %6.6s %-${free}.${free}s\n", $thread->{Id}, $thread->{User}, $thread->{Host}, $thread->{db}, $thread->{Time}, $thread->{Command}, $smInfo; print RESET() if $HAS_COLOR; $lines_left--; last if $lines_left == 0; } } ########################################################################### my $questions; sub GetQPS() { my($data) = Hashes('SHOW STATUS LIKE "Questions"'); my $num = $data->{Value}; if (not defined $questions) ## first time? { $questions = $num; return; } my $qps = $num - $questions; $questions = $num; print "$qps\n"; } ########################################################################### sub FullQueryInfo($) { my $id = shift; if (not exists $qcache{$id} or not defined $qcache{$id}) { print "*** Invalid id. ***\n"; return; } my $sql = $qcache{$id}; print $CLEAR; print "Thread $id was executing following query:\n\n"; print YELLOW(), $sql,"\n\n", RESET(); } ########################################################################### sub Explain($) { my $id = shift; if (not exists $qcache{$id} or not defined $qcache{$id}) { print "*** Invalid id. ***\n"; return; } my $sql = $qcache{$id}; my $db = $dbcache{$id}; Execute("USE $db"); my @info = Hashes("EXPLAIN $sql"); print $CLEAR; print "EXPLAIN $sql:\n\n"; PrintTable(@info); } ########################################################################### sub PrintTable(@) { my $cnt = 1; my @cols = qw(table type possible_keys key key_len ref rows Extra); for my $row (@_) { print "*** row $cnt ***\n"; for my $key (@cols) { my $val = $row->{$key} || 'NULL'; printf "%15s: %s\n", $key, $val; } $cnt++; } } ########################################################################### ########################################################################### ########################################################################### sub PrintHelp() { my $help = qq[ This is help for mytop version $main::VERSION by Jeremy D. Zawodny <${YELLOW}jzawodn\@yahoo-inc.com${RESET}> ? - display this screen d - show only a specific database e - explain the query that a thread is running f - show full query info for a given thread F - unFilter the dispaly h - show only a specifc host's connections H - toggle the mytop header i - toggle the display of idle (sleeping) threads k - kill a thread p - pause the display m - mode switch (to qps mode) o - reverse the sort order (toggle) q - quit r - reset the status counters (via FLUSH STATUS on your server) s - change the delay between screen updates u - show only a specific user : - enter a command (not yet implemented) ${GREEN}http://jeremy.zawodny.com/mysql/mytop/${RESET} (press any key to return)]; print $help; } sub Sum(@) { my $sum; while (my $val = shift @_) { $sum += $val; } return $sum; } ## A useful routine from perlfaq sub commify($) { local $_ = shift; return 0 unless defined $_; 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; return $_; } ## Run a query and return the records has an array of hashes. sub Hashes($) { my $sql = shift; my @records; if (my $sth = Execute($sql)) { while (my $ref = $sth->fetchrow_hashref) { print "record\n" if $debug; push @records, $ref; } } return @records; } ## Execute an SQL query and return the statement handle. sub Execute($) { my $sql = shift; my $sth = $dbh->prepare($sql); if (not $sth) { die $DBI::errstr; } my $ReturnCode = $sth->execute; if (not $ReturnCode) { if ($debug) { print "query failed\n"; sleep 10; } return undef; } return $sth; } =pod =head1 SYNOPSIS B [options] =head1 AVAILABILITY The latest version of B is available from http://jeremy.zawodny.com/mysql/mytop/ it B also be on CPAN as well. =head1 REQUIREMENTS In order for B to function properly, you must have the following: * Perl 5.005 or newer * Getopt::Long * DBI and DBD::mysql * Term::ReadKey from CPAN Most systems are likely to have all of those installed--except for Term::ReadKey. You will need to pick that up from the CPAN. You can pick up Term::ReadKey here: http://search.cpan.org/search?dist=TermReadKey And you obviously need access to a MySQL server (version 3.22.x or 3.23.x) with the necessary security to run the I and I commands. If you are a Windows user, using ActiveState's Perl, you can use PPM (the Perl Package Manager) to install the MySQL and Term::ReadKey modules. =head2 Optional Color Support In additon, if you want a color B (recommended), install Term::ANSIColor from the CPAN: http://search.cpan.org/search?dist=ANSIColor Once you do, B will automatically use it. However, color is not yet working on Windows. Patches welcome. :-) =head2 Optional Hi-Res Timing If you want B to provide more accurate real-time queries-per-second statistics, install the Time::HiRes module from CPAN. B will automatically notice that you have it and use it rather than the standard timing mechanism. =head2 Platforms B is known to work on: * Linux (2.2.x, 2.4.x) * FreeBSD (2.2, 3.x, 4.x) * Mac OS X * BSDI 4.x * Solaris 2.x * Windows NT 4.x (ActivePerl) If you find that it works on another platform, please let me know. Given that it is all Perl code, I expect it to be rather portable to Unix and Unix-like systems. Heck, it I even work on Win32 systems. =head1 DESCRIPTION Help is always welcome in improving this software. Feel free to contact the author (see L<"AUTHOR"> below) with bug reports, fixes, suggestions, and comments. Additionally L<"BUGS"> will provide a list of things this software is not able to do yet. Having said that, here are the details on how it works and what you can do with it. =head2 The Basics B was inspired by the system monitoring tool B. I routinely use B on Linux, FreeBSD, and Solaris. You are likely to notice features from each of them here. B will connect to a MySQL server and periodically run the I and I commands and attempt to summarize the information from them in a useful format. =head2 The Display The B display screen is really broken into two parts. The top 4 lines (header) contain summary information about your MySQL server. For example, you might see something like: MySQL on localhost (3.22.32) up 3+23:14:20 [23:54:52] Queries Total: 617 Avg/Sec: 0.00 Now/Sec: 0.05 Slow: 0 Threads Total: 1 Active: 1 Cached: 0 Key Efficiency: 88.38% Bytes in: 0 Bytes out: 0 The first line identified the hostname of the server (localhost) and the version of MySQL it is running. The right had side shows the uptime of the MySQL server process in days+hours:minutes:seconds format (much like FreeBSD's top) as well as the current time. The second line displays the total number of queries the server has processed, the average number of queries per second, the real-time number of queries per second, and the number of slow queries. The third line deals with threads. Versions of MySQL before 3.23.x didn't give out this information, so you'll see all zeros. And the fourth line displays key buffer efficiency (how often keys are read from the buffer rather than disk) and the number of bytes that MySQL has sent and received. You can toggle the header by hitting B when running B. The second part of the display lists as many threads as can fit on screen. By default they are sorted according to their idle time (least idle first). The display looks like: Id User Host Dbase Time Cmd Query or State -- ---- ---- ----- ---- --- -------------- 61 jzawodn localhost music 0 Query show processlist As you can see, the thread id, username, host from which the user is connecting, database to which the user is connected, number of seconds of idle time, the command the thread is executing, and the query info are all displayed. Often times the query info is what you are really interested in, so it is good to run B in an xterm that is wider than the normal 80 columns if possible. The thread display color-codes the threads if you have installed color support. The current color scheme only works well in a window with a dark (like black) background. The colors are selected according to the C column of the display: Query - Yellow Sleep - White Connect - Green Those are purely arbitrary and will be customizable in a future release. If they annoy you just start B with the B<-nocolor> flag or adjust your config file appropriately. =head2 Arguments B handles long and short command-line arguments. Not all options have both long and short formats, however. The long arguments can start with one or two dashes `-' or `--'. They are shown here with just one. =over =item B<-u> or B<-user> username Username to use when logging in to the MySQL server. Default: ``root''. =item B<-p> or B<-pass> or B<-password> password Password to use when logging in to the MySQL server. Default: none. =item B<-h> or B<-host> hostname[:port] Hostname of the MySQL server. The hostname may be followed by an option port number. Note that the port is specified separate from the host when using a config file. Default: ``localhost''. =item B<-port> or B<-P> port If you're running MySQL on a non-standard port, use this to specify the port number. Default: 3306. =item B<-s> or B<-delay> seconds How long between display refreshes. Default: 5 =item B<-d> or B<-db> or B<-database> database Use if you'd like B to connect to a specific database by default. Default: ``test''. =item B<-b> or B<-batch> or B<-batchmode> In batch mode, mytop runs only once, does not clear the screen, and places no limit on the number of lines it will print. This is suitable for running periodically (perhaps from cron) to capture the information into a file for later viewing. You might use batch mode in a CGI script to occasionally display your MySQL server status on the web. Default: unset. =item B<-S> or B<-socket> /path/to/socket If you're running B on the same host as MySQL, you may wish to have it use the MySQL socket directly rather than a standard TCP/IP connection. If you do,just specify one. Note that specifying a socket will make B ignore any host and/or port that you might have specified. If the socket does not exist (or the file specified is not a socket), this option will be ignored and B will use the hostname and port number instead. Default: none. =item B<-header> or B<-noheader> Sepcify if you want the header to display or not. You can toggle this with the B key while B is running. Default: header. =item B<-color> or B<-nocolor> Specify if you want a color display. This has no effect if you don't have color support available. Default: If you have color support, B will try color unless you tell it not to. =item B<-i> or B<-idle> or B<-noidle> Specify if you want idle (sleeping) threads to appear in the list. If sleeping threads are omitted, the default sorting order is reversed so that the longest running queries appear at the top of the list. Default: idle. =back Command-line arguments will always take precedence over config file options. That happens because the config file is read I the command-line arguments are applied. =head2 Config File Instead of always using bulky command-line parameters, you can also use a config file in your home directory (C<~/.mytop>). If present, B will read it automatically. It is read I any of your command-line arguments are processed, so your command-line arguments will override directives in the config file. Here is a sample config file C<~/.mytop> which implements the defaults described above. user=root pass= host=localhost db=test delay=5 port=3306 socket= batchmode=0 header=1 color=1 idle=1 Using a config file will help to ensure that your database password isn't visible to users on the command-line. Just make sure that the permissions on C<~/.mytop> are such that others cannot read it (unless you want them to, of course). You may have white space on either side of the C<=> in lines of the config file. =head2 Shortcut Keys The following keys perform various actions while B is running. Those which have not been implemented are listed as such. They are included to give the user idea of what is coming. =over =item B Display help. =item B Show only threads connected to a particular database. =item B Given a thread id, display the entire query that thread was (and still may be) running. =item B Disable all filtering (host, user, and db). =item B Only show queries from a particular host. =item B Toggle the header display. You can also specify either C or C in your config file to set the default behavior. =item B Toggle the display of idle (sleeping) threads. If sleeping threads are filtered, the default sorting order is reversed so that the longest running queries appear at the top of the list. =item B Kill a thread. =item B Toggle modes. Currently this switches from `top' mode to `qps' (Queries Per Second Mode). In this mode, mytop will write out one integer per second. The number written reflects the number of queries executed by the server in the previous one second interval. More modes may be added in the future. =item B Reverse the default sort order. =item B

Pause display. =item B Quit B =item B Reset the server's status counters via a I command. =item B Change the sleep time (number of seconds between display refreshes). =item B Show only threads owned by a giver user. =back The B key has a command-line counterpart: B<-s>. The B key has two command-line counterparts: B<-header> and B<-noheader>. =head1 BUGS This is more of a BUGS + WishList. Some performance information is not available when talking to a version 3.22.x MySQL server. Additional information (about threads mostly) was added to the output of I in MySQL 3.23.x and B makes use of it. If the information is not available, you will simply see zeros where the real numbers should be. Simply running this program will increase your overall counters (such as the number of queries run). But you may or may not view that as a bug. B consumes too much CPU time when running (verified on older versions of Linux and FreeBSD). It's likely a problem related to Term::ReadKey. I haven't had time to investigate yet, so B now automatically lowers its priority when you run it. You may also think about running B on another workstation instead of your database server. However, C on Solaris does B have this problem. Newer versions of Linux and FreeBSD seem to have fixed this. You can't specify the maximum number of threads to list. If you have many threads and a tall xterm, B will always try to display as many as it can fit. The size of most of the columns in the display has a small maximum width. If you have fairly long database/user/host names the display may appear odd. I have no good idea as to how best to deal with that yet. Suggestions are welcome. It'd be nice if you could just add B configuration directives in your C file instead of having a separate config file. You should be able to specify the columns you'd like to see in the display and the order in which they appear. If you only have one username that connects to your database, it's probably not worth having the User column appear, for example. =head1 AUTHOR mytop was developed and is maintained by Jeremy D. Zawodny (Jeremy@Zawodny.com). If you wish to e-mail me regarding this software, B subscribe to the B mailing list. See the B homepage for details. =head1 DISCLAIMER While I use this software in my job at Yahoo!, I am solely responsible for it. Yahoo! does not necessarily support this software in any way. It is merely a personal idea which happened to be very useful in my job. =head1 RECRUITING If you hack Perl and grok MySQL, come work at Yahoo! Contact me for details. Or just send me your resume. Er, unless we just had layoffs, in which case we're not hiring. :-( =head1 SEE ALSO Please check the MySQL manual if you're not sure where some of the output of B is coming from. =head1 COPYRIGHT Copyright (C) 2000-2001, Jeremy D. Zawodny. =head1 CREDITS Fix a bug. Add a feature. See your name here! Many thanks go to these fine folks: =over =item Sami Ahlroos (sami@avis-net.de) Suggested the idle/noidle stuff. =item Jan Willamowius (jan@janhh.shnet.org) Mirnor bug report. Documentation fixes. =item Alex Osipov (alex@acky.net) Long command-line options, Unix socket support. =item Stephane Enten (tuf@grolier.fr) Suggested batch mode. =item Richard Ellerbrock (richarde@eskom.co.za) Bug reports and usability suggestions. =item William R. Mattil (wrm@newton.irngtx.tel.gte.com) Bug report about empty passwords not working. =item Benjamin Pflugmann (philemon@spin.de) Suggested -P command-line flag as well as other changes. =item Justin Mecham Suggested setting $0 to `mytop'. =item Thorsten Kunz Provided a fix for cases when we try remove the domain name from the display even if it is actually an IP address. =item Sasha Pachev Provided the idea of real-time queries per second in the main display. =item Paul DuBois Pointed out some option-handling bugs. =back See the Changes file on the B distribution page for more details on what has changed. =head1 LICENSE B is licensed under the GNU General Public License version 2. For the full license information, please visit http://www.gnu.org/copyleft/gpl.html =cut __END__