check_pgsql.c 16 KB

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