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