Code

Bump plugin/ to GPLv3 (check_overcr to check_users)
[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 * 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 * 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.
21
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.
26
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/>.
29
30 * $Id$
31
32 *****************************************************************************/
34 const char *progname = "check_pgsql";
35 const char *revision = "$Revision$";
36 const char *copyright = "1999-2007";
37 const char *email = "nagiosplug-devel@lists.sourceforge.net";
39 #include "common.h"
40 #include "utils.h"
42 #include "netutils.h"
43 #include <libpq-fe.h>
45 #define DEFAULT_DB "template1"
46 #define DEFAULT_HOST "127.0.0.1"
48 enum {
49         DEFAULT_PORT = 5432,
50         DEFAULT_WARN = 2,
51         DEFAULT_CRIT = 8
52 };
56 int process_arguments (int, char **);
57 int validate_arguments (void);
58 void print_usage (void);
59 void print_help (void);
60 int is_pg_dbname (char *);
61 int is_pg_logname (char *);
63 char *pghost = NULL;                                            /* host name of the backend server */
64 char *pgport = NULL;                                            /* port of the backend server */
65 int default_port = DEFAULT_PORT;
66 char *pgoptions = NULL;
67 char *pgtty = NULL;
68 char dbName[NAMEDATALEN] = DEFAULT_DB;
69 char *pguser = NULL;
70 char *pgpasswd = NULL;
71 double twarn = (double)DEFAULT_WARN;
72 double tcrit = (double)DEFAULT_CRIT;
74 PGconn *conn;
75 /*PGresult   *res;*/
78 /******************************************************************************
80 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
81 tags in the comments. With in the tags, the XML is assembled sequentially.
82 You can define entities in tags. You also have all the #defines available as
83 entities.
85 Please note that all tags must be lowercase to use the DocBook XML DTD.
87 @@-<article>
89 <sect1>
90 <title>Quick Reference</title>
91 <!-- The refentry forms a manpage -->
92 <refentry>
93 <refmeta>
94 <manvolnum>5<manvolnum>
95 </refmeta>
96 <refnamdiv>
97 <refname>&progname;</refname>
98 <refpurpose>&SUMMARY;</refpurpose>
99 </refnamdiv>
100 </refentry>
101 </sect1>
103 <sect1>
104 <title>FAQ</title>
105 </sect1>
107 <sect1>
108 <title>Theory, Installation, and Operation</title>
110 <sect2>
111 <title>General Description</title>
112 <para>
113 &DESCRIPTION;
114 </para>
115 </sect2>
117 <sect2>
118 <title>Future Enhancements</title>
119 <para>ToDo List</para>
120 <itemizedlist>
121 <listitem>Add option to get password from a secured file rather than the command line</listitem>
122 <listitem>Add option to specify the query to execute</listitem>
123 </itemizedlist>
124 </sect2>
127 <sect2>
128 <title>Functions</title>
129 -@@
130 ******************************************************************************/
134 int
135 main (int argc, char **argv)
137         int elapsed_time;
138         int status = STATE_UNKNOWN;
140         /* begin, by setting the parameters for a backend connection if the
141          * parameters are null, then the system will try to use reasonable
142          * defaults by looking up environment variables or, failing that,
143          * using hardwired constants */
145         pgoptions = NULL;  /* special options to start up the backend server */
146         pgtty = NULL;      /* debugging tty for the backend server */
148         setlocale (LC_ALL, "");
149         bindtextdomain (PACKAGE, LOCALEDIR);
150         textdomain (PACKAGE);
152         if (process_arguments (argc, argv) == ERROR)
153                 usage4 (_("Could not parse arguments"));
155         /* Set signal handling and alarm */
156         if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
157                 usage4 (_("Cannot catch SIGALRM"));
158         }
159         alarm (timeout_interval);
161         /* make a connection to the database */
162         time (&start_time);
163         conn =
164                 PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd);
165         time (&end_time);
166         elapsed_time = (int) (end_time - start_time);
168         /* check to see that the backend connection was successfully made */
169         if (PQstatus (conn) == CONNECTION_BAD) {
170                 printf (_("CRITICAL - no connection to '%s' (%s).\n"),
171                         dbName, PQerrorMessage (conn));
172                 PQfinish (conn);
173                 return STATE_CRITICAL;
174         }
175         else if (elapsed_time > tcrit) {
176                 status = STATE_CRITICAL;
177         }
178         else if (elapsed_time > twarn) {
179                 status = STATE_WARNING;
180         }
181         else {
182                 status = STATE_OK;
183         }
184         PQfinish (conn);
185         printf (_(" %s - database %s (%d sec.)|%s\n"), 
186                 state_text(status), dbName, elapsed_time,
187                 fperfdata("time", elapsed_time, "s",
188                          (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
189         return status;
194 /* process command-line arguments */
195 int
196 process_arguments (int argc, char **argv)
198         int c;
200         int option = 0;
201         static struct option longopts[] = {
202                 {"help", no_argument, 0, 'h'},
203                 {"version", no_argument, 0, 'V'},
204                 {"timeout", required_argument, 0, 't'},
205                 {"critical", required_argument, 0, 'c'},
206                 {"warning", required_argument, 0, 'w'},
207                 {"hostname", required_argument, 0, 'H'},
208                 {"logname", required_argument, 0, 'l'},
209                 {"password", required_argument, 0, 'p'},
210                 {"authorization", required_argument, 0, 'a'},
211                 {"port", required_argument, 0, 'P'},
212                 {"database", required_argument, 0, 'd'},
213                 {0, 0, 0, 0}
214         };
216         while (1) {
217                 c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:",
218                                  longopts, &option);
220                 if (c == EOF)
221                         break;
223                 switch (c) {
224                 case '?':     /* usage */
225                         usage5 ();
226                 case 'h':     /* help */
227                         print_help ();
228                         exit (STATE_OK);
229                 case 'V':     /* version */
230                         print_revision (progname, revision);
231                         exit (STATE_OK);
232                 case 't':     /* timeout period */
233                         if (!is_integer (optarg))
234                                 usage2 (_("Timeout interval must be a positive integer"), optarg);
235                         else
236                                 timeout_interval = atoi (optarg);
237                         break;
238                 case 'c':     /* critical time threshold */
239                         if (!is_nonnegative (optarg))
240                                 usage2 (_("Critical threshold must be a positive integer"), optarg);
241                         else
242                                 tcrit = strtod (optarg, NULL);
243                         break;
244                 case 'w':     /* warning time threshold */
245                         if (!is_nonnegative (optarg))
246                                 usage2 (_("Warning threshold must be a positive integer"), optarg);
247                         else
248                                 twarn = strtod (optarg, NULL);
249                         break;
250                 case 'H':     /* host */
251                         if (!is_host (optarg))
252                                 usage2 (_("Invalid hostname/address"), optarg);
253                         else
254                                 pghost = optarg;
255                         break;
256                 case 'P':     /* port */
257                         if (!is_integer (optarg))
258                                 usage2 (_("Port must be a positive integer"), optarg);
259                         else
260                                 pgport = optarg;
261                         break;
262                 case 'd':     /* database name */
263                         if (!is_pg_dbname (optarg)) /* checks length and valid chars */
264                                 usage2 (_("Database name is not valid"), optarg);
265                         else /* we know length, and know optarg is terminated, so us strcpy */
266                                 strcpy (dbName, optarg);
267                         break;
268                 case 'l':     /* login name */
269                         if (!is_pg_logname (optarg))
270                                 usage2 (_("User name is not valid"), optarg);
271                         else
272                                 pguser = optarg;
273                         break;
274                 case 'p':     /* authentication password */
275                 case 'a':
276                         pgpasswd = optarg;
277                         break;
278                 }
279         }
281         return validate_arguments ();
285 /******************************************************************************
287 @@-
288 <sect3>
289 <title>validate_arguments</title>
291 <para>&PROTO_validate_arguments;</para>
293 <para>Given a database name, this function returns TRUE if the string
294 is a valid PostgreSQL database name, and returns false if it is
295 not.</para>
297 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
298 characters long and consist of letters, numbers, and underscores. The
299 first character cannot be a number, however.</para>
301 </sect3>
302 -@@
303 ******************************************************************************/
307 int
308 validate_arguments ()
310         return OK;
314 /******************************************************************************
316 @@-
317 <sect3>
318 <title>is_pg_dbname</title>
320 <para>&PROTO_is_pg_dbname;</para>
322 <para>Given a database name, this function returns TRUE if the string
323 is a valid PostgreSQL database name, and returns false if it is
324 not.</para>
326 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
327 characters long and consist of letters, numbers, and underscores. The
328 first character cannot be a number, however.</para>
330 </sect3>
331 -@@
332 ******************************************************************************/
336 int
337 is_pg_dbname (char *dbname)
339         char txt[NAMEDATALEN];
340         char tmp[NAMEDATALEN];
341         if (strlen (dbname) > NAMEDATALEN - 1)
342                 return (FALSE);
343         strncpy (txt, dbname, NAMEDATALEN - 1);
344         txt[NAMEDATALEN - 1] = 0;
345         if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
346                 return (TRUE);
347         if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
348                         2) return (TRUE);
349         return (FALSE);
352 /**
354 the tango program should eventually create an entity here based on the 
355 function prototype
357 @@-
358 <sect3>
359 <title>is_pg_logname</title>
361 <para>&PROTO_is_pg_logname;</para>
363 <para>Given a username, this function returns TRUE if the string is a
364 valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
365 usernames are less than &NAMEDATALEN; characters long and consist of
366 letters, numbers, dashes, and underscores, plus possibly some other
367 characters.</para>
369 <para>Currently this function only checks string length. Additional checks
370 should be added.</para>
372 </sect3>
373 -@@
374 ******************************************************************************/
378 int
379 is_pg_logname (char *username)
381         if (strlen (username) > NAMEDATALEN - 1)
382                 return (FALSE);
383         return (TRUE);
386 /******************************************************************************
387 @@-
388 </sect2> 
389 </sect1>
390 </article>
391 -@@
392 ******************************************************************************/
396 void
397 print_help (void)
399         char *myport;
401         asprintf (&myport, "%d", DEFAULT_PORT);
403         print_revision (progname, revision);
405         printf (COPYRIGHT, copyright, email);
407         printf (_("Test whether a PostgreSQL Database is accepting connections."));
409   printf ("\n\n");
411         print_usage ();
413         printf (_(UT_HELP_VRSN));
415         printf (_(UT_HOST_PORT), 'P', myport);
417         printf (_(UT_IPv46));
419         printf (" %s\n", "-d, --database=STRING");
420   printf ("    %s", _("Database to check "));
421   printf (_("(default: %s)"), DEFAULT_DB);
422   printf (" %s\n", "-l, --logname = STRING");
423   printf ("    %s\n", _("Login name of user"));
424   printf (" %s\n", "-p, --password = STRING");
425   printf ("    %s\n", _("Password (BIG SECURITY ISSUE)"));
427         printf (_(UT_WARN_CRIT));
429         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
431         printf (_(UT_VERBOSE));
433   printf ("\n");
434         printf (" %s\n", _("All parameters are optional."));
435   printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
436   printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
437   printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
438   printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
439   printf (" %s\n\n", _("PostgreSQL DBMS."));
440         printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
441   printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
442   printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
443         printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
444   printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
445   printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
447         printf (_(UT_SUPPORT));
452 void
453 print_usage (void)
455   printf (_("Usage:"));
456         printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
457   printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n");