root/src/modules/mysql.c

Revision 7b25fe3fe82c2f8e75d36eb6df7c9f19289ccb4c, 13.2 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 3 months ago)

fix mysql module to use new stasts API

  • 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 <assert.h>
40 #include <math.h>
41
42 #include <mtev_hash.h>
43
44 #include "noit_config.h"
45 #include "noit_module.h"
46 #include "noit_check.h"
47 #include "noit_check_tools.h"
48 #include "noit_mtev_bridge.h"
49
50 #ifdef HAVE_MYSQL_H
51 #include <mysql.h>
52 #else
53 #ifdef HAVE_MYSQL_MYSQL_H
54 #include <mysql/mysql.h>
55 #else
56 #error No mysql.h header present.  This is not going to work at all.
57 #endif
58 #endif
59
60 typedef struct {
61   noit_module_t *self;
62   noit_check_t *check;
63   MYSQL *conn;
64   MYSQL_RES *result;
65   double connect_duration_d;
66   double *connect_duration;
67   double query_duration_d;
68   double *query_duration;
69   int rv;
70   mtev_hash_table attrs;
71   int timed_out;
72   char *error;
73 } mysql_check_info_t;
74
75 static mtev_log_stream_t nlerr = NULL;
76 static mtev_log_stream_t nldeb = NULL;
77
78 static void mysql_cleanup(noit_module_t *self, noit_check_t *check) {
79   mysql_check_info_t *ci = check->closure;
80   if(ci) {
81     if(ci->result) mysql_free_result(ci->result);
82     if(ci->conn) mysql_close(ci->conn);
83     noit_check_release_attrs(&ci->attrs);
84     if(ci->error) free(ci->error);
85     memset(ci, 0, sizeof(*ci));
86   }
87 }
88 static void mysql_ingest_stats(mysql_check_info_t *ci) {
89   if(ci->rv > 0) {
90     /* metrics */
91     int nrows, ncols, i, j;
92     nrows = ci->rv;
93     ncols = mysql_num_fields(ci->result);
94     MYSQL_FIELD *cdesc = mysql_fetch_fields(ci->result);
95     for (i=0; i<nrows; i++) {
96       mtevL(nldeb, "mysql: row %d [%d cols]:\n", i, ncols);
97       if(ncols<2) continue;
98       MYSQL_ROW row = mysql_fetch_row(ci->result);
99       if(NULL == row[0]) continue;
100       for (j=1; j<ncols; j++) {
101         enum enum_field_types coltype;
102         int iv, *piv;
103         int64_t lv, *plv;
104         double dv, *pdv;
105         char *sv;
106         char mname[128];
107  
108         snprintf(mname, sizeof(mname), "%s`%s", row[0], cdesc[j].name);
109         coltype = cdesc[j].type;
110         mtevL(nldeb, "mysql:   col %d (%s) type %d:\n", j, mname, coltype);
111         switch(coltype) {
112           case FIELD_TYPE_TINY:
113           case FIELD_TYPE_SHORT:
114           case FIELD_TYPE_LONG:
115             if(!row[j]) piv = NULL;
116             else {
117               iv = strtol(row[j], NULL, 10);
118               piv = &iv;
119             }
120             noit_stats_set_metric(ci->check, mname, METRIC_INT32, piv);
121             break;
122           case FIELD_TYPE_INT24:
123           case FIELD_TYPE_LONGLONG:
124             if(!row[j]) plv = NULL;
125             else {
126               lv = strtoll(row[j], NULL, 10);
127               plv = &lv;
128             }
129             noit_stats_set_metric(ci->check, mname, METRIC_INT64, plv);
130             break;
131           case FIELD_TYPE_DECIMAL:
132           case FIELD_TYPE_FLOAT:
133           case FIELD_TYPE_DOUBLE:
134             if(!row[j]) pdv = NULL;
135             else {
136               dv = atof(row[j]);
137               pdv = &dv;
138             }
139             noit_stats_set_metric(ci->check, mname, METRIC_DOUBLE, pdv);
140             break;
141           default:
142             if(!row[j]) sv = NULL;
143             else sv = row[j];
144             noit_stats_set_metric(ci->check, mname, METRIC_GUESS, sv);
145             break;
146         }
147       }
148     }
149   }
150 }
151 static void mysql_log_results(noit_module_t *self, noit_check_t *check) {
152   struct timeval duration, now;
153   mysql_check_info_t *ci = check->closure;
154
155   gettimeofday(&now, NULL);
156   sub_timeval(now, check->last_fire_time, &duration);
157   noit_stats_set_whence(check, &now);
158   noit_stats_set_duration(check, duration.tv_sec * 1000 + duration.tv_usec / 1000);
159   noit_stats_set_available(check, NP_UNAVAILABLE);
160   noit_stats_set_state(check, NP_BAD);
161   if(ci->error) noit_stats_set_status(check, ci->error);
162   else if(ci->timed_out) noit_stats_set_status(check, "timeout");
163   else if(ci->rv == 0) {
164     noit_stats_set_available(check, NP_AVAILABLE);
165     noit_stats_set_state(check, NP_GOOD);
166     noit_stats_set_status(check, "no rows, ok");
167   }
168   else {
169     noit_stats_set_available(check, NP_AVAILABLE);
170     noit_stats_set_state(check, NP_GOOD);
171     noit_stats_set_status(check, "got rows, ok");
172   }
173
174   if(ci->rv >= 0)
175     noit_stats_set_metric(check, "row_count", METRIC_INT32, &ci->rv);
176   if(ci->connect_duration)
177     noit_stats_set_metric(check, "connect_duration", METRIC_DOUBLE,
178                           ci->connect_duration);
179   if(ci->query_duration)
180     noit_stats_set_metric(check, "query_duration", METRIC_DOUBLE,
181                           ci->query_duration);
182
183   noit_check_set_stats(check);
184 }
185
186 #define FETCH_CONFIG_OR(key, str) do { \
187   if(!mtev_hash_retrieve(check->config, #key, strlen(#key), (void **)&key)) \
188     key = str; \
189 } while(0)
190
191 #define AVAIL_BAIL(str) do { \
192   MYSQL *conn_swap = ci->conn; \
193   MYSQL_RES *result_swap = ci->result; \
194   if(ci->result) { \
195     ci->result = NULL; \
196     mysql_free_result(result_swap); \
197   } \
198   if(ci->conn) { \
199     ci->conn = NULL; \
200     mysql_close(conn_swap); \
201   } \
202   ci->timed_out = 0; \
203   ci->error = strdup(str); \
204   mtev_hash_destroy(&dsn_h, free, free); \
205   return 0; \
206 } while(0)
207
208 static char *
209 __noit__strndup(const char *src, int len) {
210   int slen;
211   char *dst;
212   for(slen = 0; slen < len; slen++)
213     if(src[slen] == '\0') break;
214   dst = malloc(slen + 1);
215   memcpy(dst, src, slen);
216   dst[slen] = '\0';
217   return dst;
218 }
219
220 void mysql_parse_dsn(const char *dsn, mtev_hash_table *h) {
221   const char *a=dsn, *b=NULL, *c=NULL;
222   while (a && (NULL != (b = strchr(a, '=')))) {
223     char *key, *val=NULL;
224     key = __noit__strndup(a, b-a);
225     b++;
226     if (b) {
227       if (NULL != (c = strchr(b, ' '))) {
228         val = __noit__strndup(b, c-b);
229       } else {
230         val = strdup(b);
231       }
232     }
233     mtev_hash_replace(h, key, key?strlen(key):0, val, free, free);
234     a = c;
235     if (a) a++;
236   }
237 }
238
239 static int mysql_drive_session(eventer_t e, int mask, void *closure,
240                                   struct timeval *now) {
241   const char *dsn, *sql;
242   char sql_buff[8192];
243   char dsn_buff[512];
244   mysql_check_info_t *ci = closure;
245   noit_check_t *check = ci->check;
246   struct timeval t1, t2, diff;
247   mtev_hash_table dsn_h = MTEV_HASH_EMPTY;
248   const char *host=NULL;
249   const char *user=NULL;
250   const char *password=NULL;
251   const char *dbname=NULL;
252   const char *port_s=NULL;
253   const char *socket=NULL;
254   const char *sslmode=NULL;
255   u_int32_t port;
256   unsigned long client_flag = CLIENT_IGNORE_SIGPIPE;
257   unsigned int timeout;
258
259   if(mask & (EVENTER_READ | EVENTER_WRITE)) {
260     /* this case is impossible from the eventer.  It is called as
261      * such on the synchronous completion of the event.
262      */
263     mysql_log_results(ci->self, ci->check);
264     mysql_cleanup(ci->self, ci->check);
265     check->flags &= ~NP_RUNNING;
266     return 0;
267   }
268   switch(mask) {
269     case EVENTER_ASYNCH_WORK:
270       ci->connect_duration = NULL;
271       ci->query_duration = NULL;
272
273       FETCH_CONFIG_OR(dsn, "");
274       noit_check_interpolate(dsn_buff, sizeof(dsn_buff), dsn,
275                              &ci->attrs, check->config);
276
277       mysql_parse_dsn(dsn_buff, &dsn_h);
278       mtev_hash_retrieve(&dsn_h, "host", strlen("host"), (void**)&host);
279       mtev_hash_retrieve(&dsn_h, "user", strlen("user"), (void**)&user);
280       mtev_hash_retrieve(&dsn_h, "password", strlen("password"), (void**)&password);
281       mtev_hash_retrieve(&dsn_h, "dbname", strlen("dbname"), (void**)&dbname);
282       mtev_hash_retrieve(&dsn_h, "port", strlen("port"), (void**)&port_s);
283       if(mtev_hash_retrieve(&dsn_h, "sslmode", strlen("sslmode"), (void**)&sslmode) &&
284          !strcmp(sslmode, "require"))
285         client_flag |= CLIENT_SSL;
286       port = port_s ? strtol(port_s, NULL, 10) : 3306;
287       mtev_hash_retrieve(&dsn_h, "socket", strlen("socket"), (void**)&socket);
288
289       ci->conn = mysql_init(NULL); /* allocate us a handle */
290       if(!ci->conn) AVAIL_BAIL("mysql_init failed");
291       timeout = check->timeout / 1000;
292       mysql_options(ci->conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
293       if(!mysql_real_connect(ci->conn, host, user, password,
294                              dbname, port, socket, client_flag)) {
295         mtevL(noit_stderr, "error during mysql_real_connect: %s\n",
296           mysql_error(ci->conn));
297         AVAIL_BAIL(mysql_error(ci->conn));
298       }
299       if(mysql_ping(ci->conn))
300         AVAIL_BAIL(mysql_error(ci->conn));
301
302 #if MYSQL_VERSION_ID >= 50000
303       if (sslmode && !strcmp(sslmode, "require")) {
304         /* mysql has a bad habit of silently failing to establish ssl and
305          * falling back to unencrypted, so after making the connection, let's
306          * check that we're actually using SSL by checking for a non-NULL
307          * return value from mysql_get_ssl_cipher().
308          */
309         if (mysql_get_ssl_cipher(ci->conn) == NULL) {
310           mtevL(nldeb, "mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
311           AVAIL_BAIL("mysql_get_ssl_cipher() returns NULL, but SSL mode required.");
312         }
313       }
314 #endif
315
316       gettimeofday(&t1, NULL);
317       sub_timeval(t1, check->last_fire_time, &diff);
318       ci->connect_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
319       ci->connect_duration = &ci->connect_duration_d;
320
321       FETCH_CONFIG_OR(sql, "");
322       noit_check_interpolate(sql_buff, sizeof(sql_buff), sql,
323                              &ci->attrs, check->config);
324       if (mysql_query(ci->conn, sql_buff))
325         AVAIL_BAIL(mysql_error(ci->conn));
326
327       gettimeofday(&t2, NULL);
328       sub_timeval(t2, t1, &diff);
329       ci->query_duration_d = diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0;
330       ci->query_duration = &ci->query_duration_d;
331
332       ci->result = mysql_store_result(ci->conn);
333       if(!ci->result) AVAIL_BAIL("mysql_store_result failed");
334       ci->rv = mysql_num_rows(ci->result);
335       mysql_ingest_stats(ci);
336       if(ci->result) {
337         MYSQL_RES *result_swap = ci->result;
338         ci->result = NULL;
339         mysql_free_result(result_swap);
340       }
341       if(ci->conn) {
342         MYSQL *conn_swap = ci->conn;
343         ci->conn = NULL;
344         mysql_close(conn_swap);
345       }
346       ci->timed_out = 0;
347       mtev_hash_destroy(&dsn_h, free, free);
348       return 0;
349       break;
350     case EVENTER_ASYNCH_CLEANUP:
351       /* This sets us up for a completion call. */
352       e->mask = EVENTER_READ | EVENTER_WRITE;
353       break;
354     default:
355       abort();
356   }
357   return 0;
358 }
359
360 static int mysql_initiate(noit_module_t *self, noit_check_t *check,
361                           noit_check_t *cause) {
362   mysql_check_info_t *ci = check->closure;
363   struct timeval __now;
364
365   /* We cannot be running */
366   BAIL_ON_RUNNING_CHECK(check);
367   check->flags |= NP_RUNNING;
368
369   ci->self = self;
370   ci->check = check;
371
372   ci->timed_out = 1;
373   ci->rv = -1;
374   noit_check_make_attrs(check, &ci->attrs);
375   gettimeofday(&__now, NULL);
376   memcpy(&check->last_fire_time, &__now, sizeof(__now));
377
378   /* Register a handler for the worker */
379   noit_check_run_full_asynch(check, mysql_drive_session);
380   return 0;
381 }
382
383 static int mysql_initiate_check(noit_module_t *self, noit_check_t *check,
384                                    int once, noit_check_t *cause) {
385   if(!check->closure) check->closure = calloc(1, sizeof(mysql_check_info_t));
386   INITIATE_CHECK(mysql_initiate, self, check, cause);
387   return 0;
388 }
389
390 static int mysql_onload(mtev_image_t *self) {
391   nlerr = mtev_log_stream_find("error/mysql");
392   nldeb = mtev_log_stream_find("debug/mysql");
393   if(!nlerr) nlerr = noit_stderr;
394   if(!nldeb) nldeb = noit_debug;
395
396   eventer_name_callback("mysql/mysql_drive_session", mysql_drive_session);
397   return 0;
398 }
399
400 #include "mysql.xmlh"
401 noit_module_t mysql = {
402   {
403     .magic = NOIT_MODULE_MAGIC,
404     .version = NOIT_MODULE_ABI_VERSION,
405     .name = "mysql",
406     .description = "MySQL Checker",
407     .xml_description = mysql_xml_description,
408     .onload = mysql_onload
409   },
410   NULL,
411   NULL,
412   mysql_initiate_check,
413   mysql_cleanup
414 };
415
Note: See TracBrowser for help on using the browser.