Code

The "--serverip" and "--requestedip" options now accept host names, too.
[nagiosplug.git] / plugins / check_pgsql.c
1 /******************************************************************************
2 *
3 * Nagios check_pgsql plugin
4 *
5 * License: GPL
6 * Copyright (c) 1999-2006 nagios-plugins team
7 *
8 * Last Modified: $Date$
9 *
10 * Description:
11 *
12 * This file contains the check_pgsql plugin
13 *
14 *  Test whether a PostgreSQL Database is accepting connections.
15 *
16 *
17 * License Information:
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33  $Id$
34  
35  *****************************************************************************/
37 const char *progname = "check_pgsql";
38 const char *revision = "$Revision$";
39 const char *copyright = "1999-2006";
40 const char *email = "nagiosplug-devel@lists.sourceforge.net";
42 #include "common.h"
43 #include "utils.h"
45 #include "netutils.h"
46 #include <libpq-fe.h>
48 #define DEFAULT_DB "template1"
49 #define DEFAULT_HOST "127.0.0.1"
51 enum {
52         DEFAULT_PORT = 5432,
53         DEFAULT_WARN = 2,
54         DEFAULT_CRIT = 8
55 };
59 int process_arguments (int, char **);
60 int validate_arguments (void);
61 void print_usage (void);
62 void print_help (void);
63 int is_pg_dbname (char *);
64 int is_pg_logname (char *);
66 char *pghost = NULL;                                            /* host name of the backend server */
67 char *pgport = NULL;                                            /* port of the backend server */
68 int default_port = DEFAULT_PORT;
69 char *pgoptions = NULL;
70 char *pgtty = NULL;
71 char dbName[NAMEDATALEN] = DEFAULT_DB;
72 char *pguser = NULL;
73 char *pgpasswd = NULL;
74 double twarn = (double)DEFAULT_WARN;
75 double tcrit = (double)DEFAULT_CRIT;
77 PGconn *conn;
78 /*PGresult   *res;*/
81 /******************************************************************************
83 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
84 tags in the comments. With in the tags, the XML is assembled sequentially.
85 You can define entities in tags. You also have all the #defines available as
86 entities.
88 Please note that all tags must be lowercase to use the DocBook XML DTD.
90 @@-<article>
92 <sect1>
93 <title>Quick Reference</title>
94 <!-- The refentry forms a manpage -->
95 <refentry>
96 <refmeta>
97 <manvolnum>5<manvolnum>
98 </refmeta>
99 <refnamdiv>
100 <refname>&progname;</refname>
101 <refpurpose>&SUMMARY;</refpurpose>
102 </refnamdiv>
103 </refentry>
104 </sect1>
106 <sect1>
107 <title>FAQ</title>
108 </sect1>
110 <sect1>
111 <title>Theory, Installation, and Operation</title>
113 <sect2>
114 <title>General Description</title>
115 <para>
116 &DESCRIPTION;
117 </para>
118 </sect2>
120 <sect2>
121 <title>Future Enhancements</title>
122 <para>ToDo List</para>
123 <itemizedlist>
124 <listitem>Add option to get password from a secured file rather than the command line</listitem>
125 <listitem>Add option to specify the query to execute</listitem>
126 </itemizedlist>
127 </sect2>
130 <sect2>
131 <title>Functions</title>
132 -@@
133 ******************************************************************************/
137 int
138 main (int argc, char **argv)
140         int elapsed_time;
141         int status = STATE_UNKNOWN;
143         /* begin, by setting the parameters for a backend connection if the
144          * parameters are null, then the system will try to use reasonable
145          * defaults by looking up environment variables or, failing that,
146          * using hardwired constants */
148         pgoptions = NULL;  /* special options to start up the backend server */
149         pgtty = NULL;      /* debugging tty for the backend server */
151         setlocale (LC_ALL, "");
152         bindtextdomain (PACKAGE, LOCALEDIR);
153         textdomain (PACKAGE);
155         if (process_arguments (argc, argv) == ERROR)
156                 usage4 (_("Could not parse arguments"));
158         /* Set signal handling and alarm */
159         if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
160                 usage4 (_("Cannot catch SIGALRM"));
161         }
162         alarm (timeout_interval);
164         /* make a connection to the database */
165         time (&start_time);
166         conn =
167                 PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd);
168         time (&end_time);
169         elapsed_time = (int) (end_time - start_time);
171         /* check to see that the backend connection was successfully made */
172         if (PQstatus (conn) == CONNECTION_BAD) {
173                 printf (_("CRITICAL - no connection to '%s' (%s).\n"),
174                         dbName, PQerrorMessage (conn));
175                 PQfinish (conn);
176                 return STATE_CRITICAL;
177         }
178         else if (elapsed_time > tcrit) {
179                 status = STATE_CRITICAL;
180         }
181         else if (elapsed_time > twarn) {
182                 status = STATE_WARNING;
183         }
184         else {
185                 status = STATE_OK;
186         }
187         PQfinish (conn);
188         printf (_(" %s - database %s (%d sec.)|%s\n"), 
189                 state_text(status), dbName, elapsed_time,
190                 fperfdata("time", elapsed_time, "s",
191                          (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
192         return status;
197 /* process command-line arguments */
198 int
199 process_arguments (int argc, char **argv)
201         int c;
203         int option = 0;
204         static struct option longopts[] = {
205                 {"help", no_argument, 0, 'h'},
206                 {"version", no_argument, 0, 'V'},
207                 {"timeout", required_argument, 0, 't'},
208                 {"critical", required_argument, 0, 'c'},
209                 {"warning", required_argument, 0, 'w'},
210                 {"hostname", required_argument, 0, 'H'},
211                 {"logname", required_argument, 0, 'l'},
212                 {"password", required_argument, 0, 'p'},
213                 {"authorization", required_argument, 0, 'a'},
214                 {"port", required_argument, 0, 'P'},
215                 {"database", required_argument, 0, 'd'},
216                 {0, 0, 0, 0}
217         };
219         while (1) {
220                 c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:",
221                                  longopts, &option);
223                 if (c == EOF)
224                         break;
226                 switch (c) {
227                 case '?':     /* usage */
228                         usage5 ();
229                 case 'h':     /* help */
230                         print_help ();
231                         exit (STATE_OK);
232                 case 'V':     /* version */
233                         print_revision (progname, revision);
234                         exit (STATE_OK);
235                 case 't':     /* timeout period */
236                         if (!is_integer (optarg))
237                                 usage2 (_("Timeout interval must be a positive integer"), optarg);
238                         else
239                                 timeout_interval = atoi (optarg);
240                         break;
241                 case 'c':     /* critical time threshold */
242                         if (!is_nonnegative (optarg))
243                                 usage2 (_("Critical threshold must be a positive integer"), optarg);
244                         else
245                                 tcrit = strtod (optarg, NULL);
246                         break;
247                 case 'w':     /* warning time threshold */
248                         if (!is_nonnegative (optarg))
249                                 usage2 (_("Warning threshold must be a positive integer"), optarg);
250                         else
251                                 twarn = strtod (optarg, NULL);
252                         break;
253                 case 'H':     /* host */
254                         if (!is_host (optarg))
255                                 usage2 (_("Invalid hostname/address"), optarg);
256                         else
257                                 pghost = optarg;
258                         break;
259                 case 'P':     /* port */
260                         if (!is_integer (optarg))
261                                 usage2 (_("Port must be a positive integer"), optarg);
262                         else
263                                 pgport = optarg;
264                         break;
265                 case 'd':     /* database name */
266                         if (!is_pg_dbname (optarg)) /* checks length and valid chars */
267                                 usage2 (_("Database name is not valid"), optarg);
268                         else /* we know length, and know optarg is terminated, so us strcpy */
269                                 strcpy (dbName, optarg);
270                         break;
271                 case 'l':     /* login name */
272                         if (!is_pg_logname (optarg))
273                                 usage2 (_("User name is not valid"), optarg);
274                         else
275                                 pguser = optarg;
276                         break;
277                 case 'p':     /* authentication password */
278                 case 'a':
279                         pgpasswd = optarg;
280                         break;
281                 }
282         }
284         return validate_arguments ();
288 /******************************************************************************
290 @@-
291 <sect3>
292 <title>validate_arguments</title>
294 <para>&PROTO_validate_arguments;</para>
296 <para>Given a database name, this function returns TRUE if the string
297 is a valid PostgreSQL database name, and returns false if it is
298 not.</para>
300 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
301 characters long and consist of letters, numbers, and underscores. The
302 first character cannot be a number, however.</para>
304 </sect3>
305 -@@
306 ******************************************************************************/
310 int
311 validate_arguments ()
313         return OK;
317 /******************************************************************************
319 @@-
320 <sect3>
321 <title>is_pg_dbname</title>
323 <para>&PROTO_is_pg_dbname;</para>
325 <para>Given a database name, this function returns TRUE if the string
326 is a valid PostgreSQL database name, and returns false if it is
327 not.</para>
329 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
330 characters long and consist of letters, numbers, and underscores. The
331 first character cannot be a number, however.</para>
333 </sect3>
334 -@@
335 ******************************************************************************/
339 int
340 is_pg_dbname (char *dbname)
342         char txt[NAMEDATALEN];
343         char tmp[NAMEDATALEN];
344         if (strlen (dbname) > NAMEDATALEN - 1)
345                 return (FALSE);
346         strncpy (txt, dbname, NAMEDATALEN - 1);
347         txt[NAMEDATALEN - 1] = 0;
348         if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
349                 return (TRUE);
350         if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
351                         2) return (TRUE);
352         return (FALSE);
355 /**
357 the tango program should eventually create an entity here based on the 
358 function prototype
360 @@-
361 <sect3>
362 <title>is_pg_logname</title>
364 <para>&PROTO_is_pg_logname;</para>
366 <para>Given a username, this function returns TRUE if the string is a
367 valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
368 usernames are less than &NAMEDATALEN; characters long and consist of
369 letters, numbers, dashes, and underscores, plus possibly some other
370 characters.</para>
372 <para>Currently this function only checks string length. Additional checks
373 should be added.</para>
375 </sect3>
376 -@@
377 ******************************************************************************/
381 int
382 is_pg_logname (char *username)
384         if (strlen (username) > NAMEDATALEN - 1)
385                 return (FALSE);
386         return (TRUE);
389 /******************************************************************************
390 @@-
391 </sect2> 
392 </sect1>
393 </article>
394 -@@
395 ******************************************************************************/
399 void
400 print_help (void)
402         char *myport;
404         asprintf (&myport, "%d", DEFAULT_PORT);
406         print_revision (progname, revision);
408         printf (COPYRIGHT, copyright, email);
410         printf (_("Test whether a PostgreSQL Database is accepting connections."));
412   printf ("\n\n");
414         print_usage ();
416         printf (_(UT_HELP_VRSN));
418         printf (_(UT_HOST_PORT), 'P', myport);
420         printf (_(UT_IPv46));
422         printf (" %s\n", "-d, --database=STRING");
423   printf ("    %s", _("Database to check "));
424   printf (_("(default: %s)"), DEFAULT_DB);
425   printf (" %s\n", "-l, --logname = STRING");
426   printf ("    %s\n", _("Login name of user"));
427   printf (" %s\n", "-p, --password = STRING");
428   printf ("    %s\n", _("Password (BIG SECURITY ISSUE)"));
430         printf (_(UT_WARN_CRIT));
432         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
434         printf (_(UT_VERBOSE));
436   printf ("\n");
437         printf (" %s\n", _("All parameters are optional."));
438   printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
439   printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
440   printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
441   printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
442   printf (" %s\n\n", _("PostgreSQL DBMS."));
443         printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
444   printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
445   printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
446         printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
447   printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
448   printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
450         printf (_(UT_SUPPORT));
455 void
456 print_usage (void)
458   printf (_("Usage:"));
459         printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
460   printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n");