check_dbi.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. double timediff (struct timeval, struct timeval);
  61. void np_dbi_print_error (dbi_conn, char *, ...);
  62. int do_query (dbi_conn, double *, double *);
  63. int
  64. main (int argc, char **argv)
  65. {
  66. int conntime_status = STATE_UNKNOWN;
  67. int status = STATE_UNKNOWN;
  68. int exit_status = STATE_UNKNOWN;
  69. dbi_driver driver;
  70. dbi_conn conn;
  71. struct timeval start_timeval, end_timeval;
  72. double conn_time = 0.0;
  73. double query_time = 0.0;
  74. double query_val = 0.0;
  75. int i;
  76. setlocale (LC_ALL, "");
  77. bindtextdomain (PACKAGE, LOCALEDIR);
  78. textdomain (PACKAGE);
  79. /* Parse extra opts if any */
  80. argv = np_extra_opts (&argc, argv, progname);
  81. if (process_arguments (argc, argv) == ERROR)
  82. usage4 (_("Could not parse arguments"));
  83. /* Set signal handling and alarm */
  84. if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
  85. usage4 (_("Cannot catch SIGALRM"));
  86. }
  87. alarm (timeout_interval);
  88. if (verbose > 2)
  89. printf ("Initializing DBI\n");
  90. if (dbi_initialize (NULL) < 0) {
  91. printf ("UNKNOWN - failed to initialize DBI.\n");
  92. return STATE_UNKNOWN;
  93. }
  94. if (verbose)
  95. printf ("Opening DBI driver '%s'\n", np_dbi_driver);
  96. driver = dbi_driver_open (np_dbi_driver);
  97. if (! driver) {
  98. printf ("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n",
  99. np_dbi_driver);
  100. printf ("Known drivers:\n");
  101. for (driver = dbi_driver_list (NULL); driver; driver = dbi_driver_list (driver)) {
  102. printf (" - %s\n", dbi_driver_get_name (driver));
  103. }
  104. return STATE_UNKNOWN;
  105. }
  106. /* make a connection to the database */
  107. gettimeofday (&start_timeval, NULL);
  108. conn = dbi_conn_open (driver);
  109. if (! conn) {
  110. printf ("UNKNOWN - failed top open connection object.\n");
  111. dbi_conn_close (conn);
  112. return STATE_UNKNOWN;
  113. }
  114. for (i = 0; i < np_dbi_options_num; ++i) {
  115. const char *opt;
  116. if (verbose > 1)
  117. printf ("Setting DBI driver option '%s' to '%s'\n",
  118. np_dbi_options[i].key, np_dbi_options[i].value);
  119. if (! dbi_conn_set_option (conn, np_dbi_options[i].key, np_dbi_options[i].value))
  120. continue;
  121. /* else: status != 0 */
  122. np_dbi_print_error (conn, "UNKNOWN - failed to set option '%s' to '%s'",
  123. np_dbi_options[i].key, np_dbi_options[i].value);
  124. printf ("Known driver options:\n");
  125. for (opt = dbi_conn_get_option_list (conn, NULL); opt;
  126. opt = dbi_conn_get_option_list (conn, opt)) {
  127. printf (" - %s\n", opt);
  128. }
  129. dbi_conn_close (conn);
  130. return STATE_UNKNOWN;
  131. }
  132. if (host) {
  133. if (verbose > 1)
  134. printf ("Setting DBI driver option 'host' to '%s'\n", host);
  135. dbi_conn_set_option (conn, "host", host);
  136. }
  137. if (verbose) {
  138. const char *dbname, *host;
  139. dbname = dbi_conn_get_option (conn, "dbname");
  140. host = dbi_conn_get_option (conn, "host");
  141. if (! dbname)
  142. dbname = "<unspecified>";
  143. if (! host)
  144. host = "<unspecified>";
  145. printf ("Connecting to database '%s' at host '%s'\n",
  146. dbname, host);
  147. }
  148. if (dbi_conn_connect (conn) < 0) {
  149. np_dbi_print_error (conn, "UNKOWN - failed to connect to database");
  150. return STATE_UNKNOWN;
  151. }
  152. gettimeofday (&end_timeval, NULL);
  153. conn_time = timediff (start_timeval, end_timeval);
  154. if (verbose)
  155. printf("Time elapsed: %f\n", conn_time);
  156. conntime_status = get_status (conn_time, conntime_thresholds);
  157. /* select a database */
  158. if (np_dbi_database) {
  159. if (verbose > 1)
  160. printf ("Selecting database '%s'\n", np_dbi_database);
  161. if (dbi_conn_select_db (conn, np_dbi_database)) {
  162. np_dbi_print_error (conn, "UNKOWN - failed to select database '%s'",
  163. np_dbi_database);
  164. return STATE_UNKNOWN;
  165. }
  166. }
  167. /* execute query */
  168. status = do_query (conn, &query_val, &query_time);
  169. if (status != STATE_OK)
  170. /* do_query prints an error message in this case */
  171. return status;
  172. status = get_status (query_val, query_thresholds);
  173. if (verbose)
  174. printf("Closing connection\n");
  175. dbi_conn_close (conn);
  176. /* 'conntime_status' is worse than 'status' (but not UNKOWN) */
  177. if (((conntime_status < STATE_UNKNOWN) && (conntime_status > status))
  178. /* 'status' is UNKNOWN and 'conntime_status' is not OK */
  179. || ((status >= STATE_UNKNOWN) && (conntime_status != STATE_OK)))
  180. exit_status = conntime_status;
  181. else
  182. exit_status = status;
  183. printf ("%s - %s: connection time: %fs, %s: '%s' returned %f in %fs",
  184. state_text (exit_status),
  185. state_text (conntime_status), conn_time,
  186. state_text (status), np_dbi_query, query_val, query_time);
  187. printf (" | conntime=%fs;%s;%s;0; query=%f;%s;%s;; querytime=%fs;;;0;\n", conn_time,
  188. conntime_warning_range ? conntime_warning_range : "",
  189. conntime_critical_range ? conntime_critical_range : "",
  190. query_val, warning_range ? warning_range : "", critical_range ? critical_range : "",
  191. query_time);
  192. return exit_status;
  193. }
  194. /* process command-line arguments */
  195. int
  196. process_arguments (int argc, char **argv)
  197. {
  198. int c;
  199. int option = 0;
  200. static struct option longopts[] = {
  201. STD_LONG_OPTS,
  202. {"conntime-warning", required_argument, 0, 'W'},
  203. {"conntime-critical", required_argument, 0, 'C'},
  204. {"driver", required_argument, 0, 'd'},
  205. {"option", required_argument, 0, 'o'},
  206. {"query", required_argument, 0, 'q'},
  207. {"database", required_argument, 0, 'D'},
  208. {0, 0, 0, 0}
  209. };
  210. while (1) {
  211. c = getopt_long (argc, argv, "Vvht:c:w:H:W:C:d:o:q:D:",
  212. longopts, &option);
  213. if (c == EOF)
  214. break;
  215. switch (c) {
  216. case '?': /* usage */
  217. usage5 ();
  218. case 'h': /* help */
  219. print_help ();
  220. exit (STATE_OK);
  221. case 'V': /* version */
  222. print_revision (progname, NP_VERSION);
  223. exit (STATE_OK);
  224. case 'c': /* critical range */
  225. critical_range = optarg;
  226. break;
  227. case 'w': /* warning range */
  228. warning_range = optarg;
  229. break;
  230. case 't': /* timeout */
  231. if (!is_intnonneg (optarg))
  232. usage2 (_("Timeout interval must be a positive integer"), optarg);
  233. else
  234. timeout_interval = atoi (optarg);
  235. case 'C': /* critical conntime range */
  236. conntime_critical_range = optarg;
  237. break;
  238. case 'W': /* warning conntime range */
  239. conntime_warning_range = optarg;
  240. break;
  241. case 'H': /* host */
  242. if (!is_host (optarg))
  243. usage2 (_("Invalid hostname/address"), optarg);
  244. else
  245. host = optarg;
  246. break;
  247. case 'v':
  248. verbose++;
  249. break;
  250. case 'd':
  251. np_dbi_driver = optarg;
  252. break;
  253. case 'o':
  254. {
  255. driver_option_t *new;
  256. char *k, *v;
  257. k = optarg;
  258. v = strchr (k, (int)'=');
  259. if (! v)
  260. usage2 (_("Option must be '<key>=<value>'"), optarg);
  261. *v = '\0';
  262. ++v;
  263. new = realloc (np_dbi_options,
  264. (np_dbi_options_num + 1) * sizeof (*new));
  265. if (! new) {
  266. printf ("UNKOWN - failed to reallocate memory\n");
  267. exit (STATE_UNKNOWN);
  268. }
  269. np_dbi_options = new;
  270. new = np_dbi_options + np_dbi_options_num;
  271. ++np_dbi_options_num;
  272. new->key = k;
  273. new->value = v;
  274. }
  275. break;
  276. case 'q':
  277. np_dbi_query = optarg;
  278. break;
  279. case 'D':
  280. np_dbi_database = optarg;
  281. break;
  282. }
  283. }
  284. set_thresholds (&query_thresholds, warning_range, critical_range);
  285. set_thresholds (&conntime_thresholds, conntime_warning_range, conntime_critical_range);
  286. return validate_arguments ();
  287. }
  288. int
  289. validate_arguments ()
  290. {
  291. if (! np_dbi_driver)
  292. usage ("Must specify a DBI driver");
  293. if (! np_dbi_query)
  294. usage ("Must specify an SQL query to execute");
  295. return OK;
  296. }
  297. void
  298. print_help (void)
  299. {
  300. print_revision (progname, NP_VERSION);
  301. printf (COPYRIGHT, copyright, email);
  302. printf (_("This program checks a query result against threshold levels"));
  303. printf ("\n\n");
  304. print_usage ();
  305. printf (UT_HELP_VRSN);
  306. /* include this conditionally to avoid 'zero-length printf format string'
  307. * compiler warnings */
  308. #ifdef NP_EXTRA_OPTS
  309. printf (UT_EXTRA_OPTS);
  310. #endif
  311. printf ("\n");
  312. printf (" %s\n", "-d, --driver=STRING");
  313. printf (" %s\n", _("DBI driver to use"));
  314. printf (" %s\n", "-o, --option=STRING");
  315. printf (" %s\n", _("DBI driver options"));
  316. printf (" %s\n", "-q, --query=STRING");
  317. printf (" %s\n", _("SQL query to execute"));
  318. printf ("\n");
  319. printf (UT_WARN_CRIT_RANGE);
  320. printf (" %s\n", "-W, --conntime-warning=RANGE");
  321. printf (" %s\n", _("Connection time warning range"));
  322. printf (" %s\n", "-C, --conntime-critical=RANGE");
  323. printf (" %s\n", _("Connection time critical range"));
  324. printf ("\n");
  325. printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  326. printf (UT_VERBOSE);
  327. printf ("\n");
  328. printf (" %s\n", _("A DBI driver (-d option) and a query (-q option) are required."));
  329. printf (" %s\n", _("This plugin connects to an SQL database using libdbi and executes the"));
  330. printf (" %s\n", _("specified SQL query. The first column of the first row of the result"));
  331. printf (" %s\n", _("will be used as the check result and, if specified, compared with the"));
  332. printf (" %s\n", _("warning and critical ranges. The result from the query has to be numeric"));
  333. printf (" %s\n\n", _("(strings representing numbers are fine)."));
  334. printf (" %s\n", _("The number and type of required DBI driver options depends on the actual"));
  335. printf (" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/"));
  336. printf (" %s\n", _("for details."));
  337. printf (UT_SUPPORT);
  338. }
  339. void
  340. print_usage (void)
  341. {
  342. printf ("%s\n", _("Usage:"));
  343. printf ("%s -d <DBI driver> [-o <DBI driver option> [...]] -q <SQL query>\n", progname);
  344. printf (" [-H <host>] [-c <critical range>] [-w <warning range>]\n");
  345. printf (" [-C <critical conntime range>] [-W <warning conntime range>]\n");
  346. }
  347. double
  348. get_field (dbi_conn conn, dbi_result res, unsigned short *field_type)
  349. {
  350. double val = 0.0;
  351. if (*field_type == DBI_TYPE_INTEGER) {
  352. val = (double)dbi_result_get_longlong_idx (res, 1);
  353. }
  354. else if (*field_type == DBI_TYPE_DECIMAL) {
  355. val = dbi_result_get_double_idx (res, 1);
  356. }
  357. else if (*field_type == DBI_TYPE_STRING) {
  358. const char *val_str;
  359. char *endptr = NULL;
  360. val_str = dbi_result_get_string_idx (res, 1);
  361. if ((! val_str) || (strcmp (val_str, "ERROR") == 0)) {
  362. np_dbi_print_error (conn, "CRITICAL - failed to fetch string value");
  363. *field_type = DBI_TYPE_ERROR;
  364. return 0.0;
  365. }
  366. if (verbose > 2)
  367. printf ("Query returned string '%s'\n", val_str);
  368. val = strtod (val_str, &endptr);
  369. if (endptr == val_str) {
  370. printf ("CRITICAL - result value is not a numeric: %s\n", val_str);
  371. *field_type = DBI_TYPE_ERROR;
  372. return 0.0;
  373. }
  374. else if ((endptr != NULL) && (*endptr != '\0')) {
  375. if (verbose)
  376. printf ("Garbage after value: %s\n", endptr);
  377. }
  378. }
  379. else {
  380. printf ("CRITICAL - cannot parse value of type %s (%i)\n",
  381. (*field_type == DBI_TYPE_BINARY)
  382. ? "BINARY"
  383. : (*field_type == DBI_TYPE_DATETIME)
  384. ? "DATETIME"
  385. : "<unknown>",
  386. *field_type);
  387. *field_type = DBI_TYPE_ERROR;
  388. return 0.0;
  389. }
  390. return val;
  391. }
  392. int
  393. do_query (dbi_conn conn, double *res_val, double *res_time)
  394. {
  395. dbi_result res;
  396. unsigned short field_type;
  397. double val = 0.0;
  398. struct timeval timeval_start, timeval_end;
  399. if (verbose)
  400. printf ("Executing query '%s'\n", np_dbi_query);
  401. gettimeofday (&timeval_start, NULL);
  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. gettimeofday (&timeval_end, NULL);
  431. *res_time = timediff (timeval_start, timeval_end);
  432. if (field_type == DBI_TYPE_ERROR) {
  433. np_dbi_print_error (conn, "CRITICAL - failed to fetch data");
  434. return STATE_CRITICAL;
  435. }
  436. *res_val = val;
  437. dbi_result_free (res);
  438. return STATE_OK;
  439. }
  440. double
  441. timediff (struct timeval start, struct timeval end)
  442. {
  443. double diff;
  444. while (start.tv_usec > end.tv_usec) {
  445. --end.tv_sec;
  446. end.tv_usec += 1000000;
  447. }
  448. diff = (double)(end.tv_sec - start.tv_sec)
  449. + (double)(end.tv_usec - start.tv_usec) / 1000000.0;
  450. return diff;
  451. }
  452. void
  453. np_dbi_print_error (dbi_conn conn, char *fmt, ...)
  454. {
  455. const char *errmsg = NULL;
  456. va_list ap;
  457. va_start (ap, fmt);
  458. dbi_conn_error (conn, &errmsg);
  459. vprintf (fmt, ap);
  460. printf (": %s\n", errmsg);
  461. va_end (ap);
  462. }