Drop st_mysql_options and use db->con->options instead
[collectd.git] / src / mysql.c
1 /**
2  * collectd - src/mysql.c
3  * Copyright (C) 2006-2010  Florian octo Forster
4  * Copyright (C) 2008       Mirko Buffoni
5  * Copyright (C) 2009       Doug MacEachern
6  * Copyright (C) 2009       Sebastian tokkee Harl
7  * Copyright (C) 2009       Rodolphe QuiĆ©deville
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU General Public License as published by the
11  * Free Software Foundation; only version 2 of the License is applicable.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
21  *
22  * Authors:
23  *   Florian octo Forster <octo at collectd.org>
24  *   Mirko Buffoni <briareos at eswat.org>
25  *   Doug MacEachern <dougm at hyperic.com>
26  *   Sebastian tokkee Harl <sh at tokkee.org>
27  *   Rodolphe QuiĆ©deville <rquiedeville at bearstech.com>
28  **/
29
30 #include "collectd.h"
31 #include "common.h"
32 #include "plugin.h"
33 #include "configfile.h"
34
35 #ifdef HAVE_MYSQL_H
36 #include <mysql.h>
37 #elif defined(HAVE_MYSQL_MYSQL_H)
38 #include <mysql/mysql.h>
39 #endif
40
41 /* TODO: Understand `Select_*' and possibly do that stuff as well.. */
42
43 struct mysql_database_s /* {{{ */
44 {
45         char *instance;
46         char *alias;
47         char *host;
48         char *user;
49         char *pass;
50         char *database;
51         char *socket;
52         int   port;
53         int   timeout;
54
55         _Bool master_stats;
56         _Bool slave_stats;
57
58         _Bool slave_notif;
59         _Bool slave_io_running;
60         _Bool slave_sql_running;
61
62         MYSQL *con;
63         _Bool  is_connected;
64 };
65 typedef struct mysql_database_s mysql_database_t; /* }}} */
66
67 static int mysql_read (user_data_t *ud);
68
69 void mysql_read_default_options(struct st_mysql_options *options,
70                 const char *filename,const char *group);
71
72 static void mysql_database_free (void *arg) /* {{{ */
73 {
74         mysql_database_t *db;
75
76         DEBUG ("mysql plugin: mysql_database_free (arg = %p);", arg);
77
78         db = (mysql_database_t *) arg;
79
80         if (db == NULL)
81                 return;
82
83         if (db->con != NULL)
84                 mysql_close (db->con);
85
86         sfree (db->alias);
87         sfree (db->host);
88         sfree (db->user);
89         sfree (db->pass);
90         sfree (db->socket);
91         sfree (db->instance);
92         sfree (db->database);
93         sfree (db);
94 } /* }}} void mysql_database_free */
95
96 /* Configuration handling functions {{{
97  *
98  * <Plugin mysql>
99  *   <Database "plugin_instance1">
100  *     Host "localhost"
101  *     Port 22000
102  *     ...
103  *   </Database>
104  * </Plugin>
105  */
106 static int mysql_config_database (oconfig_item_t *ci) /* {{{ */
107 {
108         mysql_database_t *db;
109         int status = 0;
110         int i;
111
112         if ((ci->values_num != 1)
113             || (ci->values[0].type != OCONFIG_TYPE_STRING))
114         {
115                 WARNING ("mysql plugin: The `Database' block "
116                          "needs exactly one string argument.");
117                 return (-1);
118         }
119
120         db = (mysql_database_t *) malloc (sizeof (*db));
121         if (db == NULL)
122         {
123                 ERROR ("mysql plugin: malloc failed.");
124                 return (-1);
125         }
126         memset (db, 0, sizeof (*db));
127
128         /* initialize all the pointers */
129         db->alias    = NULL;
130         db->host     = NULL;
131         db->user     = NULL;
132         db->pass     = NULL;
133         db->database = NULL;
134         db->socket   = NULL;
135         db->con      = NULL;
136         db->timeout  = 0;
137
138         /* trigger a notification, if it's not running */
139         db->slave_io_running  = 1;
140         db->slave_sql_running = 1;
141
142         status = cf_util_get_string (ci, &db->instance);
143         if (status != 0)
144         {
145                 sfree (db);
146                 return (status);
147         }
148         assert (db->instance != NULL);
149
150         /* Fill the `mysql_database_t' structure.. */
151         for (i = 0; i < ci->children_num; i++)
152         {
153                 oconfig_item_t *child = ci->children + i;
154
155                 if (strcasecmp ("Alias", child->key) == 0)
156                         status = cf_util_get_string (child, &db->alias);
157                 else if (strcasecmp ("Host", child->key) == 0)
158                         status = cf_util_get_string (child, &db->host);
159                 else if (strcasecmp ("User", child->key) == 0)
160                         status = cf_util_get_string (child, &db->user);
161                 else if (strcasecmp ("Password", child->key) == 0)
162                         status = cf_util_get_string (child, &db->pass);
163                 else if (strcasecmp ("Port", child->key) == 0)
164                 {
165                         status = cf_util_get_port_number (child);
166                         if (status > 0)
167                         {
168                                 db->port = status;
169                                 status = 0;
170                         }
171                 }
172                 else if (strcasecmp ("Socket", child->key) == 0)
173                         status = cf_util_get_string (child, &db->socket);
174                 else if (strcasecmp ("Database", child->key) == 0)
175                         status = cf_util_get_string (child, &db->database);
176                 else if (strcasecmp ("ConnectTimeout", child->key) == 0)
177                         status = cf_util_get_int (child, &db->timeout);
178                 else if (strcasecmp ("MasterStats", child->key) == 0)
179                         status = cf_util_get_boolean (child, &db->master_stats);
180                 else if (strcasecmp ("SlaveStats", child->key) == 0)
181                         status = cf_util_get_boolean (child, &db->slave_stats);
182                 else if (strcasecmp ("SlaveNotifications", child->key) == 0)
183                         status = cf_util_get_boolean (child, &db->slave_notif);
184                 else
185                 {
186                         WARNING ("mysql plugin: Option `%s' not allowed here.", child->key);
187                         status = -1;
188                 }
189
190                 if (status != 0)
191                         break;
192         }
193
194         /* If all went well, register this database for reading */
195         if (status == 0)
196         {
197                 user_data_t ud;
198                 char cb_name[DATA_MAX_NAME_LEN];
199
200                 DEBUG ("mysql plugin: Registering new read callback: %s",
201                                 (db->database != NULL) ? db->database : "<default>");
202
203                 memset (&ud, 0, sizeof (ud));
204                 ud.data = (void *) db;
205                 ud.free_func = mysql_database_free;
206
207                 if (db->instance != NULL)
208                         ssnprintf (cb_name, sizeof (cb_name), "mysql-%s",
209                                         db->instance);
210                 else
211                         sstrncpy (cb_name, "mysql", sizeof (cb_name));
212
213                 plugin_register_complex_read (/* group = */ NULL, cb_name,
214                                               mysql_read,
215                                               /* interval = */ NULL, &ud);
216         }
217         else
218         {
219                 mysql_database_free (db);
220                 return (-1);
221         }
222
223         return (0);
224 } /* }}} int mysql_config_database */
225
226 static int mysql_config (oconfig_item_t *ci) /* {{{ */
227 {
228         int i;
229
230         if (ci == NULL)
231                 return (EINVAL);
232
233         /* Fill the `mysql_database_t' structure.. */
234         for (i = 0; i < ci->children_num; i++)
235         {
236                 oconfig_item_t *child = ci->children + i;
237
238                 if (strcasecmp ("Database", child->key) == 0)
239                         mysql_config_database (child);
240                 else
241                         WARNING ("mysql plugin: Option \"%s\" not allowed here.",
242                                         child->key);
243         }
244
245         return (0);
246 } /* }}} int mysql_config */
247
248 /* }}} End of configuration handling functions */
249
250 static MYSQL *getconnection (mysql_database_t *db)
251 {
252         if (db->is_connected)
253         {
254                 int status;
255
256                 status = mysql_ping (db->con);
257                 if (status == 0)
258                         return (db->con);
259
260                 WARNING ("mysql plugin: Lost connection to instance \"%s\": %s",
261                                 db->instance, mysql_error (db->con));
262         }
263         db->is_connected = 0;
264
265         if (db->con == NULL)
266         {
267                 db->con = mysql_init (NULL);
268                 if (db->con == NULL)
269                 {
270                         ERROR ("mysql plugin: mysql_init failed: %s",
271                                         mysql_error (db->con));
272                         return (NULL);
273                 }
274         }
275
276         /* Configure TCP connect timeout (default: 0) */
277         db->con->options.connect_timeout = db->timeout;
278
279         if (mysql_real_connect (db->con, db->host, db->user, db->pass,
280                                 db->database, db->port, db->socket, 0) == NULL)
281         {
282                 ERROR ("mysql plugin: Failed to connect to database %s "
283                                 "at server %s: %s",
284                                 (db->database != NULL) ? db->database : "<none>",
285                                 (db->host != NULL) ? db->host : "localhost",
286                                 mysql_error (db->con));
287                 return (NULL);
288         }
289
290         INFO ("mysql plugin: Successfully connected to database %s "
291                         "at server %s (server version: %s, protocol version: %d)",
292                         (db->database != NULL) ? db->database : "<none>",
293                         mysql_get_host_info (db->con),
294                         mysql_get_server_info (db->con),
295                         mysql_get_proto_info (db->con));
296
297         db->is_connected = 1;
298         return (db->con);
299 } /* static MYSQL *getconnection (mysql_database_t *db) */
300
301 static void set_host (mysql_database_t *db, char *buf, size_t buflen)
302 {
303         if (db->alias)
304                 sstrncpy (buf, db->alias, buflen);
305         else if ((db->host == NULL)
306                         || (strcmp ("", db->host) == 0)
307                         || (strcmp ("localhost", db->host) == 0))
308                 sstrncpy (buf, hostname_g, buflen);
309         else
310                 sstrncpy (buf, db->host, buflen);
311 } /* void set_host */
312
313 static void submit (const char *type, const char *type_instance,
314                 value_t *values, size_t values_len, mysql_database_t *db)
315 {
316         value_list_t vl = VALUE_LIST_INIT;
317
318         vl.values     = values;
319         vl.values_len = values_len;
320
321         set_host (db, vl.host, sizeof (vl.host));
322
323         sstrncpy (vl.plugin, "mysql", sizeof (vl.plugin));
324
325         /* Assured by "mysql_config_database" */
326         assert (db->instance != NULL);
327         sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
328
329         sstrncpy (vl.type, type, sizeof (vl.type));
330         if (type_instance != NULL)
331                 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
332
333         plugin_dispatch_values (&vl);
334 } /* submit */
335
336 static void counter_submit (const char *type, const char *type_instance,
337                 derive_t value, mysql_database_t *db)
338 {
339         value_t values[1];
340
341         values[0].derive = value;
342         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
343 } /* void counter_submit */
344
345 static void gauge_submit (const char *type, const char *type_instance,
346                 gauge_t value, mysql_database_t *db)
347 {
348         value_t values[1];
349
350         values[0].gauge = value;
351         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
352 } /* void gauge_submit */
353
354 static void derive_submit (const char *type, const char *type_instance,
355                 derive_t value, mysql_database_t *db)
356 {
357         value_t values[1];
358
359         values[0].derive = value;
360         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
361 } /* void derive_submit */
362
363 static void traffic_submit (derive_t rx, derive_t tx, mysql_database_t *db)
364 {
365         value_t values[2];
366
367         values[0].derive = rx;
368         values[1].derive = tx;
369
370         submit ("mysql_octets", NULL, values, STATIC_ARRAY_SIZE (values), db);
371 } /* void traffic_submit */
372
373 static MYSQL_RES *exec_query (MYSQL *con, const char *query)
374 {
375         MYSQL_RES *res;
376
377         int query_len = strlen (query);
378
379         if (mysql_real_query (con, query, query_len))
380         {
381                 ERROR ("mysql plugin: Failed to execute query: %s",
382                                 mysql_error (con));
383                 INFO ("mysql plugin: SQL query was: %s", query);
384                 return (NULL);
385         }
386
387         res = mysql_store_result (con);
388         if (res == NULL)
389         {
390                 ERROR ("mysql plugin: Failed to store query result: %s",
391                                 mysql_error (con));
392                 INFO ("mysql plugin: SQL query was: %s", query);
393                 return (NULL);
394         }
395
396         return (res);
397 } /* exec_query */
398
399 static int mysql_read_master_stats (mysql_database_t *db, MYSQL *con)
400 {
401         MYSQL_RES *res;
402         MYSQL_ROW  row;
403
404         char *query;
405         int   field_num;
406         unsigned long long position;
407
408         query = "SHOW MASTER STATUS";
409
410         res = exec_query (con, query);
411         if (res == NULL)
412                 return (-1);
413
414         row = mysql_fetch_row (res);
415         if (row == NULL)
416         {
417                 ERROR ("mysql plugin: Failed to get master statistics: "
418                                 "`%s' did not return any rows.", query);
419                 mysql_free_result (res);
420                 return (-1);
421         }
422
423         field_num = mysql_num_fields (res);
424         if (field_num < 2)
425         {
426                 ERROR ("mysql plugin: Failed to get master statistics: "
427                                 "`%s' returned less than two columns.", query);
428                 mysql_free_result (res);
429                 return (-1);
430         }
431
432         position = atoll (row[1]);
433         counter_submit ("mysql_log_position", "master-bin", position, db);
434
435         row = mysql_fetch_row (res);
436         if (row != NULL)
437                 WARNING ("mysql plugin: `%s' returned more than one row - "
438                                 "ignoring further results.", query);
439
440         mysql_free_result (res);
441
442         return (0);
443 } /* mysql_read_master_stats */
444
445 static int mysql_read_slave_stats (mysql_database_t *db, MYSQL *con)
446 {
447         MYSQL_RES *res;
448         MYSQL_ROW  row;
449
450         char *query;
451         int   field_num;
452
453         /* WTF? libmysqlclient does not seem to provide any means to
454          * translate a column name to a column index ... :-/ */
455         const int READ_MASTER_LOG_POS_IDX   = 6;
456         const int SLAVE_IO_RUNNING_IDX      = 10;
457         const int SLAVE_SQL_RUNNING_IDX     = 11;
458         const int EXEC_MASTER_LOG_POS_IDX   = 21;
459         const int SECONDS_BEHIND_MASTER_IDX = 32;
460
461         query = "SHOW SLAVE STATUS";
462
463         res = exec_query (con, query);
464         if (res == NULL)
465                 return (-1);
466
467         row = mysql_fetch_row (res);
468         if (row == NULL)
469         {
470                 ERROR ("mysql plugin: Failed to get slave statistics: "
471                                 "`%s' did not return any rows.", query);
472                 mysql_free_result (res);
473                 return (-1);
474         }
475
476         field_num = mysql_num_fields (res);
477         if (field_num < 33)
478         {
479                 ERROR ("mysql plugin: Failed to get slave statistics: "
480                                 "`%s' returned less than 33 columns.", query);
481                 mysql_free_result (res);
482                 return (-1);
483         }
484
485         if (db->slave_stats)
486         {
487                 unsigned long long counter;
488                 double gauge;
489
490                 counter = atoll (row[READ_MASTER_LOG_POS_IDX]);
491                 counter_submit ("mysql_log_position", "slave-read", counter, db);
492
493                 counter = atoll (row[EXEC_MASTER_LOG_POS_IDX]);
494                 counter_submit ("mysql_log_position", "slave-exec", counter, db);
495
496                 if (row[SECONDS_BEHIND_MASTER_IDX] != NULL)
497                 {
498                         gauge = atof (row[SECONDS_BEHIND_MASTER_IDX]);
499                         gauge_submit ("time_offset", NULL, gauge, db);
500                 }
501         }
502
503         if (db->slave_notif)
504         {
505                 notification_t n = { 0, cdtime (), "", "",
506                         "mysql", "", "time_offset", "", NULL };
507
508                 char *io, *sql;
509
510                 io  = row[SLAVE_IO_RUNNING_IDX];
511                 sql = row[SLAVE_SQL_RUNNING_IDX];
512
513                 set_host (db, n.host, sizeof (n.host));
514
515                 /* Assured by "mysql_config_database" */
516                 assert (db->instance != NULL);
517                 sstrncpy (n.plugin_instance, db->instance, sizeof (n.plugin_instance));
518
519                 if (((io == NULL) || (strcasecmp (io, "yes") != 0))
520                                 && (db->slave_io_running))
521                 {
522                         n.severity = NOTIF_WARNING;
523                         ssnprintf (n.message, sizeof (n.message),
524                                         "slave I/O thread not started or not connected to master");
525                         plugin_dispatch_notification (&n);
526                         db->slave_io_running = 0;
527                 }
528                 else if (((io != NULL) && (strcasecmp (io, "yes") == 0))
529                                 && (! db->slave_io_running))
530                 {
531                         n.severity = NOTIF_OKAY;
532                         ssnprintf (n.message, sizeof (n.message),
533                                         "slave I/O thread started and connected to master");
534                         plugin_dispatch_notification (&n);
535                         db->slave_io_running = 1;
536                 }
537
538                 if (((sql == NULL) || (strcasecmp (sql, "yes") != 0))
539                                 && (db->slave_sql_running))
540                 {
541                         n.severity = NOTIF_WARNING;
542                         ssnprintf (n.message, sizeof (n.message),
543                                         "slave SQL thread not started");
544                         plugin_dispatch_notification (&n);
545                         db->slave_sql_running = 0;
546                 }
547                 else if (((sql != NULL) && (strcasecmp (sql, "yes") == 0))
548                                 && (! db->slave_sql_running))
549                 {
550                         n.severity = NOTIF_OKAY;
551                         ssnprintf (n.message, sizeof (n.message),
552                                         "slave SQL thread started");
553                         plugin_dispatch_notification (&n);
554                         db->slave_sql_running = 0;
555                 }
556         }
557
558         row = mysql_fetch_row (res);
559         if (row != NULL)
560                 WARNING ("mysql plugin: `%s' returned more than one row - "
561                                 "ignoring further results.", query);
562
563         mysql_free_result (res);
564
565         return (0);
566 } /* mysql_read_slave_stats */
567
568 static int mysql_read (user_data_t *ud)
569 {
570         mysql_database_t *db;
571         MYSQL     *con;
572         MYSQL_RES *res;
573         MYSQL_ROW  row;
574         char      *query;
575
576         derive_t qcache_hits          = 0;
577         derive_t qcache_inserts       = 0;
578         derive_t qcache_not_cached    = 0;
579         derive_t qcache_lowmem_prunes = 0;
580         gauge_t qcache_queries_in_cache = NAN;
581
582         gauge_t threads_running   = NAN;
583         gauge_t threads_connected = NAN;
584         gauge_t threads_cached    = NAN;
585         derive_t threads_created = 0;
586
587         unsigned long long traffic_incoming = 0ULL;
588         unsigned long long traffic_outgoing = 0ULL;
589
590         if ((ud == NULL) || (ud->data == NULL))
591         {
592                 ERROR ("mysql plugin: mysql_database_read: Invalid user data.");
593                 return (-1);
594         }
595
596         db = (mysql_database_t *) ud->data;
597
598         /* An error message will have been printed in this case */
599         if ((con = getconnection (db)) == NULL)
600                 return (-1);
601
602         query = "SHOW STATUS";
603         if (mysql_get_server_version (con) >= 50002)
604                 query = "SHOW GLOBAL STATUS";
605
606         res = exec_query (con, query);
607         if (res == NULL)
608                 return (-1);
609
610         while ((row = mysql_fetch_row (res)))
611         {
612                 char *key;
613                 unsigned long long val;
614
615                 key = row[0];
616                 val = atoll (row[1]);
617
618                 if (strncmp (key, "Com_", 
619                                   strlen ("Com_")) == 0)
620                 {
621                         if (val == 0ULL)
622                                 continue;
623
624                         /* Ignore `prepared statements' */
625                         if (strncmp (key, "Com_stmt_", strlen ("Com_stmt_")) != 0)
626                                 counter_submit ("mysql_commands", 
627                                                 key + strlen ("Com_"), 
628                                                 val, db);
629                 }
630                 else if (strncmp (key, "Handler_", 
631                                         strlen ("Handler_")) == 0)
632                 {
633                         if (val == 0ULL)
634                                 continue;
635
636                         counter_submit ("mysql_handler", 
637                                         key + strlen ("Handler_"), 
638                                         val, db);
639                 }
640                 else if (strncmp (key, "Qcache_",
641                                         strlen ("Qcache_")) == 0)
642                 {
643                         if (strcmp (key, "Qcache_hits") == 0)
644                                 qcache_hits = (derive_t) val;
645                         else if (strcmp (key, "Qcache_inserts") == 0)
646                                 qcache_inserts = (derive_t) val;
647                         else if (strcmp (key, "Qcache_not_cached") == 0)
648                                 qcache_not_cached = (derive_t) val;
649                         else if (strcmp (key, "Qcache_lowmem_prunes") == 0)
650                                 qcache_lowmem_prunes = (derive_t) val;
651                         else if (strcmp (key, "Qcache_queries_in_cache") == 0)
652                                 qcache_queries_in_cache = (gauge_t) val;
653                 }
654                 else if (strncmp (key, "Bytes_", 
655                                         strlen ("Bytes_")) == 0)
656                 {
657                         if (strcmp (key, "Bytes_received") == 0)
658                                 traffic_incoming += val;
659                         else if (strcmp (key, "Bytes_sent") == 0)
660                                 traffic_outgoing += val;
661                 }
662                 else if (strncmp (key, "Threads_", 
663                                         strlen ("Threads_")) == 0)
664                 {
665                         if (strcmp (key, "Threads_running") == 0)
666                                 threads_running = (gauge_t) val;
667                         else if (strcmp (key, "Threads_connected") == 0)
668                                 threads_connected = (gauge_t) val;
669                         else if (strcmp (key, "Threads_cached") == 0)
670                                 threads_cached = (gauge_t) val;
671                         else if (strcmp (key, "Threads_created") == 0)
672                                 threads_created = (derive_t) val;
673                 }
674                 else if (strncmp (key, "Table_locks_",
675                                         strlen ("Table_locks_")) == 0)
676                 {
677                         counter_submit ("mysql_locks",
678                                         key + strlen ("Table_locks_"),
679                                         val, db);
680                 }
681         }
682         mysql_free_result (res); res = NULL;
683
684         if ((qcache_hits != 0)
685                         || (qcache_inserts != 0)
686                         || (qcache_not_cached != 0)
687                         || (qcache_lowmem_prunes != 0))
688         {
689                 derive_submit ("cache_result", "qcache-hits",
690                                 qcache_hits, db);
691                 derive_submit ("cache_result", "qcache-inserts",
692                                 qcache_inserts, db);
693                 derive_submit ("cache_result", "qcache-not_cached",
694                                 qcache_not_cached, db);
695                 derive_submit ("cache_result", "qcache-prunes",
696                                 qcache_lowmem_prunes, db);
697
698                 gauge_submit ("cache_size", "qcache",
699                                 qcache_queries_in_cache, db);
700         }
701
702         if (threads_created != 0)
703         {
704                 gauge_submit ("threads", "running",
705                                 threads_running, db);
706                 gauge_submit ("threads", "connected",
707                                 threads_connected, db);
708                 gauge_submit ("threads", "cached",
709                                 threads_cached, db);
710
711                 derive_submit ("total_threads", "created",
712                                 threads_created, db);
713         }
714
715         traffic_submit  (traffic_incoming, traffic_outgoing, db);
716
717         if (db->master_stats)
718                 mysql_read_master_stats (db, con);
719
720         if ((db->slave_stats) || (db->slave_notif))
721                 mysql_read_slave_stats (db, con);
722
723         return (0);
724 } /* int mysql_read */
725
726 void module_register (void)
727 {
728         plugin_register_complex_config ("mysql", mysql_config);
729 } /* void module_register */