check_pgsql.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. /*****************************************************************************
  2. *
  3. * Nagios check_pgsql plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 1999-2011 Nagios Plugins Development Team
  7. *
  8. * Description:
  9. *
  10. * This file contains the check_pgsql plugin
  11. *
  12. * Test whether a PostgreSQL Database is accepting connections.
  13. *
  14. *
  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.
  19. *
  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.
  24. *
  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/>.
  27. *
  28. *
  29. *****************************************************************************/
  30. const char *progname = "check_pgsql";
  31. const char *copyright = "1999-2011";
  32. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  33. #include "common.h"
  34. #include "utils.h"
  35. #include "netutils.h"
  36. #include <libpq-fe.h>
  37. #include <pg_config_manual.h>
  38. #define DEFAULT_DB "template1"
  39. #define DEFAULT_HOST "127.0.0.1"
  40. /* return the PSQL server version as a 3-tuple */
  41. #define PSQL_SERVER_VERSION3(server_version) \
  42. (server_version) / 10000, \
  43. (server_version) / 100 - (int)((server_version) / 10000) * 100, \
  44. (server_version) - (int)((server_version) / 100) * 100
  45. /* return true if the given host is a UNIX domain socket */
  46. #define PSQL_IS_UNIX_DOMAIN_SOCKET(host) \
  47. ((NULL == (host)) || ('\0' == *(host)) || ('/' == *(host)))
  48. /* return a 3-tuple identifying a host/port independent of the socket type */
  49. #define PSQL_SOCKET3(host, port) \
  50. ((NULL == (host)) || ('\0' == *(host))) ? DEFAULT_PGSOCKET_DIR : host, \
  51. PSQL_IS_UNIX_DOMAIN_SOCKET (host) ? "/.s.PGSQL." : ":", \
  52. port
  53. enum {
  54. DEFAULT_PORT = 5432,
  55. DEFAULT_WARN = 2,
  56. DEFAULT_CRIT = 8
  57. };
  58. int process_arguments (int, char **);
  59. int validate_arguments (void);
  60. void print_usage (void);
  61. void print_help (void);
  62. int is_pg_dbname (char *);
  63. int is_pg_logname (char *);
  64. int do_query (PGconn *, char *);
  65. char *pghost = NULL; /* host name of the backend server */
  66. char *pgport = NULL; /* port of the backend server */
  67. int default_port = DEFAULT_PORT;
  68. char *pgoptions = NULL;
  69. char *pgtty = NULL;
  70. char dbName[NAMEDATALEN] = DEFAULT_DB;
  71. char *pguser = NULL;
  72. char *pgpasswd = NULL;
  73. char *pgparams = NULL;
  74. double twarn = (double)DEFAULT_WARN;
  75. double tcrit = (double)DEFAULT_CRIT;
  76. char *pgquery = NULL;
  77. char *query_warning = NULL;
  78. char *query_critical = NULL;
  79. thresholds *qthresholds = NULL;
  80. int verbose = 0;
  81. /******************************************************************************
  82. The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
  83. tags in the comments. With in the tags, the XML is assembled sequentially.
  84. You can define entities in tags. You also have all the #defines available as
  85. entities.
  86. Please note that all tags must be lowercase to use the DocBook XML DTD.
  87. @@-<article>
  88. <sect1>
  89. <title>Quick Reference</title>
  90. <!-- The refentry forms a manpage -->
  91. <refentry>
  92. <refmeta>
  93. <manvolnum>5<manvolnum>
  94. </refmeta>
  95. <refnamdiv>
  96. <refname>&progname;</refname>
  97. <refpurpose>&SUMMARY;</refpurpose>
  98. </refnamdiv>
  99. </refentry>
  100. </sect1>
  101. <sect1>
  102. <title>FAQ</title>
  103. </sect1>
  104. <sect1>
  105. <title>Theory, Installation, and Operation</title>
  106. <sect2>
  107. <title>General Description</title>
  108. <para>
  109. &DESCRIPTION;
  110. </para>
  111. </sect2>
  112. <sect2>
  113. <title>Future Enhancements</title>
  114. <para>ToDo List</para>
  115. </sect2>
  116. <sect2>
  117. <title>Functions</title>
  118. -@@
  119. ******************************************************************************/
  120. int
  121. main (int argc, char **argv)
  122. {
  123. PGconn *conn;
  124. char *conninfo = NULL;
  125. struct timeval start_timeval;
  126. struct timeval end_timeval;
  127. double elapsed_time;
  128. int status = STATE_UNKNOWN;
  129. int query_status = STATE_UNKNOWN;
  130. /* begin, by setting the parameters for a backend connection if the
  131. * parameters are null, then the system will try to use reasonable
  132. * defaults by looking up environment variables or, failing that,
  133. * using hardwired constants */
  134. pgoptions = NULL; /* special options to start up the backend server */
  135. pgtty = NULL; /* debugging tty for the backend server */
  136. setlocale (LC_ALL, "");
  137. bindtextdomain (PACKAGE, LOCALEDIR);
  138. textdomain (PACKAGE);
  139. /* Parse extra opts if any */
  140. argv=np_extra_opts (&argc, argv, progname);
  141. if (process_arguments (argc, argv) == ERROR)
  142. usage4 (_("Could not parse arguments"));
  143. if (verbose > 2)
  144. printf("Arguments initialized\n");
  145. /* Set signal handling and alarm */
  146. if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
  147. usage4 (_("Cannot catch SIGALRM"));
  148. }
  149. alarm (timeout_interval);
  150. if (pgparams)
  151. asprintf (&conninfo, "%s ", pgparams);
  152. asprintf (&conninfo, "%sdbname = '%s'", conninfo ? conninfo : "", dbName);
  153. if (pghost)
  154. asprintf (&conninfo, "%s host = '%s'", conninfo, pghost);
  155. if (pgport)
  156. asprintf (&conninfo, "%s port = '%s'", conninfo, pgport);
  157. if (pgoptions)
  158. asprintf (&conninfo, "%s options = '%s'", conninfo, pgoptions);
  159. /* if (pgtty) -- ignored by PQconnectdb */
  160. if (pguser)
  161. asprintf (&conninfo, "%s user = '%s'", conninfo, pguser);
  162. if (verbose) /* do not include password (see right below) in output */
  163. printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo,
  164. pgpasswd ? " password = <hidden>" : "");
  165. if (pgpasswd)
  166. asprintf (&conninfo, "%s password = '%s'", conninfo, pgpasswd);
  167. /* make a connection to the database */
  168. gettimeofday (&start_timeval, NULL);
  169. conn = PQconnectdb (conninfo);
  170. gettimeofday (&end_timeval, NULL);
  171. while (start_timeval.tv_usec > end_timeval.tv_usec) {
  172. --end_timeval.tv_sec;
  173. end_timeval.tv_usec += 1000000;
  174. }
  175. elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec)
  176. + (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0;
  177. if (verbose)
  178. printf("Time elapsed: %f\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;
  187. }
  188. else if (elapsed_time > tcrit) {
  189. status = STATE_CRITICAL;
  190. }
  191. else if (elapsed_time > twarn) {
  192. status = STATE_WARNING;
  193. }
  194. else {
  195. status = STATE_OK;
  196. }
  197. if (verbose) {
  198. char *server_host = PQhost (conn);
  199. int server_version = PQserverVersion (conn);
  200. printf ("Successfully connected to database %s (user %s) "
  201. "at server %s%s%s (server version: %d.%d.%d, "
  202. "protocol version: %d, pid: %d)\n",
  203. PQdb (conn), PQuser (conn),
  204. PSQL_SOCKET3 (server_host, PQport (conn)),
  205. PSQL_SERVER_VERSION3 (server_version),
  206. PQprotocolVersion (conn), PQbackendPID (conn));
  207. }
  208. printf (_(" %s - database %s (%f sec.)|%s\n"),
  209. state_text(status), dbName, elapsed_time,
  210. fperfdata("time", elapsed_time, "s",
  211. !!(twarn > 0.0), twarn, !!(tcrit > 0.0), tcrit, TRUE, 0, FALSE,0));
  212. if (pgquery)
  213. query_status = do_query (conn, pgquery);
  214. if (verbose)
  215. printf("Closing connection\n");
  216. PQfinish (conn);
  217. return (query_status > status) ? query_status : status;
  218. }
  219. /* process command-line arguments */
  220. int
  221. process_arguments (int argc, char **argv)
  222. {
  223. int c;
  224. int option = 0;
  225. static struct option longopts[] = {
  226. {"help", no_argument, 0, 'h'},
  227. {"version", no_argument, 0, 'V'},
  228. {"timeout", required_argument, 0, 't'},
  229. {"critical", required_argument, 0, 'c'},
  230. {"warning", required_argument, 0, 'w'},
  231. {"hostname", required_argument, 0, 'H'},
  232. {"logname", required_argument, 0, 'l'},
  233. {"password", required_argument, 0, 'p'},
  234. {"authorization", required_argument, 0, 'a'},
  235. {"port", required_argument, 0, 'P'},
  236. {"database", required_argument, 0, 'd'},
  237. {"option", required_argument, 0, 'o'},
  238. {"query", required_argument, 0, 'q'},
  239. {"query_critical", required_argument, 0, 'C'},
  240. {"query_warning", required_argument, 0, 'W'},
  241. {"verbose", no_argument, 0, 'v'},
  242. {0, 0, 0, 0}
  243. };
  244. while (1) {
  245. c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v",
  246. longopts, &option);
  247. if (c == EOF)
  248. break;
  249. switch (c) {
  250. case '?': /* usage */
  251. usage5 ();
  252. case 'h': /* help */
  253. print_help ();
  254. exit (STATE_OK);
  255. case 'V': /* version */
  256. print_revision (progname, NP_VERSION);
  257. exit (STATE_OK);
  258. case 't': /* timeout period */
  259. if (!is_integer (optarg))
  260. usage2 (_("Timeout interval must be a positive integer"), optarg);
  261. else
  262. timeout_interval = atoi (optarg);
  263. break;
  264. case 'c': /* critical time threshold */
  265. if (!is_nonnegative (optarg))
  266. usage2 (_("Critical threshold must be a positive integer"), optarg);
  267. else
  268. tcrit = strtod (optarg, NULL);
  269. break;
  270. case 'w': /* warning time threshold */
  271. if (!is_nonnegative (optarg))
  272. usage2 (_("Warning threshold must be a positive integer"), optarg);
  273. else
  274. twarn = strtod (optarg, NULL);
  275. break;
  276. case 'C': /* critical query threshold */
  277. query_critical = optarg;
  278. break;
  279. case 'W': /* warning query threshold */
  280. query_warning = optarg;
  281. break;
  282. case 'H': /* host */
  283. if ((*optarg != '/') && (!is_host (optarg)))
  284. usage2 (_("Invalid hostname/address"), optarg);
  285. else
  286. pghost = optarg;
  287. break;
  288. case 'P': /* port */
  289. if (!is_integer (optarg))
  290. usage2 (_("Port must be a positive integer"), optarg);
  291. else
  292. pgport = optarg;
  293. break;
  294. case 'd': /* database name */
  295. if (!is_pg_dbname (optarg)) /* checks length and valid chars */
  296. usage2 (_("Database name is not valid"), optarg);
  297. else /* we know length, and know optarg is terminated, so us strcpy */
  298. strcpy (dbName, optarg);
  299. break;
  300. case 'l': /* login name */
  301. if (!is_pg_logname (optarg))
  302. usage2 (_("User name is not valid"), optarg);
  303. else
  304. pguser = optarg;
  305. break;
  306. case 'p': /* authentication password */
  307. case 'a':
  308. pgpasswd = optarg;
  309. break;
  310. case 'o':
  311. if (pgparams)
  312. asprintf (&pgparams, "%s %s", pgparams, optarg);
  313. else
  314. asprintf (&pgparams, "%s", optarg);
  315. break;
  316. case 'q':
  317. pgquery = optarg;
  318. break;
  319. case 'v':
  320. verbose++;
  321. break;
  322. }
  323. }
  324. set_thresholds (&qthresholds, query_warning, query_critical);
  325. return validate_arguments ();
  326. }
  327. /******************************************************************************
  328. @@-
  329. <sect3>
  330. <title>validate_arguments</title>
  331. <para>&PROTO_validate_arguments;</para>
  332. <para>Given a database name, this function returns TRUE if the string
  333. is a valid PostgreSQL database name, and returns false if it is
  334. not.</para>
  335. <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
  336. characters long and consist of letters, numbers, and underscores. The
  337. first character cannot be a number, however.</para>
  338. </sect3>
  339. -@@
  340. ******************************************************************************/
  341. int
  342. validate_arguments ()
  343. {
  344. return OK;
  345. }
  346. /******************************************************************************
  347. @@-
  348. <sect3>
  349. <title>is_pg_dbname</title>
  350. <para>&PROTO_is_pg_dbname;</para>
  351. <para>Given a database name, this function returns TRUE if the string
  352. is a valid PostgreSQL database name, and returns false if it is
  353. not.</para>
  354. <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
  355. characters long and consist of letters, numbers, and underscores. The
  356. first character cannot be a number, however.</para>
  357. </sect3>
  358. -@@
  359. ******************************************************************************/
  360. int
  361. is_pg_dbname (char *dbname)
  362. {
  363. char txt[NAMEDATALEN];
  364. char tmp[NAMEDATALEN];
  365. if (strlen (dbname) > NAMEDATALEN - 1)
  366. return (FALSE);
  367. strncpy (txt, dbname, NAMEDATALEN - 1);
  368. txt[NAMEDATALEN - 1] = 0;
  369. if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
  370. return (TRUE);
  371. if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
  372. 2) return (TRUE);
  373. return (FALSE);
  374. }
  375. /**
  376. the tango program should eventually create an entity here based on the
  377. function prototype
  378. @@-
  379. <sect3>
  380. <title>is_pg_logname</title>
  381. <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>
  387. <para>Currently this function only checks string length. Additional checks
  388. should be added.</para>
  389. </sect3>
  390. -@@
  391. ******************************************************************************/
  392. int
  393. is_pg_logname (char *username)
  394. {
  395. if (strlen (username) > NAMEDATALEN - 1)
  396. return (FALSE);
  397. return (TRUE);
  398. }
  399. /******************************************************************************
  400. @@-
  401. </sect2>
  402. </sect1>
  403. </article>
  404. -@@
  405. ******************************************************************************/
  406. void
  407. print_help (void)
  408. {
  409. char *myport;
  410. xasprintf (&myport, "%d", DEFAULT_PORT);
  411. print_revision (progname, NP_VERSION);
  412. printf (COPYRIGHT, copyright, email);
  413. printf (_("Test whether a PostgreSQL Database is accepting connections."));
  414. printf ("\n\n");
  415. print_usage ();
  416. printf (UT_HELP_VRSN);
  417. printf (UT_EXTRA_OPTS);
  418. printf (UT_HOST_PORT, 'P', myport);
  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)"));
  426. printf (" %s\n", "-o, --option = STRING");
  427. printf (" %s\n", _("Connection parameters (keyword = value), see below"));
  428. printf (UT_WARN_CRIT);
  429. printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  430. printf (" %s\n", "-q, --query=STRING");
  431. printf (" %s\n", _("SQL query to run. Only first column in first row will be read"));
  432. printf (" %s\n", "-W, --query-warning=RANGE");
  433. printf (" %s\n", _("SQL query value to result in warning status (double)"));
  434. printf (" %s\n", "-C, --query-critical=RANGE");
  435. printf (" %s\n", _("SQL query value to result in critical status (double)"));
  436. printf (UT_VERBOSE);
  437. printf ("\n");
  438. printf (" %s\n", _("All parameters are optional."));
  439. printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
  440. printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
  441. printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
  442. printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
  443. printf (" %s\n\n", _("PostgreSQL DBMS."));
  444. printf (" %s\n", _("If a query is specified using the -q option, it will be executed after"));
  445. printf (" %s\n", _("connecting to the server. The result from the query has to be numeric."));
  446. printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
  447. printf (" %s\n", _("of the last command is taken into account only. The value of the first"));
  448. printf (" %s\n\n", _("column in the first row is used as the check result."));
  449. printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
  450. printf (" %s\n\n", _("for details about how to access internal statistics of the database server."));
  451. printf (" %s\n", _("For a list of available connection parameters which may be used with the -o"));
  452. printf (" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter"));
  453. printf (" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be"));
  454. printf (" %s\n", _("used to specify a service name in pg_service.conf to be used for additional"));
  455. printf (" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:"));
  456. printf (" %s\n\n", _("-o 'sslmode=require'."));
  457. printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
  458. printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
  459. printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
  460. printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
  461. printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
  462. printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
  463. printf (UT_SUPPORT);
  464. }
  465. void
  466. print_usage (void)
  467. {
  468. printf ("%s\n", _("Usage:"));
  469. printf ("%s [-H <host>] [-4|-6] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
  470. printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n"
  471. "[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
  472. }
  473. int
  474. do_query (PGconn *conn, char *query)
  475. {
  476. PGresult *res;
  477. char *val_str;
  478. double value;
  479. char *endptr = NULL;
  480. int my_status = STATE_UNKNOWN;
  481. if (verbose)
  482. printf ("Executing SQL query \"%s\".\n");
  483. res = PQexec (conn, query);
  484. if (PGRES_TUPLES_OK != PQresultStatus (res)) {
  485. printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
  486. PQerrorMessage (conn));
  487. return STATE_CRITICAL;
  488. }
  489. if (PQntuples (res) < 1) {
  490. printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned"));
  491. return STATE_WARNING;
  492. }
  493. if (PQnfields (res) < 1) {
  494. printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned"));
  495. return STATE_WARNING;
  496. }
  497. val_str = PQgetvalue (res, 0, 0);
  498. if (! val_str) {
  499. printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned"));
  500. return STATE_CRITICAL;
  501. }
  502. value = strtod (val_str, &endptr);
  503. if (verbose)
  504. printf ("Query result: %f\n", value);
  505. if (endptr == val_str) {
  506. printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str);
  507. return STATE_CRITICAL;
  508. }
  509. else if ((endptr != NULL) && (*endptr != '\0')) {
  510. if (verbose)
  511. printf ("Garbage after value: %s.\n", endptr);
  512. }
  513. my_status = get_status (value, qthresholds);
  514. printf ("QUERY %s - ",
  515. (my_status == STATE_OK)
  516. ? _("OK")
  517. : (my_status == STATE_WARNING)
  518. ? _("WARNING")
  519. : (my_status == STATE_CRITICAL)
  520. ? _("CRITICAL")
  521. : _("UNKNOWN"));
  522. printf (_("'%s' returned %f"), query, value);
  523. printf ("|query=%f;%s;%s;;\n", value,
  524. query_warning ? query_warning : "",
  525. query_critical ? query_critical : "");
  526. return my_status;
  527. }