root/src/modules/mysql.c

Revision b38124b904a4200406f84ce8bb362ff0b79b7426, 11.8 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 5 years ago)

this should implement sslmode=require, refs #267

  • 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   ci->timed_out = 0; \
190   ci->error = strdup(str); \
191   return 0; \
192 } while(0)
193
194 static char *
195 __noit__strndup(const char *src, int len) {
196   int slen;
197   char *dst;
198   for(slen = 0; slen < len; slen++)
199     if(src[slen] == '\0') break;
200   dst = malloc(slen + 1);
201   memcpy(dst, src, slen);
202   dst[slen] = '\0';
203   return dst;
204 }
205
206 void mysql_parse_dsn(const char *dsn, noit_hash_table *h) {
207   const char *a=dsn, *b=NULL, *c=NULL;
208   while (a && (NULL != (b = strchr(a, '=')))) {
209     char *key, *val=NULL;
210     key = __noit__strndup(a, b-a);
211     b++;
212     if (b) {
213       if (NULL != (c = strchr(b, ' '))) {
214         val = __noit__strndup(b, c-b);
215       } else {
216         val = strdup(b);
217       }
218     }
219     noit_hash_replace(h, key, key?strlen(key):0, val, free, free);
220     a = c;
221     if (a) a++;
222   }
223 }
224
225 static int mysql_drive_session(eventer_t e, int mask, void *closure,
226                                   struct timeval *now) {
227   const char *dsn, *sql;
228   char sql_buff[8192];
229   char dsn_buff[512];
230   mysql_check_info_t *ci = closure;
231   noit_check_t *check = ci->check;
232   struct timeval t1, t2, diff;
233   noit_hash_table dsn_h = NOIT_HASH_EMPTY;
234   const char *host=NULL;
235   const char *user=NULL;
236   const char *password=NULL;
237   const char *dbname=NULL;
238   const char *port_s=NULL;
239   const char *socket=NULL;
240   const char *sslmode=NULL;
241   u_int32_t port;
242   unsigned long client_flag = CLIENT_IGNORE_SIGPIPE;
243   unsigned int timeout;
244
245   if(mask & (EVENTER_READ | EVENTER_WRITE)) {
246     /* this case is impossible from the eventer.  It is called as
247      * such on the synchronous completion of the event.
248      */
249     mysql_log_results(ci->self, ci->check);
250     mysql_cleanup(ci->self, ci->check);
251     check->flags &= ~NP_RUNNING;
252     return 0;
253   }
254   switch(mask) {
255     case EVENTER_ASYNCH_WORK:
256       noit_check_stats_clear(&ci->current);
257       ci->connect_duration = NULL;
258       ci->query_duration = NULL;
259
260       FETCH_CONFIG_OR(dsn, "");
261       noit_check_interpolate(dsn_buff, sizeof(dsn_buff), dsn,
262                              &ci->attrs, check->config);
263
264       mysql_parse_dsn(dsn_buff, &dsn_h);
265       noit_hash_retrieve(&dsn_h, "host", strlen("host"), (void**)&host);
266       noit_hash_retrieve(&dsn_h, "user", strlen("user"), (void**)&user);
267       noit_hash_retrieve(&dsn_h, "password", strlen("password"), (void**)&password);
268       noit_hash_retrieve(&dsn_h, "dbname", strlen("dbname"), (void**)&dbname);
269       noit_hash_retrieve(&dsn_h, "port", strlen("port"), (void**)&port_s);
270       if(noit_hash_retrieve(&dsn_h, "sslmode", strlen("sslmode"), (void**)&sslmode) &&
271          !strcmp(sslmode, "require"))
272         client_flag |= CLIENT_SSL;
273       port = port_s ? strtol(port_s, NULL, 10) : 3306;
274       noit_hash_retrieve(&dsn_h, "socket", strlen("socket"), (void**)&socket);
275
276       ci->conn = mysql_init(NULL); /* allocate us a handle */
277       if(!ci->conn) AVAIL_BAIL("mysql_init failed");
278       timeout = check->timeout / 1000;
279       mysql_options(ci->conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
280       if(!mysql_real_connect(ci->conn, host, user, password,
281                              dbname, port, socket, client_flag)) {
282         noitL(noit_stderr, "error during mysql_real_connect: %s\n",
283           mysql_error(ci->conn));
284         AVAIL_BAIL(mysql_error(ci->conn));
285       }
286       if(mysql_ping(ci->conn))
287         AVAIL_BAIL(mysql_error(ci->conn));
288
289       gettimeofday(&t1, NULL);
290       sub_timeval(t1, check->last_fire_time, &diff);
291       ci->connect_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
292       ci->connect_duration = &ci->connect_duration_d;
293
294       FETCH_CONFIG_OR(sql, "");
295       noit_check_interpolate(sql_buff, sizeof(sql_buff), sql,
296                              &ci->attrs, check->config);
297       if (mysql_query(ci->conn, sql_buff))
298         AVAIL_BAIL(mysql_error(ci->conn));
299
300       gettimeofday(&t2, NULL);
301       sub_timeval(t2, t1, &diff);
302       ci->query_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
303       ci->query_duration = &ci->query_duration_d;
304
305       ci->result = mysql_store_result(ci->conn);
306       if(!ci->result) AVAIL_BAIL("mysql_store_result failed");
307       ci->rv = mysql_num_rows(ci->result);
308       mysql_ingest_stats(ci);
309       ci->timed_out = 0;
310       return 0;
311       break;
312     case EVENTER_ASYNCH_CLEANUP:
313       /* This sets us up for a completion call. */
314       e->mask = EVENTER_READ | EVENTER_WRITE;
315       break;
316     default:
317       abort();
318   }
319   return 0;
320 }
321
322 static int mysql_initiate(noit_module_t *self, noit_check_t *check) {
323   mysql_check_info_t *ci = check->closure;
324   struct timeval __now;
325
326   /* We cannot be running */
327   assert(!(check->flags & NP_RUNNING));
328   check->flags |= NP_RUNNING;
329
330   ci->self = self;
331   ci->check = check;
332
333   ci->timed_out = 1;
334   ci->rv = -1;
335   noit_check_make_attrs(check, &ci->attrs);
336   gettimeofday(&__now, NULL);
337   memcpy(&check->last_fire_time, &__now, sizeof(__now));
338
339   /* Register a handler for the worker */
340   noit_check_run_full_asynch(check, mysql_drive_session);
341   return 0;
342 }
343
344 static int mysql_initiate_check(noit_module_t *self, noit_check_t *check,
345                                    int once, noit_check_t *parent) {
346   if(!check->closure) check->closure = calloc(1, sizeof(mysql_check_info_t));
347   INITIATE_CHECK(mysql_initiate, self, check);
348   return 0;
349 }
350
351 static int mysql_onload(noit_image_t *self) {
352   nlerr = noit_log_stream_find("error/mysql");
353   nldeb = noit_log_stream_find("debug/mysql");
354   if(!nlerr) nlerr = noit_stderr;
355   if(!nldeb) nldeb = noit_debug;
356
357   eventer_name_callback("mysql/mysql_drive_session", mysql_drive_session);
358   return 0;
359 }
360
361 #include "mysql.xmlh"
362 noit_module_t mysql = {
363   {
364     NOIT_MODULE_MAGIC,
365     NOIT_MODULE_ABI_VERSION,
366     "mysql",
367     "MySQL Checker",
368     mysql_xml_description,
369     mysql_onload
370   },
371   NULL,
372   NULL,
373   mysql_initiate_check,
374   mysql_cleanup
375 };
376
Note: See TracBrowser for help on using the browser.