Code

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