Merge pull request #2008 from waja/2.4.0
[monitoring-plugins.git] / plugins / check_mysql.c
blob6a7daf11a12feb7bcaafc04edf0423f44071158e
1 /*****************************************************************************
2 *
3 * Monitoring check_mysql plugin
4 *
5 * License: GPL
6 * Copyright (c) 1999 Didi Rieder (adrieder@sbox.tu-graz.ac.at)
7 * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
8 * Copyright (c) 1999-2011 Monitoring Plugins Development Team
9 *
10 * Description:
12 * This file contains the check_mysql plugin
14 * This program tests connections to a mysql server
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 *****************************************************************************/
33 const char *progname = "check_mysql";
34 const char *copyright = "1999-2011";
35 const char *email = "devel@monitoring-plugins.org";
37 #define SLAVERESULTSIZE 96
39 #include "common.h"
40 #include "utils.h"
41 #include "utils_base.h"
42 #include "netutils.h"
44 #include <mysql.h>
45 #include <mysqld_error.h>
46 #include <errmsg.h>
48 char *db_user = NULL;
49 char *db_host = NULL;
50 char *db_socket = NULL;
51 char *db_pass = NULL;
52 char *db = NULL;
53 char *ca_cert = NULL;
54 char *ca_dir = NULL;
55 char *cert = NULL;
56 char *key = NULL;
57 char *ciphers = NULL;
58 bool ssl = false;
59 char *opt_file = NULL;
60 char *opt_group = NULL;
61 unsigned int db_port = MYSQL_PORT;
62 int check_slave = 0, warn_sec = 0, crit_sec = 0;
63 int ignore_auth = 0;
64 int verbose = 0;
66 static double warning_time = 0;
67 static double critical_time = 0;
69 #define LENGTH_METRIC_UNIT 6
70 static const char *metric_unit[LENGTH_METRIC_UNIT] = {
71 "Open_files",
72 "Open_tables",
73 "Qcache_free_memory",
74 "Qcache_queries_in_cache",
75 "Threads_connected",
76 "Threads_running"
79 #define LENGTH_METRIC_COUNTER 9
80 static const char *metric_counter[LENGTH_METRIC_COUNTER] = {
81 "Connections",
82 "Qcache_hits",
83 "Qcache_inserts",
84 "Qcache_lowmem_prunes",
85 "Qcache_not_cached",
86 "Queries",
87 "Questions",
88 "Table_locks_waited",
89 "Uptime"
92 #define MYSQLDUMP_THREADS_QUERY "SELECT COUNT(1) mysqldumpThreads FROM information_schema.processlist WHERE info LIKE 'SELECT /*!40001 SQL_NO_CACHE */%'"
94 thresholds *my_threshold = NULL;
96 int process_arguments (int, char **);
97 int validate_arguments (void);
98 void print_help (void);
99 void print_usage (void);
102 main (int argc, char **argv)
105 MYSQL mysql;
106 MYSQL_RES *res;
107 MYSQL_ROW row;
109 /* should be status */
111 char *result = NULL;
112 char *error = NULL;
113 char slaveresult[SLAVERESULTSIZE] = { 0 };
114 char* perf;
116 perf = strdup ("");
118 setlocale (LC_ALL, "");
119 bindtextdomain (PACKAGE, LOCALEDIR);
120 textdomain (PACKAGE);
122 /* Parse extra opts if any */
123 argv=np_extra_opts (&argc, argv, progname);
125 if (process_arguments (argc, argv) == ERROR)
126 usage4 (_("Could not parse arguments"));
128 /* initialize mysql */
129 mysql_init (&mysql);
131 if (opt_file != NULL)
132 mysql_options(&mysql,MYSQL_READ_DEFAULT_FILE,opt_file);
134 if (opt_group != NULL)
135 mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,opt_group);
136 else
137 mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"client");
139 if (ssl)
140 mysql_ssl_set(&mysql,key,cert,ca_cert,ca_dir,ciphers);
141 /* establish a connection to the server and error checking */
142 if (!mysql_real_connect(&mysql,db_host,db_user,db_pass,db,db_port,db_socket,0)) {
143 /* Depending on internally-selected auth plugin MySQL might return */
144 /* ER_ACCESS_DENIED_NO_PASSWORD_ERROR or ER_ACCESS_DENIED_ERROR. */
145 /* Semantically these errors are the same. */
146 if (ignore_auth && (mysql_errno (&mysql) == ER_ACCESS_DENIED_ERROR || mysql_errno (&mysql) == ER_ACCESS_DENIED_NO_PASSWORD_ERROR))
148 printf("MySQL OK - Version: %s (protocol %d)\n",
149 mysql_get_server_info(&mysql),
150 mysql_get_proto_info(&mysql)
152 mysql_close (&mysql);
153 return STATE_OK;
155 else if (mysql_errno (&mysql) == CR_UNKNOWN_HOST)
156 die (STATE_WARNING, "%s\n", mysql_error (&mysql));
157 else if (mysql_errno (&mysql) == CR_VERSION_ERROR)
158 die (STATE_WARNING, "%s\n", mysql_error (&mysql));
159 else if (mysql_errno (&mysql) == CR_OUT_OF_MEMORY)
160 die (STATE_WARNING, "%s\n", mysql_error (&mysql));
161 else if (mysql_errno (&mysql) == CR_IPSOCK_ERROR)
162 die (STATE_WARNING, "%s\n", mysql_error (&mysql));
163 else if (mysql_errno (&mysql) == CR_SOCKET_CREATE_ERROR)
164 die (STATE_WARNING, "%s\n", mysql_error (&mysql));
165 else
166 die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
169 /* get the server stats */
170 result = strdup (mysql_stat (&mysql));
172 /* error checking once more */
173 if (mysql_error (&mysql)) {
174 if (mysql_errno (&mysql) == CR_SERVER_GONE_ERROR)
175 die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
176 else if (mysql_errno (&mysql) == CR_SERVER_LOST)
177 die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
178 else if (mysql_errno (&mysql) == CR_UNKNOWN_ERROR)
179 die (STATE_CRITICAL, "%s\n", mysql_error (&mysql));
182 /* try to fetch some perf data */
183 if (mysql_query (&mysql, "show global status") == 0) {
184 if ( (res = mysql_store_result (&mysql)) == NULL) {
185 error = strdup(mysql_error(&mysql));
186 mysql_close (&mysql);
187 die (STATE_CRITICAL, _("status store_result error: %s\n"), error);
190 while ( (row = mysql_fetch_row (res)) != NULL) {
191 int i;
193 for(i = 0; i < LENGTH_METRIC_UNIT; i++) {
194 if (strcmp(row[0], metric_unit[i]) == 0) {
195 xasprintf(&perf, "%s%s ", perf, perfdata(metric_unit[i],
196 atol(row[1]), "", false, 0, false, 0, false, 0, false, 0));
197 continue;
200 for(i = 0; i < LENGTH_METRIC_COUNTER; i++) {
201 if (strcmp(row[0], metric_counter[i]) == 0) {
202 xasprintf(&perf, "%s%s ", perf, perfdata(metric_counter[i],
203 atol(row[1]), "c", false, 0, false, 0, false, 0, false, 0));
204 continue;
208 /* remove trailing space */
209 if (strlen(perf) > 0)
210 perf[strlen(perf) - 1] = '\0';
213 if(check_slave) {
214 /* check the slave status */
215 if (mysql_query (&mysql, "show slave status") != 0) {
216 error = strdup(mysql_error(&mysql));
217 mysql_close (&mysql);
218 die (STATE_CRITICAL, _("slave query error: %s\n"), error);
221 /* store the result */
222 if ( (res = mysql_store_result (&mysql)) == NULL) {
223 error = strdup(mysql_error(&mysql));
224 mysql_close (&mysql);
225 die (STATE_CRITICAL, _("slave store_result error: %s\n"), error);
228 /* Check there is some data */
229 if (mysql_num_rows(res) == 0) {
230 mysql_close(&mysql);
231 die (STATE_WARNING, "%s\n", _("No slaves defined"));
234 /* fetch the first row */
235 if ( (row = mysql_fetch_row (res)) == NULL) {
236 error = strdup(mysql_error(&mysql));
237 mysql_free_result (res);
238 mysql_close (&mysql);
239 die (STATE_CRITICAL, _("slave fetch row error: %s\n"), error);
242 if (mysql_field_count (&mysql) == 12) {
243 /* mysql 3.23.x */
244 snprintf (slaveresult, SLAVERESULTSIZE, _("Slave running: %s"), row[6]);
245 if (strcmp (row[6], "Yes") != 0) {
246 mysql_free_result (res);
247 mysql_close (&mysql);
248 die (STATE_CRITICAL, "%s\n", slaveresult);
251 } else {
252 /* mysql 4.x.x and mysql 5.x.x */
253 int slave_io_field = -1 , slave_sql_field = -1, seconds_behind_field = -1, i, num_fields;
254 MYSQL_FIELD* fields;
256 num_fields = mysql_num_fields(res);
257 fields = mysql_fetch_fields(res);
258 for(i = 0; i < num_fields; i++) {
259 if (strcmp(fields[i].name, "Slave_IO_Running") == 0) {
260 slave_io_field = i;
261 continue;
263 if (strcmp(fields[i].name, "Slave_SQL_Running") == 0) {
264 slave_sql_field = i;
265 continue;
267 if (strcmp(fields[i].name, "Seconds_Behind_Master") == 0) {
268 seconds_behind_field = i;
269 continue;
273 /* Check if slave status is available */
274 if ((slave_io_field < 0) || (slave_sql_field < 0) || (num_fields == 0)) {
275 mysql_free_result (res);
276 mysql_close (&mysql);
277 die (STATE_CRITICAL, "Slave status unavailable\n");
280 /* Save slave status in slaveresult */
281 snprintf (slaveresult, SLAVERESULTSIZE, "Slave IO: %s Slave SQL: %s Seconds Behind Master: %s", row[slave_io_field], row[slave_sql_field], seconds_behind_field!=-1?row[seconds_behind_field]:"Unknown");
283 /* Raise critical error if SQL THREAD or IO THREAD are stopped, but only if there are no mysqldump threads running */
284 if (strcmp (row[slave_io_field], "Yes") != 0 || strcmp (row[slave_sql_field], "Yes") != 0) {
285 MYSQL_RES *res_mysqldump;
286 MYSQL_ROW row_mysqldump;
287 unsigned int mysqldump_threads = 0;
289 if (mysql_query (&mysql, MYSQLDUMP_THREADS_QUERY) == 0) {
290 /* store the result */
291 if ( (res_mysqldump = mysql_store_result (&mysql)) != NULL) {
292 if (mysql_num_rows(res_mysqldump) == 1) {
293 if ( (row_mysqldump = mysql_fetch_row (res_mysqldump)) != NULL) {
294 mysqldump_threads = atoi(row_mysqldump[0]);
297 /* free the result */
298 mysql_free_result (res_mysqldump);
300 mysql_close (&mysql);
302 if (mysqldump_threads == 0) {
303 die (STATE_CRITICAL, "%s\n", slaveresult);
304 } else {
305 strncat(slaveresult, " Mysqldump: in progress", SLAVERESULTSIZE-1);
309 if (verbose >=3) {
310 if (seconds_behind_field == -1) {
311 printf("seconds_behind_field not found\n");
312 } else {
313 printf ("seconds_behind_field(index %d)=%s\n", seconds_behind_field, row[seconds_behind_field]);
317 /* Check Seconds Behind against threshold */
318 if ((seconds_behind_field != -1) && (row[seconds_behind_field] != NULL && strcmp (row[seconds_behind_field], "NULL") != 0)) {
319 double value = atof(row[seconds_behind_field]);
320 int status;
322 status = get_status(value, my_threshold);
324 xasprintf (&perf, "%s %s", perf, fperfdata ("seconds behind master", value, "s",
325 true, (double) warning_time,
326 true, (double) critical_time,
327 false, 0,
328 false, 0));
330 if (status == STATE_WARNING) {
331 printf("SLOW_SLAVE %s: %s|%s\n", _("WARNING"), slaveresult, perf);
332 exit(STATE_WARNING);
333 } else if (status == STATE_CRITICAL) {
334 printf("SLOW_SLAVE %s: %s|%s\n", _("CRITICAL"), slaveresult, perf);
335 exit(STATE_CRITICAL);
340 /* free the result */
341 mysql_free_result (res);
344 /* close the connection */
345 mysql_close (&mysql);
347 /* print out the result of stats */
348 if (check_slave) {
349 printf ("%s %s|%s\n", result, slaveresult, perf);
350 } else {
351 printf ("%s|%s\n", result, perf);
354 return STATE_OK;
358 /* process command-line arguments */
360 process_arguments (int argc, char **argv)
362 int c;
363 char *warning = NULL;
364 char *critical = NULL;
366 int option = 0;
367 static struct option longopts[] = {
368 {"hostname", required_argument, 0, 'H'},
369 {"socket", required_argument, 0, 's'},
370 {"database", required_argument, 0, 'd'},
371 {"username", required_argument, 0, 'u'},
372 {"password", required_argument, 0, 'p'},
373 {"file", required_argument, 0, 'f'},
374 {"group", required_argument, 0, 'g'},
375 {"port", required_argument, 0, 'P'},
376 {"critical", required_argument, 0, 'c'},
377 {"warning", required_argument, 0, 'w'},
378 {"check-slave", no_argument, 0, 'S'},
379 {"ignore-auth", no_argument, 0, 'n'},
380 {"verbose", no_argument, 0, 'v'},
381 {"version", no_argument, 0, 'V'},
382 {"help", no_argument, 0, 'h'},
383 {"ssl", no_argument, 0, 'l'},
384 {"ca-cert", optional_argument, 0, 'C'},
385 {"key", required_argument,0,'k'},
386 {"cert", required_argument,0,'a'},
387 {"ca-dir", required_argument, 0, 'D'},
388 {"ciphers", required_argument, 0, 'L'},
389 {0, 0, 0, 0}
392 if (argc < 1)
393 return ERROR;
395 while (1) {
396 c = getopt_long (argc, argv, "hlvVnSP:p:u:d:H:s:c:w:a:k:C:D:L:f:g:", longopts, &option);
398 if (c == -1 || c == EOF)
399 break;
401 switch (c) {
402 case 'H': /* hostname */
403 if (is_host (optarg)) {
404 db_host = optarg;
406 else if (*optarg == '/') {
407 db_socket = optarg;
409 else {
410 usage2 (_("Invalid hostname/address"), optarg);
412 break;
413 case 's': /* socket */
414 db_socket = optarg;
415 break;
416 case 'd': /* database */
417 db = optarg;
418 break;
419 case 'l':
420 ssl = true;
421 break;
422 case 'C':
423 ca_cert = optarg;
424 break;
425 case 'a':
426 cert = optarg;
427 break;
428 case 'k':
429 key = optarg;
430 break;
431 case 'D':
432 ca_dir = optarg;
433 break;
434 case 'L':
435 ciphers = optarg;
436 break;
437 case 'u': /* username */
438 db_user = optarg;
439 break;
440 case 'p': /* authentication information: password */
441 db_pass = strdup(optarg);
443 /* Delete the password from process list */
444 while (*optarg != '\0') {
445 *optarg = 'X';
446 optarg++;
448 break;
449 case 'f': /* client options file */
450 opt_file = optarg;
451 break;
452 case 'g': /* client options group */
453 opt_group = optarg;
454 break;
455 case 'P': /* critical time threshold */
456 db_port = atoi (optarg);
457 break;
458 case 'S':
459 check_slave = 1; /* check-slave */
460 break;
461 case 'n':
462 ignore_auth = 1; /* ignore-auth */
463 break;
464 case 'w':
465 warning = optarg;
466 warning_time = strtod (warning, NULL);
467 break;
468 case 'c':
469 critical = optarg;
470 critical_time = strtod (critical, NULL);
471 break;
472 case 'V': /* version */
473 print_revision (progname, NP_VERSION);
474 exit (STATE_UNKNOWN);
475 case 'h': /* help */
476 print_help ();
477 exit (STATE_UNKNOWN);
478 case 'v':
479 verbose++;
480 break;
481 case '?': /* help */
482 usage5 ();
486 c = optind;
488 set_thresholds(&my_threshold, warning, critical);
490 while ( argc > c ) {
492 if (db_host == NULL)
493 if (is_host (argv[c])) {
494 db_host = argv[c++];
496 else {
497 usage2 (_("Invalid hostname/address"), argv[c]);
499 else if (db_user == NULL)
500 db_user = argv[c++];
501 else if (db_pass == NULL)
502 db_pass = argv[c++];
503 else if (db == NULL)
504 db = argv[c++];
505 else if (is_intnonneg (argv[c]))
506 db_port = atoi (argv[c++]);
507 else
508 break;
511 return validate_arguments ();
516 validate_arguments (void)
518 if (db_user == NULL)
519 db_user = strdup("");
521 if (db_host == NULL)
522 db_host = strdup("");
524 if (db == NULL)
525 db = strdup("");
527 return OK;
531 void
532 print_help (void)
534 char *myport;
535 xasprintf (&myport, "%d", MYSQL_PORT);
537 print_revision (progname, NP_VERSION);
539 printf (_(COPYRIGHT), copyright, email);
541 printf ("%s\n", _("This program tests connections to a MySQL server"));
543 printf ("\n\n");
545 print_usage ();
547 printf (UT_HELP_VRSN);
548 printf (UT_EXTRA_OPTS);
550 printf (UT_HOST_PORT, 'P', myport);
551 printf (" %s\n", "-n, --ignore-auth");
552 printf (" %s\n", _("Ignore authentication failure and check for mysql connectivity only"));
554 printf (" %s\n", "-s, --socket=STRING");
555 printf (" %s\n", _("Use the specified socket (has no effect if -H is used)"));
557 printf (" %s\n", "-d, --database=STRING");
558 printf (" %s\n", _("Check database with indicated name"));
559 printf (" %s\n", "-f, --file=STRING");
560 printf (" %s\n", _("Read from the specified client options file"));
561 printf (" %s\n", "-g, --group=STRING");
562 printf (" %s\n", _("Use a client options group"));
563 printf (" %s\n", "-u, --username=STRING");
564 printf (" %s\n", _("Connect using the indicated username"));
565 printf (" %s\n", "-p, --password=STRING");
566 printf (" %s\n", _("Use the indicated password to authenticate the connection"));
567 printf (" ==> %s <==\n", _("IMPORTANT: THIS FORM OF AUTHENTICATION IS NOT SECURE!!!"));
568 printf (" %s\n", _("Your clear-text password could be visible as a process table entry"));
569 printf (" %s\n", "-S, --check-slave");
570 printf (" %s\n", _("Check if the slave thread is running properly."));
571 printf (" %s\n", "-w, --warning");
572 printf (" %s\n", _("Exit with WARNING status if slave server is more than INTEGER seconds"));
573 printf (" %s\n", _("behind master"));
574 printf (" %s\n", "-c, --critical");
575 printf (" %s\n", _("Exit with CRITICAL status if slave server is more then INTEGER seconds"));
576 printf (" %s\n", _("behind master"));
577 printf (" %s\n", "-l, --ssl");
578 printf (" %s\n", _("Use ssl encryption"));
579 printf (" %s\n", "-C, --ca-cert=STRING");
580 printf (" %s\n", _("Path to CA signing the cert"));
581 printf (" %s\n", "-a, --cert=STRING");
582 printf (" %s\n", _("Path to SSL certificate"));
583 printf (" %s\n", "-k, --key=STRING");
584 printf (" %s\n", _("Path to private SSL key"));
585 printf (" %s\n", "-D, --ca-dir=STRING");
586 printf (" %s\n", _("Path to CA directory"));
587 printf (" %s\n", "-L, --ciphers=STRING");
588 printf (" %s\n", _("List of valid SSL ciphers"));
591 printf ("\n");
592 printf (" %s\n", _("There are no required arguments. By default, the local database is checked"));
593 printf (" %s\n", _("using the default unix socket. You can force TCP on localhost by using an"));
594 printf (" %s\n", _("IP address or FQDN ('localhost' will use the socket as well)."));
596 printf ("\n");
597 printf ("%s\n", _("Notes:"));
598 printf (" %s\n", _("You must specify -p with an empty string to force an empty password,"));
599 printf (" %s\n", _("overriding any my.cnf settings."));
601 printf (UT_SUPPORT);
605 void
606 print_usage (void)
608 printf ("%s\n", _("Usage:"));
609 printf (" %s [-d database] [-H host] [-P port] [-s socket]\n",progname);
610 printf (" [-u user] [-p password] [-S] [-l] [-a cert] [-k key]\n");
611 printf (" [-C ca-cert] [-D ca-dir] [-L ciphers] [-f optfile] [-g group]\n");