1 /*****************************************************************************
3 * Monitoring check_pgsql plugin
6 * Copyright (c) 1999-2011 Monitoring Plugins Development Team
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-2011";
33 const char *email
= "devel@monitoring-plugins.org";
40 #include <pg_config_manual.h>
42 #define DEFAULT_DB "template1"
43 #define DEFAULT_HOST "127.0.0.1"
45 /* return the PSQL server version as a 3-tuple */
46 #define PSQL_SERVER_VERSION3(server_version) \
47 (server_version) / 10000, \
48 (server_version) / 100 - (int)((server_version) / 10000) * 100, \
49 (server_version) - (int)((server_version) / 100) * 100
50 /* return true if the given host is a UNIX domain socket */
51 #define PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
52 ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
53 /* return a 3-tuple identifying a host/port independent of the socket type */
54 #define PSQL_SOCKET3(host, port) \
55 ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
56 PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
67 int process_arguments (int, char **);
68 int validate_arguments (void);
69 void print_usage (void);
70 void print_help (void);
71 int is_pg_dbname (char *);
72 int is_pg_logname (char *);
73 int do_query (PGconn
*, char *);
75 char *pghost
= NULL
; /* host name of the backend server */
76 char *pgport
= NULL
; /* port of the backend server */
77 int default_port
= DEFAULT_PORT
;
78 char *pgoptions
= NULL
;
80 char dbName
[NAMEDATALEN
] = DEFAULT_DB
;
82 char *pgpasswd
= NULL
;
83 char *pgparams
= NULL
;
84 double twarn
= (double)DEFAULT_WARN
;
85 double tcrit
= (double)DEFAULT_CRIT
;
87 char *query_warning
= NULL
;
88 char *query_critical
= NULL
;
89 thresholds
*qthresholds
= NULL
;
92 /******************************************************************************
94 The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
95 tags in the comments. With in the tags, the XML is assembled sequentially.
96 You can define entities in tags. You also have all the #defines available as
99 Please note that all tags must be lowercase to use the DocBook XML DTD.
104 <title>Quick Reference</title>
105 <!-- The refentry forms a manpage -->
108 <manvolnum>5<manvolnum>
111 <refname>&progname;</refname>
112 <refpurpose>&SUMMARY;</refpurpose>
122 <title>Theory, Installation, and Operation</title>
125 <title>General Description</title>
132 <title>Future Enhancements</title>
133 <para>ToDo List</para>
138 <title>Functions</title>
140 ******************************************************************************/
145 main (int argc
, char **argv
)
148 char *conninfo
= NULL
;
150 struct timeval start_timeval
;
151 struct timeval end_timeval
;
153 int status
= STATE_UNKNOWN
;
154 int query_status
= STATE_UNKNOWN
;
156 /* begin, by setting the parameters for a backend connection if the
157 * parameters are null, then the system will try to use reasonable
158 * defaults by looking up environment variables or, failing that,
159 * using hardwired constants */
161 pgoptions
= NULL
; /* special options to start up the backend server */
162 pgtty
= NULL
; /* debugging tty for the backend server */
164 setlocale (LC_ALL
, "");
165 bindtextdomain (PACKAGE
, LOCALEDIR
);
166 textdomain (PACKAGE
);
168 /* Parse extra opts if any */
169 argv
=np_extra_opts (&argc
, argv
, progname
);
171 if (process_arguments (argc
, argv
) == ERROR
)
172 usage4 (_("Could not parse arguments"));
174 printf("Arguments initialized\n");
176 /* Set signal handling and alarm */
177 if (signal (SIGALRM
, timeout_alarm_handler
) == SIG_ERR
) {
178 usage4 (_("Cannot catch SIGALRM"));
180 alarm (timeout_interval
);
183 asprintf (&conninfo
, "%s ", pgparams
);
185 asprintf (&conninfo
, "%sdbname = '%s'", conninfo
? conninfo
: "", dbName
);
187 asprintf (&conninfo
, "%s host = '%s'", conninfo
, pghost
);
189 asprintf (&conninfo
, "%s port = '%s'", conninfo
, pgport
);
191 asprintf (&conninfo
, "%s options = '%s'", conninfo
, pgoptions
);
192 /* if (pgtty) -- ignored by PQconnectdb */
194 asprintf (&conninfo
, "%s user = '%s'", conninfo
, pguser
);
196 if (verbose
) /* do not include password (see right below) in output */
197 printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo
,
198 pgpasswd
? " password = <hidden>" : "");
201 asprintf (&conninfo
, "%s password = '%s'", conninfo
, pgpasswd
);
203 /* make a connection to the database */
204 gettimeofday (&start_timeval
, NULL
);
205 conn
= PQconnectdb (conninfo
);
206 gettimeofday (&end_timeval
, NULL
);
208 while (start_timeval
.tv_usec
> end_timeval
.tv_usec
) {
209 --end_timeval
.tv_sec
;
210 end_timeval
.tv_usec
+= 1000000;
212 elapsed_time
= (double)(end_timeval
.tv_sec
- start_timeval
.tv_sec
)
213 + (double)(end_timeval
.tv_usec
- start_timeval
.tv_usec
) / 1000000.0;
216 printf("Time elapsed: %f\n", elapsed_time
);
218 /* check to see that the backend connection was successfully made */
220 printf("Verifying connection\n");
221 if (PQstatus (conn
) == CONNECTION_BAD
) {
222 printf (_("CRITICAL - no connection to '%s' (%s).\n"),
223 dbName
, PQerrorMessage (conn
));
225 return STATE_CRITICAL
;
227 else if (elapsed_time
> tcrit
) {
228 status
= STATE_CRITICAL
;
230 else if (elapsed_time
> twarn
) {
231 status
= STATE_WARNING
;
238 char *server_host
= PQhost (conn
);
239 int server_version
= PQserverVersion (conn
);
241 printf ("Successfully connected to database %s (user %s) "
242 "at server %s%s%s (server version: %d.%d.%d, "
243 "protocol version: %d, pid: %d)\n",
244 PQdb (conn
), PQuser (conn
),
245 PSQL_SOCKET3 (server_host
, PQport (conn
)),
246 PSQL_SERVER_VERSION3 (server_version
),
247 PQprotocolVersion (conn
), PQbackendPID (conn
));
250 printf (_(" %s - database %s (%f sec.)|%s\n"),
251 state_text(status
), dbName
, elapsed_time
,
252 fperfdata("time", elapsed_time
, "s",
253 !!(twarn
> 0.0), twarn
, !!(tcrit
> 0.0), tcrit
, TRUE
, 0, FALSE
,0));
256 query_status
= do_query (conn
, pgquery
);
259 printf("Closing connection\n");
261 return (pgquery
&& query_status
> status
) ? query_status
: status
;
266 /* process command-line arguments */
268 process_arguments (int argc
, char **argv
)
273 static struct option longopts
[] = {
274 {"help", no_argument
, 0, 'h'},
275 {"version", no_argument
, 0, 'V'},
276 {"timeout", required_argument
, 0, 't'},
277 {"critical", required_argument
, 0, 'c'},
278 {"warning", required_argument
, 0, 'w'},
279 {"hostname", required_argument
, 0, 'H'},
280 {"logname", required_argument
, 0, 'l'},
281 {"password", required_argument
, 0, 'p'},
282 {"authorization", required_argument
, 0, 'a'},
283 {"port", required_argument
, 0, 'P'},
284 {"database", required_argument
, 0, 'd'},
285 {"option", required_argument
, 0, 'o'},
286 {"query", required_argument
, 0, 'q'},
287 {"query_critical", required_argument
, 0, 'C'},
288 {"query_warning", required_argument
, 0, 'W'},
289 {"verbose", no_argument
, 0, 'v'},
294 c
= getopt_long (argc
, argv
, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v",
301 case '?': /* usage */
305 exit (STATE_UNKNOWN
);
306 case 'V': /* version */
307 print_revision (progname
, NP_VERSION
);
308 exit (STATE_UNKNOWN
);
309 case 't': /* timeout period */
310 if (!is_integer (optarg
))
311 usage2 (_("Timeout interval must be a positive integer"), optarg
);
313 timeout_interval
= atoi (optarg
);
315 case 'c': /* critical time threshold */
316 if (!is_nonnegative (optarg
))
317 usage2 (_("Critical threshold must be a positive integer"), optarg
);
319 tcrit
= strtod (optarg
, NULL
);
321 case 'w': /* warning time threshold */
322 if (!is_nonnegative (optarg
))
323 usage2 (_("Warning threshold must be a positive integer"), optarg
);
325 twarn
= strtod (optarg
, NULL
);
327 case 'C': /* critical query threshold */
328 query_critical
= optarg
;
330 case 'W': /* warning query threshold */
331 query_warning
= optarg
;
334 if ((*optarg
!= '/') && (!is_host (optarg
)))
335 usage2 (_("Invalid hostname/address"), optarg
);
340 if (!is_integer (optarg
))
341 usage2 (_("Port must be a positive integer"), optarg
);
345 case 'd': /* database name */
346 if (!is_pg_dbname (optarg
)) /* checks length and valid chars */
347 usage2 (_("Database name is not valid"), optarg
);
348 else /* we know length, and know optarg is terminated, so us strcpy */
349 strcpy (dbName
, optarg
);
351 case 'l': /* login name */
352 if (!is_pg_logname (optarg
))
353 usage2 (_("User name is not valid"), optarg
);
357 case 'p': /* authentication password */
363 asprintf (&pgparams
, "%s %s", pgparams
, optarg
);
365 asprintf (&pgparams
, "%s", optarg
);
376 set_thresholds (&qthresholds
, query_warning
, query_critical
);
378 return validate_arguments ();
382 /******************************************************************************
386 <title>validate_arguments</title>
388 <para>&PROTO_validate_arguments;</para>
390 <para>Given a database name, this function returns TRUE if the string
391 is a valid PostgreSQL database name, and returns false if it is
394 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
395 characters long and consist of letters, numbers, and underscores. The
396 first character cannot be a number, however.</para>
400 ******************************************************************************/
405 validate_arguments ()
411 /******************************************************************************
415 <title>is_pg_dbname</title>
417 <para>&PROTO_is_pg_dbname;</para>
419 <para>Given a database name, this function returns TRUE if the string
420 is a valid PostgreSQL database name, and returns false if it is
423 <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
424 characters long and consist of letters, numbers, and underscores. The
425 first character cannot be a number, however.</para>
429 ******************************************************************************/
434 is_pg_dbname (char *dbname
)
436 char txt
[NAMEDATALEN
];
437 char tmp
[NAMEDATALEN
];
438 if (strlen (dbname
) > NAMEDATALEN
- 1)
440 strncpy (txt
, dbname
, NAMEDATALEN
- 1);
441 txt
[NAMEDATALEN
- 1] = 0;
442 if (sscanf (txt
, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp
, tmp
) == 1)
444 if (sscanf (txt
, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp
, tmp
, tmp
) ==
451 the tango program should eventually create an entity here based on the
456 <title>is_pg_logname</title>
458 <para>&PROTO_is_pg_logname;</para>
460 <para>Given a username, this function returns TRUE if the string is a
461 valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
462 usernames are less than &NAMEDATALEN; characters long and consist of
463 letters, numbers, dashes, and underscores, plus possibly some other
466 <para>Currently this function only checks string length. Additional checks
467 should be added.</para>
471 ******************************************************************************/
476 is_pg_logname (char *username
)
478 if (strlen (username
) > NAMEDATALEN
- 1)
483 /******************************************************************************
489 ******************************************************************************/
498 xasprintf (&myport
, "%d", DEFAULT_PORT
);
500 print_revision (progname
, NP_VERSION
);
502 printf (COPYRIGHT
, copyright
, email
);
504 printf (_("Test whether a PostgreSQL Database is accepting connections."));
510 printf (UT_HELP_VRSN
);
511 printf (UT_EXTRA_OPTS
);
513 printf (UT_HOST_PORT
, 'P', myport
);
515 printf (" %s\n", "-d, --database=STRING");
516 printf (" %s", _("Database to check "));
517 printf (_("(default: %s)\n"), DEFAULT_DB
);
518 printf (" %s\n", "-l, --logname = STRING");
519 printf (" %s\n", _("Login name of user"));
520 printf (" %s\n", "-p, --password = STRING");
521 printf (" %s\n", _("Password (BIG SECURITY ISSUE)"));
522 printf (" %s\n", "-o, --option = STRING");
523 printf (" %s\n", _("Connection parameters (keyword = value), see below"));
525 printf (UT_WARN_CRIT
);
527 printf (UT_CONN_TIMEOUT
, DEFAULT_SOCKET_TIMEOUT
);
529 printf (" %s\n", "-q, --query=STRING");
530 printf (" %s\n", _("SQL query to run. Only first column in first row will be read"));
531 printf (" %s\n", "-W, --query-warning=RANGE");
532 printf (" %s\n", _("SQL query value to result in warning status (double)"));
533 printf (" %s\n", "-C, --query-critical=RANGE");
534 printf (" %s\n", _("SQL query value to result in critical status (double)"));
539 printf (" %s\n", _("All parameters are optional."));
540 printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
541 printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
542 printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
543 printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
544 printf (" %s\n\n", _("PostgreSQL DBMS."));
546 printf (" %s\n", _("If a query is specified using the -q option, it will be executed after"));
547 printf (" %s\n", _("connecting to the server. The result from the query has to be numeric."));
548 printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
549 printf (" %s\n", _("of the last command is taken into account only. The value of the first"));
550 printf (" %s\n\n", _("column in the first row is used as the check result."));
552 printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
553 printf (" %s\n\n", _("for details about how to access internal statistics of the database server."));
555 printf (" %s\n", _("For a list of available connection parameters which may be used with the -o"));
556 printf (" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter"));
557 printf (" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be"));
558 printf (" %s\n", _("used to specify a service name in pg_service.conf to be used for additional"));
559 printf (" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:"));
560 printf (" %s\n\n", _("-o 'sslmode=require'."));
562 printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
563 printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
564 printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
566 printf (" %s\n", _("Typically, the monitoring user (unless the --logname option is used) should be"));
567 printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
568 printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
578 printf ("%s\n", _("Usage:"));
579 printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname
);
580 printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n"
581 "[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
585 do_query (PGconn
*conn
, char *query
)
594 int my_status
= STATE_UNKNOWN
;
597 printf ("Executing SQL query \"%s\".\n", query
);
598 res
= PQexec (conn
, query
);
600 if (PGRES_TUPLES_OK
!= PQresultStatus (res
)) {
601 printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
602 PQerrorMessage (conn
));
603 return STATE_CRITICAL
;
606 if (PQntuples (res
) < 1) {
607 printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned"));
608 return STATE_WARNING
;
611 if (PQnfields (res
) < 1) {
612 printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned"));
613 return STATE_WARNING
;
616 val_str
= PQgetvalue (res
, 0, 0);
618 printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned"));
619 return STATE_CRITICAL
;
622 value
= strtod (val_str
, &endptr
);
624 printf ("Query result: %f\n", value
);
626 if (endptr
== val_str
) {
627 printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str
);
628 return STATE_CRITICAL
;
630 else if ((endptr
!= NULL
) && (*endptr
!= '\0')) {
632 printf ("Garbage after value: %s.\n", endptr
);
635 my_status
= get_status (value
, qthresholds
);
636 printf ("QUERY %s - ",
637 (my_status
== STATE_OK
)
639 : (my_status
== STATE_WARNING
)
641 : (my_status
== STATE_CRITICAL
)
644 printf (_("'%s' returned %f"), query
, value
);
645 printf ("|query=%f;%s;%s;;\n", value
,
646 query_warning
? query_warning
: "",
647 query_critical
? query_critical
: "");