Back to index

nagios-plugins  1.4.16
check_pgsql.c
Go to the documentation of this file.
00001 /*****************************************************************************
00002 * 
00003 * Nagios check_pgsql plugin
00004 * 
00005 * License: GPL
00006 * Copyright (c) 1999-2007 Nagios Plugins Development Team
00007 * 
00008 * Description:
00009 * 
00010 * This file contains the check_pgsql plugin
00011 * 
00012 * Test whether a PostgreSQL Database is accepting connections.
00013 * 
00014 * 
00015 * This program is free software: you can redistribute it and/or modify
00016 * it under the terms of the GNU General Public License as published by
00017 * the Free Software Foundation, either version 3 of the License, or
00018 * (at your option) any later version.
00019 * 
00020 * This program is distributed in the hope that it will be useful,
00021 * but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 * GNU General Public License for more details.
00024 * 
00025 * You should have received a copy of the GNU General Public License
00026 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00027 * 
00028 * 
00029 *****************************************************************************/
00030 
00031 const char *progname = "check_pgsql";
00032 const char *copyright = "1999-2007";
00033 const char *email = "nagiosplug-devel@lists.sourceforge.net";
00034 
00035 #include "common.h"
00036 #include "utils.h"
00037 
00038 #include "netutils.h"
00039 #include <libpq-fe.h>
00040 #include <pg_config_manual.h>
00041 
00042 #define DEFAULT_DB "template1"
00043 #define DEFAULT_HOST "127.0.0.1"
00044 
00045 enum {
00046        DEFAULT_PORT = 5432,
00047        DEFAULT_WARN = 2,
00048        DEFAULT_CRIT = 8
00049 };
00050 
00051 
00052 
00053 int process_arguments (int, char **);
00054 int validate_arguments (void);
00055 void print_usage (void);
00056 void print_help (void);
00057 int is_pg_dbname (char *);
00058 int is_pg_logname (char *);
00059 
00060 char *pghost = NULL;                                    /* host name of the backend server */
00061 char *pgport = NULL;                                    /* port of the backend server */
00062 int default_port = DEFAULT_PORT;
00063 char *pgoptions = NULL;
00064 char *pgtty = NULL;
00065 char dbName[NAMEDATALEN] = DEFAULT_DB;
00066 char *pguser = NULL;
00067 char *pgpasswd = NULL;
00068 double twarn = (double)DEFAULT_WARN;
00069 double tcrit = (double)DEFAULT_CRIT;
00070 int verbose = 0;
00071 
00072 PGconn *conn;
00073 /*PGresult   *res;*/
00074 
00075 
00076 /******************************************************************************
00077 
00078 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
00079 tags in the comments. With in the tags, the XML is assembled sequentially.
00080 You can define entities in tags. You also have all the #defines available as
00081 entities.
00082 
00083 Please note that all tags must be lowercase to use the DocBook XML DTD.
00084 
00085 @@-<article>
00086 
00087 <sect1>
00088 <title>Quick Reference</title>
00089 <!-- The refentry forms a manpage -->
00090 <refentry>
00091 <refmeta>
00092 <manvolnum>5<manvolnum>
00093 </refmeta>
00094 <refnamdiv>
00095 <refname>&progname;</refname>
00096 <refpurpose>&SUMMARY;</refpurpose>
00097 </refnamdiv>
00098 </refentry>
00099 </sect1>
00100 
00101 <sect1>
00102 <title>FAQ</title>
00103 </sect1>
00104 
00105 <sect1>
00106 <title>Theory, Installation, and Operation</title>
00107 
00108 <sect2>
00109 <title>General Description</title>
00110 <para>
00111 &DESCRIPTION;
00112 </para>
00113 </sect2>
00114 
00115 <sect2>
00116 <title>Future Enhancements</title>
00117 <para>ToDo List</para>
00118 <itemizedlist>
00119 <listitem>Add option to get password from a secured file rather than the command line</listitem>
00120 <listitem>Add option to specify the query to execute</listitem>
00121 </itemizedlist>
00122 </sect2>
00123 
00124 
00125 <sect2>
00126 <title>Functions</title>
00127 -@@
00128 ******************************************************************************/
00129 
00130 
00131 
00132 int
00133 main (int argc, char **argv)
00134 {
00135        int elapsed_time;
00136        int status = STATE_UNKNOWN;
00137 
00138        /* begin, by setting the parameters for a backend connection if the
00139         * parameters are null, then the system will try to use reasonable
00140         * defaults by looking up environment variables or, failing that,
00141         * using hardwired constants */
00142 
00143        pgoptions = NULL;  /* special options to start up the backend server */
00144        pgtty = NULL;      /* debugging tty for the backend server */
00145 
00146        setlocale (LC_ALL, "");
00147        bindtextdomain (PACKAGE, LOCALEDIR);
00148        textdomain (PACKAGE);
00149 
00150        /* Parse extra opts if any */
00151        argv=np_extra_opts (&argc, argv, progname);
00152 
00153        if (process_arguments (argc, argv) == ERROR)
00154               usage4 (_("Could not parse arguments"));
00155        if (verbose > 2)
00156               printf("Arguments initialized\n");
00157 
00158        /* Set signal handling and alarm */
00159        if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
00160               usage4 (_("Cannot catch SIGALRM"));
00161        }
00162        alarm (timeout_interval);
00163 
00164        if (verbose)
00165               printf("Connecting to database:\n DB: %s\n User: %s\n Host: %s\n Port: %d\n", dbName,
00166               (pguser != NULL) ? pguser : "unspecified",
00167               (pghost != NULL) ? pghost : "unspecified",
00168               (pgport != NULL) ? atoi(pgport) : DEFAULT_PORT);
00169 
00170        /* make a connection to the database */
00171        time (&start_time);
00172        conn =
00173               PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd);
00174        time (&end_time);
00175        elapsed_time = (int) (end_time - start_time);
00176        if (verbose)
00177               printf("Time elapsed: %d\n", elapsed_time);
00178 
00179        /* check to see that the backend connection was successfully made */
00180        if (verbose)
00181               printf("Verifying connection\n");
00182        if (PQstatus (conn) == CONNECTION_BAD) {
00183               printf (_("CRITICAL - no connection to '%s' (%s).\n"),
00184                       dbName,      PQerrorMessage (conn));
00185               PQfinish (conn);
00186               return STATE_CRITICAL;
00187        }
00188        else if (elapsed_time > tcrit) {
00189               status = STATE_CRITICAL;
00190        }
00191        else if (elapsed_time > twarn) {
00192               status = STATE_WARNING;
00193        }
00194        else {
00195               status = STATE_OK;
00196        }
00197        if (verbose)
00198               printf("Closing connection\n");
00199        PQfinish (conn);
00200        printf (_(" %s - database %s (%d sec.)|%s\n"),
00201                state_text(status), dbName, elapsed_time,
00202                fperfdata("time", elapsed_time, "s",
00203                         (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
00204        return status;
00205 }
00206 
00207 
00208 
00209 /* process command-line arguments */
00210 int
00211 process_arguments (int argc, char **argv)
00212 {
00213        int c;
00214 
00215        int option = 0;
00216        static struct option longopts[] = {
00217               {"help", no_argument, 0, 'h'},
00218               {"version", no_argument, 0, 'V'},
00219               {"timeout", required_argument, 0, 't'},
00220               {"critical", required_argument, 0, 'c'},
00221               {"warning", required_argument, 0, 'w'},
00222               {"hostname", required_argument, 0, 'H'},
00223               {"logname", required_argument, 0, 'l'},
00224               {"password", required_argument, 0, 'p'},
00225               {"authorization", required_argument, 0, 'a'},
00226               {"port", required_argument, 0, 'P'},
00227               {"database", required_argument, 0, 'd'},
00228               {"verbose", no_argument, 0, 'v'},
00229               {0, 0, 0, 0}
00230        };
00231 
00232        while (1) {
00233               c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:v",
00234                                longopts, &option);
00235 
00236               if (c == EOF)
00237                      break;
00238 
00239               switch (c) {
00240               case '?':     /* usage */
00241                      usage5 ();
00242               case 'h':     /* help */
00243                      print_help ();
00244                      exit (STATE_OK);
00245               case 'V':     /* version */
00246                      print_revision (progname, NP_VERSION);
00247                      exit (STATE_OK);
00248               case 't':     /* timeout period */
00249                      if (!is_integer (optarg))
00250                             usage2 (_("Timeout interval must be a positive integer"), optarg);
00251                      else
00252                             timeout_interval = atoi (optarg);
00253                      break;
00254               case 'c':     /* critical time threshold */
00255                      if (!is_nonnegative (optarg))
00256                             usage2 (_("Critical threshold must be a positive integer"), optarg);
00257                      else
00258                             tcrit = strtod (optarg, NULL);
00259                      break;
00260               case 'w':     /* warning time threshold */
00261                      if (!is_nonnegative (optarg))
00262                             usage2 (_("Warning threshold must be a positive integer"), optarg);
00263                      else
00264                             twarn = strtod (optarg, NULL);
00265                      break;
00266               case 'H':     /* host */
00267                      if (!is_host (optarg))
00268                             usage2 (_("Invalid hostname/address"), optarg);
00269                      else
00270                             pghost = optarg;
00271                      break;
00272               case 'P':     /* port */
00273                      if (!is_integer (optarg))
00274                             usage2 (_("Port must be a positive integer"), optarg);
00275                      else
00276                             pgport = optarg;
00277                      break;
00278               case 'd':     /* database name */
00279                      if (!is_pg_dbname (optarg)) /* checks length and valid chars */
00280                             usage2 (_("Database name is not valid"), optarg);
00281                      else /* we know length, and know optarg is terminated, so us strcpy */
00282                             strcpy (dbName, optarg);
00283                      break;
00284               case 'l':     /* login name */
00285                      if (!is_pg_logname (optarg))
00286                             usage2 (_("User name is not valid"), optarg);
00287                      else
00288                             pguser = optarg;
00289                      break;
00290               case 'p':     /* authentication password */
00291               case 'a':
00292                      pgpasswd = optarg;
00293                      break;
00294               case 'v':
00295                      verbose++;
00296                      break;
00297               }
00298        }
00299 
00300        return validate_arguments ();
00301 }
00302 
00303 
00304 /******************************************************************************
00305 
00306 @@-
00307 <sect3>
00308 <title>validate_arguments</title>
00309 
00310 <para>&PROTO_validate_arguments;</para>
00311 
00312 <para>Given a database name, this function returns TRUE if the string
00313 is a valid PostgreSQL database name, and returns false if it is
00314 not.</para>
00315 
00316 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
00317 characters long and consist of letters, numbers, and underscores. The
00318 first character cannot be a number, however.</para>
00319 
00320 </sect3>
00321 -@@
00322 ******************************************************************************/
00323 
00324 
00325 
00326 int
00327 validate_arguments ()
00328 {
00329        return OK;
00330 }
00331 
00332 
00333 /******************************************************************************
00334 
00335 @@-
00336 <sect3>
00337 <title>is_pg_dbname</title>
00338 
00339 <para>&PROTO_is_pg_dbname;</para>
00340 
00341 <para>Given a database name, this function returns TRUE if the string
00342 is a valid PostgreSQL database name, and returns false if it is
00343 not.</para>
00344 
00345 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
00346 characters long and consist of letters, numbers, and underscores. The
00347 first character cannot be a number, however.</para>
00348 
00349 </sect3>
00350 -@@
00351 ******************************************************************************/
00352 
00353 
00354 
00355 int
00356 is_pg_dbname (char *dbname)
00357 {
00358        char txt[NAMEDATALEN];
00359        char tmp[NAMEDATALEN];
00360        if (strlen (dbname) > NAMEDATALEN - 1)
00361               return (FALSE);
00362        strncpy (txt, dbname, NAMEDATALEN - 1);
00363        txt[NAMEDATALEN - 1] = 0;
00364        if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
00365               return (TRUE);
00366        if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
00367                      2) return (TRUE);
00368        return (FALSE);
00369 }
00370 
00397 int
00398 is_pg_logname (char *username)
00399 {
00400        if (strlen (username) > NAMEDATALEN - 1)
00401               return (FALSE);
00402        return (TRUE);
00403 }
00404 
00405 /******************************************************************************
00406 @@-
00407 </sect2>
00408 </sect1>
00409 </article>
00410 -@@
00411 ******************************************************************************/
00412 
00413 
00414 
00415 void
00416 print_help (void)
00417 {
00418        char *myport;
00419 
00420        asprintf (&myport, "%d", DEFAULT_PORT);
00421 
00422        print_revision (progname, NP_VERSION);
00423 
00424        printf (COPYRIGHT, copyright, email);
00425 
00426        printf (_("Test whether a PostgreSQL Database is accepting connections."));
00427 
00428        printf ("\n\n");
00429 
00430        print_usage ();
00431 
00432        printf (UT_HELP_VRSN);
00433        printf (UT_EXTRA_OPTS);
00434 
00435        printf (UT_HOST_PORT, 'P', myport);
00436 
00437        printf (UT_IPv46);
00438 
00439        printf (" %s\n", "-d, --database=STRING");
00440        printf ("    %s", _("Database to check "));
00441        printf (_("(default: %s)"), DEFAULT_DB);
00442        printf (" %s\n", "-l, --logname = STRING");
00443        printf ("    %s\n", _("Login name of user"));
00444        printf (" %s\n", "-p, --password = STRING");
00445        printf ("    %s\n", _("Password (BIG SECURITY ISSUE)"));
00446 
00447        printf (UT_WARN_CRIT);
00448 
00449        printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
00450 
00451        printf (UT_VERBOSE);
00452 
00453        printf ("\n");
00454        printf (" %s\n", _("All parameters are optional."));
00455        printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
00456        printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
00457        printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
00458        printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
00459        printf (" %s\n\n", _("PostgreSQL DBMS."));
00460 
00461        printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
00462        printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
00463        printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
00464 
00465        printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
00466        printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
00467        printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
00468 
00469        printf (UT_SUPPORT);
00470 }
00471 
00472 
00473 
00474 void
00475 print_usage (void)
00476 {
00477        printf ("%s\n", _("Usage:"));
00478        printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
00479        printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n");
00480 }