check_pgsql.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. char *pghost = NULL; /* host name of the backend server */
  52. char *pgport = NULL; /* port of the backend server */
  53. int default_port = DEFAULT_PORT;
  54. char *pgoptions = NULL;
  55. char *pgtty = NULL;
  56. char dbName[NAMEDATALEN] = DEFAULT_DB;
  57. char *pguser = NULL;
  58. char *pgpasswd = NULL;
  59. double twarn = (double)DEFAULT_WARN;
  60. double tcrit = (double)DEFAULT_CRIT;
  61. int verbose = 0;
  62. PGconn *conn;
  63. /*PGresult *res;*/
  64. /******************************************************************************
  65. The (psuedo?)literate programming XML is contained within \@\@\- <XML> \-\@\@
  66. tags in the comments. With in the tags, the XML is assembled sequentially.
  67. You can define entities in tags. You also have all the #defines available as
  68. entities.
  69. Please note that all tags must be lowercase to use the DocBook XML DTD.
  70. @@-<article>
  71. <sect1>
  72. <title>Quick Reference</title>
  73. <!-- The refentry forms a manpage -->
  74. <refentry>
  75. <refmeta>
  76. <manvolnum>5<manvolnum>
  77. </refmeta>
  78. <refnamdiv>
  79. <refname>&progname;</refname>
  80. <refpurpose>&SUMMARY;</refpurpose>
  81. </refnamdiv>
  82. </refentry>
  83. </sect1>
  84. <sect1>
  85. <title>FAQ</title>
  86. </sect1>
  87. <sect1>
  88. <title>Theory, Installation, and Operation</title>
  89. <sect2>
  90. <title>General Description</title>
  91. <para>
  92. &DESCRIPTION;
  93. </para>
  94. </sect2>
  95. <sect2>
  96. <title>Future Enhancements</title>
  97. <para>ToDo List</para>
  98. <itemizedlist>
  99. <listitem>Add option to get password from a secured file rather than the command line</listitem>
  100. <listitem>Add option to specify the query to execute</listitem>
  101. </itemizedlist>
  102. </sect2>
  103. <sect2>
  104. <title>Functions</title>
  105. -@@
  106. ******************************************************************************/
  107. int
  108. main (int argc, char **argv)
  109. {
  110. int elapsed_time;
  111. int status = STATE_UNKNOWN;
  112. /* begin, by setting the parameters for a backend connection if the
  113. * parameters are null, then the system will try to use reasonable
  114. * defaults by looking up environment variables or, failing that,
  115. * using hardwired constants */
  116. pgoptions = NULL; /* special options to start up the backend server */
  117. pgtty = NULL; /* debugging tty for the backend server */
  118. setlocale (LC_ALL, "");
  119. bindtextdomain (PACKAGE, LOCALEDIR);
  120. textdomain (PACKAGE);
  121. /* Parse extra opts if any */
  122. argv=np_extra_opts (&argc, argv, progname);
  123. if (process_arguments (argc, argv) == ERROR)
  124. usage4 (_("Could not parse arguments"));
  125. if (verbose > 2)
  126. printf("Arguments initialized\n");
  127. /* Set signal handling and alarm */
  128. if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
  129. usage4 (_("Cannot catch SIGALRM"));
  130. }
  131. alarm (timeout_interval);
  132. if (verbose)
  133. printf("Connecting to database:\n DB: %s\n User: %s\n Host: %s\n Port: %d\n", dbName,
  134. (pguser != NULL) ? pguser : "unspecified",
  135. (pghost != NULL) ? pghost : "unspecified",
  136. (pgport != NULL) ? atoi(pgport) : DEFAULT_PORT);
  137. /* make a connection to the database */
  138. time (&start_time);
  139. conn =
  140. PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd);
  141. time (&end_time);
  142. elapsed_time = (int) (end_time - start_time);
  143. if (verbose)
  144. printf("Time elapsed: %d\n", elapsed_time);
  145. /* check to see that the backend connection was successfully made */
  146. if (verbose)
  147. printf("Verifying connection\n");
  148. if (PQstatus (conn) == CONNECTION_BAD) {
  149. printf (_("CRITICAL - no connection to '%s' (%s).\n"),
  150. dbName, PQerrorMessage (conn));
  151. PQfinish (conn);
  152. return STATE_CRITICAL;
  153. }
  154. else if (elapsed_time > tcrit) {
  155. status = STATE_CRITICAL;
  156. }
  157. else if (elapsed_time > twarn) {
  158. status = STATE_WARNING;
  159. }
  160. else {
  161. status = STATE_OK;
  162. }
  163. if (verbose)
  164. printf("Closing connection\n");
  165. PQfinish (conn);
  166. printf (_(" %s - database %s (%d sec.)|%s\n"),
  167. state_text(status), dbName, elapsed_time,
  168. fperfdata("time", elapsed_time, "s",
  169. (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0));
  170. return status;
  171. }
  172. /* process command-line arguments */
  173. int
  174. process_arguments (int argc, char **argv)
  175. {
  176. int c;
  177. int option = 0;
  178. static struct option longopts[] = {
  179. {"help", no_argument, 0, 'h'},
  180. {"version", no_argument, 0, 'V'},
  181. {"timeout", required_argument, 0, 't'},
  182. {"critical", required_argument, 0, 'c'},
  183. {"warning", required_argument, 0, 'w'},
  184. {"hostname", required_argument, 0, 'H'},
  185. {"logname", required_argument, 0, 'l'},
  186. {"password", required_argument, 0, 'p'},
  187. {"authorization", required_argument, 0, 'a'},
  188. {"port", required_argument, 0, 'P'},
  189. {"database", required_argument, 0, 'd'},
  190. {"verbose", no_argument, 0, 'v'},
  191. {0, 0, 0, 0}
  192. };
  193. while (1) {
  194. c = getopt_long (argc, argv, "hVt:c:w:H:P:d:l:p:a:v",
  195. longopts, &option);
  196. if (c == EOF)
  197. break;
  198. switch (c) {
  199. case '?': /* usage */
  200. usage5 ();
  201. case 'h': /* help */
  202. print_help ();
  203. exit (STATE_OK);
  204. case 'V': /* version */
  205. print_revision (progname, NP_VERSION);
  206. exit (STATE_OK);
  207. case 't': /* timeout period */
  208. if (!is_integer (optarg))
  209. usage2 (_("Timeout interval must be a positive integer"), optarg);
  210. else
  211. timeout_interval = atoi (optarg);
  212. break;
  213. case 'c': /* critical time threshold */
  214. if (!is_nonnegative (optarg))
  215. usage2 (_("Critical threshold must be a positive integer"), optarg);
  216. else
  217. tcrit = strtod (optarg, NULL);
  218. break;
  219. case 'w': /* warning time threshold */
  220. if (!is_nonnegative (optarg))
  221. usage2 (_("Warning threshold must be a positive integer"), optarg);
  222. else
  223. twarn = strtod (optarg, NULL);
  224. break;
  225. case 'H': /* host */
  226. if (!is_host (optarg))
  227. usage2 (_("Invalid hostname/address"), optarg);
  228. else
  229. pghost = optarg;
  230. break;
  231. case 'P': /* port */
  232. if (!is_integer (optarg))
  233. usage2 (_("Port must be a positive integer"), optarg);
  234. else
  235. pgport = optarg;
  236. break;
  237. case 'd': /* database name */
  238. if (!is_pg_dbname (optarg)) /* checks length and valid chars */
  239. usage2 (_("Database name is not valid"), optarg);
  240. else /* we know length, and know optarg is terminated, so us strcpy */
  241. strcpy (dbName, optarg);
  242. break;
  243. case 'l': /* login name */
  244. if (!is_pg_logname (optarg))
  245. usage2 (_("User name is not valid"), optarg);
  246. else
  247. pguser = optarg;
  248. break;
  249. case 'p': /* authentication password */
  250. case 'a':
  251. pgpasswd = optarg;
  252. break;
  253. case 'v':
  254. verbose++;
  255. break;
  256. }
  257. }
  258. return validate_arguments ();
  259. }
  260. /******************************************************************************
  261. @@-
  262. <sect3>
  263. <title>validate_arguments</title>
  264. <para>&PROTO_validate_arguments;</para>
  265. <para>Given a database name, this function returns TRUE if the string
  266. is a valid PostgreSQL database name, and returns false if it is
  267. not.</para>
  268. <para>Valid PostgreSQL database names are less than &NAMEDATALEN;
  269. characters long and consist of letters, numbers, and underscores. The
  270. first character cannot be a number, however.</para>
  271. </sect3>
  272. -@@
  273. ******************************************************************************/
  274. int
  275. validate_arguments ()
  276. {
  277. return OK;
  278. }
  279. /******************************************************************************
  280. @@-
  281. <sect3>
  282. <title>is_pg_dbname</title>
  283. <para>&PROTO_is_pg_dbname;</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. is_pg_dbname (char *dbname)
  295. {
  296. char txt[NAMEDATALEN];
  297. char tmp[NAMEDATALEN];
  298. if (strlen (dbname) > NAMEDATALEN - 1)
  299. return (FALSE);
  300. strncpy (txt, dbname, NAMEDATALEN - 1);
  301. txt[NAMEDATALEN - 1] = 0;
  302. if (sscanf (txt, "%[_a-zA-Z]%[^_a-zA-Z0-9-]", tmp, tmp) == 1)
  303. return (TRUE);
  304. if (sscanf (txt, "%[_a-zA-Z]%[_a-zA-Z0-9-]%[^_a-zA-Z0-9-]", tmp, tmp, tmp) ==
  305. 2) return (TRUE);
  306. return (FALSE);
  307. }
  308. /**
  309. the tango program should eventually create an entity here based on the
  310. function prototype
  311. @@-
  312. <sect3>
  313. <title>is_pg_logname</title>
  314. <para>&PROTO_is_pg_logname;</para>
  315. <para>Given a username, this function returns TRUE if the string is a
  316. valid PostgreSQL username, and returns false if it is not. Valid PostgreSQL
  317. usernames are less than &NAMEDATALEN; characters long and consist of
  318. letters, numbers, dashes, and underscores, plus possibly some other
  319. characters.</para>
  320. <para>Currently this function only checks string length. Additional checks
  321. should be added.</para>
  322. </sect3>
  323. -@@
  324. ******************************************************************************/
  325. int
  326. is_pg_logname (char *username)
  327. {
  328. if (strlen (username) > NAMEDATALEN - 1)
  329. return (FALSE);
  330. return (TRUE);
  331. }
  332. /******************************************************************************
  333. @@-
  334. </sect2>
  335. </sect1>
  336. </article>
  337. -@@
  338. ******************************************************************************/
  339. void
  340. print_help (void)
  341. {
  342. char *myport;
  343. asprintf (&myport, "%d", DEFAULT_PORT);
  344. print_revision (progname, NP_VERSION);
  345. printf (COPYRIGHT, copyright, email);
  346. printf (_("Test whether a PostgreSQL Database is accepting connections."));
  347. printf ("\n\n");
  348. print_usage ();
  349. printf (_(UT_HELP_VRSN));
  350. printf (_(UT_EXTRA_OPTS));
  351. printf (_(UT_HOST_PORT), 'P', myport);
  352. printf (_(UT_IPv46));
  353. printf (" %s\n", "-d, --database=STRING");
  354. printf (" %s", _("Database to check "));
  355. printf (_("(default: %s)"), DEFAULT_DB);
  356. printf (" %s\n", "-l, --logname = STRING");
  357. printf (" %s\n", _("Login name of user"));
  358. printf (" %s\n", "-p, --password = STRING");
  359. printf (" %s\n", _("Password (BIG SECURITY ISSUE)"));
  360. printf (_(UT_WARN_CRIT));
  361. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  362. printf (_(UT_VERBOSE));
  363. printf ("\n");
  364. printf (" %s\n", _("All parameters are optional."));
  365. printf (" %s\n", _("This plugin tests a PostgreSQL DBMS to determine whether it is active and"));
  366. printf (" %s\n", _("accepting queries. In its current operation, it simply connects to the"));
  367. printf (" %s\n", _("specified database, and then disconnects. If no database is specified, it"));
  368. printf (" %s\n", _("connects to the template1 database, which is present in every functioning"));
  369. printf (" %s\n\n", _("PostgreSQL DBMS."));
  370. printf (" %s\n", _("The plugin will connect to a local postmaster if no host is specified. To"));
  371. printf (" %s\n", _("connect to a remote host, be sure that the remote postmaster accepts TCP/IP"));
  372. printf (" %s\n\n", _("connections (start the postmaster with the -i option)."));
  373. printf (" %s\n", _("Typically, the nagios user (unless the --logname option is used) should be"));
  374. printf (" %s\n", _("able to connect to the database without a password. The plugin can also send"));
  375. printf (" %s\n", _("a password, but no effort is made to obsure or encrypt the password."));
  376. #ifdef NP_EXTRA_OPTS
  377. printf ("\n");
  378. printf ("%s\n", _("Notes:"));
  379. printf (_(UT_EXTRA_OPTS_NOTES));
  380. #endif
  381. printf (_(UT_SUPPORT));
  382. }
  383. void
  384. print_usage (void)
  385. {
  386. printf (_("Usage:"));
  387. printf ("%s [-H <host>] [-P <port>] [-c <critical time>] [-w <warning time>]\n", progname);
  388. printf (" [-t <timeout>] [-d <database>] [-l <logname>] [-p <password>]\n");
  389. }