4
0

check_pgsql.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. /*****************************************************************************
  2. *
  3. * Nagios check_pgsql plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 1999-2014 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-2014";
  32. const char *email = "devel@nagios-plugins.org";
  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 (pseudo?)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 (pgquery && 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. timeout_interval = parse_timeout_string (optarg);
  260. break;
  261. case 'c': /* critical time threshold */
  262. if (!is_nonnegative (optarg))
  263. usage2 (_("Critical threshold must be a positive integer"), optarg);
  264. else
  265. tcrit = strtod (optarg, NULL);
  266. break;
  267. case 'w': /* warning time threshold */
  268. if (!is_nonnegative (optarg))
  269. usage2 (_("Warning threshold must be a positive integer"), optarg);
  270. else
  271. twarn = strtod (optarg, NULL);
  272. break;
  273. case 'C': /* critical query threshold */
  274. query_critical = optarg;
  275. break;
  276. case 'W': /* warning query threshold */
  277. query_warning = optarg;
  278. break;
  279. case 'H': /* host */
  280. if ((*optarg != '/') && (!is_host (optarg)))
  281. usage2 (_("Invalid hostname/address"), optarg);
  282. else
  283. pghost = optarg;
  284. break;
  285. case 'P': /* port */
  286. if (!is_integer (optarg))
  287. usage2 (_("Port must be a positive integer"), optarg);
  288. else
  289. pgport = optarg;
  290. break;
  291. case 'd': /* database name */
  292. if (!is_pg_dbname (optarg)) /* checks length and valid chars */
  293. usage2 (_("Database name is not valid"), optarg);
  294. else /* we know length, and know optarg is terminated, so us strcpy */
  295. strcpy (dbName, optarg);
  296. break;
  297. case 'l': /* login name */
  298. if (!is_pg_logname (optarg))
  299. usage2 (_("User name is not valid"), optarg);
  300. else
  301. pguser = optarg;
  302. break;
  303. case 'p': /* authentication password */
  304. case 'a':
  305. pgpasswd = optarg;
  306. break;
  307. case 'o':
  308. if (pgparams)
  309. asprintf (&pgparams, "%s %s", pgparams, optarg);
  310. else
  311. asprintf (&pgparams, "%s", optarg);
  312. break;
  313. case 'q':
  314. pgquery = optarg;
  315. break;
  316. case 'v':
  317. verbose++;
  318. break;
  319. }
  320. }
  321. set_thresholds (&qthresholds, query_warning, query_critical);
  322. return validate_arguments ();
  323. }
  324. /******************************************************************************
  325. @@-
  326. <sect3>
  327. <title>validate_arguments</title>
  328. <para>&PROTO_validate_arguments;</para>
  329. <para>Given a database name, this function returns TRUE if the string
  330. is a valid PostgreSQL database name, and returns false if it is
  331. not.</para>
  332. <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
  333. characters long and consist of letters, numbers, and underscores. The
  334. first character cannot be a number, however.</para>
  335. </sect3>
  336. -@@
  337. ******************************************************************************/
  338. int
  339. validate_arguments ()
  340. {
  341. return OK;
  342. }
  343. /******************************************************************************
  344. @@-
  345. <sect3>
  346. <title>is_pg_dbname</title>
  347. <para>&PROTO_is_pg_dbname;</para>
  348. <para>Given a database name, this function returns TRUE if the string
  349. is a valid PostgreSQL database name, and returns false if it is
  350. not.</para>
  351. <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
  352. characters long and consist of letters, numbers, and underscores. The
  353. first character cannot be a number, however.</para>
  354. </sect3>
  355. -@@
  356. ******************************************************************************/
  357. int
  358. is_pg_dbname (char *dbname)
  359. {
  360. char txt[NAMEDATALEN];
  361. char tmp[NAMEDATALEN];
  362. if (strlen (dbname) > NAMEDATALEN - 1)
  363. return (FALSE);
  364. strncpy (txt, dbname, NAMEDATALEN - 1);
  365. txt[NAMEDATALEN - 1] = 0;
  366. if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
  367. return (TRUE);
  368. if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
  369. 2) return (TRUE);
  370. return (FALSE);
  371. }
  372. /**
  373. the tango program should eventually create an entity here based on the
  374. function prototype
  375. @@-
  376. <sect3>
  377. <title>is_pg_logname</title>
  378. <para>&PROTO_is_pg_logname;</para>
  379. <para>Given a username, this function returns TRUE if the string is a
  380. valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
  381. usernames are less than &NAMEDATALEN; characters long and consist of
  382. letters, numbers, dashes, and underscores, plus possibly some other
  383. characters.</para>
  384. <para>Currently this function only checks string length. Additional checks
  385. should be added.</para>
  386. </sect3>
  387. -@@
  388. ******************************************************************************/
  389. int
  390. is_pg_logname (char *username)
  391. {
  392. if (strlen (username) > NAMEDATALEN - 1)
  393. return (FALSE);
  394. return (TRUE);
  395. }
  396. /******************************************************************************
  397. @@-
  398. </sect2>
  399. </sect1>
  400. </article>
  401. -@@
  402. ******************************************************************************/
  403. void
  404. print_help (void)
  405. {
  406. char *myport;
  407. xasprintf (&myport, "%d", DEFAULT_PORT);
  408. print_revision (progname, NP_VERSION);
  409. printf (COPYRIGHT, copyright, email);
  410. printf (_("Test whether a PostgreSQL Database is accepting connections."));
  411. printf ("\n\n");
  412. print_usage ();
  413. printf (UT_HELP_VRSN);
  414. printf (UT_EXTRA_OPTS);
  415. printf (UT_HOST_PORT, 'P', myport);
  416. printf (" %s\n", "-d, --database=STRING");
  417. printf (" %s", _("Database to check "));
  418. printf (_("(default: %s)\n"), DEFAULT_DB);
  419. printf (" %s\n", "-l, --logname = STRING");
  420. printf (" %s\n", _("Login name of user"));
  421. printf (" %s\n", "-p, --password = STRING");
  422. printf (" %s\n", _("Password (BIG SECURITY ISSUE)"));
  423. printf (" %s\n", "-o, --option = STRING");
  424. printf (" %s\n", _("Connection parameters (keyword = value), see below"));
  425. printf (UT_WARN_CRIT);
  426. printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  427. printf (" %s\n", "-q, --query=STRING");
  428. printf (" %s\n", _("SQL query to run. Only first column in first row will be read"));
  429. printf (" %s\n", "-W, --query-warning=RANGE");
  430. printf (" %s\n", _("SQL query value to result in warning status (double)"));
  431. printf (" %s\n", "-C, --query-critical=RANGE");
  432. printf (" %s\n", _("SQL query value to result in critical status (double)"));
  433. printf (UT_VERBOSE);
  434. printf ("\n");
  435. printf (" %s\n", _("All parameters are optional."));
  436. printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
  437. printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
  438. printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
  439. printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
  440. printf (" %s\n\n", _("PostgreSQL DBMS."));
  441. printf (" %s\n", _("If a query is specified using the -q option, it will be executed after"));
  442. printf (" %s\n", _("connecting to the server. The result from the query has to be numeric."));
  443. printf (" %s\n", _("Multiple SQL commands, separated by semicolon, are allowed but the result "));
  444. printf (" %s\n", _("of the last command is taken into account only. The value of the first"));
  445. printf (" %s\n\n", _("column in the first row is used as the check result."));
  446. printf (" %s\n", _("See the chapter \"Monitoring Database Activity\" of the PostgreSQL manual"));
  447. printf (" %s\n\n", _("for details about how to access internal statistics of the database server."));
  448. printf (" %s\n", _("For a list of available connection parameters which may be used with the -o"));
  449. printf (" %s\n", _("command line option, see the documentation for PQconnectdb() in the chapter"));
  450. printf (" %s\n", _("\"libpq - C Library\" of the PostgreSQL manual. For example, this may be"));
  451. printf (" %s\n", _("used to specify a service name in pg_service.conf to be used for additional"));
  452. printf (" %s\n", _("connection parameters: -o 'service=<name>' or to specify the SSL mode:"));
  453. printf (" %s\n\n", _("-o 'sslmode=require'."));
  454. printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
  455. printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
  456. printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
  457. printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
  458. printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
  459. printf (" %s\n", _("a password, but no effort is made to obscure or encrypt the password."));
  460. printf (UT_SUPPORT);
  461. }
  462. void
  463. print_usage (void)
  464. {
  465. printf ("%s\n", _("Usage:"));
  466. printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
  467. printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n"
  468. "[-q <query>] [-C <critical query range>] [-W <warning query range>]\n");
  469. }
  470. int
  471. do_query (PGconn *conn, char *query)
  472. {
  473. PGresult *res;
  474. char *val_str;
  475. double value;
  476. char *endptr = NULL;
  477. int my_status = STATE_UNKNOWN;
  478. if (verbose)
  479. printf ("Executing SQL query \"%s\".\n", query);
  480. res = PQexec (conn, query);
  481. if (PGRES_TUPLES_OK != PQresultStatus (res)) {
  482. printf (_("QUERY %s - %s: %s.\n"), _("CRITICAL"), _("Error with query"),
  483. PQerrorMessage (conn));
  484. return STATE_CRITICAL;
  485. }
  486. if (PQntuples (res) < 1) {
  487. printf ("QUERY %s - %s.\n", _("WARNING"), _("No rows returned"));
  488. return STATE_WARNING;
  489. }
  490. if (PQnfields (res) < 1) {
  491. printf ("QUERY %s - %s.\n", _("WARNING"), _("No columns returned"));
  492. return STATE_WARNING;
  493. }
  494. val_str = PQgetvalue (res, 0, 0);
  495. if (! val_str) {
  496. printf ("QUERY %s - %s.\n", _("CRITICAL"), _("No data returned"));
  497. return STATE_CRITICAL;
  498. }
  499. value = strtod (val_str, &endptr);
  500. if (verbose)
  501. printf ("Query result: %f\n", value);
  502. if (endptr == val_str) {
  503. printf ("QUERY %s - %s: %s\n", _("CRITICAL"), _("Is not a numeric"), val_str);
  504. return STATE_CRITICAL;
  505. }
  506. else if ((endptr != NULL) && (*endptr != '\0')) {
  507. if (verbose)
  508. printf ("Garbage after value: %s.\n", endptr);
  509. }
  510. my_status = get_status (value, qthresholds);
  511. printf ("QUERY %s - ",
  512. (my_status == STATE_OK)
  513. ? _("OK")
  514. : (my_status == STATE_WARNING)
  515. ? _("WARNING")
  516. : (my_status == STATE_CRITICAL)
  517. ? _("CRITICAL")
  518. : _("UNKNOWN"));
  519. printf (_("'%s' returned %f"), query, value);
  520. printf ("|query=%f;%s;%s;;\n", value,
  521. query_warning ? query_warning : "",
  522. query_critical ? query_critical : "");
  523. return my_status;
  524. }