root/src/modules/mysql.c

Revision 8b4fa37022bbd7722fbaab59a19c7b7e21547ea5, 12.9 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 3 years ago)

missed this fix for causal prototype

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