root/src/modules/mysql.c

Revision 70c30ef22f6d1312375e0392164d755db5824cb5, 13.2 kB (checked in by Phil Maddox <philip.maddox@circonus.com>, 1 week ago)

Use mtevAssert and mtevFatal Instead Of assert() and abort()

Use libmtev calls to safely flush logs and abort rather than calling
the assert and abort calls directly.

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  * Copyright (c) 2015, Circonus, Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  *     * Redistributions of source code must retain the above copyright
11  *       notice, this list of conditions and the following disclaimer.
12  *     * Redistributions in binary form must reproduce the above
13  *       copyright notice, this list of conditions and the following
14  *       disclaimer in the documentation and/or other materials provided
15  *       with the distribution.
16  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
17  *       of its contributors may be used to endorse or promote products
18  *       derived from this software without specific prior written
19  *       permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <mtev_defines.h>
35
36 #include <stdio.h>
37 #include <unistd.h>
38 #include <errno.h>
39 #include <math.h>
40
41 #include <mtev_hash.h>
42
43 #include "noit_config.h"
44 #include "noit_module.h"
45 #include "noit_check.h"
46 #include "noit_check_tools.h"
47 #include "noit_mtev_bridge.h"
48
49 #ifdef HAVE_MYSQL_H
50 #include <mysql.h>
51 #else
52 #ifdef HAVE_MYSQL_MYSQL_H
53 #include <mysql/mysql.h>
54 #else
55 #error No mysql.h header present.  This is not going to work at all.
56 #endif
57 #endif
58
59 typedef struct {
60   noit_module_t *self;
61   noit_check_t *check;
62   MYSQL *conn;
63   MYSQL_RES *result;
64   double connect_duration_d;
65   double *connect_duration;
66   double query_duration_d;
67   double *query_duration;
68   int rv;
69   mtev_hash_table attrs;
70   int timed_out;
71   char *error;
72 } mysql_check_info_t;
73
74 static mtev_log_stream_t nlerr = NULL;
75 static mtev_log_stream_t nldeb = NULL;
76
77 static void mysql_cleanup(noit_module_t *self, noit_check_t *check) {
78   mysql_check_info_t *ci = check->closure;
79   if(ci) {
80     if(ci->result) mysql_free_result(ci->result);
81     if(ci->conn) mysql_close(ci->conn);
82     noit_check_release_attrs(&ci->attrs);
83     if(ci->error) free(ci->error);
84     memset(ci, 0, sizeof(*ci));
85   }
86 }
87 static void mysql_ingest_stats(mysql_check_info_t *ci) {
88   if(ci->rv > 0) {
89     /* metrics */
90     int nrows, ncols, i, j;
91     nrows = ci->rv;
92     ncols = mysql_num_fields(ci->result);
93     MYSQL_FIELD *cdesc = mysql_fetch_fields(ci->result);
94     for (i=0; i<nrows; i++) {
95       mtevL(nldeb, "mysql: row %d [%d cols]:\n", i, ncols);
96       if(ncols<2) continue;
97       MYSQL_ROW row = mysql_fetch_row(ci->result);
98       if(NULL == row[0]) continue;
99       for (j=1; j<ncols; j++) {
100         enum enum_field_types coltype;
101         int iv, *piv;
102         int64_t lv, *plv;
103         double dv, *pdv;
104         char *sv;
105         char mname[128];
106  
107         snprintf(mname, sizeof(mname), "%s`%s", row[0], cdesc[j].name);
108         coltype = cdesc[j].type;
109         mtevL(nldeb, "mysql:   col %d (%s) type %d:\n", j, mname, coltype);
110         switch(coltype) {
111           case FIELD_TYPE_TINY:
112           case FIELD_TYPE_SHORT:
113           case FIELD_TYPE_LONG:
114             if(!row[j]) piv = NULL;
115             else {
116               iv = strtol(row[j], NULL, 10);
117               piv = &iv;
118             }
119             noit_stats_set_metric(ci->check, mname, METRIC_INT32, piv);
120             break;
121           case FIELD_TYPE_INT24:
122           case FIELD_TYPE_LONGLONG:
123             if(!row[j]) plv = NULL;
124             else {
125               lv = strtoll(row[j], NULL, 10);
126               plv = &lv;
127             }
128             noit_stats_set_metric(ci->check, mname, METRIC_INT64, plv);
129             break;
130           case FIELD_TYPE_DECIMAL:
131           case FIELD_TYPE_FLOAT:
132           case FIELD_TYPE_DOUBLE:
133             if(!row[j]) pdv = NULL;
134             else {
135               dv = atof(row[j]);
136               pdv = &dv;
137             }
138             noit_stats_set_metric(ci->check, mname, METRIC_DOUBLE, pdv);
139             break;
140           default:
141             if(!row[j]) sv = NULL;
142             else sv = row[j];
143             noit_stats_set_metric(ci->check, mname, METRIC_GUESS, sv);
144             break;
145         }
146       }
147     }
148   }
149 }
150 static void mysql_log_results(noit_module_t *self, noit_check_t *check) {
151   struct timeval duration, now;
152   mysql_check_info_t *ci = check->closure;
153
154   gettimeofday(&now, NULL);
155   sub_timeval(now, check->last_fire_time, &duration);
156   noit_stats_set_whence(check, &now);
157   noit_stats_set_duration(check, duration.tv_sec * 1000 + duration.tv_usec / 1000);
158   noit_stats_set_available(check, NP_UNAVAILABLE);
159   noit_stats_set_state(check, NP_BAD);
160   if(ci->error) noit_stats_set_status(check, ci->error);
161   else if(ci->timed_out) noit_stats_set_status(check, "timeout");
162   else if(ci->rv == 0) {
163     noit_stats_set_available(check, NP_AVAILABLE);
164     noit_stats_set_state(check, NP_GOOD);
165     noit_stats_set_status(check, "no rows, ok");
166   }
167   else {
168     noit_stats_set_available(check, NP_AVAILABLE);
169     noit_stats_set_state(check, NP_GOOD);
170     noit_stats_set_status(check, "got rows, ok");
171   }
172
173   if(ci->rv >= 0)
174     noit_stats_set_metric(check, "row_count", METRIC_INT32, &ci->rv);
175   if(ci->connect_duration)
176     noit_stats_set_metric(check, "connect_duration", METRIC_DOUBLE,
177                           ci->connect_duration);
178   if(ci->query_duration)
179     noit_stats_set_metric(check, "query_duration", METRIC_DOUBLE,
180                           ci->query_duration);
181
182   noit_check_set_stats(check);
183 }
184
185 #define FETCH_CONFIG_OR(key, str) do { \
186   if(!mtev_hash_retrieve(check->config, #key, strlen(#key), (void **)&key)) \
187     key = str; \
188 } while(0)
189
190 #define AVAIL_BAIL(str) do { \
191   MYSQL *conn_swap = ci->conn; \
192   MYSQL_RES *result_swap = ci->result; \
193   if(ci->result) { \
194     ci->result = NULL; \
195     mysql_free_result(result_swap); \
196   } \
197   if(ci->conn) { \
198     ci->conn = NULL; \
199     mysql_close(conn_swap); \
200   } \
201   ci->timed_out = 0; \
202   ci->error = strdup(str); \
203   mtev_hash_destroy(&dsn_h, free, free); \
204   return 0; \
205 } while(0)
206
207 static char *
208 __noit__strndup(const char *src, int len) {
209   int slen;
210   char *dst;
211   for(slen = 0; slen < len; slen++)
212     if(src[slen] == '\0') break;
213   dst = malloc(slen + 1);
214   memcpy(dst, src, slen);
215   dst[slen] = '\0';
216   return dst;
217 }
218
219 void mysql_parse_dsn(const char *dsn, mtev_hash_table *h) {
220   const char *a=dsn, *b=NULL, *c=NULL;
221   while (a && (NULL != (b = strchr(a, '=')))) {
222     char *key, *val=NULL;
223     key = __noit__strndup(a, b-a);
224     b++;
225     if (b) {
226       if (NULL != (c = strchr(b, ' '))) {
227         val = __noit__strndup(b, c-b);
228       } else {
229         val = strdup(b);
230       }
231     }
232     mtev_hash_replace(h, key, key?strlen(key):0, val, free, free);
233     a = c;
234     if (a) a++;
235   }
236 }
237
238 static int mysql_drive_session(eventer_t e, int mask, void *closure,
239                                   struct timeval *now) {
240   const char *dsn, *sql;
241   char sql_buff[8192];
242   char dsn_buff[512];
243   mysql_check_info_t *ci = closure;
244   noit_check_t *check = ci->check;
245   struct timeval t1, t2, diff;
246   mtev_hash_table dsn_h = MTEV_HASH_EMPTY;
247   const char *host=NULL;
248   const char *user=NULL;
249   const char *password=NULL;
250   const char *dbname=NULL;
251   const char *port_s=NULL;
252   const char *socket=NULL;
253   const char *sslmode=NULL;
254   u_int32_t port;
255   unsigned long client_flag = CLIENT_IGNORE_SIGPIPE;
256   unsigned int timeout;
257
258   if(mask & (EVENTER_READ | EVENTER_WRITE)) {
259     /* this case is impossible from the eventer.  It is called as
260      * such on the synchronous completion of the event.
261      */
262     mysql_log_results(ci->self, ci->check);
263     mysql_cleanup(ci->self, ci->check);
264     check->flags &= ~NP_RUNNING;
265     return 0;
266   }
267   switch(mask) {
268     case EVENTER_ASYNCH_WORK:
269       ci->connect_duration = NULL;
270       ci->query_duration = NULL;
271
272       FETCH_CONFIG_OR(dsn, "");
273       noit_check_interpolate(dsn_buff, sizeof(dsn_buff), dsn,
274                              &ci->attrs, check->config);
275
276       mysql_parse_dsn(dsn_buff, &dsn_h);
277       mtev_hash_retrieve(&dsn_h, "host", strlen("host"), (void**)&host);
278       mtev_hash_retrieve(&dsn_h, "user", strlen("user"), (void**)&user);
279       mtev_hash_retrieve(&dsn_h, "password", strlen("password"), (void**)&password);
280       mtev_hash_retrieve(&dsn_h, "dbname", strlen("dbname"), (void**)&dbname);
281       mtev_hash_retrieve(&dsn_h, "port", strlen("port"), (void**)&port_s);
282       if(mtev_hash_retrieve(&dsn_h, "sslmode", strlen("sslmode"), (void**)&sslmode) &&
283          !strcmp(sslmode, "require"))
284         client_flag |= CLIENT_SSL;
285       port = port_s ? strtol(port_s, NULL, 10) : 3306;
286       mtev_hash_retrieve(&dsn_h, "socket", strlen("socket"), (void**)&socket);
287
288       ci->conn = mysql_init(NULL); /* allocate us a handle */
289       if(!ci->conn) AVAIL_BAIL("mysql_init failed");
290       timeout = check->timeout / 1000;
291       mysql_options(ci->conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
292       if(!mysql_real_connect(ci->conn, host, user, password,
293                              dbname, port, socket, client_flag)) {
294         mtevL(noit_stderr, "error during mysql_real_connect: %s\n",
295           mysql_error(ci->conn));
296         AVAIL_BAIL(mysql_error(ci->conn));
297       }
298       if(mysql_ping(ci->conn))
299         AVAIL_BAIL(mysql_error(ci->conn));
300
301 #if MYSQL_VERSION_ID >= 50000
302       if (sslmode && !strcmp(sslmode, "require")) {
303         /* mysql has a bad habit of silently failing to establish ssl and
304          * falling back to unencrypted, so after making the connection, let's
305          * check that we're actually using SSL by checking for a non-NULL
306          * return value from mysql_get_ssl_cipher().
307          */
308         if (mysql_get_ssl_cipher(ci->conn) == NULL) {
309           mtevL(nldeb, "mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
310           AVAIL_BAIL("mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
311         }
312       }
313 #endif
314
315       gettimeofday(&t1, NULL);
316       sub_timeval(t1, check->last_fire_time, &diff);
317       ci->connect_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
318       ci->connect_duration = &ci->connect_duration_d;
319
320       FETCH_CONFIG_OR(sql, "");
321       noit_check_interpolate(sql_buff, sizeof(sql_buff), sql,
322                              &ci->attrs, check->config);
323       if (mysql_query(ci->conn, sql_buff))
324         AVAIL_BAIL(mysql_error(ci->conn));
325
326       gettimeofday(&t2, NULL);
327       sub_timeval(t2, t1, &diff);
328       ci->query_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
329       ci->query_duration = &ci->query_duration_d;
330
331       ci->result = mysql_store_result(ci->conn);
332       if(!ci->result) AVAIL_BAIL("mysql_store_result failed");
333       ci->rv = mysql_num_rows(ci->result);
334       mysql_ingest_stats(ci);
335       if(ci->result) {
336         MYSQL_RES *result_swap = ci->result;
337         ci->result = NULL;
338         mysql_free_result(result_swap);
339       }
340       if(ci->conn) {
341         MYSQL *conn_swap = ci->conn;
342         ci->conn = NULL;
343         mysql_close(conn_swap);
344       }
345       ci->timed_out = 0;
346       mtev_hash_destroy(&dsn_h, free, free);
347       return 0;
348       break;
349     case EVENTER_ASYNCH_CLEANUP:
350       /* This sets us up for a completion call. */
351       e->mask = EVENTER_READ | EVENTER_WRITE;
352       break;
353     default:
354       mtevFatal(mtev_error, "Unknown mask: 0x%04x\n", mask);
355   }
356   return 0;
357 }
358
359 static int mysql_initiate(noit_module_t *self, noit_check_t *check,
360                           noit_check_t *cause) {
361   mysql_check_info_t *ci = check->closure;
362   struct timeval __now;
363
364   /* We cannot be running */
365   BAIL_ON_RUNNING_CHECK(check);
366   check->flags |= NP_RUNNING;
367
368   ci->self = self;
369   ci->check = check;
370
371   ci->timed_out = 1;
372   ci->rv = -1;
373   noit_check_make_attrs(check, &ci->attrs);
374   gettimeofday(&__now, NULL);
375   memcpy(&check->last_fire_time, &__now, sizeof(__now));
376
377   /* Register a handler for the worker */
378   noit_check_run_full_asynch(check, mysql_drive_session);
379   return 0;
380 }
381
382 static int mysql_initiate_check(noit_module_t *self, noit_check_t *check,
383                                    int once, noit_check_t *cause) {
384   if(!check->closure) check->closure = calloc(1, sizeof(mysql_check_info_t));
385   INITIATE_CHECK(mysql_initiate, self, check, cause);
386   return 0;
387 }
388
389 static int mysql_onload(mtev_image_t *self) {
390   nlerr = mtev_log_stream_find("error/mysql");
391   nldeb = mtev_log_stream_find("debug/mysql");
392   if(!nlerr) nlerr = noit_stderr;
393   if(!nldeb) nldeb = noit_debug;
394
395   eventer_name_callback("mysql/mysql_drive_session", mysql_drive_session);
396   return 0;
397 }
398
399 #include "mysql.xmlh"
400 noit_module_t mysql = {
401   {
402     .magic = NOIT_MODULE_MAGIC,
403     .version = NOIT_MODULE_ABI_VERSION,
404     .name = "mysql",
405     .description = "MySQL Checker",
406     .xml_description = mysql_xml_description,
407     .onload = mysql_onload
408   },
409   NULL,
410   NULL,
411   mysql_initiate_check,
412   mysql_cleanup
413 };
414
Note: See TracBrowser for help on using the browser.