check_dbi.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /*****************************************************************************
  2. *
  3. * Nagios check_dbi plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 2011 Nagios Plugins Development Team
  7. * Author: Sebastian 'tokkee' Harl <sh@teamix.net>
  8. *
  9. * Description:
  10. *
  11. * This file contains the check_dbi plugin
  12. *
  13. * Runs an arbitrary SQL command and checks the result.
  14. *
  15. *
  16. * This program is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation, either version 3 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. *
  29. *
  30. *****************************************************************************/
  31. const char *progname = "check_dbi";
  32. const char *copyright = "2011";
  33. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  34. #include "common.h"
  35. #include "utils.h"
  36. #include "netutils.h"
  37. #include <dbi/dbi.h>
  38. #include <stdarg.h>
  39. typedef struct {
  40. char *key;
  41. char *value;
  42. } driver_option_t;
  43. char *host = NULL;
  44. int verbose = 0;
  45. char *warning_range = NULL;
  46. char *critical_range = NULL;
  47. thresholds *query_thresholds = NULL;
  48. char *conntime_warning_range = NULL;
  49. char *conntime_critical_range = NULL;
  50. thresholds *conntime_thresholds = NULL;
  51. char *np_dbi_driver = NULL;
  52. driver_option_t *np_dbi_options = NULL;
  53. int np_dbi_options_num = 0;
  54. char *np_dbi_database = NULL;
  55. char *np_dbi_query = NULL;
  56. int process_arguments (int, char **);
  57. int validate_arguments (void);
  58. void print_usage (void);
  59. void print_help (void);
  60. void np_dbi_print_error (dbi_conn, char *, ...);
  61. int do_query (dbi_conn, double *);
  62. int
  63. main (int argc, char **argv)
  64. {
  65. int conntime_status = STATE_UNKNOWN;
  66. int status = STATE_UNKNOWN;
  67. int exit_status = STATE_UNKNOWN;
  68. dbi_driver driver;
  69. dbi_conn conn;
  70. struct timeval start_timeval, end_timeval;
  71. double elapsed_time;
  72. double query_val = 0.0;
  73. int i;
  74. setlocale (LC_ALL, "");
  75. bindtextdomain (PACKAGE, LOCALEDIR);
  76. textdomain (PACKAGE);
  77. /* Parse extra opts if any */
  78. argv = np_extra_opts (&argc, argv, progname);
  79. if (process_arguments (argc, argv) == ERROR)
  80. usage4 (_("Could not parse arguments"));
  81. /* Set signal handling and alarm */
  82. if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
  83. usage4 (_("Cannot catch SIGALRM"));
  84. }
  85. alarm (timeout_interval);
  86. if (verbose > 2)
  87. printf ("Initializing DBI\n");
  88. if (dbi_initialize (NULL) < 0) {
  89. printf ("UNKNOWN - failed to initialize DBI.\n");
  90. return STATE_UNKNOWN;
  91. }
  92. if (verbose)
  93. printf ("Opening DBI driver '%s'\n", np_dbi_driver);
  94. driver = dbi_driver_open (np_dbi_driver);
  95. if (! driver) {
  96. printf ("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n",
  97. np_dbi_driver);
  98. printf ("Known drivers:\n");
  99. for (driver = dbi_driver_list (NULL); driver; driver = dbi_driver_list (driver)) {
  100. printf (" - %s\n", dbi_driver_get_name (driver));
  101. }
  102. return STATE_UNKNOWN;
  103. }
  104. /* make a connection to the database */
  105. gettimeofday (&start_timeval, NULL);
  106. conn = dbi_conn_open (driver);
  107. if (! conn) {
  108. printf ("UNKNOWN - failed top open connection object.\n");
  109. dbi_conn_close (conn);
  110. return STATE_UNKNOWN;
  111. }
  112. for (i = 0; i < np_dbi_options_num; ++i) {
  113. const char *opt;
  114. if (verbose > 1)
  115. printf ("Setting DBI driver option '%s' to '%s'\n",
  116. np_dbi_options[i].key, np_dbi_options[i].value);
  117. if (! dbi_conn_set_option (conn, np_dbi_options[i].key, np_dbi_options[i].value))
  118. continue;
  119. /* else: status != 0 */
  120. np_dbi_print_error (conn, "UNKNOWN - failed to set option '%s' to '%s'",
  121. np_dbi_options[i].key, np_dbi_options[i].value);
  122. printf ("Known driver options:\n");
  123. for (opt = dbi_conn_get_option_list (conn, NULL); opt;
  124. opt = dbi_conn_get_option_list (conn, opt)) {
  125. printf (" - %s\n", opt);
  126. }
  127. dbi_conn_close (conn);
  128. return STATE_UNKNOWN;
  129. }
  130. if (host) {
  131. if (verbose > 1)
  132. printf ("Setting DBI driver option 'host' to '%s'\n", host);
  133. dbi_conn_set_option (conn, "host", host);
  134. }
  135. if (verbose) {
  136. const char *dbname, *host;
  137. dbname = dbi_conn_get_option (conn, "dbname");
  138. host = dbi_conn_get_option (conn, "host");
  139. if (! dbname)
  140. dbname = "<unspecified>";
  141. if (! host)
  142. host = "<unspecified>";
  143. printf ("Connecting to database '%s' at host '%s'\n",
  144. dbname, host);
  145. }
  146. if (dbi_conn_connect (conn) < 0) {
  147. np_dbi_print_error (conn, "UNKOWN - failed to connect to database");
  148. return STATE_UNKNOWN;
  149. }
  150. gettimeofday (&end_timeval, NULL);
  151. while (start_timeval.tv_usec > end_timeval.tv_usec) {
  152. --end_timeval.tv_sec;
  153. end_timeval.tv_usec += 1000000;
  154. }
  155. elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec)
  156. + (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0;
  157. if (verbose)
  158. printf("Time elapsed: %f\n", elapsed_time);
  159. conntime_status = get_status (elapsed_time, conntime_thresholds);
  160. /* select a database */
  161. if (np_dbi_database) {
  162. if (verbose > 1)
  163. printf ("Selecting database '%s'\n", np_dbi_database);
  164. if (dbi_conn_select_db (conn, np_dbi_database)) {
  165. np_dbi_print_error (conn, "UNKOWN - failed to select database '%s'",
  166. np_dbi_database);
  167. return STATE_UNKNOWN;
  168. }
  169. }
  170. /* execute query */
  171. status = do_query (conn, &query_val);
  172. if (status != STATE_OK)
  173. /* do_query prints an error message in this case */
  174. return status;
  175. status = get_status (query_val, query_thresholds);
  176. if (verbose)
  177. printf("Closing connection\n");
  178. dbi_conn_close (conn);
  179. /* 'conntime_status' is worse than 'status' (but not UNKOWN) */
  180. if (((conntime_status < STATE_UNKNOWN) && (conntime_status > status))
  181. /* 'status' is UNKNOWN and 'conntime_status' is not OK */
  182. || ((status >= STATE_UNKNOWN) && (conntime_status != STATE_OK)))
  183. exit_status = conntime_status;
  184. else
  185. exit_status = status;
  186. printf ("%s - %s: connection time: %fs, %s: '%s' returned %f",
  187. state_text (exit_status),
  188. state_text (conntime_status), elapsed_time,
  189. state_text (status), np_dbi_query, query_val);
  190. printf (" | conntime=%fs;%s;%s;0 query=%f;%s;%s;0\n", elapsed_time,
  191. conntime_warning_range ? conntime_warning_range : "",
  192. conntime_critical_range ? conntime_critical_range : "",
  193. query_val, warning_range ? warning_range : "", critical_range ? critical_range : "");
  194. return exit_status;
  195. }
  196. /* process command-line arguments */
  197. int
  198. process_arguments (int argc, char **argv)
  199. {
  200. int c;
  201. int option = 0;
  202. static struct option longopts[] = {
  203. STD_LONG_OPTS,
  204. {"conntime-warning", required_argument, 0, 'W'},
  205. {"conntime-critical", required_argument, 0, 'C'},
  206. {"driver", required_argument, 0, 'd'},
  207. {"option", required_argument, 0, 'o'},
  208. {"query", required_argument, 0, 'q'},
  209. {"database", required_argument, 0, 'D'},
  210. {0, 0, 0, 0}
  211. };
  212. while (1) {
  213. c = getopt_long (argc, argv, "Vvht:c:w:H:W:C:d:o:q:D:",
  214. longopts, &option);
  215. if (c == EOF)
  216. break;
  217. switch (c) {
  218. case '?': /* usage */
  219. usage5 ();
  220. case 'h': /* help */
  221. print_help ();
  222. exit (STATE_OK);
  223. case 'V': /* version */
  224. print_revision (progname, NP_VERSION);
  225. exit (STATE_OK);
  226. case 'c': /* critical range */
  227. critical_range = optarg;
  228. break;
  229. case 'w': /* warning range */
  230. warning_range = optarg;
  231. break;
  232. case 't': /* timeout */
  233. if (!is_intnonneg (optarg))
  234. usage2 (_("Timeout interval must be a positive integer"), optarg);
  235. else
  236. timeout_interval = atoi (optarg);
  237. case 'C': /* critical conntime range */
  238. conntime_critical_range = optarg;
  239. break;
  240. case 'W': /* warning conntime range */
  241. conntime_warning_range = optarg;
  242. break;
  243. case 'H': /* host */
  244. if (!is_host (optarg))
  245. usage2 (_("Invalid hostname/address"), optarg);
  246. else
  247. host = optarg;
  248. break;
  249. case 'v':
  250. verbose++;
  251. break;
  252. case 'd':
  253. np_dbi_driver = optarg;
  254. break;
  255. case 'o':
  256. {
  257. driver_option_t *new;
  258. char *k, *v;
  259. k = optarg;
  260. v = strchr (k, (int)'=');
  261. if (! v)
  262. usage2 (_("Option must be '<key>=<value>'"), optarg);
  263. *v = '\0';
  264. ++v;
  265. new = realloc (np_dbi_options,
  266. (np_dbi_options_num + 1) * sizeof (*new));
  267. if (! new) {
  268. printf ("UNKOWN - failed to reallocate memory\n");
  269. exit (STATE_UNKNOWN);
  270. }
  271. np_dbi_options = new;
  272. new = np_dbi_options + np_dbi_options_num;
  273. ++np_dbi_options_num;
  274. new->key = k;
  275. new->value = v;
  276. }
  277. break;
  278. case 'q':
  279. np_dbi_query = optarg;
  280. break;
  281. case 'D':
  282. np_dbi_database = optarg;
  283. break;
  284. }
  285. }
  286. set_thresholds (&query_thresholds, warning_range, critical_range);
  287. set_thresholds (&conntime_thresholds, conntime_warning_range, conntime_critical_range);
  288. return validate_arguments ();
  289. }
  290. int
  291. validate_arguments ()
  292. {
  293. if (! np_dbi_driver)
  294. usage ("Must specify a DBI driver");
  295. if (! np_dbi_query)
  296. usage ("Must specify an SQL query to execute");
  297. return OK;
  298. }
  299. void
  300. print_help (void)
  301. {
  302. print_revision (progname, NP_VERSION);
  303. printf (COPYRIGHT, copyright, email);
  304. printf (_("This program checks a query result against threshold levels"));
  305. printf ("\n\n");
  306. print_usage ();
  307. printf (UT_HELP_VRSN);
  308. /* include this conditionally to avoid 'zero-length printf format string'
  309. * compiler warnings */
  310. #ifdef NP_EXTRA_OPTS
  311. printf (UT_EXTRA_OPTS);
  312. #endif
  313. printf ("\n");
  314. printf (" %s\n", "-d, --driver=STRING");
  315. printf (" %s\n", _("DBI driver to use"));
  316. printf (" %s\n", "-o, --option=STRING");
  317. printf (" %s\n", _("DBI driver options"));
  318. printf (" %s\n", "-q, --query=STRING");
  319. printf (" %s\n", _("SQL query to execute"));
  320. printf ("\n");
  321. printf (UT_WARN_CRIT_RANGE);
  322. printf (" %s\n", "-W, --conntime-warning=RANGE");
  323. printf (" %s\n", _("Connection time warning range"));
  324. printf (" %s\n", "-C, --conntime-critical=RANGE");
  325. printf (" %s\n", _("Connection time critical range"));
  326. printf ("\n");
  327. printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  328. printf (UT_VERBOSE);
  329. printf ("\n");
  330. printf (" %s\n", _("A DBI driver (-d option) and a query (-q option) are required."));
  331. printf (" %s\n", _("This plugin connects to an SQL database using libdbi and executes the"));
  332. printf (" %s\n", _("specified SQL query. The first column of the first row of the result"));
  333. printf (" %s\n", _("will be used as the check result and, if specified, compared with the"));
  334. printf (" %s\n", _("warning and critical ranges. The result from the query has to be numeric"));
  335. printf (" %s\n\n", _("(strings representing numbers are fine)."));
  336. printf (" %s\n", _("The number and type of required DBI driver options depends on the actual"));
  337. printf (" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/"));
  338. printf (" %s\n", _("for details."));
  339. printf (UT_SUPPORT);
  340. }
  341. void
  342. print_usage (void)
  343. {
  344. printf ("%s\n", _("Usage:"));
  345. printf ("%s -d <DBI driver> [-o <DBI driver option> [...]] -q <SQL query>\n", progname);
  346. printf (" [-H <host>] [-c <critical range>] [-w <warning range>]\n");
  347. printf (" [-C <critical conntime range>] [-W <warning conntime range>]\n");
  348. }
  349. double
  350. get_field (dbi_conn conn, dbi_result res, unsigned short *field_type)
  351. {
  352. double val = 0.0;
  353. if (*field_type == DBI_TYPE_INTEGER) {
  354. val = (double)dbi_result_get_longlong_idx (res, 1);
  355. }
  356. else if (*field_type == DBI_TYPE_DECIMAL) {
  357. val = dbi_result_get_double_idx (res, 1);
  358. }
  359. else if (*field_type == DBI_TYPE_STRING) {
  360. const char *val_str;
  361. char *endptr = NULL;
  362. val_str = dbi_result_get_string_idx (res, 1);
  363. if ((! val_str) || (strcmp (val_str, "ERROR") == 0)) {
  364. np_dbi_print_error (conn, "CRITICAL - failed to fetch string value");
  365. *field_type = DBI_TYPE_ERROR;
  366. return 0.0;
  367. }
  368. if (verbose > 2)
  369. printf ("Query returned string '%s'\n", val_str);
  370. val = strtod (val_str, &endptr);
  371. if (endptr == val_str) {
  372. printf ("CRITICAL - result value is not a numeric: %s\n", val_str);
  373. *field_type = DBI_TYPE_ERROR;
  374. return 0.0;
  375. }
  376. else if ((endptr != NULL) && (*endptr != '\0')) {
  377. if (verbose)
  378. printf ("Garbage after value: %s\n", endptr);
  379. }
  380. }
  381. else {
  382. printf ("CRITICAL - cannot parse value of type %s (%i)\n",
  383. (*field_type == DBI_TYPE_BINARY)
  384. ? "BINARY"
  385. : (*field_type == DBI_TYPE_DATETIME)
  386. ? "DATETIME"
  387. : "<unknown>",
  388. *field_type);
  389. *field_type = DBI_TYPE_ERROR;
  390. return 0.0;
  391. }
  392. return val;
  393. }
  394. int
  395. do_query (dbi_conn conn, double *res_val)
  396. {
  397. dbi_result res;
  398. unsigned short field_type;
  399. double val = 0.0;
  400. if (verbose)
  401. printf ("Executing query '%s'\n", np_dbi_query);
  402. res = dbi_conn_query (conn, np_dbi_query);
  403. if (! res) {
  404. np_dbi_print_error (conn, "CRITICAL - failed to execute query '%s'", np_dbi_query);
  405. return STATE_CRITICAL;
  406. }
  407. if (dbi_result_get_numrows (res) == DBI_ROW_ERROR) {
  408. np_dbi_print_error (conn, "CRITICAL - failed to fetch rows");
  409. return STATE_CRITICAL;
  410. }
  411. if (dbi_result_get_numrows (res) < 1) {
  412. printf ("WARNING - no rows returned\n");
  413. return STATE_WARNING;
  414. }
  415. if (dbi_result_get_numfields (res) == DBI_FIELD_ERROR) {
  416. np_dbi_print_error (conn, "CRITICAL - failed to fetch fields");
  417. return STATE_CRITICAL;
  418. }
  419. if (dbi_result_get_numfields (res) < 1) {
  420. printf ("WARNING - no fields returned\n");
  421. return STATE_WARNING;
  422. }
  423. if (dbi_result_first_row (res) != 1) {
  424. np_dbi_print_error (conn, "CRITICAL - failed to fetch first row");
  425. return STATE_CRITICAL;
  426. }
  427. field_type = dbi_result_get_field_type_idx (res, 1);
  428. if (field_type != DBI_TYPE_ERROR)
  429. val = get_field (conn, res, &field_type);
  430. if (field_type == DBI_TYPE_ERROR) {
  431. np_dbi_print_error (conn, "CRITICAL - failed to fetch data");
  432. return STATE_CRITICAL;
  433. }
  434. *res_val = val;
  435. dbi_result_free (res);
  436. return STATE_OK;
  437. }
  438. void
  439. np_dbi_print_error (dbi_conn conn, char *fmt, ...)
  440. {
  441. const char *errmsg = NULL;
  442. va_list ap;
  443. va_start (ap, fmt);
  444. dbi_conn_error (conn, &errmsg);
  445. vprintf (fmt, ap);
  446. printf (": %s\n", errmsg);
  447. va_end (ap);
  448. }