root/src/modules/mysql.c

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

fixes #163

  • 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   MYSQL *conn;
61   MYSQL_RES *result;
62   int rv;
63   noit_hash_table attrs;
64   int timed_out;
65   char *error;
66 } mysql_check_info_t;
67
68 static noit_log_stream_t nlerr = NULL;
69 static noit_log_stream_t nldeb = NULL;
70
71 static void mysql_cleanup(noit_module_t *self, noit_check_t *check) {
72   mysql_check_info_t *ci = check->closure;
73   if(ci) {
74     if(ci->result) mysql_free_result(ci->result);
75     if(ci->conn) mysql_close(ci->conn);
76     noit_check_release_attrs(&ci->attrs);
77     if(ci->error) free(ci->error);
78     memset(ci, 0, sizeof(*ci));
79   }
80 }
81 static void mysql_log_results(noit_module_t *self, noit_check_t *check) {
82   stats_t current;
83   struct timeval duration;
84   mysql_check_info_t *ci = check->closure;
85
86   noit_check_stats_clear(&current);
87
88   gettimeofday(&current.whence, NULL);
89   sub_timeval(current.whence, check->last_fire_time, &duration);
90   current.duration = duration.tv_sec * 1000 + duration.tv_usec / 1000;
91   current.available = NP_UNAVAILABLE;
92   current.state = NP_BAD;
93   if(ci->error) current.status = ci->error;
94   else if(ci->timed_out) current.status = "timeout";
95   else if(ci->rv == 0) {
96     current.available = NP_AVAILABLE;
97     current.state = NP_GOOD;
98     current.status = "no rows, ok";
99   }
100   else {
101     current.available = NP_AVAILABLE;
102     current.state = NP_GOOD;
103     current.status = "got rows, ok";
104   }
105
106   if(ci->rv > 0) {
107     /* metrics */
108     int nrows, ncols, i, j;
109     nrows = ci->rv;
110     ncols = mysql_num_fields(ci->result);
111     MYSQL_FIELD *cdesc = mysql_fetch_fields(ci->result);
112     for (i=0; i<nrows; i++) {
113       noitL(nldeb, "mysql: row %d [%d cols]:\n", i, ncols);
114       if(ncols<2) continue;
115       MYSQL_ROW row = mysql_fetch_row(ci->result);
116       if(NULL == row[0]) continue;
117       for (j=1; j<ncols; j++) {
118         enum enum_field_types coltype;
119         int iv, *piv;
120         int64_t lv, *plv;
121         double dv, *pdv;
122         char *sv;
123         char mname[128];
124  
125         snprintf(mname, sizeof(mname), "%s`%s", row[0], cdesc[j].name);
126         coltype = cdesc[j].type;
127         noitL(nldeb, "mysql:   col %d (%s) type %d:\n", j, mname, coltype);
128         switch(coltype) {
129           case FIELD_TYPE_TINY:
130           case FIELD_TYPE_SHORT:
131           case FIELD_TYPE_LONG:
132             if(!row[j]) piv = NULL;
133             else {
134               iv = strtol(row[j], NULL, 10);
135               piv = &iv;
136             }
137             noit_stats_set_metric(&current, mname, METRIC_INT32, piv);
138             break;
139           case FIELD_TYPE_INT24:
140           case FIELD_TYPE_LONGLONG:
141             if(!row[j]) plv = NULL;
142             else {
143               lv = strtoll(row[j], NULL, 10);
144               plv = &lv;
145             }
146             noit_stats_set_metric(&current, mname, METRIC_INT64, plv);
147             break;
148           case FIELD_TYPE_DECIMAL:
149           case FIELD_TYPE_FLOAT:
150           case FIELD_TYPE_DOUBLE:
151             if(!row[j]) pdv = NULL;
152             else {
153               dv = atof(row[j]);
154               pdv = &dv;
155             }
156             noit_stats_set_metric(&current, mname, METRIC_DOUBLE, pdv);
157             break;
158           default:
159             if(!row[j]) sv = NULL;
160             else sv = row[j];
161             noit_stats_set_metric(&current, mname, METRIC_GUESS, sv);
162             break;
163         }
164       }
165     }
166   }
167   noit_check_set_stats(self, check, &current);
168 }
169
170 #define FETCH_CONFIG_OR(key, str) do { \
171   if(!noit_hash_retrieve(check->config, #key, strlen(#key), (void **)&key)) \
172     key = str; \
173 } while(0)
174
175 #define AVAIL_BAIL(str) do { \
176   ci->timed_out = 0; \
177   ci->error = strdup(str); \
178   return 0; \
179 } while(0)
180
181 static char *
182 __noit__strndup(const char *src, int len) {
183   int slen;
184   char *dst;
185   for(slen = 0; slen < len; slen++)
186     if(src[slen] == '\0') break;
187   dst = malloc(slen + 1);
188   memcpy(dst, src, slen);
189   dst[slen] = '\0';
190   return dst;
191 }
192
193 void mysql_parse_dsn(const char *dsn, noit_hash_table *h) {
194   const char *a=dsn, *b=NULL, *c=NULL;
195   while (a && (NULL != (b = strchr(a, '=')))) {
196     char *key, *val=NULL;
197     key = __noit__strndup(a, b-a);
198     b++;
199     if (b) {
200       if (NULL != (c = strchr(b, ' '))) {
201         val = __noit__strndup(b, c-b);
202       } else {
203         val = strdup(b);
204       }
205     }
206     noit_hash_replace(h, key, key?strlen(key):0, val, free, free);
207     a = c;
208     if (a) a++;
209   }
210 }
211
212 static int mysql_drive_session(eventer_t e, int mask, void *closure,
213                                   struct timeval *now) {
214   const char *dsn, *sql;
215   char sql_buff[8192];
216   char dsn_buff[512];
217   mysql_check_info_t *ci = closure;
218   noit_check_t *check = ci->check;
219   noit_hash_table dsn_h = NOIT_HASH_EMPTY;
220   const char *host=NULL;
221   const char *user=NULL;
222   const char *password=NULL;
223   const char *dbname=NULL;
224   const char *port_s=NULL;
225   const char *socket=NULL;
226   u_int32_t port;
227   unsigned int timeout;
228
229   if(mask & (EVENTER_READ | EVENTER_WRITE)) {
230     /* this case is impossible from the eventer.  It is called as
231      * such on the synchronous completion of the event.
232      */
233     mysql_log_results(ci->self, ci->check);
234     mysql_cleanup(ci->self, ci->check);
235     check->flags &= ~NP_RUNNING;
236     return 0;
237   }
238   switch(mask) {
239     case EVENTER_ASYNCH_WORK:
240       FETCH_CONFIG_OR(dsn, "");
241       noit_check_interpolate(dsn_buff, sizeof(dsn_buff), dsn,
242                              &ci->attrs, check->config);
243
244       mysql_parse_dsn(dsn_buff, &dsn_h);
245       noit_hash_retrieve(&dsn_h, "host", strlen("host"), (void**)&host);
246       noit_hash_retrieve(&dsn_h, "user", strlen("user"), (void**)&user);
247       noit_hash_retrieve(&dsn_h, "password", strlen("password"), (void**)&password);
248       noit_hash_retrieve(&dsn_h, "dbname", strlen("dbname"), (void**)&dbname);
249       noit_hash_retrieve(&dsn_h, "port", strlen("port"), (void**)&port_s);
250       port = port_s ? strtol(port_s, NULL, 10) : 3306;
251       noit_hash_retrieve(&dsn_h, "socket", strlen("socket"), (void**)&socket);
252
253       ci->conn = mysql_init(NULL); /* allocate us a handle */
254       if(!ci->conn) AVAIL_BAIL("mysql_init failed");
255       timeout = check->timeout / 1000;
256       mysql_options(ci->conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
257       if(!mysql_real_connect(ci->conn, host, user, password,
258                              dbname, port, socket, CLIENT_IGNORE_SIGPIPE)) {
259         noitL(noit_stderr, "error during mysql_real_connect: %s\n",
260           mysql_error(ci->conn));
261         AVAIL_BAIL(mysql_error(ci->conn));
262       }
263       if(mysql_ping(ci->conn))
264         AVAIL_BAIL(mysql_error(ci->conn));
265
266       FETCH_CONFIG_OR(sql, "");
267       noit_check_interpolate(sql_buff, sizeof(sql_buff), sql,
268                              &ci->attrs, check->config);
269       if (mysql_query(ci->conn, sql_buff))
270         AVAIL_BAIL(mysql_error(ci->conn));
271       ci->result = mysql_store_result(ci->conn);
272       if(!ci->result) AVAIL_BAIL("mysql_store_result failed");
273       ci->rv = mysql_num_rows(ci->result);
274       ci->timed_out = 0;
275       return 0;
276       break;
277     case EVENTER_ASYNCH_CLEANUP:
278       /* This sets us up for a completion call. */
279       e->mask = EVENTER_READ | EVENTER_WRITE;
280       break;
281     default:
282       abort();
283   }
284   return 0;
285 }
286
287 static int mysql_initiate(noit_module_t *self, noit_check_t *check) {
288   mysql_check_info_t *ci = check->closure;
289   struct timeval __now;
290
291   /* We cannot be running */
292   assert(!(check->flags & NP_RUNNING));
293   check->flags |= NP_RUNNING;
294
295   ci->self = self;
296   ci->check = check;
297
298   ci->timed_out = 1;
299   ci->rv = -1;
300   noit_check_make_attrs(check, &ci->attrs);
301   gettimeofday(&__now, NULL);
302   memcpy(&check->last_fire_time, &__now, sizeof(__now));
303
304   /* Register a handler for the worker */
305   noit_check_run_full_asynch(check, mysql_drive_session);
306   return 0;
307 }
308
309 static int mysql_initiate_check(noit_module_t *self, noit_check_t *check,
310                                    int once, noit_check_t *parent) {
311   if(!check->closure) check->closure = calloc(1, sizeof(mysql_check_info_t));
312   INITIATE_CHECK(mysql_initiate, self, check);
313   return 0;
314 }
315
316 static int mysql_onload(noit_image_t *self) {
317   nlerr = noit_log_stream_find("error/mysql");
318   nldeb = noit_log_stream_find("debug/mysql");
319   if(!nlerr) nlerr = noit_stderr;
320   if(!nldeb) nldeb = noit_debug;
321
322   eventer_name_callback("mysql/mysql_drive_session", mysql_drive_session);
323   return 0;
324 }
325
326 #include "mysql.xmlh"
327 noit_module_t mysql = {
328   {
329     NOIT_MODULE_MAGIC,
330     NOIT_MODULE_ABI_VERSION,
331     "mysql",
332     "MySQL Checker",
333     mysql_xml_description,
334     mysql_onload
335   },
336   NULL,
337   NULL,
338   mysql_initiate_check,
339   mysql_cleanup
340 };
341
Note: See TracBrowser for help on using the browser.