1 /*****************************************************************************
2 *
3 * Monitoring check_pgsql plugin
4 *
5 * License: GPL
6 * Copyright (c) 1999-2011 Monitoring Plugins Development Team
7 *
8 * Description:
9 *
10 * This file contains the check_pgsql plugin
11 *
12 * Test whether a PostgreSQL Database is accepting connections.
13 *
14 *
15 * This program is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
27 *
28 *
29 *****************************************************************************/
30 
31 const char *progname = "check_pgsql";
32 const char *copyright = "1999-2011";
33 const char *email = "devel@monitoring-plugins.org";
34 
35 #include "common.h"
36 #include "utils.h"
37 #include "utils_cmd.h"
38 
39 #include "netutils.h"
40 #include <libpq-fe.h>
41 #include <pg_config_manual.h>
42 
43 #define DEFAULT_DB "template1"
44 #define DEFAULT_HOST "127.0.0.1"
45 
46 /* return the PSQL server version as a 3-tuple */
47 #define PSQL_SERVER_VERSION3(server_version) \
48 	(server_version) / 10000, \
49 	(server_version) / 100 - (int)((server_version) / 10000) * 100, \
50 	(server_version) - (int)((server_version) / 100) * 100
51 /* return true if the given host is a UNIX domain socket */
52 #define PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
53 	((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
54 /* return a 3-tuple identifying a host/port independent of the socket type */
55 #define PSQL_SOCKET3(host, port) \
56 	((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
57 	PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
58 	port
59 
60 enum {
61 	DEFAULT_PORT = 5432,
62 	DEFAULT_WARN = 2,
63 	DEFAULT_CRIT = 8
64 };
65 
66 
67 
68 int process_arguments (int, char **);
69 int validate_arguments (void);
70 void print_usage (void);
71 void print_help (void);
72 int is_pg_dbname (char *);
73 int is_pg_logname (char *);
74 int do_query (PGconn *, char *);
75 
76 char *pghost = NULL;						/* host name of the backend server */
77 char *pgport = NULL;						/* port of the backend server */
78 int default_port = DEFAULT_PORT;
79 char *pgoptions = NULL;
80 char *pgtty = NULL;
81 char dbName[NAMEDATALEN] = DEFAULT_DB;
82 char *pguser = NULL;
83 char *pgpasswd = NULL;
84 char *pgparams = NULL;
85 double twarn = (double)DEFAULT_WARN;
86 double tcrit = (double)DEFAULT_CRIT;
87 char *pgquery = NULL;
88 char *query_warning = NULL;
89 char *query_critical = NULL;
90 thresholds *qthresholds = NULL;
91 int verbose = 0;
92 
93 /******************************************************************************
94 
95 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
96 tags in the comments. With in the tags, the XML is assembled sequentially.
97 You can define entities in tags. You also have all the #defines available as
98 entities.
99 
100 Please note that all tags must be lowercase to use the DocBook XML DTD.
101 
102 @@-<article>
103 
104 <sect1>
105 <title>Quick Reference</title>
106 <!-- The refentry forms a manpage -->
107 <refentry>
108 <refmeta>
109 <manvolnum>5<manvolnum>
110 </refmeta>
111 <refnamdiv>
112 <refname>&progname;</refname>
113 <refpurpose>&SUMMARY;</refpurpose>
114 </refnamdiv>
115 </refentry>
116 </sect1>
117 
118 <sect1>
119 <title>FAQ</title>
120 </sect1>
121 
122 <sect1>
123 <title>Theory, Installation, and Operation</title>
124 
125 <sect2>
126 <title>General Description</title>
127 <para>
128 &DESCRIPTION;
129 </para>
130 </sect2>
131 
132 <sect2>
133 <title>Future Enhancements</title>
134 <para>ToDo List</para>
135 </sect2>
136 
137 
138 <sect2>
139 <title>Functions</title>
140 -@@
141 ******************************************************************************/
142 
143 
144 
145 int
main(int argc,char ** argv)146 main (int argc, char **argv)
147 {
148 	PGconn *conn;
149 	char *conninfo = NULL;
150 
151 	struct timeval start_timeval;
152 	struct timeval end_timeval;
153 	double elapsed_time;
154 	int status = STATE_UNKNOWN;
155 	int query_status = STATE_UNKNOWN;
156 
157 	/* begin, by setting the parameters for a backend connection if the
158 	 * parameters are null, then the system will try to use reasonable
159 	 * defaults by looking up environment variables or, failing that,
160 	 * using hardwired constants */
161 
162 	pgoptions = NULL;  /* special options to start up the backend server */
163 	pgtty = NULL;      /* debugging tty for the backend server */
164 
165 	setlocale (LC_ALL, ""); setlocale(LC_NUMERIC, "C");
166 	bindtextdomain (PACKAGE, LOCALEDIR);
167 	textdomain (PACKAGE);
168 
169 	/* Parse extra opts if any */
170 	argv=np_extra_opts (&argc, argv, progname);
171 
172 	if (process_arguments (argc, argv) == ERROR)
173 		usage4 (_("Could not parse arguments"));
174 	if (verbose > 2)
175 		printf("Arguments initialized\n");
176 
177 	/* Set signal handling and alarm */
178 	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
179 		usage4 (_("Cannot catch SIGALRM"));
180 	}
181 	alarm (timeout_interval);
182 
183 	if (pgparams)
184 		asprintf (&conninfo, "%s ", pgparams);
185 
186 	asprintf (&conninfo, "%sdbname = '%s'", conninfo ? conninfo : "", dbName);
187 	if (pghost)
188 		asprintf (&conninfo, "%s host = '%s'", conninfo, pghost);
189 	if (pgport)
190 		asprintf (&conninfo, "%s port = '%s'", conninfo, pgport);
191 	if (pgoptions)
192 		asprintf (&conninfo, "%s options = '%s'", conninfo, pgoptions);
193 	/* if (pgtty) -- ignored by PQconnectdb */
194 	if (pguser)
195 		asprintf (&conninfo, "%s user = '%s'", conninfo, pguser);
196 
197 	if (verbose) /* do not include password (see right below) in output */
198 		printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo,
199 				pgpasswd ? " password = <hidden>" : "");
200 
201 	if (pgpasswd)
202 		asprintf (&conninfo, "%s password = '%s'", conninfo, pgpasswd);
203 
204 	/* make a connection to the database */
205 	gettimeofday (&start_timeval, NULL);
206 	conn = PQconnectdb (conninfo);
207 	gettimeofday (&end_timeval, NULL);
208 
209 	while (start_timeval.tv_usec > end_timeval.tv_usec) {
210 		--end_timeval.tv_sec;
211 		end_timeval.tv_usec += 1000000;
212 	}
213 	elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec)
214 		+ (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0;
215 
216 	if (verbose)
217 		printf("Time elapsed: %f\n", elapsed_time);
218 
219 	/* check to see that the backend connection was successfully made */
220 	if (verbose)
221 		printf("Verifying connection\n");
222 	if (PQstatus (conn) == CONNECTION_BAD) {
223 		printf (_("CRITICAL - no connection to '%s' (%s).\n"),
224 		        dbName,	PQerrorMessage (conn));
225 		PQfinish (conn);
226 		return STATE_CRITICAL;
227 	}
228 	else if (elapsed_time > tcrit) {
229 		status = STATE_CRITICAL;
230 	}
231 	else if (elapsed_time > twarn) {
232 		status = STATE_WARNING;
233 	}
234 	else {
235 		status = STATE_OK;
236 	}
237 
238 	if (verbose) {
239 		char *server_host = PQhost (conn);
240 		int server_version = PQserverVersion (conn);
241 
242 		printf ("Successfully connected to database %s (user %s) "
243 				"at server %s%s%s (server version: %d.%d.%d, "
244 				"protocol version: %d, pid: %d)\n",
245 				PQdb (conn), PQuser (conn),
246 				PSQL_SOCKET3 (server_host, PQport (conn)),
247 				PSQL_SERVER_VERSION3 (server_version),
248 				PQprotocolVersion (conn), PQbackendPID (conn));
249 	}
250 
251 	printf (_(" %s - database %s (%f sec.)|%s\n"),
252 	        state_text(status), dbName, elapsed_time,
253 	        fperfdata("time", elapsed_time, "s",
254 	                 !!(twarn > 0.0), twarn, !!(tcrit > 0.0), tcrit, TRUE, 0, FALSE,0));
255 
256 	if (pgquery)
257 		query_status = do_query (conn, pgquery);
258 
259 	if (verbose)
260 		printf("Closing connection\n");
261 	PQfinish (conn);
262 	return (pgquery && query_status > status) ? query_status : status;
263 }
264 
265 
266 
267 /* process command-line arguments */
268 int
process_arguments(int argc,char ** argv)269 process_arguments (int argc, char **argv)
270 {
271 	int c;
272 
273 	int option = 0;
274 	static struct option longopts[] = {
275 		{"help", no_argument, 0, 'h'},
276 		{"version", no_argument, 0, 'V'},
277 		{"timeout", required_argument, 0, 't'},
278 		{"critical", required_argument, 0, 'c'},
279 		{"warning", required_argument, 0, 'w'},
280 		{"hostname", required_argument, 0, 'H'},
281 		{"logname", required_argument, 0, 'l'},
282 		{"password", required_argument, 0, 'p'},
283 		{"authorization", required_argument, 0, 'a'},
284 		{"port", required_argument, 0, 'P'},
285 		{"database", required_argument, 0, 'd'},
286 		{"option", required_argument, 0, 'o'},
287 		{"query", required_argument, 0, 'q'},
288 		{"query_critical", required_argument, 0, 'C'},
289 		{"query_warning", required_argument, 0, 'W'},
290 		{"verbose", no_argument, 0, 'v'},
291 		{0, 0, 0, 0}
292 	};
293 
294 	while (1) {
295 		c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v",
296 		                 longopts, &option);
297 
298 		if (c == EOF)
299 			break;
300 
301 		switch (c) {
302 		case '?':     /* usage */
303 			usage5 ();
304 		case 'h':     /* help */
305 			print_help ();
306 			exit (STATE_UNKNOWN);
307 		case 'V':     /* version */
308 			print_revision (progname, NP_VERSION);
309 			exit (STATE_UNKNOWN);
310 		case 't':     /* timeout period */
311 			if (!is_integer (optarg))
312 				usage2 (_("Timeout interval must be a positive integer"), optarg);
313 			else
314 				timeout_interval = atoi (optarg);
315 			break;
316 		case 'c':     /* critical time threshold */
317 			if (!is_nonnegative (optarg))
318 				usage2 (_("Critical threshold must be a positive integer"), optarg);
319 			else
320 				tcrit = strtod (optarg, NULL);
321 			break;
322 		case 'w':     /* warning time threshold */
323 			if (!is_nonnegative (optarg))
324 				usage2 (_("Warning threshold must be a positive integer"), optarg);
325 			else
326 				twarn = strtod (optarg, NULL);
327 			break;
328 		case 'C':     /* critical query threshold */
329 			query_critical = optarg;
330 			break;
331 		case 'W':     /* warning query threshold */
332 			query_warning = optarg;
333 			break;
334 		case 'H':     /* host */
335 			if ((*optarg != '/') && (!is_host (optarg)))
336 				usage2 (_("Invalid hostname/address"), optarg);
337 			else
338 				pghost = optarg;
339 			break;
340 		case 'P':     /* port */
341 			if (!is_integer (optarg))
342 				usage2 (_("Port must be a positive integer"), optarg);
343 			else
344 				pgport = optarg;
345 			break;
346 		case 'd':     /* database name */
347 			if (!is_pg_dbname (optarg)) /* checks length and valid chars */
348 				usage2 (_("Database name is not valid"), optarg);
349 			else /* we know length, and know optarg is terminated, so us strcpy */
350 				snprintf(dbName, NAMEDATALEN, "%s", optarg);
351 			break;
352 		case 'l':     /* login name */
353 			if (!is_pg_logname (optarg))
354 				usage2 (_("User name is not valid"), optarg);
355 			else
356 				pguser = optarg;
357 			break;
358 		case 'p':     /* authentication password */
359 		case 'a':
360 			pgpasswd = optarg;
361 			break;
362 		case 'o':
363 			if (pgparams)
364 				asprintf (&pgparams, "%s %s", pgparams, optarg);
365 			else
366 				asprintf (&pgparams, "%s", optarg);
367 			break;
368 		case 'q':
369 			pgquery = optarg;
370 			break;
371 		case 'v':
372 			verbose++;
373 			break;
374 		}
375 	}
376 
377 	set_thresholds (&qthresholds, query_warning, query_critical);
378 
379 	return validate_arguments ();
380 }
381 
382 
383 /******************************************************************************
384 
385 @@-
386 <sect3>
387 <title>validate_arguments</title>
388 
389 <para>&PROTO_validate_arguments;</para>
390 
391 <para>Given a database name, this function returns TRUE if the string
392 is a valid PostgreSQL database name, and returns false if it is
393 not.</para>
394 
395 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
396 characters long and consist of letters, numbers, and underscores. The
397 first character cannot be a number, however.</para>
398 
399 </sect3>
400 -@@
401 ******************************************************************************/
402 
403 
404 
405 int
validate_arguments()406 validate_arguments ()
407 {
408 	return OK;
409 }
410 
411 
412 /******************************************************************************
413 
414 @@-
415 <sect3>
416 <title>is_pg_dbname</title>
417 
418 <para>&PROTO_is_pg_dbname;</para>
419 
420 <para>Given a database name, this function returns TRUE if the string
421 is a valid PostgreSQL database name, and returns false if it is
422 not.</para>
423 
424 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
425 characters long and consist of letters, numbers, and underscores. The
426 first character cannot be a number, however.</para>
427 
428 </sect3>
429 -@@
430 ******************************************************************************/
431 
432 
433 
434 int
is_pg_dbname(char * dbname)435 is_pg_dbname (char *dbname)
436 {
437 	char txt[NAMEDATALEN];
438 	char tmp[NAMEDATALEN];
439 	if (strlen (dbname) > NAMEDATALEN - 1)
440 		return (FALSE);
441 	strncpy (txt, dbname, NAMEDATALEN - 1);
442 	txt[NAMEDATALEN - 1] = 0;
443 	if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
444 		return (TRUE);
445 	if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
446 			2) return (TRUE);
447 	return (FALSE);
448 }
449 
450 /**
451 
452 the tango program should eventually create an entity here based on the
453 function prototype
454 
455 @@-
456 <sect3>
457 <title>is_pg_logname</title>
458 
459 <para>&PROTO_is_pg_logname;</para>
460 
461 <para>Given a username, this function returns TRUE if the string is a
462 valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
463 usernames are less than &NAMEDATALEN; characters long and consist of
464 letters, numbers, dashes, and underscores, plus possibly some other
465 characters.</para>
466 
467 <para>Currently this function only checks string length. Additional checks
468 should be added.</para>
469 
470 </sect3>
471 -@@
472 ******************************************************************************/
473 
474 
475 
476 int
is_pg_logname(char * username)477 is_pg_logname (char *username)
478 {
479 	if (strlen (username) > NAMEDATALEN - 1)
480 		return (FALSE);
481 	return (TRUE);
482 }
483 
484 /******************************************************************************
485 @@-
486 </sect2>
487 </sect1>
488 </article>
489 -@@
490 ******************************************************************************/
491 
492 
493 
494 void
print_help(void)495 print_help (void)
496 {
497 	char *myport;
498 
499 	xasprintf (&myport, "%d", DEFAULT_PORT);
500 
501 	print_revision (progname, NP_VERSION);
502 
503 	printf (COPYRIGHT, copyright, email);
504 
505 	printf (_("Test whether a PostgreSQL Database is accepting connections."));
506 
507 	printf ("\n\n");
508 
509 	print_usage ();
510 
511 	printf (UT_HELP_VRSN);
512 	printf (UT_EXTRA_OPTS);
513 
514 	printf (UT_HOST_PORT, 'P', myport);
515 
516 	printf (" %s\n", "-d, --database=STRING");
517 	printf ("    %s", _("Database to check "));
518 	printf (_("(default: %s)\n"), DEFAULT_DB);
519 	printf (" %s\n", "-l, --logname = STRING");
520 	printf ("    %s\n", _("Login name of user"));
521 	printf (" %s\n", "-p, --password = STRING");
522 	printf ("    %s\n", _("Password (BIG SECURITY ISSUE)"));
523 	printf (" %s\n", "-o, --option = STRING");
524 	printf ("    %s\n", _("Connection parameters (keyword = value), see below"));
525 
526 	printf (UT_WARN_CRIT);
527 
528 	printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
529 
530 	printf (" %s\n", "-q, --query=STRING");
531 	printf ("    %s\n", _("SQL query to run. Only first column in first row will be read"));
532 	printf (" %s\n", "-W, --query-warning=RANGE");
533 	printf ("    %s\n", _("SQL query value to result in warning status (double)"));
534 	printf (" %s\n", "-C, --query-critical=RANGE");
535 	printf ("    %s\n", _("SQL query value to result in critical status (double)"));
536 
537 	printf (UT_VERBOSE);
538 
539 	printf ("\n");
540 	printf (" %s\n", _("All parameters are optional."));
541 	printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
542 	printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
543 	printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
544 	printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
545 	printf (" %s\n\n", _("PostgreSQL DBMS."));
546 
547 	printf (" %s\n", _("If a query is specified using the -q option, it will be executed after"));
548 	printf (" %s\n", _("connecting to the server. The result from the query has to be numeric."));
549 	printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
550 	printf (" %s\n", _("of the last command is taken into account only. The value of the first"));
551 	printf (" %s\n\n", _("column in the first row is used as the check result."));
552 
553 	printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
554 	printf (" %s\n\n", _("for details about how to access internal statistics of the database server."));
555 
556 	printf (" %s\n", _("For a list of available connection parameters which may be used with the -o"));
557 	printf (" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter"));
558 	printf (" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be"));
559 	printf (" %s\n", _("used to specify a service name in pg_service.conf to be used for additional"));
560 	printf (" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:"));
561 	printf (" %s\n\n", _("-o 'sslmode=require'."));
562 
563 	printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
564 	printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
565 	printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
566 
567 	printf (" %s\n", _("Typically, the monitoring user (unless the --logname option is used) should be"));
568 	printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
569 	printf (" %s\n", _("a password, but no effort is made to obscure or encrypt the password."));
570 
571 	printf (UT_SUPPORT);
572 }
573 
574 
575 
576 void
print_usage(void)577 print_usage (void)
578 {
579 	printf ("%s\n", _("Usage:"));
580 	printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
581 	printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n"
582 			"[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
583 }
584 
585 int
do_query(PGconn * conn,char * query)586 do_query (PGconn *conn, char *query)
587 {
588 	PGresult *res;
589 
590 	char *val_str;
591 	double value;
592 
593 	char *endptr = NULL;
594 
595 	int my_status = STATE_UNKNOWN;
596 
597 	if (verbose)
598 		printf ("Executing SQL query \"%s\".\n", query);
599 	res = PQexec (conn, query);
600 
601 	if (PGRES_TUPLES_OK != PQresultStatus (res)) {
602 		printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
603 					PQerrorMessage (conn));
604 		return STATE_CRITICAL;
605 	}
606 
607 	if (PQntuples (res) < 1) {
608 		printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned"));
609 		return STATE_WARNING;
610 	}
611 
612 	if (PQnfields (res) < 1) {
613 		printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned"));
614 		return STATE_WARNING;
615 	}
616 
617 	val_str = PQgetvalue (res, 0, 0);
618 	if (! val_str) {
619 		printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned"));
620 		return STATE_CRITICAL;
621 	}
622 
623 	value = strtod (val_str, &endptr);
624 	if (verbose)
625 		printf ("Query result: %f\n", value);
626 
627 	if (endptr == val_str) {
628 		printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str);
629 		return STATE_CRITICAL;
630 	}
631 	else if ((endptr != NULL) && (*endptr != '\0')) {
632 		if (verbose)
633 			printf ("Garbage after value: %s.\n", endptr);
634 	}
635 
636 	my_status = get_status (value, qthresholds);
637 	printf ("QUERY %s - ",
638 			(my_status == STATE_OK)
639 				? _("OK")
640 				: (my_status == STATE_WARNING)
641 					? _("WARNING")
642 					: (my_status == STATE_CRITICAL)
643 						? _("CRITICAL")
644 						: _("UNKNOWN"));
645 	printf (_("'%s' returned %f"), query, value);
646 	printf ("|query=%f;%s;%s;;\n", value,
647 			query_warning ? query_warning : "",
648 			query_critical ? query_critical : "");
649 	return my_status;
650 }
651 
652