Code

mysql plugin: Remove the "mysql_qcache" type.
[collectd.git] / src / mysql.c
1 /**
2  * collectd - src/mysql.c
3  * Copyright (C) 2006-2009  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 verplant.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  **/
30 #include "collectd.h"
31 #include "common.h"
32 #include "plugin.h"
33 #include "configfile.h"
35 #ifdef HAVE_MYSQL_H
36 #include <mysql.h>
37 #elif defined(HAVE_MYSQL_MYSQL_H)
38 #include <mysql/mysql.h>
39 #endif
41 /* TODO: Understand `Select_*' and possibly do that stuff as well.. */
43 struct mysql_database_s /* {{{ */
44 {
45         /* instance == NULL  =>  legacy mode */
46         char *instance;
47         char *host;
48         char *user;
49         char *pass;
50         char *database;
51         char *socket;
52         int   port;
54         _Bool master_stats;
55         _Bool slave_stats;
57         _Bool slave_notif;
58         _Bool slave_io_running;
59         _Bool slave_sql_running;
61         MYSQL *con;
62         int    state;
63 };
64 typedef struct mysql_database_s mysql_database_t; /* }}} */
66 static int mysql_read (user_data_t *ud);
68 static void mysql_database_free (void *arg) /* {{{ */
69 {
70         mysql_database_t *db;
72         DEBUG ("mysql plugin: mysql_database_free (arg = %p);", arg);
74         db = (mysql_database_t *) arg;
76         if (db == NULL)
77                 return;
79         if (db->con != NULL)
80                 mysql_close (db->con);
82         sfree (db->host);
83         sfree (db->user);
84         sfree (db->pass);
85         sfree (db->socket);
86         sfree (db->instance);
87         sfree (db->database);
88         sfree (db);
89 } /* }}} void mysql_database_free */
91 /* Configuration handling functions {{{
92  *
93  * <Plugin mysql>
94  *   <Database "plugin_instance1">
95  *     Host "localhost"
96  *     Port 22000
97  *     ...
98  *   </Database>
99  * </Plugin>
100  */
101 static int mysql_config_database (oconfig_item_t *ci) /* {{{ */
103         mysql_database_t *db;
104         int status = 0;
105         int i;
107         if ((ci->values_num != 1)
108             || (ci->values[0].type != OCONFIG_TYPE_STRING))
109         {
110                 WARNING ("mysql plugin: The `Database' block "
111                          "needs exactly one string argument.");
112                 return (-1);
113         }
115         db = (mysql_database_t *) malloc (sizeof (*db));
116         if (db == NULL)
117         {
118                 ERROR ("mysql plugin: malloc failed.");
119                 return (-1);
120         }
121         memset (db, 0, sizeof (*db));
123         /* initialize all the pointers */
124         db->host     = NULL;
125         db->user     = NULL;
126         db->pass     = NULL;
127         db->database = NULL;
128         db->socket   = NULL;
129         db->con      = NULL;
131         /* trigger a notification, if it's not running */
132         db->slave_io_running  = 1;
133         db->slave_sql_running = 1;
135         status = cf_util_get_string (ci, &db->instance);
136         if (status != 0)
137         {
138                 sfree (db);
139                 return (status);
140         }
141         assert (db->instance != NULL);
143         /* Fill the `mysql_database_t' structure.. */
144         for (i = 0; i < ci->children_num; i++)
145         {
146                 oconfig_item_t *child = ci->children + i;
148                 if (strcasecmp ("Host", child->key) == 0)
149                         status = cf_util_get_string (child, &db->host);
150                 else if (strcasecmp ("User", child->key) == 0)
151                         status = cf_util_get_string (child, &db->user);
152                 else if (strcasecmp ("Password", child->key) == 0)
153                         status = cf_util_get_string (child, &db->pass);
154                 else if (strcasecmp ("Port", child->key) == 0)
155                 {
156                         status = cf_util_get_port_number (child);
157                         if (status > 0)
158                         {
159                                 db->port = status;
160                                 status = 0;
161                         }
162                 }
163                 else if (strcasecmp ("Socket", child->key) == 0)
164                         status = cf_util_get_string (child, &db->socket);
165                 else if (strcasecmp ("Database", child->key) == 0)
166                         status = cf_util_get_string (child, &db->database);
167                 else if (strcasecmp ("MasterStats", child->key) == 0)
168                         status = cf_util_get_boolean (child, &db->master_stats);
169                 else if (strcasecmp ("SlaveStats", child->key) == 0)
170                         status = cf_util_get_boolean (child, &db->slave_stats);
171                 else if (strcasecmp ("SlaveNotifications", child->key) == 0)
172                         status = cf_util_get_boolean (child, &db->slave_notif);
173                 else
174                 {
175                         WARNING ("mysql plugin: Option `%s' not allowed here.", child->key);
176                         status = -1;
177                 }
179                 if (status != 0)
180                         break;
181         }
183         /* If all went well, register this database for reading */
184         if (status == 0)
185         {
186                 user_data_t ud;
187                 char cb_name[DATA_MAX_NAME_LEN];
189                 DEBUG ("mysql plugin: Registering new read callback: %s",
190                                 (db->database != NULL) ? db->database : "<default>");
192                 memset (&ud, 0, sizeof (ud));
193                 ud.data = (void *) db;
194                 ud.free_func = mysql_database_free;
196                 if (db->database != NULL)
197                         ssnprintf (cb_name, sizeof (cb_name), "mysql-%s",
198                                         db->database);
199                 else
200                         sstrncpy (cb_name, "mysql", sizeof (cb_name));
202                 plugin_register_complex_read (/* group = */ NULL, cb_name,
203                                               mysql_read,
204                                               /* interval = */ NULL, &ud);
205         }
206         else
207         {
208                 mysql_database_free (db);
209                 return (-1);
210         }
212         return (0);
213 } /* }}} int mysql_config_database */
215 static int mysql_config (oconfig_item_t *ci) /* {{{ */
217         int i;
219         if (ci == NULL)
220                 return (EINVAL);
222         /* Fill the `mysql_database_t' structure.. */
223         for (i = 0; i < ci->children_num; i++)
224         {
225                 oconfig_item_t *child = ci->children + i;
227                 if (strcasecmp ("Database", child->key) == 0)
228                         mysql_config_database (child);
229                 else
230                         WARNING ("mysql plugin: Option \"%s\" not allowed here.",
231                                         child->key);
232         }
234         return (0);
235 } /* }}} int mysql_config */
237 /* }}} End of configuration handling functions */
239 static MYSQL *getconnection (mysql_database_t *db)
241         if (db->state != 0)
242         {
243                 int err;
244                 if ((err = mysql_ping (db->con)) != 0)
245                 {
246                         WARNING ("mysql_ping failed for %s: %s",
247                                         (db->instance != NULL)
248                                         ? db->instance
249                                         : "<legacy>",
250                                         mysql_error (db->con));
251                         db->state = 0;
252                 }
253                 else
254                 {
255                         db->state = 1;
256                         return (db->con);
257                 }
258         }
260         if ((db->con = mysql_init (db->con)) == NULL)
261         {
262                 ERROR ("mysql_init failed: %s", mysql_error (db->con));
263                 db->state = 0;
264                 return (NULL);
265         }
267         if (mysql_real_connect (db->con, db->host, db->user, db->pass,
268                                 db->database, db->port, db->socket, 0) == NULL)
269         {
270                 ERROR ("mysql plugin: Failed to connect to database %s "
271                                 "at server %s: %s",
272                                 (db->database != NULL) ? db->database : "<none>",
273                                 (db->host != NULL) ? db->host : "localhost",
274                                 mysql_error (db->con));
275                 db->state = 0;
276                 return (NULL);
277         }
278         else
279         {
280                 INFO ("mysql plugin: Successfully connected to database %s "
281                                 "at server %s (server version: %s, protocol version: %d)",
282                                 (db->database != NULL) ? db->database : "<none>",
283                                 mysql_get_host_info (db->con),
284                                 mysql_get_server_info (db->con),
285                                 mysql_get_proto_info (db->con));
286                 db->state = 1;
287                 return (db->con);
288         }
289 } /* static MYSQL *getconnection (mysql_database_t *db) */
291 static void set_host (mysql_database_t *db, char *buf, size_t buflen)
293         /* XXX legacy mode - use hostname_g */
294         if (db->instance == NULL)
295                 sstrncpy (buf, hostname_g, buflen);
296         else
297         {
298                 if ((db->host == NULL)
299                                 || (strcmp ("", db->host) == 0)
300                                 || (strcmp ("localhost", db->host) == 0))
301                         sstrncpy (buf, hostname_g, buflen);
302                 else
303                         sstrncpy (buf, db->host, buflen);
304         }
307 static void set_plugin_instance (mysql_database_t *db,
308                 char *buf, size_t buflen)
310         /* XXX legacy mode - no plugin_instance */
311         if (db->instance == NULL)
312                 sstrncpy (buf, "", buflen);
313         else
314                 sstrncpy (buf, db->instance, buflen);
317 static void submit (const char *type, const char *type_instance,
318                 value_t *values, size_t values_len, mysql_database_t *db)
320         value_list_t vl = VALUE_LIST_INIT;
322         vl.values     = values;
323         vl.values_len = values_len;
325         set_host (db, vl.host, sizeof (vl.host));
327         sstrncpy (vl.plugin, "mysql", sizeof (vl.plugin));
328         set_plugin_instance (db, vl.plugin_instance, sizeof (vl.plugin_instance));
330         sstrncpy (vl.type, type, sizeof (vl.type));
331         if (type_instance != NULL)
332                 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
334         plugin_dispatch_values (&vl);
335 } /* submit */
337 static void counter_submit (const char *type, const char *type_instance,
338                 counter_t value, mysql_database_t *db)
340         value_t values[1];
342         values[0].counter = value;
343         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
344 } /* void counter_submit */
346 static void gauge_submit (const char *type, const char *type_instance,
347                 gauge_t value, mysql_database_t *db)
349         value_t values[1];
351         values[0].gauge = value;
352         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
353 } /* void gauge_submit */
355 static void derive_submit (const char *type, const char *type_instance,
356                 derive_t value, mysql_database_t *db)
358         value_t values[1];
360         values[0].derive = value;
361         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
362 } /* void derive_submit */
364 static void threads_submit (gauge_t running, gauge_t connected, gauge_t cached,
365                 counter_t created, mysql_database_t *db)
367         value_t values[4];
369         values[0].gauge   = running;
370         values[1].gauge   = connected;
371         values[2].gauge   = cached;
372         values[3].counter = created;
374         submit ("mysql_threads", NULL, values, STATIC_ARRAY_SIZE (values), db);
375 } /* void threads_submit */
377 static void traffic_submit (counter_t rx, counter_t tx, mysql_database_t *db)
379         value_t values[2];
381         values[0].counter = rx;
382         values[1].counter = tx;
384         submit ("mysql_octets", NULL, values, STATIC_ARRAY_SIZE (values), db);
385 } /* void traffic_submit */
387 static MYSQL_RES *exec_query (MYSQL *con, const char *query)
389         MYSQL_RES *res;
391         int query_len = strlen (query);
393         if (mysql_real_query (con, query, query_len))
394         {
395                 ERROR ("mysql plugin: Failed to execute query: %s",
396                                 mysql_error (con));
397                 INFO ("mysql plugin: SQL query was: %s", query);
398                 return (NULL);
399         }
401         res = mysql_store_result (con);
402         if (res == NULL)
403         {
404                 ERROR ("mysql plugin: Failed to store query result: %s",
405                                 mysql_error (con));
406                 INFO ("mysql plugin: SQL query was: %s", query);
407                 return (NULL);
408         }
410         return (res);
411 } /* exec_query */
413 static int mysql_read_master_stats (mysql_database_t *db, MYSQL *con)
415         MYSQL_RES *res;
416         MYSQL_ROW  row;
418         char *query;
419         int   field_num;
420         unsigned long long position;
422         query = "SHOW MASTER STATUS";
424         res = exec_query (con, query);
425         if (res == NULL)
426                 return (-1);
428         row = mysql_fetch_row (res);
429         if (row == NULL)
430         {
431                 ERROR ("mysql plugin: Failed to get master statistics: "
432                                 "`%s' did not return any rows.", query);
433                 return (-1);
434         }
436         field_num = mysql_num_fields (res);
437         if (field_num < 2)
438         {
439                 ERROR ("mysql plugin: Failed to get master statistics: "
440                                 "`%s' returned less than two columns.", query);
441                 return (-1);
442         }
444         position = atoll (row[1]);
445         counter_submit ("mysql_log_position", "master-bin", position, db);
447         row = mysql_fetch_row (res);
448         if (row != NULL)
449                 WARNING ("mysql plugin: `%s' returned more than one row - "
450                                 "ignoring further results.", query);
452         mysql_free_result (res);
454         return (0);
455 } /* mysql_read_master_stats */
457 static int mysql_read_slave_stats (mysql_database_t *db, MYSQL *con)
459         MYSQL_RES *res;
460         MYSQL_ROW  row;
462         char *query;
463         int   field_num;
465         /* WTF? libmysqlclient does not seem to provide any means to
466          * translate a column name to a column index ... :-/ */
467         const int READ_MASTER_LOG_POS_IDX   = 6;
468         const int SLAVE_IO_RUNNING_IDX      = 10;
469         const int SLAVE_SQL_RUNNING_IDX     = 11;
470         const int EXEC_MASTER_LOG_POS_IDX   = 21;
471         const int SECONDS_BEHIND_MASTER_IDX = 32;
473         query = "SHOW SLAVE STATUS";
475         res = exec_query (con, query);
476         if (res == NULL)
477                 return (-1);
479         row = mysql_fetch_row (res);
480         if (row == NULL)
481         {
482                 ERROR ("mysql plugin: Failed to get slave statistics: "
483                                 "`%s' did not return any rows.", query);
484                 return (-1);
485         }
487         field_num = mysql_num_fields (res);
488         if (field_num < 33)
489         {
490                 ERROR ("mysql plugin: Failed to get slave statistics: "
491                                 "`%s' returned less than 33 columns.", query);
492                 return (-1);
493         }
495         if (db->slave_stats)
496         {
497                 unsigned long long counter;
498                 double gauge;
500                 counter = atoll (row[READ_MASTER_LOG_POS_IDX]);
501                 counter_submit ("mysql_log_position", "slave-read", counter, db);
503                 counter = atoll (row[EXEC_MASTER_LOG_POS_IDX]);
504                 counter_submit ("mysql_log_position", "slave-exec", counter, db);
506                 if (row[SECONDS_BEHIND_MASTER_IDX] != NULL)
507                 {
508                         gauge = atof (row[SECONDS_BEHIND_MASTER_IDX]);
509                         gauge_submit ("time_offset", NULL, gauge, db);
510                 }
511         }
513         if (db->slave_notif)
514         {
515                 notification_t n = { 0, time (NULL), "", "",
516                         "mysql", "", "time_offset", "", NULL };
518                 char *io, *sql;
520                 io  = row[SLAVE_IO_RUNNING_IDX];
521                 sql = row[SLAVE_SQL_RUNNING_IDX];
523                 set_host (db, n.host, sizeof (n.host));
524                 set_plugin_instance (db,
525                                 n.plugin_instance, sizeof (n.plugin_instance));
527                 if (((io == NULL) || (strcasecmp (io, "yes") != 0))
528                                 && (db->slave_io_running))
529                 {
530                         n.severity = NOTIF_WARNING;
531                         ssnprintf (n.message, sizeof (n.message),
532                                         "slave I/O thread not started or not connected to master");
533                         plugin_dispatch_notification (&n);
534                         db->slave_io_running = 0;
535                 }
536                 else if (((io != NULL) && (strcasecmp (io, "yes") == 0))
537                                 && (! db->slave_io_running))
538                 {
539                         n.severity = NOTIF_OKAY;
540                         ssnprintf (n.message, sizeof (n.message),
541                                         "slave I/O thread started and connected to master");
542                         plugin_dispatch_notification (&n);
543                         db->slave_io_running = 1;
544                 }
546                 if (((sql == NULL) || (strcasecmp (sql, "yes") != 0))
547                                 && (db->slave_sql_running))
548                 {
549                         n.severity = NOTIF_WARNING;
550                         ssnprintf (n.message, sizeof (n.message),
551                                         "slave SQL thread not started");
552                         plugin_dispatch_notification (&n);
553                         db->slave_sql_running = 0;
554                 }
555                 else if (((sql != NULL) && (strcasecmp (sql, "yes") == 0))
556                                 && (! db->slave_sql_running))
557                 {
558                         n.severity = NOTIF_OKAY;
559                         ssnprintf (n.message, sizeof (n.message),
560                                         "slave SQL thread started");
561                         plugin_dispatch_notification (&n);
562                         db->slave_sql_running = 0;
563                 }
564         }
566         row = mysql_fetch_row (res);
567         if (row != NULL)
568                 WARNING ("mysql plugin: `%s' returned more than one row - "
569                                 "ignoring further results.", query);
571         mysql_free_result (res);
573         return (0);
574 } /* mysql_read_slave_stats */
576 static int mysql_read (user_data_t *ud)
578         mysql_database_t *db;
579         MYSQL     *con;
580         MYSQL_RES *res;
581         MYSQL_ROW  row;
582         char      *query;
583         int        field_num;
585         derive_t qcache_hits          = 0;
586         derive_t qcache_inserts       = 0;
587         derive_t qcache_not_cached    = 0;
588         derive_t qcache_lowmem_prunes = 0;
589         gauge_t qcache_queries_in_cache = NAN;
591         int threads_running   = -1;
592         int threads_connected = -1;
593         int threads_cached    = -1;
594         unsigned long long threads_created = 0ULL;
596         unsigned long long traffic_incoming = 0ULL;
597         unsigned long long traffic_outgoing = 0ULL;
599         if ((ud == NULL) || (ud->data == NULL))
600         {
601                 ERROR ("mysql plugin: mysql_database_read: Invalid user data.");
602                 return (-1);
603         }
605         db = (mysql_database_t *) ud->data;
607         /* An error message will have been printed in this case */
608         if ((con = getconnection (db)) == NULL)
609                 return (-1);
611         query = "SHOW STATUS";
612         if (mysql_get_server_version (con) >= 50002)
613                 query = "SHOW GLOBAL STATUS";
615         res = exec_query (con, query);
616         if (res == NULL)
617                 return (-1);
619         field_num = mysql_num_fields (res);
620         while ((row = mysql_fetch_row (res)))
621         {
622                 char *key;
623                 unsigned long long val;
625                 key = row[0];
626                 val = atoll (row[1]);
628                 if (strncmp (key, "Com_", 
629                                   strlen ("Com_")) == 0)
630                 {
631                         if (val == 0ULL)
632                                 continue;
634                         /* Ignore `prepared statements' */
635                         if (strncmp (key, "Com_stmt_", strlen ("Com_stmt_")) != 0)
636                                 counter_submit ("mysql_commands", 
637                                                 key + strlen ("Com_"), 
638                                                 val, db);
639                 }
640                 else if (strncmp (key, "Handler_", 
641                                         strlen ("Handler_")) == 0)
642                 {
643                         if (val == 0ULL)
644                                 continue;
646                         counter_submit ("mysql_handler", 
647                                         key + strlen ("Handler_"), 
648                                         val, db);
649                 }
650                 else if (strncmp (key, "Qcache_",
651                                         strlen ("Qcache_")) == 0)
652                 {
653                         if (strcmp (key, "Qcache_hits") == 0)
654                                 qcache_hits = (derive_t) val;
655                         else if (strcmp (key, "Qcache_inserts") == 0)
656                                 qcache_inserts = (derive_t) val;
657                         else if (strcmp (key, "Qcache_not_cached") == 0)
658                                 qcache_not_cached = (derive_t) val;
659                         else if (strcmp (key, "Qcache_lowmem_prunes") == 0)
660                                 qcache_lowmem_prunes = (derive_t) val;
661                         else if (strcmp (key, "Qcache_queries_in_cache") == 0)
662                                 qcache_queries_in_cache = (gauge_t) val;
663                 }
664                 else if (strncmp (key, "Bytes_", 
665                                         strlen ("Bytes_")) == 0)
666                 {
667                         if (strcmp (key, "Bytes_received") == 0)
668                                 traffic_incoming += val;
669                         else if (strcmp (key, "Bytes_sent") == 0)
670                                 traffic_outgoing += val;
671                 }
672                 else if (strncmp (key, "Threads_", 
673                                         strlen ("Threads_")) == 0)
674                 {
675                         if (strcmp (key, "Threads_running") == 0)
676                                 threads_running = (int) val;
677                         else if (strcmp (key, "Threads_connected") == 0)
678                                 threads_connected = (int) val;
679                         else if (strcmp (key, "Threads_cached") == 0)
680                                 threads_cached = (int) val;
681                         else if (strcmp (key, "Threads_created") == 0)
682                                 threads_created = val;
683                 }
684                 else if (strncmp (key, "Table_locks_",
685                                         strlen ("Table_locks_")) == 0)
686                 {
687                         counter_submit ("mysql_locks",
688                                         key + strlen ("Table_locks_"),
689                                         val, db);
690                 }
691         }
692         mysql_free_result (res); res = NULL;
694         if ((qcache_hits != 0)
695                         || (qcache_inserts != 0)
696                         || (qcache_not_cached != 0)
697                         || (qcache_lowmem_prunes != 0))
698         {
699                 derive_submit ("cache_result", "qcache-hits",
700                                 qcache_hits, db);
701                 derive_submit ("cache_result", "qcache-inserts",
702                                 qcache_inserts, db);
703                 derive_submit ("cache_result", "qcache-not_cached",
704                                 qcache_not_cached, db);
705                 derive_submit ("cache_result", "qcache-prunes",
706                                 qcache_lowmem_prunes, db);
708                 gauge_submit ("cache_size", "qcache",
709                                 qcache_queries_in_cache, db);
710         }
712         if (threads_created != 0ULL)
713                 threads_submit (threads_running, threads_connected,
714                                 threads_cached, threads_created, db);
716         traffic_submit  (traffic_incoming, traffic_outgoing, db);
718         if (db->master_stats)
719                 mysql_read_master_stats (db, con);
721         if ((db->slave_stats) || (db->slave_notif))
722                 mysql_read_slave_stats (db, con);
724         return (0);
725 } /* int mysql_read */
727 void module_register (void)
729         plugin_register_complex_config ("mysql", mysql_config);
730 } /* void module_register */