check_pgsql.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. int elapsed_time;
  126. int status = STATE_UNKNOWN;
  127. int query_status = STATE_UNKNOWN;
  128. /* begin, by setting the parameters for a backend connection if the
  129. * parameters are null, then the system will try to use reasonable
  130. * defaults by looking up environment variables or, failing that,
  131. * using hardwired constants */
  132. pgoptions = NULL; /* special options to start up the backend server */
  133. pgtty = NULL; /* debugging tty for the backend server */
  134. setlocale (LC_ALL, "");
  135. bindtextdomain (PACKAGE, LOCALEDIR);
  136. textdomain (PACKAGE);
  137. /* Parse extra opts if any */
  138. argv=np_extra_opts (&argc, argv, progname);
  139. if (process_arguments (argc, argv) == ERROR)
  140. usage4 (_("Could not parse arguments"));
  141. if (verbose > 2)
  142. printf("Arguments initialized\n");
  143. /* Set signal handling and alarm */
  144. if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
  145. usage4 (_("Cannot catch SIGALRM"));
  146. }
  147. alarm (timeout_interval);
  148. if (pgparams)
  149. asprintf (&conninfo, "%s ", pgparams);
  150. asprintf (&conninfo, "%sdbname = '%s'", conninfo ? conninfo : "", dbName);
  151. if (pghost)
  152. asprintf (&conninfo, "%s host = '%s'", conninfo, pghost);
  153. if (pgport)
  154. asprintf (&conninfo, "%s port = '%s'", conninfo, pgport);
  155. if (pgoptions)
  156. asprintf (&conninfo, "%s options = '%s'", conninfo, pgoptions);
  157. /* if (pgtty) -- ignored by PQconnectdb */
  158. if (pguser)
  159. asprintf (&conninfo, "%s user = '%s'", conninfo, pguser);
  160. if (verbose) /* do not include password (see right below) in output */
  161. printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo,
  162. pgpasswd ? " password = <hidden>" : "");
  163. if (pgpasswd)
  164. asprintf (&conninfo, "%s password = '%s'", conninfo, pgpasswd);
  165. /* make a connection to the database */
  166. time (&start_time);
  167. conn = PQconnectdb (conninfo);
  168. time (&end_time);
  169. elapsed_time = (int) (end_time - start_time);
  170. if (verbose)
  171. printf("Time elapsed: %d\n", elapsed_time);
  172. /* check to see that the backend connection was successfully made */
  173. if (verbose)
  174. printf("Verifying connection\n");
  175. if (PQstatus (conn) == CONNECTION_BAD) {
  176. printf (_("CRITICAL - no connection to '%s' (%s).\n"),
  177. dbName, PQerrorMessage (conn));
  178. PQfinish (conn);
  179. return STATE_CRITICAL;
  180. }
  181. else if (elapsed_time > tcrit) {
  182. status = STATE_CRITICAL;
  183. }
  184. else if (elapsed_time > twarn) {
  185. status = STATE_WARNING;
  186. }
  187. else {
  188. status = STATE_OK;
  189. }
  190. if (verbose) {
  191. char *server_host = PQhost (conn);
  192. int server_version = PQserverVersion (conn);
  193. printf ("Successfully connected to database %s (user %s) "
  194. "at server %s%s%s (server version: %d.%d.%d, "
  195. "protocol version: %d, pid: %d)\n",
  196. PQdb (conn), PQuser (conn),
  197. PSQL_SOCKET3 (server_host, PQport (conn)),
  198. PSQL_SERVER_VERSION3 (server_version),
  199. PQprotocolVersion (conn), PQbackendPID (conn));
  200. }
  201. printf (_(" %s - database %s (%d sec.)|%s\n"),
  202. state_text(status), dbName, elapsed_time,
  203. fperfdata("time", elapsed_time, "s",
  204. (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
  205. if (pgquery)
  206. query_status = do_query (conn, pgquery);
  207. if (verbose)
  208. printf("Closing connection\n");
  209. PQfinish (conn);
  210. return (query_status > status) ? query_status : status;
  211. }
  212. /* process command-line arguments */
  213. int
  214. process_arguments (int argc, char **argv)
  215. {
  216. int c;
  217. int option = 0;
  218. static struct option longopts[] = {
  219. {"help", no_argument, 0, 'h'},
  220. {"version", no_argument, 0, 'V'},
  221. {"timeout", required_argument, 0, 't'},
  222. {"critical", required_argument, 0, 'c'},
  223. {"warning", required_argument, 0, 'w'},
  224. {"hostname", required_argument, 0, 'H'},
  225. {"logname", required_argument, 0, 'l'},
  226. {"password", required_argument, 0, 'p'},
  227. {"authorization", required_argument, 0, 'a'},
  228. {"port", required_argument, 0, 'P'},
  229. {"database", required_argument, 0, 'd'},
  230. {"option", required_argument, 0, 'o'},
  231. {"query", required_argument, 0, 'q'},
  232. {"query_critical", required_argument, 0, 'C'},
  233. {"query_warning", required_argument, 0, 'W'},
  234. {"verbose", no_argument, 0, 'v'},
  235. {0, 0, 0, 0}
  236. };
  237. while (1) {
  238. c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:o:q:C:W:v",
  239. longopts, &option);
  240. if (c == EOF)
  241. break;
  242. switch (c) {
  243. case '?': /* usage */
  244. usage5 ();
  245. case 'h': /* help */
  246. print_help ();
  247. exit (STATE_OK);
  248. case 'V': /* version */
  249. print_revision (progname, NP_VERSION);
  250. exit (STATE_OK);
  251. case 't': /* timeout period */
  252. if (!is_integer (optarg))
  253. usage2 (_("Timeout interval must be a positive integer"), optarg);
  254. else
  255. timeout_interval = atoi (optarg);
  256. break;
  257. case 'c': /* critical time threshold */
  258. if (!is_nonnegative (optarg))
  259. usage2 (_("Critical threshold must be a positive integer"), optarg);
  260. else
  261. tcrit = strtod (optarg, NULL);
  262. break;
  263. case 'w': /* warning time threshold */
  264. if (!is_nonnegative (optarg))
  265. usage2 (_("Warning threshold must be a positive integer"), optarg);
  266. else
  267. twarn = strtod (optarg, NULL);
  268. break;
  269. case 'C': /* critical query threshold */
  270. query_critical = optarg;
  271. break;
  272. case 'W': /* warning query threshold */
  273. query_warning = optarg;
  274. break;
  275. case 'H': /* host */
  276. if ((*optarg != '/') && (!is_host (optarg)))
  277. usage2 (_("Invalid hostname/address"), optarg);
  278. else
  279. pghost = optarg;
  280. break;
  281. case 'P': /* port */
  282. if (!is_integer (optarg))
  283. usage2 (_("Port must be a positive integer"), optarg);
  284. else
  285. pgport = optarg;
  286. break;
  287. case 'd': /* database name */
  288. if (!is_pg_dbname (optarg)) /* checks length and valid chars */
  289. usage2 (_("Database name is not valid"), optarg);
  290. else /* we know length, and know optarg is terminated, so us strcpy */
  291. strcpy (dbName, optarg);
  292. break;
  293. case 'l': /* login name */
  294. if (!is_pg_logname (optarg))
  295. usage2 (_("User name is not valid"), optarg);
  296. else
  297. pguser = optarg;
  298. break;
  299. case 'p': /* authentication password */
  300. case 'a':
  301. pgpasswd = optarg;
  302. break;
  303. case 'o':
  304. if (pgparams)
  305. asprintf (&pgparams, "%s %s", pgparams, optarg);
  306. else
  307. asprintf (&pgparams, "%s", optarg);
  308. break;
  309. case 'q':
  310. pgquery = optarg;
  311. break;
  312. case 'v':
  313. verbose++;
  314. break;
  315. }
  316. }
  317. set_thresholds (&qthresholds, query_warning, query_critical);
  318. return validate_arguments ();
  319. }
  320. /******************************************************************************
  321. @@-
  322. <sect3>
  323. <title>validate_arguments</title>
  324. <para>&PROTO_validate_arguments;</para>
  325. <para>Given a database name, this function returns TRUE if the string
  326. is a valid PostgreSQL database name, and returns false if it is
  327. not.</para>
  328. <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
  329. characters long and consist of letters, numbers, and underscores. The
  330. first character cannot be a number, however.</para>
  331. </sect3>
  332. -@@
  333. ******************************************************************************/
  334. int
  335. validate_arguments ()
  336. {
  337. return OK;
  338. }
  339. /******************************************************************************
  340. @@-
  341. <sect3>
  342. <title>is_pg_dbname</title>
  343. <para>&PROTO_is_pg_dbname;</para>
  344. <para>Given a database name, this function returns TRUE if the string
  345. is a valid PostgreSQL database name, and returns false if it is
  346. not.</para>
  347. <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
  348. characters long and consist of letters, numbers, and underscores. The
  349. first character cannot be a number, however.</para>
  350. </sect3>
  351. -@@
  352. ******************************************************************************/
  353. int
  354. is_pg_dbname (char *dbname)
  355. {
  356. char txt[NAMEDATALEN];
  357. char tmp[NAMEDATALEN];
  358. if (strlen (dbname) > NAMEDATALEN - 1)
  359. return (FALSE);
  360. strncpy (txt, dbname, NAMEDATALEN - 1);
  361. txt[NAMEDATALEN - 1] = 0;
  362. if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
  363. return (TRUE);
  364. if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
  365. 2) return (TRUE);
  366. return (FALSE);
  367. }
  368. /**
  369. the tango program should eventually create an entity here based on the
  370. function prototype
  371. @@-
  372. <sect3>
  373. <title>is_pg_logname</title>
  374. <para>&PROTO_is_pg_logname;</para>
  375. <para>Given a username, this function returns TRUE if the string is a
  376. valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
  377. usernames are less than &NAMEDATALEN; characters long and consist of
  378. letters, numbers, dashes, and underscores, plus possibly some other
  379. characters.</para>
  380. <para>Currently this function only checks string length. Additional checks
  381. should be added.</para>
  382. </sect3>
  383. -@@
  384. ******************************************************************************/
  385. int
  386. is_pg_logname (char *username)
  387. {
  388. if (strlen (username) > NAMEDATALEN - 1)
  389. return (FALSE);
  390. return (TRUE);
  391. }
  392. /******************************************************************************
  393. @@-
  394. </sect2>
  395. </sect1>
  396. </article>
  397. -@@
  398. ******************************************************************************/
  399. void
  400. print_help (void)
  401. {
  402. char *myport;
  403. xasprintf (&myport, "%d", DEFAULT_PORT);
  404. print_revision (progname, NP_VERSION);
  405. printf (COPYRIGHT, copyright, email);
  406. printf (_("Test whether a PostgreSQL Database is accepting connections."));
  407. printf ("\n\n");
  408. print_usage ();
  409. printf (UT_HELP_VRSN);
  410. printf (UT_EXTRA_OPTS);
  411. printf (UT_HOST_PORT, 'P', myport);
  412. printf (" %s\n", "-d, --database=STRING");
  413. printf (" %s", _("Database to check "));
  414. printf (_("(default: %s)"), DEFAULT_DB);
  415. printf (" %s\n", "-l, --logname = STRING");
  416. printf (" %s\n", _("Login name of user"));
  417. printf (" %s\n", "-p, --password = STRING");
  418. printf (" %s\n", _("Password (BIG SECURITY ISSUE)"));
  419. printf (" %s\n", "-o, --option = STRING");
  420. printf (" %s\n", _("Connection parameters (keyword = value), see below"));
  421. printf (UT_WARN_CRIT);
  422. printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  423. printf (" %s\n", "-q, --query=STRING");
  424. printf (" %s\n", _("SQL query to run. Only first column in first row will be read"));
  425. printf (" %s\n", "-W, --query-warning=RANGE");
  426. printf (" %s\n", _("SQL query value to result in warning status (double)"));
  427. printf (" %s\n", "-C, --query-critical=RANGE");
  428. printf (" %s\n", _("SQL query value to result in critical status (double)"));
  429. printf (UT_VERBOSE);
  430. printf ("\n");
  431. printf (" %s\n", _("All parameters are optional."));
  432. printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
  433. printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
  434. printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
  435. printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
  436. printf (" %s\n\n", _("PostgreSQL DBMS."));
  437. printf (" %s\n", _("If a query is specified using the -q option, it will be executed after"));
  438. printf (" %s\n", _("connecting to the server. The result from the query has to be numeric."));
  439. printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
  440. printf (" %s\n", _("of the last command is taken into account only. The value of the first"));
  441. printf (" %s\n\n", _("column in the first row is used as the check result."));
  442. printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
  443. printf (" %s\n\n", _("for details about how to access internal statistics of the database server."));
  444. printf (" %s\n", _("For a list of available connection parameters which may be used with the -o"));
  445. printf (" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter"));
  446. printf (" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be"));
  447. printf (" %s\n", _("used to specify a service name in pg_service.conf to be used for additional"));
  448. printf (" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:"));
  449. printf (" %s\n\n", _("-o 'sslmode=require'."));
  450. printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
  451. printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
  452. printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
  453. printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
  454. printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
  455. printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
  456. printf (UT_SUPPORT);
  457. }
  458. void
  459. print_usage (void)
  460. {
  461. printf ("%s\n", _("Usage:"));
  462. printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
  463. printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n"
  464. "[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
  465. }
  466. int
  467. do_query (PGconn *conn, char *query)
  468. {
  469. PGresult *res;
  470. char *val_str;
  471. double value;
  472. char *endptr = NULL;
  473. int my_status = STATE_UNKNOWN;
  474. if (verbose)
  475. printf ("Executing SQL query \"%s\".\n");
  476. res = PQexec (conn, query);
  477. if (PGRES_TUPLES_OK != PQresultStatus (res)) {
  478. printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
  479. PQerrorMessage (conn));
  480. return STATE_CRITICAL;
  481. }
  482. if (PQntuples (res) < 1) {
  483. printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned"));
  484. return STATE_WARNING;
  485. }
  486. if (PQnfields (res) < 1) {
  487. printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned"));
  488. return STATE_WARNING;
  489. }
  490. val_str = PQgetvalue (res, 0, 0);
  491. if (! val_str) {
  492. printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned"));
  493. return STATE_CRITICAL;
  494. }
  495. value = strtod (val_str, &endptr);
  496. if (verbose)
  497. printf ("Query result: %f\n", value);
  498. if (endptr == val_str) {
  499. printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str);
  500. return STATE_CRITICAL;
  501. }
  502. else if ((endptr != NULL) && (*endptr != '\0')) {
  503. if (verbose)
  504. printf ("Garbage after value: %s.\n", endptr);
  505. }
  506. my_status = get_status (value, qthresholds);
  507. printf ("QUERY %s - ",
  508. (my_status == STATE_OK)
  509. ? _("OK")
  510. : (my_status == STATE_WARNING)
  511. ? _("WARNING")
  512. : (my_status == STATE_CRITICAL)
  513. ? _("CRITICAL")
  514. : _("UNKNOWN"));
  515. printf (_("'%s' returned %f"), query, value);
  516. printf ("|query=%f;%s;%s;;\n", value,
  517. query_warning ? query_warning : "",
  518. query_critical ? query_critical : "");
  519. return my_status;
  520. }