root/src/modules/mysql.c

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

Move Check Hash Inits To noit_check_make_attrs()

Rather than initializing a hash table for attrs, then passing it to
noit_check_make_attrs, just init inside noit_check_make_attrs itself.

  • 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;
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   mtev_hash_init(&dsn_h);
259
260   if(mask & (EVENTER_READ | EVENTER_WRITE)) {
261     /* this case is impossible from the eventer.  It is called as
262      * such on the synchronous completion of the event.
263      */
264     mysql_log_results(ci->self, ci->check);
265     mysql_cleanup(ci->self, ci->check);
266     check->flags &= ~NP_RUNNING;
267     return 0;
268   }
269   switch(mask) {
270     case EVENTER_ASYNCH_WORK:
271       ci->connect_duration = NULL;
272       ci->query_duration = NULL;
273
274       FETCH_CONFIG_OR(dsn, "");
275       noit_check_interpolate(dsn_buff, sizeof(dsn_buff), dsn,
276                              &ci->attrs, check->config);
277
278       mysql_parse_dsn(dsn_buff, &dsn_h);
279       mtev_hash_retrieve(&dsn_h, "host", strlen("host"), (void**)&host);
280       mtev_hash_retrieve(&dsn_h, "user", strlen("user"), (void**)&user);
281       mtev_hash_retrieve(&dsn_h, "password", strlen("password"), (void**)&password);
282       mtev_hash_retrieve(&dsn_h, "dbname", strlen("dbname"), (void**)&dbname);
283       mtev_hash_retrieve(&dsn_h, "port", strlen("port"), (void**)&port_s);
284       if(mtev_hash_retrieve(&dsn_h, "sslmode", strlen("sslmode"), (void**)&sslmode) &&
285          !strcmp(sslmode, "require"))
286         client_flag |= CLIENT_SSL;
287       port = port_s ? strtol(port_s, NULL, 10) : 3306;
288       mtev_hash_retrieve(&dsn_h, "socket", strlen("socket"), (void**)&socket);
289
290       ci->conn = mysql_init(NULL); /* allocate us a handle */
291       if(!ci->conn) AVAIL_BAIL("mysql_init failed");
292       timeout = check->timeout / 1000;
293       mysql_options(ci->conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
294       if(!mysql_real_connect(ci->conn, host, user, password,
295                              dbname, port, socket, client_flag)) {
296         mtevL(noit_stderr, "error during mysql_real_connect: %s\n",
297           mysql_error(ci->conn));
298         AVAIL_BAIL(mysql_error(ci->conn));
299       }
300       if(mysql_ping(ci->conn))
301         AVAIL_BAIL(mysql_error(ci->conn));
302
303 #if MYSQL_VERSION_ID >= 50000
304       if (sslmode && !strcmp(sslmode, "require")) {
305         /* mysql has a bad habit of silently failing to establish ssl and
306          * falling back to unencrypted, so after making the connection, let's
307          * check that we're actually using SSL by checking for a non-NULL
308          * return value from mysql_get_ssl_cipher().
309          */
310         if (mysql_get_ssl_cipher(ci->conn) == NULL) {
311           mtevL(nldeb, "mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
312           AVAIL_BAIL("mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
313         }
314       }
315 #endif
316
317       gettimeofday(&t1, NULL);
318       sub_timeval(t1, check->last_fire_time, &diff);
319       ci->connect_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
320       ci->connect_duration = &ci->connect_duration_d;
321
322       FETCH_CONFIG_OR(sql, "");
323       noit_check_interpolate(sql_buff, sizeof(sql_buff), sql,
324                              &ci->attrs, check->config);
325       if (mysql_query(ci->conn, sql_buff))
326         AVAIL_BAIL(mysql_error(ci->conn));
327
328       gettimeofday(&t2, NULL);
329       sub_timeval(t2, t1, &diff);
330       ci->query_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
331       ci->query_duration = &ci->query_duration_d;
332
333       ci->result = mysql_store_result(ci->conn);
334       if(!ci->result) AVAIL_BAIL("mysql_store_result failed");
335       ci->rv = mysql_num_rows(ci->result);
336       mysql_ingest_stats(ci);
337       if(ci->result) {
338         MYSQL_RES *result_swap = ci->result;
339         ci->result = NULL;
340         mysql_free_result(result_swap);
341       }
342       if(ci->conn) {
343         MYSQL *conn_swap = ci->conn;
344         ci->conn = NULL;
345         mysql_close(conn_swap);
346       }
347       ci->timed_out = 0;
348       mtev_hash_destroy(&dsn_h, free, free);
349       return 0;
350       break;
351     case EVENTER_ASYNCH_CLEANUP:
352       /* This sets us up for a completion call. */
353       e->mask = EVENTER_READ | EVENTER_WRITE;
354       break;
355     default:
356       mtevFatal(mtev_error, "Unknown mask: 0x%04x\n", mask);
357   }
358   return 0;
359 }
360
361 static int mysql_initiate(noit_module_t *self, noit_check_t *check,
362                           noit_check_t *cause) {
363   mysql_check_info_t *ci = check->closure;
364   struct timeval __now;
365
366   /* We cannot be running */
367   BAIL_ON_RUNNING_CHECK(check);
368   check->flags |= NP_RUNNING;
369
370   ci->self = self;
371   ci->check = check;
372
373   ci->timed_out = 1;
374   ci->rv = -1;
375   noit_check_make_attrs(check, &ci->attrs);
376   gettimeofday(&__now, NULL);
377   memcpy(&check->last_fire_time, &__now, sizeof(__now));
378
379   /* Register a handler for the worker */
380   noit_check_run_full_asynch(check, mysql_drive_session);
381   return 0;
382 }
383
384 static int mysql_initiate_check(noit_module_t *self, noit_check_t *check,
385                                    int once, noit_check_t *cause) {
386   if(!check->closure) {
387     mysql_check_info_t *check_info = calloc(1, sizeof(mysql_check_info_t));
388     check->closure = (void*)check_info;
389   }
390   INITIATE_CHECK(mysql_initiate, self, check, cause);
391   return 0;
392 }
393
394 static int mysql_onload(mtev_image_t *self) {
395   nlerr = mtev_log_stream_find("error/mysql");
396   nldeb = mtev_log_stream_find("debug/mysql");
397   if(!nlerr) nlerr = noit_stderr;
398   if(!nldeb) nldeb = noit_debug;
399
400   eventer_name_callback("mysql/mysql_drive_session", mysql_drive_session);
401   return 0;
402 }
403
404 #include "mysql.xmlh"
405 noit_module_t mysql = {
406   {
407     .magic = NOIT_MODULE_MAGIC,
408     .version = NOIT_MODULE_ABI_VERSION,
409     .name = "mysql",
410     .description = "MySQL Checker",
411     .xml_description = mysql_xml_description,
412     .onload = mysql_onload
413   },
414   NULL,
415   NULL,
416   mysql_initiate_check,
417   mysql_cleanup
418 };
419
Note: See TracBrowser for help on using the browser.