check_dbi.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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 "regex.h"
  38. /* required for NAN */
  39. #ifndef _ISOC99_SOURCE
  40. #define _ISOC99_SOURCE
  41. #endif
  42. #include <assert.h>
  43. #include <math.h>
  44. #include <dbi/dbi.h>
  45. #include <stdarg.h>
  46. typedef enum {
  47. METRIC_CONN_TIME,
  48. METRIC_QUERY_RESULT,
  49. METRIC_QUERY_TIME,
  50. } np_dbi_metric_t;
  51. typedef enum {
  52. TYPE_NUMERIC,
  53. TYPE_STRING,
  54. } np_dbi_type_t;
  55. typedef struct {
  56. char *key;
  57. char *value;
  58. } driver_option_t;
  59. char *host = NULL;
  60. int verbose = 0;
  61. char *warning_range = NULL;
  62. char *critical_range = NULL;
  63. thresholds *dbi_thresholds = NULL;
  64. char *expect = NULL;
  65. regex_t expect_re;
  66. char *expect_re_str = NULL;
  67. int expect_re_cflags = 0;
  68. np_dbi_metric_t metric = METRIC_QUERY_RESULT;
  69. np_dbi_type_t type = TYPE_NUMERIC;
  70. char *np_dbi_driver = NULL;
  71. driver_option_t *np_dbi_options = NULL;
  72. int np_dbi_options_num = 0;
  73. char *np_dbi_database = NULL;
  74. char *np_dbi_query = NULL;
  75. int process_arguments (int, char **);
  76. int validate_arguments (void);
  77. void print_usage (void);
  78. void print_help (void);
  79. double timediff (struct timeval, struct timeval);
  80. void np_dbi_print_error (dbi_conn, char *, ...);
  81. int do_query (dbi_conn, const char **, double *, double *);
  82. int
  83. main (int argc, char **argv)
  84. {
  85. int status = STATE_UNKNOWN;
  86. dbi_driver driver;
  87. dbi_conn conn;
  88. struct timeval start_timeval, end_timeval;
  89. double conn_time = 0.0;
  90. double query_time = 0.0;
  91. const char *query_val_str = NULL;
  92. double query_val = 0.0;
  93. int i;
  94. setlocale (LC_ALL, "");
  95. bindtextdomain (PACKAGE, LOCALEDIR);
  96. textdomain (PACKAGE);
  97. /* Parse extra opts if any */
  98. argv = np_extra_opts (&argc, argv, progname);
  99. if (process_arguments (argc, argv) == ERROR)
  100. usage4 (_("Could not parse arguments"));
  101. /* Set signal handling and alarm */
  102. if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
  103. usage4 (_("Cannot catch SIGALRM"));
  104. }
  105. alarm (timeout_interval);
  106. if (verbose > 2)
  107. printf ("Initializing DBI\n");
  108. if (dbi_initialize (NULL) < 0) {
  109. printf ("UNKNOWN - failed to initialize DBI.\n");
  110. return STATE_UNKNOWN;
  111. }
  112. if (verbose)
  113. printf ("Opening DBI driver '%s'\n", np_dbi_driver);
  114. driver = dbi_driver_open (np_dbi_driver);
  115. if (! driver) {
  116. printf ("UNKNOWN - failed to open DBI driver '%s'; possibly it's not installed.\n",
  117. np_dbi_driver);
  118. printf ("Known drivers:\n");
  119. for (driver = dbi_driver_list (NULL); driver; driver = dbi_driver_list (driver)) {
  120. printf (" - %s\n", dbi_driver_get_name (driver));
  121. }
  122. return STATE_UNKNOWN;
  123. }
  124. /* make a connection to the database */
  125. gettimeofday (&start_timeval, NULL);
  126. conn = dbi_conn_open (driver);
  127. if (! conn) {
  128. printf ("UNKNOWN - failed top open connection object.\n");
  129. dbi_conn_close (conn);
  130. return STATE_UNKNOWN;
  131. }
  132. for (i = 0; i < np_dbi_options_num; ++i) {
  133. const char *opt;
  134. if (verbose > 1)
  135. printf ("Setting DBI driver option '%s' to '%s'\n",
  136. np_dbi_options[i].key, np_dbi_options[i].value);
  137. if (! dbi_conn_set_option (conn, np_dbi_options[i].key, np_dbi_options[i].value))
  138. continue;
  139. /* else: status != 0 */
  140. np_dbi_print_error (conn, "UNKNOWN - failed to set option '%s' to '%s'",
  141. np_dbi_options[i].key, np_dbi_options[i].value);
  142. printf ("Known driver options:\n");
  143. for (opt = dbi_conn_get_option_list (conn, NULL); opt;
  144. opt = dbi_conn_get_option_list (conn, opt)) {
  145. printf (" - %s\n", opt);
  146. }
  147. dbi_conn_close (conn);
  148. return STATE_UNKNOWN;
  149. }
  150. if (host) {
  151. if (verbose > 1)
  152. printf ("Setting DBI driver option 'host' to '%s'\n", host);
  153. dbi_conn_set_option (conn, "host", host);
  154. }
  155. if (verbose) {
  156. const char *dbname, *host;
  157. dbname = dbi_conn_get_option (conn, "dbname");
  158. host = dbi_conn_get_option (conn, "host");
  159. if (! dbname)
  160. dbname = "<unspecified>";
  161. if (! host)
  162. host = "<unspecified>";
  163. printf ("Connecting to database '%s' at host '%s'\n",
  164. dbname, host);
  165. }
  166. if (dbi_conn_connect (conn) < 0) {
  167. np_dbi_print_error (conn, "UNKOWN - failed to connect to database");
  168. return STATE_UNKNOWN;
  169. }
  170. gettimeofday (&end_timeval, NULL);
  171. conn_time = timediff (start_timeval, end_timeval);
  172. if (verbose)
  173. printf("Time elapsed: %f\n", conn_time);
  174. if (metric == METRIC_CONN_TIME)
  175. status = get_status (conn_time, dbi_thresholds);
  176. /* select a database */
  177. if (np_dbi_database) {
  178. if (verbose > 1)
  179. printf ("Selecting database '%s'\n", np_dbi_database);
  180. if (dbi_conn_select_db (conn, np_dbi_database)) {
  181. np_dbi_print_error (conn, "UNKOWN - failed to select database '%s'",
  182. np_dbi_database);
  183. return STATE_UNKNOWN;
  184. }
  185. }
  186. if (np_dbi_query) {
  187. /* execute query */
  188. status = do_query (conn, &query_val_str, &query_val, &query_time);
  189. if (status != STATE_OK)
  190. /* do_query prints an error message in this case */
  191. return status;
  192. if (metric == METRIC_QUERY_RESULT) {
  193. if (expect) {
  194. if ((! query_val_str) || strcmp (query_val_str, expect))
  195. status = STATE_CRITICAL;
  196. else
  197. status = STATE_OK;
  198. }
  199. else if (expect_re_str) {
  200. int err;
  201. err = regexec (&expect_re, query_val_str, 0, NULL, /* flags = */ 0);
  202. if (! err)
  203. status = STATE_OK;
  204. else if (err == REG_NOMATCH)
  205. status = STATE_CRITICAL;
  206. else {
  207. char errmsg[1024];
  208. regerror (err, &expect_re, errmsg, sizeof (errmsg));
  209. printf ("ERROR - failed to execute regular expression: %s\n",
  210. errmsg);
  211. status = STATE_CRITICAL;
  212. }
  213. }
  214. else
  215. status = get_status (query_val, dbi_thresholds);
  216. }
  217. else if (metric == METRIC_QUERY_TIME)
  218. status = get_status (query_time, dbi_thresholds);
  219. }
  220. if (verbose)
  221. printf("Closing connection\n");
  222. dbi_conn_close (conn);
  223. /* In case of METRIC_QUERY_RESULT, isnan(query_val) indicates an error
  224. * which should have been reported and handled (abort) before
  225. * ... unless we expected a string to be returned */
  226. assert ((metric != METRIC_QUERY_RESULT) || (! isnan (query_val))
  227. || (type == TYPE_STRING));
  228. assert ((type != TYPE_STRING) || (expect || expect_re_str));
  229. printf ("%s - connection time: %fs", state_text (status), conn_time);
  230. if (np_dbi_query) {
  231. if (type == TYPE_STRING) {
  232. assert (expect || expect_re_str);
  233. printf (", '%s' returned '%s' in %fs", np_dbi_query,
  234. query_val_str ? query_val_str : "<nothing>", query_time);
  235. if (status != STATE_OK) {
  236. if (expect)
  237. printf (" (expected '%s')", expect);
  238. else if (expect_re_str)
  239. printf (" (expected regex /%s/%s)", expect_re_str,
  240. ((expect_re_cflags & REG_ICASE) ? "i" : ""));
  241. }
  242. }
  243. else if (isnan (query_val))
  244. printf (", '%s' query execution time: %fs", np_dbi_query, query_time);
  245. else
  246. printf (", '%s' returned %f in %fs", np_dbi_query, query_val, query_time);
  247. }
  248. printf (" | conntime=%fs;%s;%s;0;", conn_time,
  249. ((metric == METRIC_CONN_TIME) && warning_range) ? warning_range : "",
  250. ((metric == METRIC_CONN_TIME) && critical_range) ? critical_range : "");
  251. if (np_dbi_query) {
  252. if (! isnan (query_val)) /* this is also true when -e is used */
  253. printf (" query=%f;%s;%s;;", query_val,
  254. ((metric == METRIC_QUERY_RESULT) && warning_range) ? warning_range : "",
  255. ((metric == METRIC_QUERY_RESULT) && critical_range) ? critical_range : "");
  256. printf (" querytime=%fs;%s;%s;0;", query_time,
  257. ((metric == METRIC_QUERY_TIME) && warning_range) ? warning_range : "",
  258. ((metric == METRIC_QUERY_TIME) && critical_range) ? critical_range : "");
  259. }
  260. printf ("\n");
  261. return status;
  262. }
  263. /* process command-line arguments */
  264. int
  265. process_arguments (int argc, char **argv)
  266. {
  267. int c;
  268. int option = 0;
  269. static struct option longopts[] = {
  270. STD_LONG_OPTS,
  271. {"expect", required_argument, 0, 'e'},
  272. {"regex", required_argument, 0, 'r'},
  273. {"regexi", required_argument, 0, 'R'},
  274. {"metric", required_argument, 0, 'm'},
  275. {"driver", required_argument, 0, 'd'},
  276. {"option", required_argument, 0, 'o'},
  277. {"query", required_argument, 0, 'q'},
  278. {"database", required_argument, 0, 'D'},
  279. {0, 0, 0, 0}
  280. };
  281. while (1) {
  282. c = getopt_long (argc, argv, "Vvht:c:w:e:r:R:m:H:d:o:q:D:",
  283. longopts, &option);
  284. if (c == EOF)
  285. break;
  286. switch (c) {
  287. case '?': /* usage */
  288. usage5 ();
  289. case 'h': /* help */
  290. print_help ();
  291. exit (STATE_OK);
  292. case 'V': /* version */
  293. print_revision (progname, NP_VERSION);
  294. exit (STATE_OK);
  295. case 'c': /* critical range */
  296. critical_range = optarg;
  297. type = TYPE_NUMERIC;
  298. break;
  299. case 'w': /* warning range */
  300. warning_range = optarg;
  301. type = TYPE_NUMERIC;
  302. break;
  303. case 'e':
  304. expect = optarg;
  305. type = TYPE_STRING;
  306. break;
  307. case 'R':
  308. expect_re_cflags = REG_ICASE;
  309. /* fall through */
  310. case 'r':
  311. {
  312. int err;
  313. expect_re_cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
  314. expect_re_str = optarg;
  315. type = TYPE_STRING;
  316. err = regcomp (&expect_re, expect_re_str, expect_re_cflags);
  317. if (err) {
  318. char errmsg[1024];
  319. regerror (err, &expect_re, errmsg, sizeof (errmsg));
  320. printf ("ERROR - failed to compile regular expression: %s\n",
  321. errmsg);
  322. return ERROR;
  323. }
  324. break;
  325. }
  326. case 'm':
  327. if (! strcasecmp (optarg, "CONN_TIME"))
  328. metric = METRIC_CONN_TIME;
  329. else if (! strcasecmp (optarg, "QUERY_RESULT"))
  330. metric = METRIC_QUERY_RESULT;
  331. else if (! strcasecmp (optarg, "QUERY_TIME"))
  332. metric = METRIC_QUERY_TIME;
  333. else
  334. usage2 (_("Invalid metric"), optarg);
  335. break;
  336. case 't': /* timeout */
  337. if (!is_intnonneg (optarg))
  338. usage2 (_("Timeout interval must be a positive integer"), optarg);
  339. else
  340. timeout_interval = atoi (optarg);
  341. case 'H': /* host */
  342. if (!is_host (optarg))
  343. usage2 (_("Invalid hostname/address"), optarg);
  344. else
  345. host = optarg;
  346. break;
  347. case 'v':
  348. verbose++;
  349. break;
  350. case 'd':
  351. np_dbi_driver = optarg;
  352. break;
  353. case 'o':
  354. {
  355. driver_option_t *new;
  356. char *k, *v;
  357. k = optarg;
  358. v = strchr (k, (int)'=');
  359. if (! v)
  360. usage2 (_("Option must be '<key>=<value>'"), optarg);
  361. *v = '\0';
  362. ++v;
  363. new = realloc (np_dbi_options,
  364. (np_dbi_options_num + 1) * sizeof (*new));
  365. if (! new) {
  366. printf ("UNKOWN - failed to reallocate memory\n");
  367. exit (STATE_UNKNOWN);
  368. }
  369. np_dbi_options = new;
  370. new = np_dbi_options + np_dbi_options_num;
  371. ++np_dbi_options_num;
  372. new->key = k;
  373. new->value = v;
  374. }
  375. break;
  376. case 'q':
  377. np_dbi_query = optarg;
  378. break;
  379. case 'D':
  380. np_dbi_database = optarg;
  381. break;
  382. }
  383. }
  384. set_thresholds (&dbi_thresholds, warning_range, critical_range);
  385. return validate_arguments ();
  386. }
  387. int
  388. validate_arguments ()
  389. {
  390. if (! np_dbi_driver)
  391. usage ("Must specify a DBI driver");
  392. if (((metric == METRIC_QUERY_RESULT) || (metric == METRIC_QUERY_TIME))
  393. && (! np_dbi_query))
  394. usage ("Must specify a query to execute (metric == QUERY_RESULT)");
  395. if ((metric != METRIC_CONN_TIME)
  396. && (metric != METRIC_QUERY_RESULT)
  397. && (metric != METRIC_QUERY_TIME))
  398. usage ("Invalid metric specified");
  399. if (expect && (warning_range || critical_range || expect_re_str))
  400. usage ("Do not mix -e and -w/-c/-r/-R");
  401. if (expect_re_str && (warning_range || critical_range || expect))
  402. usage ("Do not mix -r/-R and -w/-c/-e");
  403. if (expect && (metric != METRIC_QUERY_RESULT))
  404. usage ("Option -e requires metric QUERY_RESULT");
  405. if (expect_re_str && (metric != METRIC_QUERY_RESULT))
  406. usage ("Options -r/-R require metric QUERY_RESULT");
  407. return OK;
  408. }
  409. void
  410. print_help (void)
  411. {
  412. print_revision (progname, NP_VERSION);
  413. printf (COPYRIGHT, copyright, email);
  414. printf (_("This program connects to an (SQL) database using DBI and checks the\n"
  415. "specified metric against threshold levels. The default metric is\n"
  416. "the result of the specified query.\n"));
  417. printf ("\n\n");
  418. print_usage ();
  419. printf (UT_HELP_VRSN);
  420. /* include this conditionally to avoid 'zero-length printf format string'
  421. * compiler warnings */
  422. #ifdef NP_EXTRA_OPTS
  423. printf (UT_EXTRA_OPTS);
  424. #endif
  425. printf ("\n");
  426. printf (" %s\n", "-d, --driver=STRING");
  427. printf (" %s\n", _("DBI driver to use"));
  428. printf (" %s\n", "-o, --option=STRING");
  429. printf (" %s\n", _("DBI driver options"));
  430. printf (" %s\n", "-q, --query=STRING");
  431. printf (" %s\n", _("query to execute"));
  432. printf ("\n");
  433. printf (UT_WARN_CRIT_RANGE);
  434. printf (" %s\n", "-e, --expect=STRING");
  435. printf (" %s\n", _("String to expect as query result"));
  436. printf (" %s\n", _("Do not mix with -w, -c, -r, or -R!"));
  437. printf (" %s\n", "-r, --regex=REGEX");
  438. printf (" %s\n", _("Extended POSIX regular expression to check query result against"));
  439. printf (" %s\n", _("Do not mix with -w, -c, -e, or -R!"));
  440. printf (" %s\n", "-R, --regexi=REGEX");
  441. printf (" %s\n", _("Case-insensitive extended POSIX regex to check query result against"));
  442. printf (" %s\n", _("Do not mix with -w, -c, -e, or -r!"));
  443. printf (" %s\n", "-m, --metric=METRIC");
  444. printf (" %s\n", _("Metric to check thresholds against. Available metrics:"));
  445. printf (" CONN_TIME - %s\n", _("time used for setting up the database connection"));
  446. printf (" QUERY_RESULT - %s\n", _("result (first column of first row) of the query"));
  447. printf (" QUERY_TIME - %s\n", _("time used to execute the query"));
  448. printf (" %s\n", _("(ignore the query result)"));
  449. printf ("\n");
  450. printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  451. printf (UT_VERBOSE);
  452. printf ("\n");
  453. printf (" %s\n", _("A DBI driver (-d option) is required. If the specified metric operates"));
  454. printf (" %s\n\n", _("on a query, one has to be specified (-q option)."));
  455. printf (" %s\n", _("This plugin connects to an (SQL) database using libdbi and, optionally,"));
  456. printf (" %s\n", _("executes the specified query. The first column of the first row of the"));
  457. printf (" %s\n", _("result will be parsed and, in QUERY_RESULT mode, compared with the"));
  458. printf (" %s\n", _("warning and critical ranges. The result from the query has to be numeric"));
  459. printf (" %s\n\n", _("(strings representing numbers are fine)."));
  460. printf (" %s\n", _("The number and type of required DBI driver options depends on the actual"));
  461. printf (" %s\n", _("driver. See its documentation at http://libdbi-drivers.sourceforge.net/"));
  462. printf (" %s\n\n", _("for details."));
  463. printf (" %s\n", _("Examples:"));
  464. printf (" check_dbi -d pgsql -o username=postgres -m QUERY_RESULT \\\n");
  465. printf (" -q 'SELECT COUNT(*) FROM pg_stat_activity' -w 5 -c 10\n");
  466. printf (" Warning if more than five connections; critical if more than ten.\n\n");
  467. printf (" check_dbi -d mysql -H localhost -o username=user -o password=secret \\\n");
  468. printf (" -q 'SELECT COUNT(*) FROM logged_in_users -w 5:20 -c 0:50\n");
  469. printf (" Warning if less than 5 or more than 20 users are logged in; critical\n");
  470. printf (" if more than 50 users.\n\n");
  471. printf (" check_dbi -d firebird -o username=user -o password=secret -o dbname=foo \\\n");
  472. printf (" -m CONN_TIME -w 0.5 -c 2\n");
  473. printf (" Warning if connecting to the database takes more than half of a second;\n");
  474. printf (" critical if it takes more than 2 seconds.\n");
  475. printf (UT_SUPPORT);
  476. }
  477. void
  478. print_usage (void)
  479. {
  480. printf ("%s\n", _("Usage:"));
  481. printf ("%s -d <DBI driver> [-o <DBI driver option> [...]] [-q <query>]\n", progname);
  482. printf (" [-H <host>] [-c <critical range>] [-w <warning range>] [-m <metric>]\n");
  483. printf (" [-e <string>] [-r|-R <regex>]\n");
  484. }
  485. #define CHECK_IGNORE_ERROR(s) \
  486. do { \
  487. if (metric != METRIC_QUERY_RESULT) \
  488. return (s); \
  489. } while (0)
  490. const char *
  491. get_field_str (dbi_conn conn, dbi_result res, unsigned short field_type)
  492. {
  493. const char *str;
  494. if (field_type != DBI_TYPE_STRING) {
  495. printf ("CRITICAL - result value is not a string\n");
  496. return NULL;
  497. }
  498. str = dbi_result_get_string_idx (res, 1);
  499. if ((! str) || (strcmp (str, "ERROR") == 0)) {
  500. CHECK_IGNORE_ERROR (NULL);
  501. np_dbi_print_error (conn, "CRITICAL - failed to fetch string value");
  502. return NULL;
  503. }
  504. if ((verbose && (type == TYPE_STRING)) || (verbose > 2))
  505. printf ("Query returned string '%s'\n", str);
  506. return str;
  507. }
  508. double
  509. get_field (dbi_conn conn, dbi_result res, unsigned short *field_type)
  510. {
  511. double val = NAN;
  512. if (*field_type == DBI_TYPE_INTEGER) {
  513. val = (double)dbi_result_get_longlong_idx (res, 1);
  514. }
  515. else if (*field_type == DBI_TYPE_DECIMAL) {
  516. val = dbi_result_get_double_idx (res, 1);
  517. }
  518. else if (*field_type == DBI_TYPE_STRING) {
  519. const char *val_str;
  520. char *endptr = NULL;
  521. val_str = get_field_str (conn, res, *field_type);
  522. if (! val_str) {
  523. CHECK_IGNORE_ERROR (NAN);
  524. *field_type = DBI_TYPE_ERROR;
  525. return NAN;
  526. }
  527. val = strtod (val_str, &endptr);
  528. if (endptr == val_str) {
  529. CHECK_IGNORE_ERROR (NAN);
  530. printf ("CRITICAL - result value is not a numeric: %s\n", val_str);
  531. *field_type = DBI_TYPE_ERROR;
  532. return NAN;
  533. }
  534. else if ((endptr != NULL) && (*endptr != '\0')) {
  535. if (verbose)
  536. printf ("Garbage after value: %s\n", endptr);
  537. }
  538. }
  539. else {
  540. CHECK_IGNORE_ERROR (NAN);
  541. printf ("CRITICAL - cannot parse value of type %s (%i)\n",
  542. (*field_type == DBI_TYPE_BINARY)
  543. ? "BINARY"
  544. : (*field_type == DBI_TYPE_DATETIME)
  545. ? "DATETIME"
  546. : "<unknown>",
  547. *field_type);
  548. *field_type = DBI_TYPE_ERROR;
  549. return NAN;
  550. }
  551. return val;
  552. }
  553. double
  554. get_query_result (dbi_conn conn, dbi_result res, const char **res_val_str, double *res_val)
  555. {
  556. unsigned short field_type;
  557. double val = NAN;
  558. if (dbi_result_get_numrows (res) == DBI_ROW_ERROR) {
  559. CHECK_IGNORE_ERROR (STATE_OK);
  560. np_dbi_print_error (conn, "CRITICAL - failed to fetch rows");
  561. return STATE_CRITICAL;
  562. }
  563. if (dbi_result_get_numrows (res) < 1) {
  564. CHECK_IGNORE_ERROR (STATE_OK);
  565. printf ("WARNING - no rows returned\n");
  566. return STATE_WARNING;
  567. }
  568. if (dbi_result_get_numfields (res) == DBI_FIELD_ERROR) {
  569. CHECK_IGNORE_ERROR (STATE_OK);
  570. np_dbi_print_error (conn, "CRITICAL - failed to fetch fields");
  571. return STATE_CRITICAL;
  572. }
  573. if (dbi_result_get_numfields (res) < 1) {
  574. CHECK_IGNORE_ERROR (STATE_OK);
  575. printf ("WARNING - no fields returned\n");
  576. return STATE_WARNING;
  577. }
  578. if (dbi_result_first_row (res) != 1) {
  579. CHECK_IGNORE_ERROR (STATE_OK);
  580. np_dbi_print_error (conn, "CRITICAL - failed to fetch first row");
  581. return STATE_CRITICAL;
  582. }
  583. field_type = dbi_result_get_field_type_idx (res, 1);
  584. if (field_type != DBI_TYPE_ERROR) {
  585. if (type == TYPE_STRING)
  586. /* the value will be freed in dbi_result_free */
  587. *res_val_str = strdup (get_field_str (conn, res, field_type));
  588. else
  589. val = get_field (conn, res, &field_type);
  590. }
  591. *res_val = val;
  592. if (field_type == DBI_TYPE_ERROR) {
  593. CHECK_IGNORE_ERROR (STATE_OK);
  594. np_dbi_print_error (conn, "CRITICAL - failed to fetch data");
  595. return STATE_CRITICAL;
  596. }
  597. dbi_result_free (res);
  598. return STATE_OK;
  599. }
  600. #undef CHECK_IGNORE_ERROR
  601. int
  602. do_query (dbi_conn conn, const char **res_val_str, double *res_val, double *res_time)
  603. {
  604. dbi_result res;
  605. struct timeval timeval_start, timeval_end;
  606. int status = STATE_OK;
  607. assert (np_dbi_query);
  608. if (verbose)
  609. printf ("Executing query '%s'\n", np_dbi_query);
  610. gettimeofday (&timeval_start, NULL);
  611. res = dbi_conn_query (conn, np_dbi_query);
  612. if (! res) {
  613. np_dbi_print_error (conn, "CRITICAL - failed to execute query '%s'", np_dbi_query);
  614. return STATE_CRITICAL;
  615. }
  616. status = get_query_result (conn, res, res_val_str, res_val);
  617. gettimeofday (&timeval_end, NULL);
  618. *res_time = timediff (timeval_start, timeval_end);
  619. if (verbose)
  620. printf ("Time elapsed: %f\n", *res_time);
  621. return status;
  622. }
  623. double
  624. timediff (struct timeval start, struct timeval end)
  625. {
  626. double diff;
  627. while (start.tv_usec > end.tv_usec) {
  628. --end.tv_sec;
  629. end.tv_usec += 1000000;
  630. }
  631. diff = (double)(end.tv_sec - start.tv_sec)
  632. + (double)(end.tv_usec - start.tv_usec) / 1000000.0;
  633. return diff;
  634. }
  635. void
  636. np_dbi_print_error (dbi_conn conn, char *fmt, ...)
  637. {
  638. const char *errmsg = NULL;
  639. va_list ap;
  640. va_start (ap, fmt);
  641. dbi_conn_error (conn, &errmsg);
  642. vprintf (fmt, ap);
  643. printf (": %s\n", errmsg);
  644. va_end (ap);
  645. }