#!/usr/local/bin/perl -w
##################################################################
# $Id: mrtg-mysql-load,v 1.9 2002/02/01 13:43:56 carsten Exp $
#
# Copyright (c) 2001 Carsten H. Pedersen <carsten.pedersen@bitbybit.dk>. 
# All Rights Reserved.
#
# Losely based on mrtg-ping-probe 1.2 Copyright (c) 1997-2001 
# Peter W. Osel <pwo@guug.de>.
#
# Copyright Carsten H. Pedersen <carsten.pedersen@bitbybit.dk> 2001.
# This file is released under the GNU General Public License.
# See file COPYRIGHT for details
#
##################################################################
require 5.003;
use Getopt::Std;
use File::Basename;
use Config;

sub dbg_print; 
sub read_config;
sub get_questions;
sub get_slow_queries;
sub get_uptime;
sub get_version;
sub write_output;

# prevent warnings for command-line variables which 
# Perl thinks we only use once.
$opt_o = ""; 
$opt_v = ""; 

$Prog_name = basename($0);		# Who I am

# Usage message

$Usage = "$Prog_name: Outputs the number of questions and slow queries since
last restart of the MySQL server. The output is formatted according to
mrtg requirements.

Usage: $Prog_name [-h host] [-P port] [-u username] [-ppassword] 
          [-c /path/to/config.file] [-d] [-v] [-l filename]

    Options -h, -P, -u and -p are equivalent (and map directly) to the 
        same options for mysqladmin.
    -l: Write a copy of the output to file filename
    -c: Read all the options from config file. Command line flags
        override options in config file.
    -o: Print command and options used when calling mysqladmin; exit
    -d: Print lots of ugly debugging messages to STDERR
    -v: Output version info; exit
"; # end $Usage

# Version message

$version = "1.02";
$dispversion = "[mrtg-mysql-load v. $version]";
$Version = "mrtg-mysql-load v. $version
Copyright (c) 2001-2002 Carsten H. Pedersen <carsten.pedersen\@bitbybit.dk>. 
All Rights Reserved.
"; # end version


# Parse Command Line:
if (!getopts('h:P:u:p:t:c:l:dvo')) {
    $output = $Usage;
    write_output;
    die $output;
}

# if debug is turned on, tell us so
if ($opt_d) {
    dbg_print "Debugging is on";
}

dbg_print "Done parsing command line";

# if -v: Echo version info and exit
if ($opt_v) {
    dbg_print "Version info requested";
    print $Version;
    exit(0);
} else {
	dbg_print "Version info not requested";
}

# reset all variables to known values
$host = "";
$port = "";
$username = "";
$password = "";
$logfile = "";

# If the config file has been specified, read the options from that
# first.
if ($opt_c) {
    read_config($opt_c);
} else {
    dbg_print "Config file NOT specified";
}

# Other command line options. They may already
# have been specified in a config file, but we
# override if they are defined on the command line.
$host     = defined($opt_h) ? $opt_h : $host;
$port     = defined($opt_P) ? $opt_P : $port;
$username = defined($opt_u) ? $opt_u : $username;
$password = defined($opt_p) ? $opt_p : $password;
$logfile  = defined($opt_l) ? $opt_l : $logfile;

if (@ARGV > 0) {
    print STDERR "$Prog_name: ERROR: ignoring superfluous arguments\n";
    print STDERR "$Usage";
}

# construct command used for calling mysqladmin
$cmd = "mysqladmin ".
    ($host ? "-h $host " : "").
    ($port ? "-P $port " : "").
    ($username ? "-u $username " : "").
    ($password ? "-p$password " : "").

    # Note that we use the "version" command rather than
    # the "status" command, as version returns the same
    # status info plus the version number, albeit formatted
    # somewhat differently. As a plus, it also returns the
    # uptime info in a much more human-readable format.
    "version ".
    
    # we need to redirect stderr to catch error messages
    "2>&1 ".
    "";

# If command line option -o is given, display $cmd and exit
if ($opt_o) {
    print "$cmd\n";
    exit(0);
}

unless (open(MYSQLA, "$cmd |")) {
    print STDERR "${Prog_name}: ERROR: Can't open $cmd: $!";
    exit(1);
}

$mysqladmin_output = join('', <MYSQLA>);
close MYSQLA;

# A better error handling could probably be implemented.
# For now, we simply check whether mysqladmin returns the
# string "mysqladmin: " as the first part of either stderr
# or stdout if an error occurs. In that case, we assume 
# that something odd happened.

if ($mysqladmin_output =~ /^.mysqladmin:/) {
    $output = 
	"ERROR: mysqladmin returned an error message:\n$mysqladmin_output";
    write_output;
    die $output;
}

get_questions;
get_slow_queries;
get_uptime;
get_version;

# Now we have all the data we need to output to mrtg:

# The external mrtg probe returns up to 4 lines of output:
#	1. Line: current state of the 'incoming bytes counter'
#	2. Line: current state of the 'outgoing bytes counter'
#	3. Line: string, telling the uptime of the target.
#	4. Line: telling the name of the target.

$output = sprintf("%d\n%d\n%s\n%s", $questions, $slow_queries, 
		  $uptime, $version);

write_output;

exit(0);

# dbg_print: Print string to STDERR if debug is turned on

sub dbg_print {
    if ($opt_d) {
	print STDERR "$Prog_name-dbg: ";
	print STDERR "@_\n";
    }
}

# read_config: Attempt to read in the configuration file and set
# variables accordingly. The format of the config file is:
# # - comment, ignored
# var=value<nl>
# where var is one of 'host', 'port', 'username' or 'password' 
# and value is the corresponding value, no quotation

sub read_config {
    my $configfile = $_[0];
    my $lnum = 0;
    
    if (!open(CFG, "<$configfile")) {
	$output = 
	    "ERROR: Unable to read config file $configfile";
	write_output;
	die $output;
    }
    dbg_print("Reading config from file $configfile");
    for $line (<CFG>) {
	$lnum++;
	chomp $line;
	if ($line !~ /^$/ ) { # ignore empty lines
    	    if ($line=~/(host|port|username|password|logfile)=(.{1,})/ ) {
		dbg_print("Got value $2 for parameter $1");
		$ {$1} = $2;
	    } else {
		# a comment or an error?
		if ($line =~ /^#/ ) {
		    dbg_print "Ignored comment: $line";
		} else {
		    print STDERR "$Prog_name: Error: I don't understand line ".
			"$lnum of $configfile\n";
		    exit(1);
		}
	    }
	}
    }
    dbg_print("Done reading config file");
}


# get_questions: Extract "Questions: NNNN" from $mysqladmin_output and
# tie the value to $questions

sub get_questions {
    if ($mysqladmin_output !~ /Questions: ([0-9]+)/ ) {
	$output = "ERROR: could not find match for 'Questions:' in ".
	    "mysqladmin output\n\n:$mysqladmin_output";
	write_output;
	die $output;
    }
    dbg_print "Questions: $1";
    $questions = $1;
}

# get_slow_queries: Extract "Questions: NNNN" from $mysqladmin_output and
# tie the value to $slow_queries

sub get_slow_queries {
    if ($mysqladmin_output !~ /Slow queries: ([0-9]+)/ ) { 
	$output = "ERROR: could not find match for 'slow queries:' in ".
	    "mysqladmin output\n\n:$mysqladmin_output"; 
	write_output;
	die $output;
    }
    dbg_print "Slow queries: $1";
    $slow_queries = $1;
}

# get_uptime: Extract "Uptime:[\t\ ]+dd days hh hours mm min ss sec
# from $mysqladmin_output, convert it all to seconds, and tie the 
# final value to $version

sub get_uptime {
    # Catch "xx day(s) xx hour(s) xx min xx sec" line from output.
    # mysqladmin outputs no data for days, hours, minutes until the
    # values is at least 1.
    if ($mysqladmin_output !~ /Uptime:\s+(\d+.+)/ ) {
	$output = "ERROR: could not find match for 'Uptime:' in ".
	    "mysqladmin output\n\n:$mysqladmin_output"; 
	write_output;
	die $output;
    }
    $uptime_s = $1;
    dbg_print "Caught Uptime line: '$uptime_s'";

    $uptime = $1;
}

# get_version: Extract "Server version[\t\ ]+x.yy.zz ... \n" from 
# $mysqladmin_output and tie the value to $version

sub get_version {
    if ($mysqladmin_output !~ /Server version[ \t]+([^\n]+)/ ) {
	$output = "ERROR: could find match for 'Server version' in\n".
	    "mysqladmin output\n\n:$mysqladmin_output";
	write_output;
	die $output;
    }
    dbg_print "Version: $1";
    $version = "MySQL version $1 $dispversion";
}

# write_output: write $output to stdout. If a logfile has been specified,
# output to that as well. In this implementation, it's expected that
# writing of output happens only once during the execution of the program.

sub write_output {
    # If we are to write to a log file, do it now.
    # The format of the log file is -- (dash-dash), timestamp, --, <nl>, 
    #   the output, <nl>
    if ($logfile) {
	($t_sec, $t_min, $t_hour, $t_mday, $t_mon, $t_year, 
	 $t_wday, $t_yday, $t_isdst) = localtime(time);
	unless (open(LOGFILE, ">>$logfile")) {
	    print STDERR "${Prog_name}: ".
	      "ERROR: Can't open logfile $logfile: $!";
	    exit(1);
	}
	$t_year += 1900;
	print LOGFILE "--$t_year-$t_mon-$t_mday $t_hour:$t_min:$t_sec--\n";
	print LOGFILE "$output\n";
	close LOGFILE;
	# hmmm... need to do something with these in order 
        # not to get warnings...
	$t_wday = 0; $t_yday = 0; $t_isdst = 0;
    }

    # Now, output to stdout:
    printf $output;
}

__END__

=head1 NAME

mrtg-mysql-load - a MySQL load analysis fetcher for MRTG

=head1 SYNOPSIS

B<mrtg-mysq-load>
[ B<-h> I<hostname> ]
[ B<-P> I<port> ]
[ B<-u> I<username> ]
[ B<-p> I<password> ]
[ B<-c> I</path/to/config/file> ]
[ B<-o> ]
[ B<-d> ]
[ B<-v> ]
[ B<-l> I</path/to/log/file> ]

=head1 DESCRIPTION

B<mrtg-mysql-load> runs B<mysqladmin> (which is assumed to be
available on the host), passing the I<-h, -P, -u> and I<-p> options
as they are given. On normal exit, B<mrtg-mysql-load> writes each
of the values of I<questions, slow queries, uptime> and I<version>
to stdout, one line per value.

It is meant to be called by the Multi Router Traffic Grapher (MRTG).

=head1 INSTALLING

Please see the file INSTALLING for examples.

=head1 OPTIONS

=over 8

=item B<-h>

the hostname to query (as I<-h> for mysqladmin).

=item B<-P>

The port on which to talk with the MySQL server
(as I<-P> for mysqladmin).

=item B<-u>

The MySQL username to use

=item B<-p>

The password to use when calling mysqladmin. Note that 
B<mrtg-mysql-load>, unlike I<mysqladmin>, doesn't care whether
you put whitespace between the B<-p> and the password or not. 

=item B<-c>

Read the values for host, port, username and password
from a configuration file. The configuration file consists of 
lines of the form I<var=value>,
where I<var> is one of 'host', 'port', 'username' or 'password' 
and I<value> is the (unquoted) corresponding value.
Blank lines may be added to the configuration file for readability,
and comments may be entered on separate lines starting with '#'.

If the same value is defined in the configuration file and on
the command line, the value on the command line takes precence.

=item B<-o>

Print the command that would have been used to call mysqladmin 
using the given options and configuration file, then exit.

=item B<-d>

Will print a lot of very ugly debugging info to stderr. Mostly good
for demonstrating the programmer's lack of trust in his Perl skills.

=item B<-v>

Print version information to stdout, then exit.

=item B<-l>

The name of an optional log file. This file will log all output (including
error messages) generated by the program to that file.

=back


=head1 RETURN VALUE

The program exits with an exit value 0, if it believes it was
successful.

=head1 USING CONFIGURATION FILES

When using B<mrtg-mysql-load> with B<mrtg>, there are several places
that may define the parameters used for connection. As noted above,
B<mrtg-mysql-load> is a wrapper around the B<mysqladmin> program.
B<mysqladmin> will first search for its parameters from the files 
B</etc/my.cnf> and B<~/my.cnf>, having options in the latter overriding
those of the first.

B<mrtg-mysql-load> uses the command line of B<mysqladmin> to specify
the parameters, and these will override any options set by B<mysqladmin>'s
configuration files. Thus, parameters set in B<mrtg-mysql-load>'s 
configuration file will override any options set in  
B</etc/my.cnf> and/or B<~/my.cnf>.

Any options set on the command line of B<mrtg-mysql-load> will override
any other options set by one of the previous methods. The command line
switches are most frequently used directly in the B<mrtg> config file,
when specifying the B<Target> option:

=over 4

=item C<Target[trgt.MySQL]: `/path/to/mrtg-mysql-load -opt1 val1 -opt2 val2 ... `>

=back

To sum up, the parameters used when specifying the parameters for
making a connection to the MySQL server may be specified in no 
less than 4 places, which are, in increasing order of precedence,

=over 4

=item *

/etc/my.cnf

=item *

~/my.cnf

=item *

a configuration file for B<mrtg-mysql-load> specified by the -c
parameter

=item *

switches set on the command line (or, more frequently, 
in the B<mrtg> config file).

=back

=head1 EXAMPLES

=over 4

=item B<mrtg-mysql-load>

This is the most basic way to call mrtg-mysql-load. It will work,
too, if run on the same host as mysqld and mysqld is configured to
let local users connect. (By default, it does, though I believe this
is a really stupid decision on the part of the developers. You 
really should set permissions in MySQL to disallow this.

=item B<mrtg-mysql-load -h <mysql.host.nameE<gt> -u <usernameE<gt> -p <passwordE<gt> >

The format you would most likely use for calling mrtg-mysql-load.

=back

=over 4

=item *

An example B<mrtg> configuration file, mrtg-cfg.example,
is provided in the document directory of the distribution.

=item *

An example B<mrtg-mysql-load> configuration file, 
mysql-load-cfg.example, is provided in the document directory of 
the distribution.

=back

=head1 FILES

B<mrtg-mysql-load> uses B<mysqladmin>, which is assumed to be
available in the path of the user running the program.

=head1 SEE ALSO

mrtg(1), mrtg-cfg.example, mysql-load-cfg.example

http://www.mrtg.org/

http://www.bitbybit.dk/mysqlfaq/mrtg-mysql-load/

=head1 DIAGNOSTICS

=over 4

=item ERROR: ignoring superfluous arguments

B<mrtg-mysql-load> doesn't take any command-line arguments. If you
get this message, you most likely forgot to specify a switch name.

=item ERROR: Can't open mysqladmin ...

B<mysqladmin> could not be run. Check that mysqladmin is available
and that the user running B<mrtg-mysql-load> has the proper permissions.

=item ERROR: mysqladmin returned an error message: ...

B<mysqladmin> did run, but hit a snag, probably when connecting to the
server. Check the displayed error message, and/or check whether you
have specified the correct host, username and password.

=item ERROR: Unable to read config file ...

B<mrtg-mysql-load> could not open the config file specified by the
B<-c> switch. Make sure the file exists and that the user running
mrtg-mysql-load has the permissions to read it.

=item Error: I don't understand line xx of E<lt>configfileE<gt>

There was an error on line xx of the configuration file. Each
line must either be blank, start with a '#' to mark it as a
comment, or have the form I<var=value>,
where I<var> is one of 'host', 'port', 'username' or 'password' 
and I<value> is the (unquoted) corresponding value.

=item ERROR: could not find match for 'xxx' in mysqladmin output ...

B<mysqladmin> returned some output, but it was not formatted as expected.
Your particular version of mysqladmin may not match the author's. 
The current version of B<mrtg-mysql-load> was written for mysql v. 3.23.35;
Please contact the author with more information, and he'll try to make
it match your particular version.

=back

=head1 RESTRICTIONS

B<mrtg-mysql-load> is a Perl script. It has been created with and
tested on Perl v. 5.6.0-i386-linux. Minimum requirement is Perl 5.003.

B<mrtg-mysql-load> relies on access to B<mysqladmin>. If mysqladmin is
not installed on the machine, or the user running mrtg-mysql-load
does not have the proper permissions to run mysqladmin, the program
will fail.

The <MySQL> server must be configured with a user capable of connecting
to the server and retrieve the information.

=head1 BUGS

The -t option which was available in previous versions, has now been
removed. It seems to have been removed from recent versions of mysqladmin,
and it caused a lot of trouble anyway -- at least according to users on 
the MySQL mailing list.

Most error messages are written to stdout as well as stderr. This may cause
some confusion, if the program is run from the console.

=head1 COPYRIGHT

Copyright (c) 2001 Carsten H. Pedersen <carsten.pedersen@bitbybit.dk>.
All Rights Reserved.

See the file COPYRIGHT in the distribution for the exact terms.

=head1 AUTHOR

Written by Carsten H. Pedersen E<lt>carsten.pedersen@bitbybit.dkE<gt>.

