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