aboutsummaryrefslogtreecommitdiff
path: root/setup/mysqlstat-setup.pl
blob: 6c8eecca7a94e44be692d2da4e1107ab4339f268 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#!/usr/bin/perl
# This file is part of Mysqlstat 
# Copyright (C) 2016 Sergey Poznyakoff
#
# Mysqlstat is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# Mysqlstat is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mysqlstat.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use DBI;
use Pod::Usage;
use Pod::Man;
use Getopt::Long qw(:config gnu_getopt no_ignore_case);
use File::Basename;
use File::Temp qw{tempfile};

=head1 NAME

mysqlstat-setup - sets up mysqlstat Net-SNMP module
    
=head1 SYNOPSIS

B<mysqlstat-setup>
[B<-f>]    
[B<-u> I<USER>]
[B<-p> I<PASSWORD>]
[B<-C> I<CONFDIR>]    
[B<-L> I<LIBDIR>]    
[B<--defaults-file=>I<FILE>]
[B<--force>]    
[B<--host=>I<HOST>]
[B<--user=>I<USER>]    
[B<--password=>I<PASSWORD>]
[B<--snmp-user=>I<USER>]
[B<--snmp-password=>I<PASSWORD>]
[B<--snmp-host=>I<HOSTNAME>]    
[B<--confdir> I<CONFDIR>]    
[B<--libdir> I<LIBDIR>]    
    
B<mysqlstat-setup>
[B<-h>]
[B<--help>]
[B<--usage>]    
    
=head1 DESCRIPTION

This utility configures B<snmpd>(8) and B<mysqld>(8) servers for using
the B<mysqlstat>(8) module.  It performs the following actions:

=over 4

=item 1. Creates MySQL user and grants it the necessary privileges.

By default the user B<snmp> is created with empty password.  This can be
controlled using the following command line options:

=over 8

=item B<--snmp-user=>I<USER>

Sets the MySQL user name to use.
    
=item B<--snmp-password=>I<PASSWORD>

Sets the MySQL password.
    
=item B<--snmp-host=>I<HOSTNAME>

Sets the source host name or IP address to use.  Default is B<localhost>.

=back

Credentials for connecting the MySQL server are read from file B<~/.my.cnf>,
if such file exists.  Another file may be given using the B<--defaults-file>
option.  Credentials can also be given from command line, using the options
B<--user>, B<--password> and B<--host>, although such usage is not recommended
for security reasons.    
    
=item 2. Creates the B</etc/snmp/mysqlstat.cnf> file.

This file defines the MySQL credentials to use when connecting to the
B<mysqld> server.  If that file already exists, B<mysqlstat-setup> assumes the
module has already been configured and refuses to run (unless given the
B<--force> option).

=item 3. Edits the B</etc/snmp/snmpd.conf> file.

The B<dlmod> statement is inserted, which instructs B<snmpd> to load the
module.

=back    
    
=head1 OPTIONS    

In most cases, it suffices to run the utility without any special options.
Nevertheless, the following options are provided that alter its behavior:
    
=over 4

=item B<-f>, B<--force>

Force operation even if it is detected that the B<mysqlstat> module has already
been set up.    
    
=item B<-u>, B<--user=>I<USER>

Connect to MySQL using I<USER> as user name.  This user must have B<GRANT>
privileges.

B<Note:> it is not the user that will be used by the B<mysqlstat>
module.  For that, see B<--snmp-user>, below.    
    
=item B<-p>, B<--password=>I<PASSWORD>

Connect to MySQL using the supplied password.

B<Note:> it is not the password that the B<mysqlstat> module will be using.
For that, see B<--snmp-password>, below.    
    
=item B<--host=>I<HOST>

Connect to MySQL server running at I<HOST> (hostname or IP address).  This will
also be stored in F</etc/snmp/mysqlstat.cnf> for use by the B<mysqlstat> module.

=item B<--defaults-file=>I<FILE>

Read MySQL access credentials from I<FILE>.  By default F<~/.my.cnf> is read
if it exists.  This way of supplying access credentials is preferred over
the command line options.    
    
=item B<--snmp-user=>I<USER>

MySQL user to be used by the B<mysqlstat> module.  Default is B<snmp>.
    
=item B<--snmp-password=>I<PASSWORD>

MySQL password to be used by the B<mysqlstat> module.  Default is empty
password.
    
=item B<--snmp-host=>I<HOSTNAME>

Hostname or IP address the B<mysqlstat> module will connect from.  This is
used when granting MySQL user privileges.    
    
=item B<-C>, B<--confdir=>I<DIR>

Assume I<DIR> instead of F</etc/snmp>.
    
=item B<-L>, B<--libdir=>I<LIBDIR>

Net-snmp modules are installed to I<LIBDIR>.
    
=back

The following options provide informational output:

=over 4

=item B<-h>

Print short help summary.
    
=item B<--help>

Print the manpage.    
    
=item B<--usage>

Show a terse command line usage summary.    

=back    
    
=head1 SEE ALSO

B<mysqlstat>(8).    
    
=cut

my $progname = basename($0);
my $progdescr = 'Set up mysqlstat module';

use constant EX_OK  => 0;
use constant EX_ERR => 1;

my $libdir = q{@DLMODDIR@};   # Directory where mysqlstat.so lives.
my $confdir = q{@CONFDIR@};   # SNMP configuration directory. 

my $mysql_user;           # MySQL administrator user
my $mysql_password;       # His password 
my $mysql_defaults_file;  # Options file to use (default ~/.my.cnf)
my $mysql_host;           # Host name or IP
my $mysql_port;           # Port the server is listening on.

my $snmp_user = 'snmp';       # MySQL user the plugin will be using.
my $snmp_password;            # MySQL password for $snmp_user
my $snmp_host = 'localhost';  # Host to use 
my $force;                # Force setup even if $confdir/mysqlstat.cnf is found.

my $sofile;               # Full pathname of mysqlstat.so   
my $mysqlstat_cnf;        # Full pathname of mysqlstat.cnf

my $owner_uid;            # Owner UID ...
my $owner_gid;            # ... and GID for the mysqlstat.cnf file.

sub error {
    my $text = shift;
    print STDERR "$progname: $text\n";
    if (@_) {
	print STDERR "\n";
	foreach $text (@_) {
	    print STDERR "  $text\n";
	}
	print STDERR "\n";	
    }
}

sub db_connect {
    my $arg;
    $arg .= ":host=$mysql_host" if defined $mysql_host;
    $arg .= ":port=$mysql_port" if defined $mysql_port;
    $arg .= ":;mysql_read_default_file=$mysql_defaults_file"
        if defined $mysql_defaults_file;
    my $my_cnf = "$ENV{HOME}/.my.cnf";
    if (!$arg
        or (!defined($mysql_user) and !defined($mysql_defaults_file))) {
        if (-r $my_cnf) {
            error("info: using mysql option file $my_cnf");
            $arg .= ":;mysql_read_default_file=$my_cnf";
        }
    }
    $arg = 'DBI:mysql'.($arg || ':');

    my $dbd = DBI->connect($arg, $mysql_user, $mysql_password,
			   { PrintError => 0, AutoCommit => 1 });
    unless ($dbd) {
	error("can't connect to MySQL server: ".$DBI::errstr,
          "This usually means that the credentials you supplied are incorrect.",
	  "The utility needs to connect to the MySQL server as a user with GRANT",
	  "privileges.  There are several ways of supplying the credentials:",
	  "",
	  "  1. In $my_cnf file.",
	  "  2. In another MySQL option file.",
	  "     In that case, use the option --defaults-file=FILENAME",
	  "  3. Via command line options --user, --password, and --host.",
	  "",
	  "Please verify that the supplied options are correct and rerun $progname.");
	exit EX_ERR;
    }
    return $dbd;
}

# db_modify(DB, QUERY, ARGS)
sub db_modify {
    my $dbd = shift;
    my $q = shift;
    my $sth = $dbd->prepare($q);
    my $res = $sth->execute(@_) or croak($sth->errstr);
    $sth->finish;
    return $res;
}

sub sql_create_user {
    my $dbd = db_connect();
    my $q = q{GRANT PROCESS, REPLICATION CLIENT ON *.* TO ?@?};
    my @args = ($snmp_user, $snmp_host);
    if ($snmp_password) {
	push @args, $snmp_password;
	$q .= ' IDENTIFIED BY ?';
    }
    db_modify($dbd, $q, @args);
    db_modify($dbd, 'FLUSH PRIVILEGES');
    $dbd->disconnect;
}

sub edit_cnf {
    my $m = umask(077);
    open(my $fd, '>', $mysqlstat_cnf)
	or die "can't open $mysqlstat_cnf for writing: $!";
    print $fd "[mysqlstat]\n";
    print $fd "user=$snmp_user\n";
    print $fd "password=$snmp_password\n" if $snmp_password;
    print $fd "host=$mysql_host\n" if $mysql_host and $mysql_host ne 'localhost';
    chown $owner_uid, $owner_gid, $fd;
    close $fd;
    umask($m);
}

sub backup {
    my $name = shift;
    my $bkname = "${name}~";
    backup($bkname) if -f $bkname;
    unless (rename($name, $bkname)) {
	error("can't create backup file $bkname: $!");
	return 0;
    }
    return 1;
}

sub edit_snmp_conf {
    my $snmpd_conf = "$confdir/snmpd.conf";
    $snmpd_conf = readlink $snmpd_conf if -l $snmpd_conf;

    open(my $fd, '<', $snmpd_conf)
	or die "can't open $snmpd_conf for reading: $!";
    
    my $line = 0;
    my $dlmod_line;
    while (<$fd>) {
	++$line;
	chomp;
	s/^\s+//;
	next if /^#/;
	if (/^dlmod\s/) {
	    my @a = split /\s+/;
	    if ($a[$#a] eq $sofile) {
		error("info: $sofile already loaded in $snmpd_conf:$line");
		return 1;
	    }
	    $dlmod_line = $line;
	}
    }
    seek $fd, 0, 0;
    
    my ($ofd, $filename) = tempfile('snmpd.XXXXXX', DIR => $confdir);
    if ($dlmod_line) {
	$line = 0;
	while (<$fd>) {
	    print $ofd $_;
	    if (++$line == $dlmod_line) {
		print $ofd "# This line was added by $progname\n";
		print $ofd "dlmod mysqlstat_mib $sofile\n";
	    }
	}
    } else {
	while (<$fd>) {
	    print $ofd $_;
	}
	print $ofd "# This line was added by $progname\n";
	print $ofd "dlmod mysqlstat_mib $sofile\n";
    }
    close $fd;
    close $ofd;

    unless (backup($snmpd_conf)) {
	error("can't preserve backup copy of $snmpd_conf");
	error("updated configuration left in file $filename");
    } elsif (not rename($filename, $snmpd_conf)) {
	error("failed to rename $filename to $snmpd_conf");
	error("updated configuration left in file $filename");
    }
}

# 
GetOptions("h" => sub {
               pod2usage(-message => "$progname: $progdescr",
		         -exitstatus => EX_OK);
	   },
	   "help" => sub {
	       pod2usage(-exitstatus => EX_OK, -verbose => 2);
	   },
	   "usage" => sub {
	       pod2usage(-exitstatus => EX_OK, -verbose => 0);
	   },
	   "user|u=s" => \$mysql_user,
	   "password|p=s" => \$mysql_password,
	   "defaults-file=s" => \$mysql_defaults_file,
	   "host=s" => \$mysql_host,
	   "snmp-user=s" => \$snmp_user,
	   "snmp-password=s" => \$snmp_password,
	   "snmp-host=s" => \$snmp_host,
	   "confdir|C=s" => \$confdir,
	   "libdir|L=s" => \$libdir,
	   "force|f" => \$force
    ) or exit(EX_ERR);

unless ($< == 0) {
    error("must be run as root");
    exit EX_ERR;
}

unless ($libdir =~ m#^/#) {
    error('NetSNMP library directory is not set',
      "It appears you invoked a copy of $progname that hasn't been installed.",
      "If you are confident in what you're doing, then please use",
      "the --libdir=DIR option to inform the program about the location of the",
      "library directory.  Otherwise, please use the program that has been",
      "installed properly.");
    exit EX_ERR;
}

unless ($confdir =~ m#^/#) {
    error('NetSNMP configuration directory is not set',
      "It appears you invoked a copy of $progname that hasn't been installed.",
      "If you are confident in what you're doing, then please use",
      "the --confdir=DIR option to inform the program about the location of the",
      "configuration directory.  Otherwise, please use the program that has been",
      "installed properly.");
    exit EX_ERR;
}

$sofile = "$libdir/mysqlstat.so";

unless (-f $sofile) {
    error("the library $sofile is not found");
    exit EX_ERR;
}

$mysqlstat_cnf = "$confdir/mysqlstat.cnf";
if (-e $mysqlstat_cnf and not $force) {
    error("file $mysqlstat_cnf already exists",
	  "If you are sure you wan't to re-setup mysqlstat, use the --force option, e.g.:",
	  "  $progname --force");
    exit EX_ERR;
}

unless (-d $confdir) {
    error("no such directory: $confdir");
    exit EX_ERR;
}

unless (-r "$confdir/snmpd.conf") {
    error("the file $confdir/snmpd.conf does not exist or is not readable",
	  "If NetSNMP configuration files are located in another directory,",
	  "then reconfigure mysqlstat with the --with-snmp-config-dir=DIR option",
	  "and rerun $progname");
    exit EX_ERR;
}
    
my @st = stat "$confdir/snmpd.conf"
    or die "can't stat $confdir/snmpd.conf: $!";
($owner_uid, $owner_gid) = @st[4..5];

# 1. Create MySQL user & grant it the necessary privs.
sql_create_user;
# 2. Edit $CONFDIR/mysqlstat.cnf
edit_cnf;    
# 3. Edit snmpd.conf
edit_snmp_conf;

print "$progname: Done.\n";
print "$progname: Please restart snmpd in order for changes to make effect.\n";

Return to:

Send suggestions and report system problems to the System administrator.