Code

Bulk EOL cleanup
[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>
44 #include <pg_config_manual.h>
46 #define DEFAULT_DB "template1"
47 #define DEFAULT_HOST "127.0.0.1"
49 enum {
50         DEFAULT_PORT = 5432,
51         DEFAULT_WARN = 2,
52         DEFAULT_CRIT = 8
53 };
57 int process_arguments (int, char **);
58 int validate_arguments (void);
59 void print_usage (void);
60 void print_help (void);
61 int is_pg_dbname (char *);
62 int is_pg_logname (char *);
64 char *pghost = NULL;                                            /* host name of the backend server */
65 char *pgport = NULL;                                            /* port of the backend server */
66 int default_port = DEFAULT_PORT;
67 char *pgoptions = NULL;
68 char *pgtty = NULL;
69 char dbName[NAMEDATALEN] = DEFAULT_DB;
70 char *pguser = NULL;
71 char *pgpasswd = NULL;
72 double twarn = (double)DEFAULT_WARN;
73 double tcrit = (double)DEFAULT_CRIT;
75 PGconn *conn;
76 /*PGresult   *res;*/
79 /******************************************************************************
81 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
82 tags in the comments. With in the tags, the XML is assembled sequentially.
83 You can define entities in tags. You also have all the #defines available as
84 entities.
86 Please note that all tags must be lowercase to use the DocBook XML DTD.
88 @@-<article>
90 <sect1>
91 <title>Quick Reference</title>
92 <!-- The refentry forms a manpage -->
93 <refentry>
94 <refmeta>
95 <manvolnum>5<manvolnum>
96 </refmeta>
97 <refnamdiv>
98 <refname>&progname;</refname>
99 <refpurpose>&SUMMARY;</refpurpose>
100 </refnamdiv>
101 </refentry>
102 </sect1>
104 <sect1>
105 <title>FAQ</title>
106 </sect1>
108 <sect1>
109 <title>Theory, Installation, and Operation</title>
111 <sect2>
112 <title>General Description</title>
113 <para>
114 &DESCRIPTION;
115 </para>
116 </sect2>
118 <sect2>
119 <title>Future Enhancements</title>
120 <para>ToDo List</para>
121 <itemizedlist>
122 <listitem>Add option to get password from a secured file rather than the command line</listitem>
123 <listitem>Add option to specify the query to execute</listitem>
124 </itemizedlist>
125 </sect2>
128 <sect2>
129 <title>Functions</title>
130 -@@
131 ******************************************************************************/
135 int
136 main (int argc, char **argv)
138         int elapsed_time;
139         int status = STATE_UNKNOWN;
141         /* begin, by setting the parameters for a backend connection if the
142          * parameters are null, then the system will try to use reasonable
143          * defaults by looking up environment variables or, failing that,
144          * using hardwired constants */
146         pgoptions = NULL;  /* special options to start up the backend server */
147         pgtty = NULL;      /* debugging tty for the backend server */
149         setlocale (LC_ALL, "");
150         bindtextdomain (PACKAGE, LOCALEDIR);
151         textdomain (PACKAGE);
153         /* Parse extra opts if any */
154         argv=np_extra_opts (&argc, argv, progname);
156         if (process_arguments (argc, argv) == ERROR)
157                 usage4 (_("Could not parse arguments"));
159         /* Set signal handling and alarm */
160         if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
161                 usage4 (_("Cannot catch SIGALRM"));
162         }
163         alarm (timeout_interval);
165         /* make a connection to the database */
166         time (&start_time);
167         conn =
168                 PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd);
169         time (&end_time);
170         elapsed_time = (int) (end_time - start_time);
172         /* check to see that the backend connection was successfully made */
173         if (PQstatus (conn) == CONNECTION_BAD) {
174                 printf (_("CRITICAL - no connection to '%s' (%s).\n"),
175                         dbName, PQerrorMessage (conn));
176                 PQfinish (conn);
177                 return STATE_CRITICAL;
178         }
179         else if (elapsed_time > tcrit) {
180                 status = STATE_CRITICAL;
181         }
182         else if (elapsed_time > twarn) {
183                 status = STATE_WARNING;
184         }
185         else {
186                 status = STATE_OK;
187         }
188         PQfinish (conn);
189         printf (_(" %s - database %s (%d sec.)|%s\n"),
190                 state_text(status), dbName, elapsed_time,
191                 fperfdata("time", elapsed_time, "s",
192                          (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
193         return status;
198 /* process command-line arguments */
199 int
200 process_arguments (int argc, char **argv)
202         int c;
204         int option = 0;
205         static struct option longopts[] = {
206                 {"help", no_argument, 0, 'h'},
207                 {"version", no_argument, 0, 'V'},
208                 {"timeout", required_argument, 0, 't'},
209                 {"critical", required_argument, 0, 'c'},
210                 {"warning", required_argument, 0, 'w'},
211                 {"hostname", required_argument, 0, 'H'},
212                 {"logname", required_argument, 0, 'l'},
213                 {"password", required_argument, 0, 'p'},
214                 {"authorization", required_argument, 0, 'a'},
215                 {"port", required_argument, 0, 'P'},
216                 {"database", required_argument, 0, 'd'},
217                 {0, 0, 0, 0}
218         };
220         while (1) {
221                 c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:",
222                                  longopts, &option);
224                 if (c == EOF)
225                         break;
227                 switch (c) {
228                 case '?':     /* usage */
229                         usage5 ();
230                 case 'h':     /* help */
231                         print_help ();
232                         exit (STATE_OK);
233                 case 'V':     /* version */
234                         print_revision (progname, revision);
235                         exit (STATE_OK);
236                 case 't':     /* timeout period */
237                         if (!is_integer (optarg))
238                                 usage2 (_("Timeout interval must be a positive integer"), optarg);
239                         else
240                                 timeout_interval = atoi (optarg);
241                         break;
242                 case 'c':     /* critical time threshold */
243                         if (!is_nonnegative (optarg))
244                                 usage2 (_("Critical threshold must be a positive integer"), optarg);
245                         else
246                                 tcrit = strtod (optarg, NULL);
247                         break;
248                 case 'w':     /* warning time threshold */
249                         if (!is_nonnegative (optarg))
250                                 usage2 (_("Warning threshold must be a positive integer"), optarg);
251                         else
252                                 twarn = strtod (optarg, NULL);
253                         break;
254                 case 'H':     /* host */
255                         if (!is_host (optarg))
256                                 usage2 (_("Invalid hostname/address"), optarg);
257                         else
258                                 pghost = optarg;
259                         break;
260                 case 'P':     /* port */
261                         if (!is_integer (optarg))
262                                 usage2 (_("Port must be a positive integer"), optarg);
263                         else
264                                 pgport = optarg;
265                         break;
266                 case 'd':     /* database name */
267                         if (!is_pg_dbname (optarg)) /* checks length and valid chars */
268                                 usage2 (_("Database name is not valid"), optarg);
269                         else /* we know length, and know optarg is terminated, so us strcpy */
270                                 strcpy (dbName, optarg);
271                         break;
272                 case 'l':     /* login name */
273                         if (!is_pg_logname (optarg))
274                                 usage2 (_("User name is not valid"), optarg);
275                         else
276                                 pguser = optarg;
277                         break;
278                 case 'p':     /* authentication password */
279                 case 'a':
280                         pgpasswd = optarg;
281                         break;
282                 }
283         }
285         return validate_arguments ();
289 /******************************************************************************
291 @@-
292 <sect3>
293 <title>validate_arguments</title>
295 <para>&PROTO_validate_arguments;</para>
297 <para>Given a database name, this function returns TRUE if the string
298 is a valid PostgreSQL database name, and returns false if it is
299 not.</para>
301 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
302 characters long and consist of letters, numbers, and underscores. The
303 first character cannot be a number, however.</para>
305 </sect3>
306 -@@
307 ******************************************************************************/
311 int
312 validate_arguments ()
314         return OK;
318 /******************************************************************************
320 @@-
321 <sect3>
322 <title>is_pg_dbname</title>
324 <para>&PROTO_is_pg_dbname;</para>
326 <para>Given a database name, this function returns TRUE if the string
327 is a valid PostgreSQL database name, and returns false if it is
328 not.</para>
330 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
331 characters long and consist of letters, numbers, and underscores. The
332 first character cannot be a number, however.</para>
334 </sect3>
335 -@@
336 ******************************************************************************/
340 int
341 is_pg_dbname (char *dbname)
343         char txt[NAMEDATALEN];
344         char tmp[NAMEDATALEN];
345         if (strlen (dbname) > NAMEDATALEN - 1)
346                 return (FALSE);
347         strncpy (txt, dbname, NAMEDATALEN - 1);
348         txt[NAMEDATALEN - 1] = 0;
349         if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
350                 return (TRUE);
351         if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
352                         2) return (TRUE);
353         return (FALSE);
356 /**
358 the tango program should eventually create an entity here based on the
359 function prototype
361 @@-
362 <sect3>
363 <title>is_pg_logname</title>
365 <para>&PROTO_is_pg_logname;</para>
367 <para>Given a username, this function returns TRUE if the string is a
368 valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
369 usernames are less than &NAMEDATALEN; characters long and consist of
370 letters, numbers, dashes, and underscores, plus possibly some other
371 characters.</para>
373 <para>Currently this function only checks string length. Additional checks
374 should be added.</para>
376 </sect3>
377 -@@
378 ******************************************************************************/
382 int
383 is_pg_logname (char *username)
385         if (strlen (username) > NAMEDATALEN - 1)
386                 return (FALSE);
387         return (TRUE);
390 /******************************************************************************
391 @@-
392 </sect2>
393 </sect1>
394 </article>
395 -@@
396 ******************************************************************************/
400 void
401 print_help (void)
403         char *myport;
405         asprintf (&myport, "%d", DEFAULT_PORT);
407         print_revision (progname, revision);
409         printf (COPYRIGHT, copyright, email);
411         printf (_("Test whether a PostgreSQL Database is accepting connections."));
413   printf ("\n\n");
415         print_usage ();
417         printf (_(UT_HELP_VRSN));
418         printf (_(UT_EXTRA_OPTS));
420         printf (_(UT_HOST_PORT), 'P', myport);
422         printf (_(UT_IPv46));
424         printf (" %s\n", "-d, --database=STRING");
425   printf ("    %s", _("Database to check "));
426   printf (_("(default: %s)"), DEFAULT_DB);
427   printf (" %s\n", "-l, --logname = STRING");
428   printf ("    %s\n", _("Login name of user"));
429   printf (" %s\n", "-p, --password = STRING");
430   printf ("    %s\n", _("Password (BIG SECURITY ISSUE)"));
432         printf (_(UT_WARN_CRIT));
434         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
436         printf (_(UT_VERBOSE));
438   printf ("\n");
439         printf (" %s\n", _("All parameters are optional."));
440   printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
441   printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
442   printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
443   printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
444   printf (" %s\n\n", _("PostgreSQL DBMS."));
446         printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
447   printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
448   printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
450         printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
451   printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
452   printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
454 #ifdef NP_EXTRA_OPTS
455   printf ("\n");
456   printf ("%s\n", _("Notes:"));
457   printf (_(UT_EXTRA_OPTS_NOTES));
458 #endif
460         printf (_(UT_SUPPORT));
465 void
466 print_usage (void)
468   printf (_("Usage:"));
469         printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
470   printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n");