Debian Codegraph @

check_mysql_health/check_mysql_health-2.2.2/plugins-scripts/check_mysql_health.pl

raw
1
2 package main;
3
4 use strict;
5 use Getopt::Long qw(:config no_ignore_case);
6 use File::Basename;
7 use lib dirname($0);
8 use Nagios::DBD::MySQL::Server;
9 use Nagios::DBD::MySQL::Cluster;
10
11
12 my %ERRORS=( OK => 0, WARNING => 1, CRITICAL => 2, UNKNOWN => 3 );
13 my %ERRORCODES=( 0 => 'OK', 1 => 'WARNING', 2 => 'CRITICAL', 3 => 'UNKNOWN' );
14
15 use vars qw ($PROGNAME $REVISION $CONTACT $TIMEOUT $STATEFILESDIR $needs_restart %commandline);
16
17 $PROGNAME = "check_mysql_health";
18 $REVISION = '$Revision: #PACKAGE_VERSION# $';
19 $CONTACT = '[email protected]';
20 $TIMEOUT = 60;
21 $STATEFILESDIR = '#STATEFILES_DIR#';
22 $needs_restart = 0;
23
24 my @modes = (
25 ['server::connectiontime',
26 'connection-time', undef,
27 'Time to connect to the server' ],
28 ['server::uptime',
29 'uptime', undef,
30 'Time the server is running' ],
31 ['server::instance::connectedthreads',
32 'threads-connected', undef,
33 'Number of currently open connections' ],
34 ['server::instance::threadcachehitrate',
35 'threadcache-hitrate', undef,
36 'Hit rate of the thread-cache' ],
37 ['server::instance::createdthreads',
38 'threads-created', undef,
39 'Number of threads created per sec' ],
40 ['server::instance::runningthreads',
41 'threads-running', undef,
42 'Number of currently running threads' ],
43 ['server::instance::cachedthreads',
44 'threads-cached', undef,
45 'Number of currently cached threads' ],
46 ['server::instance::abortedconnects',
47 'connects-aborted', undef,
48 'Number of aborted connections per sec' ],
49 ['server::instance::abortedclients',
50 'clients-aborted', undef,
51 'Number of aborted connections (because the client died) per sec' ],
52 ['server::instance::replication::slavelag',
53 'slave-lag', ['replication-slave-lag'],
54 'Seconds behind master' ],
55 ['server::instance::replication::slaveiorunning',
56 'slave-io-running', ['replication-slave-io-running'],
57 'Slave io running: Yes' ],
58 ['server::instance::replication::slavesqlrunning',
59 'slave-sql-running', ['replication-slave-sql-running'],
60 'Slave sql running: Yes' ],
61 ['server::instance::querycachehitrate',
62 'qcache-hitrate', ['querycache-hitrate'],
63 'Query cache hitrate' ],
64 ['server::instance::querycachelowmemprunes',
65 'qcache-lowmem-prunes', ['querycache-lowmem-prunes'],
66 'Query cache entries pruned because of low memory' ],
67 ['server::instance::myisam::keycache::hitrate',
68 'keycache-hitrate', ['myisam-keycache-hitrate'],
69 'MyISAM key cache hitrate' ],
70 ['server::instance::innodb::bufferpool::hitrate',
71 'bufferpool-hitrate', ['innodb-bufferpool-hitrate'],
72 'InnoDB buffer pool hitrate' ],
73 ['server::instance::innodb::bufferpool::waitfree',
74 'bufferpool-wait-free', ['innodb-bufferpool-wait-free'],
75 'InnoDB buffer pool waits for clean page available' ],
76 ['server::instance::innodb::logwaits',
77 'log-waits', ['innodb-log-waits'],
78 'InnoDB log waits because of a too small log buffer' ],
79 ['server::instance::tablecachehitrate',
80 'tablecache-hitrate', undef,
81 'Table cache hitrate' ],
82 ['server::instance::tablelockcontention',
83 'table-lock-contention', undef,
84 'Table lock contention' ],
85 ['server::instance::tableindexusage',
86 'index-usage', undef,
87 'Usage of indices' ],
88 ['server::instance::tabletmpondisk',
89 'tmp-disk-tables', undef,
90 'Percent of temp tables created on disk' ],
91 ['server::instance::needoptimize',
92 'table-fragmentation', undef,
93 'Show tables which should be optimized' ],
94 ['server::instance::openfiles',
95 'open-files', undef,
96 'Percent of opened files' ],
97 ['server::instance::slowqueries',
98 'slow-queries', undef,
99 'Slow queries' ],
100 ['server::instance::longprocs',
101 'long-running-procs', undef,
102 'long running processes' ],
103 ['cluster::ndbdrunning',
104 'cluster-ndbd-running', undef,
105 'ndnd nodes are up and running' ],
106 ['server::sql',
107 'sql', undef,
108 'any sql command returning a single number' ],
109 );
110
111 # rrd data store names are limited to 19 characters
112 my %labels = (
113 bufferpool_hitrate => {
114 groundwork => 'bp_hitrate',
115 },
116 bufferpool_hitrate_now => {
117 groundwork => 'bp_hitrate_now',
118 },
119 bufferpool_free_waits_rate => {
120 groundwork => 'bp_freewaits',
121 },
122 innodb_log_waits_rate => {
123 groundwork => 'inno_log_waits',
124 },
125 keycache_hitrate => {
126 groundwork => 'kc_hitrate',
127 },
128 keycache_hitrate_now => {
129 groundwork => 'kc_hitrate_now',
130 },
131 threads_created_per_sec => {
132 groundwork => 'thrds_creat_per_s',
133 },
134 connects_aborted_per_sec => {
135 groundwork => 'conn_abrt_per_s',
136 },
137 clients_aborted_per_sec => {
138 groundwork => 'clnt_abrt_per_s',
139 },
140 thread_cache_hitrate => {
141 groundwork => 'tc_hitrate',
142 },
143 thread_cache_hitrate_now => {
144 groundwork => 'tc_hitrate_now',
145 },
146 qcache_lowmem_prunes_rate => {
147 groundwork => 'qc_lowm_prnsrate',
148 },
149 slow_queries_rate => {
150 groundwork => 'slow_q_rate',
151 },
152 tablecache_hitrate => {
153 groundwork => 'tac_hitrate',
154 },
155 tablecache_fillrate => {
156 groundwork => 'tac_fillrate',
157 },
158 tablelock_contention => {
159 groundwork => 'tl_contention',
160 },
161 tablelock_contention_now => {
162 groundwork => 'tl_contention_now',
163 },
164 pct_tmp_table_on_disk => {
165 groundwork => 'tmptab_on_disk',
166 },
167 pct_tmp_table_on_disk_now => {
168 groundwork => 'tmptab_on_disk_now',
169 },
170 );
171
172 sub print_usage () {
173 print <<EOUS;
174 Usage:
175 $PROGNAME [-v] [-t <timeout>] [[--hostname <hostname>]
176 [--port <port> | --socket <socket>]
177 --username <username> --password <password>] --mode <mode>
178 [--method mysql]
179 $PROGNAME [-h | --help]
180 $PROGNAME [-V | --version]
181
182 Options:
183 --hostname
184 the database server's hostname
185 --port
186 the database's port. (default: 3306)
187 --socket
188 the database's unix socket.
189 --username
190 the mysql db user
191 --password
192 the mysql db user's password
193 --database
194 the database's name. (default: information_schema)
195 --replication-user
196 the database's replication user name (default: replication)
197 --warning
198 the warning range
199 --critical
200 the critical range
201 --mode
202 the mode of the plugin. select one of the following keywords:
203 EOUS
204 my $longest = length ((reverse sort {length $a <=> length $b} map { $_->[1] } @modes)[0]);
205 my $format = " %-".
206 (length ((reverse sort {length $a <=> length $b} map { $_->[1] } @modes)[0])).
207 "s\t(%s)\n";
208 foreach (@modes) {
209 printf $format, $_->[1], $_->[3];
210 }
211 printf "\n";
212 print <<EOUS;
213 --name
214 the name of something that needs to be further specified,
215 currently only used for sql statements
216 --name2
217 if name is a sql statement, this statement would appear in
218 the output and the performance data. This can be ugly, so
219 name2 can be used to appear instead.
220 --regexp
221 if this parameter is used, name will be interpreted as a
222 regular expression.
223 --units
224 one of %, KB, MB, GB. This is used for a better output of mode=sql
225 and for specifying thresholds for mode=tablespace-free
226 --labelformat
227 one of pnp4nagios (which is the default) or groundwork.
228 It is used to shorten performance data labels to 19 characters.
229
230 In mode sql you can url-encode the statement so you will not have to mess
231 around with special characters in your Nagios service definitions.
232 Instead of
233 --name="select count(*) from v\$session where status = 'ACTIVE'"
234 you can say
235 --name=select%20count%28%2A%29%20from%20v%24session%20where%20status%20%3D%20%27ACTIVE%27
236 For your convenience you can call check_mysql_health with the --mode encode
237 option and it will encode the standard input.
238
239 You can find the full documentation at
240 https://labs.consol.de/nagios/check_mysql_health/
241
242 EOUS
243
244 }
245
246 sub print_help () {
247 print "Copyright (c) 2009 Gerhard Lausser\n\n";
248 print "\n";
249 print " Check various parameters of MySQL databases \n";
250 print "\n";
251 print_usage();
252 support();
253 }
254
255
256 sub print_revision ($$) {
257 my $commandName = shift;
258 my $pluginRevision = shift;
259 $pluginRevision =~ s/^\$Revision: //;
260 $pluginRevision =~ s/ \$\s*$//;
261 print "$commandName ($pluginRevision)\n";
262 print "This nagios plugin comes with ABSOLUTELY NO WARRANTY. You may redistribute\ncopies of this plugin under the terms of the GNU General Public License.\n";
263 }
264
265 sub support () {
266 my $support='Send email to [email protected] if you have questions\nregarding use of this software. \nPlease include version information with all correspondence (when possible,\nuse output from the --version option of the plugin itself).\n';
267 $support =~ s/@/\@/g;
268 $support =~ s/\\n/\n/g;
269 print $support;
270 }
271
272 sub contact_author ($$) {
273 my $item = shift;
274 my $strangepattern = shift;
275 if ($commandline{verbose}) {
276 printf STDERR
277 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n".
278 "You found a line which is not recognized by %s\n".
279 "This means, certain components of your system cannot be checked.\n".
280 "Please contact the author %s and\nsend him the following output:\n\n".
281 "%s /%s/\n\nThank you!\n".
282 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
283 $PROGNAME, $CONTACT, $item, $strangepattern;
284 }
285 }
286
287 %commandline = ();
288 my @params = (
289 "timeout|t=i",
290 "version|V",
291 "help|h",
292 "verbose|v",
293 "debug|d",
294 "hostname|H=s",
295 "database=s",
296 "port|P=s",
297 "socket|S=s",
298 "username|u=s",
299 "password|p=s",
300 "replication-user=s",
301 "mycnf=s",
302 "mycnfgroup=s",
303 "mode|m=s",
304 "name=s",
305 "name2=s",
306 "regexp",
307 "perfdata",
308 "warning=s",
309 "critical=s",
310 "dbthresholds:s",
311 "absolute|a",
312 "environment|e=s%",
313 "negate=s%",
314 "method=s",
315 "runas|r=s",
316 "scream",
317 "shell",
318 "eyecandy",
319 "encode",
320 "units=s",
321 "lookback=i",
322 "3",
323 "statefilesdir=s",
324 "with-mymodules-dyn-dir=s",
325 "report=s",
326 "labelformat=s",
327 "extra-opts:s");
328
329 if (! GetOptions(\%commandline, @params)) {
330 print_help();
331 exit $ERRORS{UNKNOWN};
332 }
333
334 if (exists $commandline{'extra-opts'}) {
335 # read the extra file and overwrite other parameters
336 my $extras = Extraopts->new(file => $commandline{'extra-opts'}, commandline =>
337 \%commandline);
338 if (! $extras->is_valid()) {
339 printf "extra-opts are not valid: %s\n", $extras->{errors};
340 exit $ERRORS{UNKNOWN};
341 } else {
342 $extras->overwrite();
343 }
344 }
345
346 if (exists $commandline{version}) {
347 print_revision($PROGNAME, $REVISION);
348 exit $ERRORS{OK};
349 }
350
351 if (exists $commandline{help}) {
352 print_help();
353 exit $ERRORS{OK};
354 } elsif (! exists $commandline{mode}) {
355 printf "Please select a mode\n";
356 print_help();
357 exit $ERRORS{OK};
358 }
359
360 if ($commandline{mode} eq "encode") {
361 my $input = <>;
362 chomp $input;
363 $input =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
364 printf "%s\n", $input;
365 exit $ERRORS{OK};
366 }
367
368 if (exists $commandline{3}) {
369 $ENV{NRPE_MULTILINESUPPORT} = 1;
370 }
371
372 if (exists $commandline{timeout}) {
373 $TIMEOUT = $commandline{timeout};
374 }
375
376 if (exists $commandline{verbose}) {
377 $DBD::MySQL::Server::verbose = exists $commandline{verbose};
378 }
379
380 if (exists $commandline{scream}) {
381 # $DBD::MySQL::Server::hysterical = exists $commandline{scream};
382 }
383
384 if (exists $commandline{method}) {
385 # snmp or mysql cmdline
386 } else {
387 $commandline{method} = "dbi";
388 }
389
390 if (exists $commandline{report}) {
391 # short, long, html
392 } else {
393 $commandline{report} = "long";
394 }
395
396 if (exists $commandline{labelformat}) {
397 # groundwork
398 } else {
399 $commandline{labelformat} = "pnp4nagios";
400 }
401
402 if (exists $commandline{'with-mymodules-dyn-dir'}) {
403 $DBD::MySQL::Server::my_modules_dyn_dir = $commandline{'with-mymodules-dyn-dir'};
404 } else {
405 $DBD::MySQL::Server::my_modules_dyn_dir = '#MYMODULES_DYN_DIR#';
406 }
407
408 if (exists $commandline{environment}) {
409 # if the desired environment variable values are different from
410 # the environment of this running script, then a restart is necessary.
411 # because setting $ENV does _not_ change the environment of the running script.
412 foreach (keys %{$commandline{environment}}) {
413 if ((! $ENV{$_}) || ($ENV{$_} ne $commandline{environment}->{$_})) {
414 $needs_restart = 1;
415 $ENV{$_} = $commandline{environment}->{$_};
416 printf STDERR "new %s=%s forces restart\n", $_, $ENV{$_}
417 if $DBD::MySQL::Server::verbose;
418 }
419 }
420 # e.g. called with --runas dbnagio. shlib_path environment variable is stripped
421 # during the sudo.
422 # so the perl interpreter starts without a shlib_path. but --runas cares for
423 # a --environment shlib_path=...
424 # so setting the environment variable in the code above and restarting the
425 # perl interpreter will help it find shared libs
426 }
427
428 if (exists $commandline{runas}) {
429 # remove the runas parameter
430 # exec sudo $0 ... the remaining parameters
431 $needs_restart = 1;
432 # if the calling script has a path for shared libs and there is no --environment
433 # parameter then the called script surely needs the variable too.
434 foreach my $important_env (qw(LD_LIBRARY_PATH SHLIB_PATH
435 ORACLE_HOME TNS_ADMIN ORA_NLS ORA_NLS33 ORA_NLS10)) {
436 if ($ENV{$important_env} && ! scalar(grep { /^$important_env=/ }
437 keys %{$commandline{environment}})) {
438 $commandline{environment}->{$important_env} = $ENV{$important_env};
439 printf STDERR "add important --environment %s=%s\n",
440 $important_env, $ENV{$important_env} if $DBD::MySQL::Server::verbose;
441 }
442 }
443 }
444
445 if ($needs_restart) {
446 my @newargv = ();
447 my $runas = undef;
448 if (exists $commandline{runas}) {
449 $runas = $commandline{runas};
450 delete $commandline{runas};
451 }
452 foreach my $option (keys %commandline) {
453 if (grep { /^$option/ && /=/ } @params) {
454 if (ref ($commandline{$option}) eq "HASH") {
455 foreach (keys %{$commandline{$option}}) {
456 push(@newargv, sprintf "--%s", $option);
457 push(@newargv, sprintf "%s=%s", $_, $commandline{$option}->{$_});
458 }
459 } else {
460 push(@newargv, sprintf "--%s", $option);
461 push(@newargv, sprintf "%s", $commandline{$option});
462 }
463 } else {
464 push(@newargv, sprintf "--%s", $option);
465 }
466 }
467 if ($runas) {
468 exec "sudo", "-S", "-u", $runas, $0, @newargv;
469 } else {
470 exec $0, @newargv;
471 # this makes sure that even a SHLIB or LD_LIBRARY_PATH are set correctly
472 # when the perl interpreter starts. Setting them during runtime does not
473 # help loading e.g. libclntsh.so
474 }
475 exit;
476 }
477
478 if (exists $commandline{shell}) {
479 # forget what you see here.
480 system("/bin/sh");
481 }
482
483 if (! exists $commandline{statefilesdir}) {
484 if (exists $ENV{OMD_ROOT}) {
485 $commandline{statefilesdir} = $ENV{OMD_ROOT}."/var/tmp/check_mysql_health";
486 } else {
487 $commandline{statefilesdir} = $STATEFILESDIR;
488 }
489 }
490
491 if (exists $commandline{name}) {
492 if ($^O =~ /MSWin/ && $commandline{name} =~ /^'(.*)'$/) {
493 # putting arguments in single ticks under Windows CMD leaves the ' intact
494 # we remove them
495 $commandline{name} = $1;
496 }
497 # objects can be encoded like an url
498 # with s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
499 if (($commandline{mode} ne "sql") ||
500 (($commandline{mode} eq "sql") &&
501 ($commandline{name} =~ /select%20/i))) { # protect ... like '%cac%' ... from decoding
502 $commandline{name} =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
503 }
504 if ($commandline{name} =~ /^0$/) {
505 # without this, $params{selectname} would be treated like undef
506 $commandline{name} = "00";
507 }
508 }
509
510 $SIG{'ALRM'} = sub {
511 printf "UNKNOWN - %s timed out after %d seconds\n", $PROGNAME, $TIMEOUT;
512 exit $ERRORS{UNKNOWN};
513 };
514 alarm($TIMEOUT);
515
516 my $nagios_level = $ERRORS{UNKNOWN};
517 my $nagios_message = "";
518 my $perfdata = "";
519 if ($commandline{mode} =~ /^my-([^\-.]+)/) {
520 my $param = $commandline{mode};
521 $param =~ s/\-/::/g;
522 push(@modes, [$param, $commandline{mode}, undef, 'my extension']);
523 } elsif ((! grep { $commandline{mode} eq $_ } map { $_->[1] } @modes) &&
524 (! grep { $commandline{mode} eq $_ } map { defined $_->[2] ? @{$_->[2]} : () } @modes)) {
525 printf "UNKNOWN - mode %s\n", $commandline{mode};
526 print_usage();
527 exit 3;
528 }
529 my %params = (
530 timeout => $TIMEOUT,
531 mode => (
532 map { $_->[0] }
533 grep {
534 ($commandline{mode} eq $_->[1]) ||
535 ( defined $_->[2] && grep { $commandline{mode} eq $_ } @{$_->[2]})
536 } @modes
537 )[0],
538 cmdlinemode => $commandline{mode},
539 method => $commandline{method} ||
540 $ENV{NAGIOS__SERVICEMYSQL_METH} ||
541 $ENV{NAGIOS__HOSTMYSQL_METH} || 'dbi',
542 hostname => $commandline{hostname} ||
543 $ENV{NAGIOS__SERVICEMYSQL_HOST} ||
544 $ENV{NAGIOS__HOSTMYSQL_HOST} || 'localhost',
545 database => $commandline{database} ||
546 $ENV{NAGIOS__SERVICEMYSQL_DATABASE} ||
547 $ENV{NAGIOS__HOSTMYSQL_DATABASE} || 'information_schema',
548 port => $commandline{port} || (($commandline{mode} =~ /^cluster/) ?
549 ($ENV{NAGIOS__SERVICENDBMGM_PORT} || $ENV{NAGIOS__HOSTNDBMGM_PORT} || 1186) :
550 ($ENV{NAGIOS__SERVICEMYSQL_PORT} || $ENV{NAGIOS__HOSTMYSQL_PORT} || 3306)),
551 socket => $commandline{socket} ||
552 $ENV{NAGIOS__SERVICEMYSQL_SOCKET} ||
553 $ENV{NAGIOS__HOSTMYSQL_SOCKET},
554 username => $commandline{username} ||
555 $ENV{NAGIOS__SERVICEMYSQL_USER} ||
556 $ENV{NAGIOS__HOSTMYSQL_USER},
557 password => $commandline{password} ||
558 $ENV{NAGIOS__SERVICEMYSQL_PASS} ||
559 $ENV{NAGIOS__HOSTMYSQL_PASS},
560 replication_user => $commandline{'replication-user'} || 'replication',
561 mycnf => $commandline{mycnf} ||
562 $ENV{NAGIOS__SERVICEMYSQL_MYCNF} ||
563 $ENV{NAGIOS__HOSTMYSQL_MYCNF},
564 mycnfgroup => $commandline{mycnfgroup} ||
565 $ENV{NAGIOS__SERVICEMYSQL_MYCNFGROUP} ||
566 $ENV{NAGIOS__HOSTMYSQL_MYCNFGROUP},
567 warningrange => $commandline{warning},
568 criticalrange => $commandline{critical},
569 dbthresholds => $commandline{dbthresholds},
570 absolute => $commandline{absolute},
571 lookback => $commandline{lookback},
572 selectname => $commandline{name} || $commandline{tablespace} || $commandline{datafile},
573 regexp => $commandline{regexp},
574 name => $commandline{name},
575 name2 => $commandline{name2} || $commandline{name},
576 units => $commandline{units},
577 lookback => $commandline{lookback} || 0,
578 eyecandy => $commandline{eyecandy},
579 statefilesdir => $commandline{statefilesdir},
580 verbose => $commandline{verbose},
581 report => $commandline{report},
582 labelformat => $commandline{labelformat},
583 negate => $commandline{negate},
584 );
585
586 my $server = undef;
587 my $cluster = undef;
588
589 if ($params{mode} =~ /^(server|my)/) {
590 $server = DBD::MySQL::Server->new(%params);
591 $server->nagios(%params);
592 $server->calculate_result(\%labels);
593 $nagios_message = $server->{nagios_message};
594 $nagios_level = $server->{nagios_level};
595 $perfdata = $server->{perfdata};
596 } elsif ($params{mode} =~ /^cluster/) {
597 $cluster = DBD::MySQL::Cluster->new(%params);
598 $cluster->nagios(%params);
599 $cluster->calculate_result(\%labels);
600 $nagios_message = $cluster->{nagios_message};
601 $nagios_level = $cluster->{nagios_level};
602 $perfdata = $cluster->{perfdata};
603 }
604
605 printf "%s - %s", $ERRORCODES{$nagios_level}, $nagios_message;
606 printf " | %s", $perfdata if $perfdata;
607 printf "\n";
608 exit $nagios_level;
609
610
611 __END__
612
613