Code

6251e0b21ed199f02639e8dedfbc0da69bbf0eec
[nagiosplug.git] / plugins / check_pgsql.c
1 /*****************************************************************************
2
3 * Nagios check_pgsql plugin
4
5 * License: GPL
6 * Copyright (c) 1999-2007 Nagios 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 *****************************************************************************/
31 const char *progname = "check_pgsql";
32 const char *copyright = "1999-2007";
33 const char *email = "nagiosplug-devel@lists.sourceforge.net";
35 #include "common.h"
36 #include "utils.h"
38 #include "netutils.h"
39 #include <libpq-fe.h>
40 #include <pg_config_manual.h>
42 #define DEFAULT_DB "template1"
43 #define DEFAULT_HOST "127.0.0.1"
45 /* return the PSQL server version as a 3-tuple */
46 #define PSQL_SERVER_VERSION3(server_version) \
47         (server_version) / 10000, \
48         (server_version) / 100 - (int)((server_version) / 10000) * 100, \
49         (server_version) - (int)((server_version) / 100) * 100
50 /* return true if the given host is a UNIX domain socket */
51 #define PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
52         ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
53 /* return a 3-tuple identifying a host/port independent of the socket type */
54 #define PSQL_SOCKET3(host, port) \
55         ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
56         PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
57         port
59 enum {
60         DEFAULT_PORT = 5432,
61         DEFAULT_WARN = 2,
62         DEFAULT_CRIT = 8
63 };
67 int process_arguments (int, char **);
68 int validate_arguments (void);
69 void print_usage (void);
70 void print_help (void);
71 int is_pg_dbname (char *);
72 int is_pg_logname (char *);
73 int do_query (PGconn *, char *);
75 char *pghost = NULL;                                            /* host name of the backend server */
76 char *pgport = NULL;                                            /* port of the backend server */
77 int default_port = DEFAULT_PORT;
78 char *pgoptions = NULL;
79 char *pgtty = NULL;
80 char dbName[NAMEDATALEN] = DEFAULT_DB;
81 char *pguser = NULL;
82 char *pgpasswd = NULL;
83 double twarn = (double)DEFAULT_WARN;
84 double tcrit = (double)DEFAULT_CRIT;
85 char *pgquery = NULL;
86 char *query_warning = NULL;
87 char *query_critical = NULL;
88 thresholds *qthresholds = NULL;
89 int verbose = 0;
91 /******************************************************************************
93 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
94 tags in the comments. With in the tags, the XML is assembled sequentially.
95 You can define entities in tags. You also have all the #defines available as
96 entities.
98 Please note that all tags must be lowercase to use the DocBook XML DTD.
100 @@-<article>
102 <sect1>
103 <title>Quick Reference</title>
104 <!-- The refentry forms a manpage -->
105 <refentry>
106 <refmeta>
107 <manvolnum>5<manvolnum>
108 </refmeta>
109 <refnamdiv>
110 <refname>&progname;</refname>
111 <refpurpose>&SUMMARY;</refpurpose>
112 </refnamdiv>
113 </refentry>
114 </sect1>
116 <sect1>
117 <title>FAQ</title>
118 </sect1>
120 <sect1>
121 <title>Theory, Installation, and Operation</title>
123 <sect2>
124 <title>General Description</title>
125 <para>
126 &DESCRIPTION;
127 </para>
128 </sect2>
130 <sect2>
131 <title>Future Enhancements</title>
132 <para>ToDo List</para>
133 <itemizedlist>
134 <listitem>Add option to get password from a secured file rather than the command line</listitem>
135 </itemizedlist>
136 </sect2>
139 <sect2>
140 <title>Functions</title>
141 -@@
142 ******************************************************************************/
146 int
147 main (int argc, char **argv)
149         PGconn *conn;
150         char *conninfo = NULL;
152         int elapsed_time;
153         int status = STATE_UNKNOWN;
154         int query_status = STATE_UNKNOWN;
156         /* begin, by setting the parameters for a backend connection if the
157          * parameters are null, then the system will try to use reasonable
158          * defaults by looking up environment variables or, failing that,
159          * using hardwired constants */
161         pgoptions = NULL;  /* special options to start up the backend server */
162         pgtty = NULL;      /* debugging tty for the backend server */
164         setlocale (LC_ALL, "");
165         bindtextdomain (PACKAGE, LOCALEDIR);
166         textdomain (PACKAGE);
168         /* Parse extra opts if any */
169         argv=np_extra_opts (&argc, argv, progname);
171         if (process_arguments (argc, argv) == ERROR)
172                 usage4 (_("Could not parse arguments"));
173         if (verbose > 2)
174                 printf("Arguments initialized\n");
176         /* Set signal handling and alarm */
177         if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
178                 usage4 (_("Cannot catch SIGALRM"));
179         }
180         alarm (timeout_interval);
182         asprintf (&conninfo, "dbname = '%s'", dbName);
183         if (pghost)
184                 asprintf (&conninfo, "%s host = '%s'", conninfo, pghost);
185         if (pgport)
186                 asprintf (&conninfo, "%s port = '%s'", conninfo, pgport);
187         if (pgoptions)
188                 asprintf (&conninfo, "%s options = '%s'", conninfo, pgoptions);
189         /* if (pgtty) -- ignored by PQconnectdb */
190         if (pguser)
191                 asprintf (&conninfo, "%s user = '%s'", conninfo, pguser);
193         if (verbose) /* do not include password (see right below) in output */
194                 printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo,
195                                 pgpasswd ? " password = <hidden>" : "");
197         if (pgpasswd)
198                 asprintf (&conninfo, "%s password = '%s'", conninfo, pgpasswd);
200         /* make a connection to the database */
201         time (&start_time);
202         conn = PQconnectdb (conninfo);
203         time (&end_time);
204         elapsed_time = (int) (end_time - start_time);
206         if (verbose)
207                 printf("Time elapsed: %d\n", elapsed_time);
209         /* check to see that the backend connection was successfully made */
210         if (verbose)
211                 printf("Verifying connection\n");
212         if (PQstatus (conn) == CONNECTION_BAD) {
213                 printf (_("CRITICAL - no connection to '%s' (%s).\n"),
214                         dbName, PQerrorMessage (conn));
215                 PQfinish (conn);
216                 return STATE_CRITICAL;
217         }
218         else if (elapsed_time > tcrit) {
219                 status = STATE_CRITICAL;
220         }
221         else if (elapsed_time > twarn) {
222                 status = STATE_WARNING;
223         }
224         else {
225                 status = STATE_OK;
226         }
228         if (verbose) {
229                 char *server_host = PQhost (conn);
230                 int server_version = PQserverVersion (conn);
232                 printf ("Successfully connected to database %s (user %s) "
233                                 "at server %s%s%s (server version: %d.%d.%d, "
234                                 "protocol version: %d, pid: %d)\n",
235                                 PQdb (conn), PQuser (conn),
236                                 PSQL_SOCKET3 (server_host, PQport (conn)),
237                                 PSQL_SERVER_VERSION3 (server_version),
238                                 PQprotocolVersion (conn), PQbackendPID (conn));
239         }
241         printf (_(" %s - database %s (%d sec.)|%s\n"),
242                 state_text(status), dbName, elapsed_time,
243                 fperfdata("time", elapsed_time, "s",
244                          (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
246         if (pgquery)
247                 query_status = do_query (conn, pgquery);
249         if (verbose)
250                 printf("Closing connection\n");
251         PQfinish (conn);
252         return (query_status > status) ? query_status : status;
257 /* process command-line arguments */
258 int
259 process_arguments (int argc, char **argv)
261         int c;
263         int option = 0;
264         static struct option longopts[] = {
265                 {"help", no_argument, 0, 'h'},
266                 {"version", no_argument, 0, 'V'},
267                 {"timeout", required_argument, 0, 't'},
268                 {"critical", required_argument, 0, 'c'},
269                 {"warning", required_argument, 0, 'w'},
270                 {"hostname", required_argument, 0, 'H'},
271                 {"logname", required_argument, 0, 'l'},
272                 {"password", required_argument, 0, 'p'},
273                 {"authorization", required_argument, 0, 'a'},
274                 {"port", required_argument, 0, 'P'},
275                 {"database", required_argument, 0, 'd'},
276                 {"query", required_argument, 0, 'q'},
277                 {"query_critical", required_argument, 0, 'C'},
278                 {"query_warning", required_argument, 0, 'W'},
279                 {"verbose", no_argument, 0, 'v'},
280                 {0, 0, 0, 0}
281         };
283         while (1) {
284                 c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:q:C:W:v",
285                                  longopts, &option);
287                 if (c == EOF)
288                         break;
290                 switch (c) {
291                 case '?':     /* usage */
292                         usage5 ();
293                 case 'h':     /* help */
294                         print_help ();
295                         exit (STATE_OK);
296                 case 'V':     /* version */
297                         print_revision (progname, NP_VERSION);
298                         exit (STATE_OK);
299                 case 't':     /* timeout period */
300                         if (!is_integer (optarg))
301                                 usage2 (_("Timeout interval must be a positive integer"), optarg);
302                         else
303                                 timeout_interval = atoi (optarg);
304                         break;
305                 case 'c':     /* critical time threshold */
306                         if (!is_nonnegative (optarg))
307                                 usage2 (_("Critical threshold must be a positive integer"), optarg);
308                         else
309                                 tcrit = strtod (optarg, NULL);
310                         break;
311                 case 'w':     /* warning time threshold */
312                         if (!is_nonnegative (optarg))
313                                 usage2 (_("Warning threshold must be a positive integer"), optarg);
314                         else
315                                 twarn = strtod (optarg, NULL);
316                         break;
317                 case 'C':     /* critical query threshold */
318                         query_critical = optarg;
319                         break;
320                 case 'W':     /* warning query threshold */
321                         query_warning = optarg;
322                         break;
323                 case 'H':     /* host */
324                         if ((*optarg != '/') && (!is_host (optarg)))
325                                 usage2 (_("Invalid hostname/address"), optarg);
326                         else
327                                 pghost = optarg;
328                         break;
329                 case 'P':     /* port */
330                         if (!is_integer (optarg))
331                                 usage2 (_("Port must be a positive integer"), optarg);
332                         else
333                                 pgport = optarg;
334                         break;
335                 case 'd':     /* database name */
336                         if (!is_pg_dbname (optarg)) /* checks length and valid chars */
337                                 usage2 (_("Database name is not valid"), optarg);
338                         else /* we know length, and know optarg is terminated, so us strcpy */
339                                 strcpy (dbName, optarg);
340                         break;
341                 case 'l':     /* login name */
342                         if (!is_pg_logname (optarg))
343                                 usage2 (_("User name is not valid"), optarg);
344                         else
345                                 pguser = optarg;
346                         break;
347                 case 'p':     /* authentication password */
348                 case 'a':
349                         pgpasswd = optarg;
350                         break;
351                 case 'q':
352                         pgquery = optarg;
353                         break;
354                 case 'v':
355                         verbose++;
356                         break;
357                 }
358         }
360         set_thresholds (&qthresholds, query_warning, query_critical);
362         return validate_arguments ();
366 /******************************************************************************
368 @@-
369 <sect3>
370 <title>validate_arguments</title>
372 <para>&PROTO_validate_arguments;</para>
374 <para>Given a database name, this function returns TRUE if the string
375 is a valid PostgreSQL database name, and returns false if it is
376 not.</para>
378 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
379 characters long and consist of letters, numbers, and underscores. The
380 first character cannot be a number, however.</para>
382 </sect3>
383 -@@
384 ******************************************************************************/
388 int
389 validate_arguments ()
391         return OK;
395 /******************************************************************************
397 @@-
398 <sect3>
399 <title>is_pg_dbname</title>
401 <para>&PROTO_is_pg_dbname;</para>
403 <para>Given a database name, this function returns TRUE if the string
404 is a valid PostgreSQL database name, and returns false if it is
405 not.</para>
407 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
408 characters long and consist of letters, numbers, and underscores. The
409 first character cannot be a number, however.</para>
411 </sect3>
412 -@@
413 ******************************************************************************/
417 int
418 is_pg_dbname (char *dbname)
420         char txt[NAMEDATALEN];
421         char tmp[NAMEDATALEN];
422         if (strlen (dbname) > NAMEDATALEN - 1)
423                 return (FALSE);
424         strncpy (txt, dbname, NAMEDATALEN - 1);
425         txt[NAMEDATALEN - 1] = 0;
426         if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
427                 return (TRUE);
428         if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
429                         2) return (TRUE);
430         return (FALSE);
433 /**
435 the tango program should eventually create an entity here based on the
436 function prototype
438 @@-
439 <sect3>
440 <title>is_pg_logname</title>
442 <para>&PROTO_is_pg_logname;</para>
444 <para>Given a username, this function returns TRUE if the string is a
445 valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
446 usernames are less than &NAMEDATALEN; characters long and consist of
447 letters, numbers, dashes, and underscores, plus possibly some other
448 characters.</para>
450 <para>Currently this function only checks string length. Additional checks
451 should be added.</para>
453 </sect3>
454 -@@
455 ******************************************************************************/
459 int
460 is_pg_logname (char *username)
462         if (strlen (username) > NAMEDATALEN - 1)
463                 return (FALSE);
464         return (TRUE);
467 /******************************************************************************
468 @@-
469 </sect2>
470 </sect1>
471 </article>
472 -@@
473 ******************************************************************************/
477 void
478 print_help (void)
480         char *myport;
482         asprintf (&myport, "%d", DEFAULT_PORT);
484         print_revision (progname, NP_VERSION);
486         printf (COPYRIGHT, copyright, email);
488         printf (_("Test whether a PostgreSQL Database is accepting connections."));
490         printf ("\n\n");
492         print_usage ();
494         printf (UT_HELP_VRSN);
495         printf (UT_EXTRA_OPTS);
497         printf (UT_HOST_PORT, 'P', myport);
499         printf (UT_IPv46);
501         printf (" %s\n", "-d, --database=STRING");
502         printf ("    %s", _("Database to check "));
503         printf (_("(default: %s)"), DEFAULT_DB);
504         printf (" %s\n", "-l, --logname = STRING");
505         printf ("    %s\n", _("Login name of user"));
506         printf (" %s\n", "-p, --password = STRING");
507         printf ("    %s\n", _("Password (BIG SECURITY ISSUE)"));
509         printf (UT_WARN_CRIT);
511         printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
513         printf (" %s\n", "-q, --query=STRING");
514         printf ("    %s\n", _("SQL query to run. Only first column in first row will be read"));
515         printf (" %s\n", "-W, --query-warning=RANGE");
516         printf ("    %s\n", _("SQL query value to result in warning status (double)"));
517         printf (" %s\n", "-C, --query-critical=RANGE");
518         printf ("    %s\n", _("SQL query value to result in critical status (double)"));
520         printf (UT_VERBOSE);
522         printf ("\n");
523         printf (" %s\n", _("All parameters are optional."));
524         printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
525         printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
526         printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
527         printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
528         printf (" %s\n\n", _("PostgreSQL DBMS."));
530         printf (" %s\n", _("If a query is specified using the -q option, it will be executed after"));
531         printf (" %s\n", _("connecting to the server. The result from the query has to be numeric."));
532         printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
533         printf (" %s\n", _("of the last command is taken into account only. The value of the first"));
534         printf (" %s\n\n", _("column in the first row is used as the check result."));
536         printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
537         printf (" %s\n\n", _("for details about how to access internal statistics of the database server."));
539         printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
540         printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
541         printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
543         printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
544         printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
545         printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
547         printf (UT_SUPPORT);
552 void
553 print_usage (void)
555         printf ("%s\n", _("Usage:"));
556         printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
557         printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n"
558                         "[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
561 int
562 do_query (PGconn *conn, char *query)
564         PGresult *res;
566         char *val_str;
567         double value;
569         char *endptr = NULL;
571         int my_status = STATE_UNKNOWN;
573         if (verbose)
574                 printf ("Executing SQL query \"%s\".\n");
575         res = PQexec (conn, query);
577         if (PGRES_TUPLES_OK != PQresultStatus (res)) {
578                 printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
579                                         PQerrorMessage (conn));
580                 return STATE_CRITICAL;
581         }
583         if (PQntuples (res) < 1) {
584                 printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned"));
585                 return STATE_WARNING;
586         }
588         if (PQnfields (res) < 1) {
589                 printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned"));
590                 return STATE_WARNING;
591         }
593         val_str = PQgetvalue (res, 0, 0);
594         if (! val_str) {
595                 printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned"));
596                 return STATE_CRITICAL;
597         }
599         value = strtod (val_str, &endptr);
600         if (verbose)
601                 printf ("Query result: %f\n", value);
603         if (endptr == val_str) {
604                 printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str);
605                 return STATE_CRITICAL;
606         }
607         else if ((endptr != NULL) && (*endptr != '\0')) {
608                 if (verbose)
609                         printf ("Garbage after value: %s.\n", endptr);
610         }
612         my_status = get_status (value, qthresholds);
613         printf ("QUERY %s - ",
614                         (my_status == STATE_OK)
615                                 ? _("OK")
616                                 : (my_status == STATE_WARNING)
617                                         ? _("WARNING")
618                                         : (my_status == STATE_CRITICAL)
619                                                 ? _("CRITICAL")
620                                                 : _("UNKNOWN"));
621         printf (_("'%s' returned %f"), query, value);
622         printf ("|query=%f;%s;%s;0\n", value,
623                         query_warning ? query_warning : "",
624                         query_critical ? query_critical : "");
625         return my_status;