Merge branch 'master' of ssh://tonvoon@nagiosplug.git.sourceforge.net/gitroot/nagiosp...
[monitoring-plugins.git] / plugins / check_pgsql.c
blob19c3117d72929e6d29495ea3569c62c1f8426f7e
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
12 * Test whether a PostgreSQL Database is accepting connections.
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.
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.
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/>.
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 enum {
46 DEFAULT_PORT = 5432,
47 DEFAULT_WARN = 2,
48 DEFAULT_CRIT = 8
53 int process_arguments (int, char **);
54 int validate_arguments (void);
55 void print_usage (void);
56 void print_help (void);
57 int is_pg_dbname (char *);
58 int is_pg_logname (char *);
60 char *pghost = NULL; /* host name of the backend server */
61 char *pgport = NULL; /* port of the backend server */
62 int default_port = DEFAULT_PORT;
63 char *pgoptions = NULL;
64 char *pgtty = NULL;
65 char dbName[NAMEDATALEN] = DEFAULT_DB;
66 char *pguser = NULL;
67 char *pgpasswd = NULL;
68 double twarn = (double)DEFAULT_WARN;
69 double tcrit = (double)DEFAULT_CRIT;
70 int verbose = 0;
72 PGconn *conn;
73 /*PGresult *res;*/
76 /******************************************************************************
78 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
79 tags in the comments. With in the tags, the XML is assembled sequentially.
80 You can define entities in tags. You also have all the #defines available as
81 entities.
83 Please note that all tags must be lowercase to use the DocBook XML DTD.
85 @@-<article>
87 <sect1>
88 <title>Quick Reference</title>
89 <!-- The refentry forms a manpage -->
90 <refentry>
91 <refmeta>
92 <manvolnum>5<manvolnum>
93 </refmeta>
94 <refnamdiv>
95 <refname>&progname;</refname>
96 <refpurpose>&SUMMARY;</refpurpose>
97 </refnamdiv>
98 </refentry>
99 </sect1>
101 <sect1>
102 <title>FAQ</title>
103 </sect1>
105 <sect1>
106 <title>Theory, Installation, and Operation</title>
108 <sect2>
109 <title>General Description</title>
110 <para>
111 &DESCRIPTION;
112 </para>
113 </sect2>
115 <sect2>
116 <title>Future Enhancements</title>
117 <para>ToDo List</para>
118 <itemizedlist>
119 <listitem>Add option to get password from a secured file rather than the command line</listitem>
120 <listitem>Add option to specify the query to execute</listitem>
121 </itemizedlist>
122 </sect2>
125 <sect2>
126 <title>Functions</title>
128 ******************************************************************************/
133 main (int argc, char **argv)
135 int elapsed_time;
136 int status = STATE_UNKNOWN;
138 /* begin, by setting the parameters for a backend connection if the
139 * parameters are null, then the system will try to use reasonable
140 * defaults by looking up environment variables or, failing that,
141 * using hardwired constants */
143 pgoptions = NULL; /* special options to start up the backend server */
144 pgtty = NULL; /* debugging tty for the backend server */
146 setlocale (LC_ALL, "");
147 bindtextdomain (PACKAGE, LOCALEDIR);
148 textdomain (PACKAGE);
150 /* Parse extra opts if any */
151 argv=np_extra_opts (&argc, argv, progname);
153 if (process_arguments (argc, argv) == ERROR)
154 usage4 (_("Could not parse arguments"));
155 if (verbose > 2)
156 printf("Arguments initialized\n");
158 /* Set signal handling and alarm */
159 if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
160 usage4 (_("Cannot catch SIGALRM"));
162 alarm (timeout_interval);
164 if (verbose)
165 printf("Connecting to database:\n DB: %s\n User: %s\n Host: %s\n Port: %d\n", dbName,
166 (pguser != NULL) ? pguser : "unspecified",
167 (pghost != NULL) ? pghost : "unspecified",
168 (pgport != NULL) ? atoi(pgport) : DEFAULT_PORT);
170 /* make a connection to the database */
171 time (&start_time);
172 conn =
173 PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd);
174 time (&end_time);
175 elapsed_time = (int) (end_time - start_time);
176 if (verbose)
177 printf("Time elapsed: %d\n", elapsed_time);
179 /* check to see that the backend connection was successfully made */
180 if (verbose)
181 printf("Verifying connection\n");
182 if (PQstatus (conn) == CONNECTION_BAD) {
183 printf (_("CRITICAL - no connection to '%s' (%s).\n"),
184 dbName, PQerrorMessage (conn));
185 PQfinish (conn);
186 return STATE_CRITICAL;
188 else if (elapsed_time > tcrit) {
189 status = STATE_CRITICAL;
191 else if (elapsed_time > twarn) {
192 status = STATE_WARNING;
194 else {
195 status = STATE_OK;
197 if (verbose)
198 printf("Closing connection\n");
199 PQfinish (conn);
200 printf (_(" %s - database %s (%d sec.)|%s\n"),
201 state_text(status), dbName, elapsed_time,
202 fperfdata("time", elapsed_time, "s",
203 (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
204 return status;
209 /* process command-line arguments */
211 process_arguments (int argc, char **argv)
213 int c;
215 int option = 0;
216 static struct option longopts[] = {
217 {"help", no_argument, 0, 'h'},
218 {"version", no_argument, 0, 'V'},
219 {"timeout", required_argument, 0, 't'},
220 {"critical", required_argument, 0, 'c'},
221 {"warning", required_argument, 0, 'w'},
222 {"hostname", required_argument, 0, 'H'},
223 {"logname", required_argument, 0, 'l'},
224 {"password", required_argument, 0, 'p'},
225 {"authorization", required_argument, 0, 'a'},
226 {"port", required_argument, 0, 'P'},
227 {"database", required_argument, 0, 'd'},
228 {"verbose", no_argument, 0, 'v'},
229 {0, 0, 0, 0}
232 while (1) {
233 c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:v",
234 longopts, &option);
236 if (c == EOF)
237 break;
239 switch (c) {
240 case '?': /* usage */
241 usage5 ();
242 case 'h': /* help */
243 print_help ();
244 exit (STATE_OK);
245 case 'V': /* version */
246 print_revision (progname, NP_VERSION);
247 exit (STATE_OK);
248 case 't': /* timeout period */
249 if (!is_integer (optarg))
250 usage2 (_("Timeout interval must be a positive integer"), optarg);
251 else
252 timeout_interval = atoi (optarg);
253 break;
254 case 'c': /* critical time threshold */
255 if (!is_nonnegative (optarg))
256 usage2 (_("Critical threshold must be a positive integer"), optarg);
257 else
258 tcrit = strtod (optarg, NULL);
259 break;
260 case 'w': /* warning time threshold */
261 if (!is_nonnegative (optarg))
262 usage2 (_("Warning threshold must be a positive integer"), optarg);
263 else
264 twarn = strtod (optarg, NULL);
265 break;
266 case 'H': /* host */
267 if (!is_host (optarg))
268 usage2 (_("Invalid hostname/address"), optarg);
269 else
270 pghost = optarg;
271 break;
272 case 'P': /* port */
273 if (!is_integer (optarg))
274 usage2 (_("Port must be a positive integer"), optarg);
275 else
276 pgport = optarg;
277 break;
278 case 'd': /* database name */
279 if (!is_pg_dbname (optarg)) /* checks length and valid chars */
280 usage2 (_("Database name is not valid"), optarg);
281 else /* we know length, and know optarg is terminated, so us strcpy */
282 strcpy (dbName, optarg);
283 break;
284 case 'l': /* login name */
285 if (!is_pg_logname (optarg))
286 usage2 (_("User name is not valid"), optarg);
287 else
288 pguser = optarg;
289 break;
290 case 'p': /* authentication password */
291 case 'a':
292 pgpasswd = optarg;
293 break;
294 case 'v':
295 verbose++;
296 break;
300 return validate_arguments ();
304 /******************************************************************************
307 <sect3>
308 <title>validate_arguments</title>
310 <para>&PROTO_validate_arguments;</para>
312 <para>Given a database name, this function returns TRUE if the string
313 is a valid PostgreSQL database name, and returns false if it is
314 not.</para>
316 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
317 characters long and consist of letters, numbers, and underscores. The
318 first character cannot be a number, however.</para>
320 </sect3>
322 ******************************************************************************/
327 validate_arguments ()
329 return OK;
333 /******************************************************************************
336 <sect3>
337 <title>is_pg_dbname</title>
339 <para>&PROTO_is_pg_dbname;</para>
341 <para>Given a database name, this function returns TRUE if the string
342 is a valid PostgreSQL database name, and returns false if it is
343 not.</para>
345 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
346 characters long and consist of letters, numbers, and underscores. The
347 first character cannot be a number, however.</para>
349 </sect3>
351 ******************************************************************************/
356 is_pg_dbname (char *dbname)
358 char txt[NAMEDATALEN];
359 char tmp[NAMEDATALEN];
360 if (strlen (dbname) > NAMEDATALEN - 1)
361 return (FALSE);
362 strncpy (txt, dbname, NAMEDATALEN - 1);
363 txt[NAMEDATALEN - 1] = 0;
364 if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
365 return (TRUE);
366 if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
367 2) return (TRUE);
368 return (FALSE);
373 the tango program should eventually create an entity here based on the
374 function prototype
377 <sect3>
378 <title>is_pg_logname</title>
380 <para>&PROTO_is_pg_logname;</para>
382 <para>Given a username, this function returns TRUE if the string is a
383 valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
384 usernames are less than &NAMEDATALEN; characters long and consist of
385 letters, numbers, dashes, and underscores, plus possibly some other
386 characters.</para>
388 <para>Currently this function only checks string length. Additional checks
389 should be added.</para>
391 </sect3>
393 ******************************************************************************/
398 is_pg_logname (char *username)
400 if (strlen (username) > NAMEDATALEN - 1)
401 return (FALSE);
402 return (TRUE);
405 /******************************************************************************
407 </sect2>
408 </sect1>
409 </article>
411 ******************************************************************************/
415 void
416 print_help (void)
418 char *myport;
420 asprintf (&myport, "%d", DEFAULT_PORT);
422 print_revision (progname, NP_VERSION);
424 printf (COPYRIGHT, copyright, email);
426 printf (_("Test whether a PostgreSQL Database is accepting connections."));
428 printf ("\n\n");
430 print_usage ();
432 printf (UT_HELP_VRSN);
433 printf (UT_EXTRA_OPTS);
435 printf (UT_HOST_PORT, 'P', myport);
437 printf (UT_IPv46);
439 printf (" %s\n", "-d, --database=STRING");
440 printf (" %s", _("Database to check "));
441 printf (_("(default: %s)"), DEFAULT_DB);
442 printf (" %s\n", "-l, --logname = STRING");
443 printf (" %s\n", _("Login name of user"));
444 printf (" %s\n", "-p, --password = STRING");
445 printf (" %s\n", _("Password (BIG SECURITY ISSUE)"));
447 printf (UT_WARN_CRIT);
449 printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
451 printf (UT_VERBOSE);
453 printf ("\n");
454 printf (" %s\n", _("All parameters are optional."));
455 printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
456 printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
457 printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
458 printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
459 printf (" %s\n\n", _("PostgreSQL DBMS."));
461 printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
462 printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
463 printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
465 printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
466 printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
467 printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
469 printf (UT_SUPPORT);
474 void
475 print_usage (void)
477 printf ("%s\n", _("Usage:"));
478 printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
479 printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n");