Merge branch 'collectd-5.5'
[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 struct mysql_database_s /* {{{ */
42 {
43         char *instance;
44         char *alias;
45         char *host;
46         char *user;
47         char *pass;
48         char *database;
49         char *socket;
50         int   port;
51         int   timeout;
52
53         _Bool master_stats;
54         _Bool slave_stats;
55         _Bool innodb_stats;
56
57         _Bool slave_notif;
58         _Bool slave_io_running;
59         _Bool slave_sql_running;
60
61         MYSQL *con;
62         _Bool  is_connected;
63 };
64 typedef struct mysql_database_s mysql_database_t; /* }}} */
65
66 static int mysql_read (user_data_t *ud);
67
68 static void mysql_database_free (void *arg) /* {{{ */
69 {
70         mysql_database_t *db;
71
72         DEBUG ("mysql plugin: mysql_database_free (arg = %p);", arg);
73
74         db = (mysql_database_t *) arg;
75
76         if (db == NULL)
77                 return;
78
79         if (db->con != NULL)
80                 mysql_close (db->con);
81
82         sfree (db->alias);
83         sfree (db->host);
84         sfree (db->user);
85         sfree (db->pass);
86         sfree (db->socket);
87         sfree (db->instance);
88         sfree (db->database);
89         sfree (db);
90 } /* }}} void mysql_database_free */
91
92 /* Configuration handling functions {{{
93  *
94  * <Plugin mysql>
95  *   <Database "plugin_instance1">
96  *     Host "localhost"
97  *     Port 22000
98  *     ...
99  *   </Database>
100  * </Plugin>
101  */
102 static int mysql_config_database (oconfig_item_t *ci) /* {{{ */
103 {
104         mysql_database_t *db;
105         int status = 0;
106         int i;
107
108         if ((ci->values_num != 1)
109             || (ci->values[0].type != OCONFIG_TYPE_STRING))
110         {
111                 WARNING ("mysql plugin: The `Database' block "
112                          "needs exactly one string argument.");
113                 return (-1);
114         }
115
116         db = (mysql_database_t *) malloc (sizeof (*db));
117         if (db == NULL)
118         {
119                 ERROR ("mysql plugin: malloc failed.");
120                 return (-1);
121         }
122         memset (db, 0, sizeof (*db));
123
124         /* initialize all the pointers */
125         db->alias    = NULL;
126         db->host     = NULL;
127         db->user     = NULL;
128         db->pass     = NULL;
129         db->database = NULL;
130         db->socket   = NULL;
131         db->con      = NULL;
132         db->timeout  = 0;
133
134         /* trigger a notification, if it's not running */
135         db->slave_io_running  = 1;
136         db->slave_sql_running = 1;
137
138         status = cf_util_get_string (ci, &db->instance);
139         if (status != 0)
140         {
141                 sfree (db);
142                 return (status);
143         }
144         assert (db->instance != NULL);
145
146         /* Fill the `mysql_database_t' structure.. */
147         for (i = 0; i < ci->children_num; i++)
148         {
149                 oconfig_item_t *child = ci->children + i;
150
151                 if (strcasecmp ("Alias", child->key) == 0)
152                         status = cf_util_get_string (child, &db->alias);
153                 else if (strcasecmp ("Host", child->key) == 0)
154                         status = cf_util_get_string (child, &db->host);
155                 else if (strcasecmp ("User", child->key) == 0)
156                         status = cf_util_get_string (child, &db->user);
157                 else if (strcasecmp ("Password", child->key) == 0)
158                         status = cf_util_get_string (child, &db->pass);
159                 else if (strcasecmp ("Port", child->key) == 0)
160                 {
161                         status = cf_util_get_port_number (child);
162                         if (status > 0)
163                         {
164                                 db->port = status;
165                                 status = 0;
166                         }
167                 }
168                 else if (strcasecmp ("Socket", child->key) == 0)
169                         status = cf_util_get_string (child, &db->socket);
170                 else if (strcasecmp ("Database", child->key) == 0)
171                         status = cf_util_get_string (child, &db->database);
172                 else if (strcasecmp ("ConnectTimeout", child->key) == 0)
173                         status = cf_util_get_int (child, &db->timeout);
174                 else if (strcasecmp ("MasterStats", child->key) == 0)
175                         status = cf_util_get_boolean (child, &db->master_stats);
176                 else if (strcasecmp ("SlaveStats", child->key) == 0)
177                         status = cf_util_get_boolean (child, &db->slave_stats);
178                 else if (strcasecmp ("SlaveNotifications", child->key) == 0)
179                         status = cf_util_get_boolean (child, &db->slave_notif);
180                 else if (strcasecmp ("InnodbStats", child->key) == 0)
181                         status = cf_util_get_boolean (child, &db->innodb_stats);
182                 else
183                 {
184                         WARNING ("mysql plugin: Option `%s' not allowed here.", child->key);
185                         status = -1;
186                 }
187
188                 if (status != 0)
189                         break;
190         }
191
192         /* If all went well, register this database for reading */
193         if (status == 0)
194         {
195                 user_data_t ud;
196                 char cb_name[DATA_MAX_NAME_LEN];
197
198                 DEBUG ("mysql plugin: Registering new read callback: %s",
199                                 (db->database != NULL) ? db->database : "<default>");
200
201                 memset (&ud, 0, sizeof (ud));
202                 ud.data = (void *) db;
203                 ud.free_func = mysql_database_free;
204
205                 if (db->instance != NULL)
206                         ssnprintf (cb_name, sizeof (cb_name), "mysql-%s",
207                                         db->instance);
208                 else
209                         sstrncpy (cb_name, "mysql", sizeof (cb_name));
210
211                 plugin_register_complex_read (/* group = */ NULL, cb_name,
212                                               mysql_read,
213                                               /* interval = */ 0, &ud);
214         }
215         else
216         {
217                 mysql_database_free (db);
218                 return (-1);
219         }
220
221         return (0);
222 } /* }}} int mysql_config_database */
223
224 static int mysql_config (oconfig_item_t *ci) /* {{{ */
225 {
226         int i;
227
228         if (ci == NULL)
229                 return (EINVAL);
230
231         /* Fill the `mysql_database_t' structure.. */
232         for (i = 0; i < ci->children_num; i++)
233         {
234                 oconfig_item_t *child = ci->children + i;
235
236                 if (strcasecmp ("Database", child->key) == 0)
237                         mysql_config_database (child);
238                 else
239                         WARNING ("mysql plugin: Option \"%s\" not allowed here.",
240                                         child->key);
241         }
242
243         return (0);
244 } /* }}} int mysql_config */
245
246 /* }}} End of configuration handling functions */
247
248 static MYSQL *getconnection (mysql_database_t *db)
249 {
250         if (db->is_connected)
251         {
252                 int status;
253
254                 status = mysql_ping (db->con);
255                 if (status == 0)
256                         return (db->con);
257
258                 WARNING ("mysql plugin: Lost connection to instance \"%s\": %s",
259                                 db->instance, mysql_error (db->con));
260         }
261         db->is_connected = 0;
262
263         if (db->con == NULL)
264         {
265                 db->con = mysql_init (NULL);
266                 if (db->con == NULL)
267                 {
268                         ERROR ("mysql plugin: mysql_init failed: %s",
269                                         mysql_error (db->con));
270                         return (NULL);
271                 }
272         }
273
274         /* Configure TCP connect timeout (default: 0) */
275         db->con->options.connect_timeout = db->timeout;
276
277         if (mysql_real_connect (db->con, db->host, db->user, db->pass,
278                                 db->database, db->port, db->socket, 0) == NULL)
279         {
280                 ERROR ("mysql plugin: Failed to connect to database %s "
281                                 "at server %s: %s",
282                                 (db->database != NULL) ? db->database : "<none>",
283                                 (db->host != NULL) ? db->host : "localhost",
284                                 mysql_error (db->con));
285                 return (NULL);
286         }
287
288         INFO ("mysql plugin: Successfully connected to database %s "
289                         "at server %s (server version: %s, protocol version: %d)",
290                         (db->database != NULL) ? db->database : "<none>",
291                         mysql_get_host_info (db->con),
292                         mysql_get_server_info (db->con),
293                         mysql_get_proto_info (db->con));
294
295         db->is_connected = 1;
296         return (db->con);
297 } /* static MYSQL *getconnection (mysql_database_t *db) */
298
299 static void set_host (mysql_database_t *db, char *buf, size_t buflen)
300 {
301         if (db->alias)
302                 sstrncpy (buf, db->alias, buflen);
303         else if ((db->host == NULL)
304                         || (strcmp ("", db->host) == 0)
305                         || (strcmp ("127.0.0.1", db->host) == 0)
306                         || (strcmp ("localhost", db->host) == 0))
307                 sstrncpy (buf, hostname_g, buflen);
308         else
309                 sstrncpy (buf, db->host, buflen);
310 } /* void set_host */
311
312 static void submit (const char *type, const char *type_instance,
313                 value_t *values, size_t values_len, mysql_database_t *db)
314 {
315         value_list_t vl = VALUE_LIST_INIT;
316
317         vl.values     = values;
318         vl.values_len = values_len;
319
320         set_host (db, vl.host, sizeof (vl.host));
321
322         sstrncpy (vl.plugin, "mysql", sizeof (vl.plugin));
323
324         /* Assured by "mysql_config_database" */
325         assert (db->instance != NULL);
326         sstrncpy (vl.plugin_instance, db->instance, sizeof (vl.plugin_instance));
327
328         sstrncpy (vl.type, type, sizeof (vl.type));
329         if (type_instance != NULL)
330                 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
331
332         plugin_dispatch_values (&vl);
333 } /* submit */
334
335 static void counter_submit (const char *type, const char *type_instance,
336                 derive_t value, mysql_database_t *db)
337 {
338         value_t values[1];
339
340         values[0].derive = value;
341         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
342 } /* void counter_submit */
343
344 static void gauge_submit (const char *type, const char *type_instance,
345                 gauge_t value, mysql_database_t *db)
346 {
347         value_t values[1];
348
349         values[0].gauge = value;
350         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
351 } /* void gauge_submit */
352
353 static void derive_submit (const char *type, const char *type_instance,
354                 derive_t value, mysql_database_t *db)
355 {
356         value_t values[1];
357
358         values[0].derive = value;
359         submit (type, type_instance, values, STATIC_ARRAY_SIZE (values), db);
360 } /* void derive_submit */
361
362 static void traffic_submit (derive_t rx, derive_t tx, mysql_database_t *db)
363 {
364         value_t values[2];
365
366         values[0].derive = rx;
367         values[1].derive = tx;
368
369         submit ("mysql_octets", NULL, values, STATIC_ARRAY_SIZE (values), db);
370 } /* void traffic_submit */
371
372 static MYSQL_RES *exec_query (MYSQL *con, const char *query)
373 {
374         MYSQL_RES *res;
375
376         int query_len = strlen (query);
377
378         if (mysql_real_query (con, query, query_len))
379         {
380                 ERROR ("mysql plugin: Failed to execute query: %s",
381                                 mysql_error (con));
382                 INFO ("mysql plugin: SQL query was: %s", query);
383                 return (NULL);
384         }
385
386         res = mysql_store_result (con);
387         if (res == NULL)
388         {
389                 ERROR ("mysql plugin: Failed to store query result: %s",
390                                 mysql_error (con));
391                 INFO ("mysql plugin: SQL query was: %s", query);
392                 return (NULL);
393         }
394
395         return (res);
396 } /* exec_query */
397
398 static int mysql_read_master_stats (mysql_database_t *db, MYSQL *con)
399 {
400         MYSQL_RES *res;
401         MYSQL_ROW  row;
402
403         const char *query;
404         int         field_num;
405         unsigned long long position;
406
407         query = "SHOW MASTER STATUS";
408
409         res = exec_query (con, query);
410         if (res == NULL)
411                 return (-1);
412
413         row = mysql_fetch_row (res);
414         if (row == NULL)
415         {
416                 ERROR ("mysql plugin: Failed to get master statistics: "
417                                 "`%s' did not return any rows.", query);
418                 mysql_free_result (res);
419                 return (-1);
420         }
421
422         field_num = mysql_num_fields (res);
423         if (field_num < 2)
424         {
425                 ERROR ("mysql plugin: Failed to get master statistics: "
426                                 "`%s' returned less than two columns.", query);
427                 mysql_free_result (res);
428                 return (-1);
429         }
430
431         position = atoll (row[1]);
432         counter_submit ("mysql_log_position", "master-bin", position, db);
433
434         row = mysql_fetch_row (res);
435         if (row != NULL)
436                 WARNING ("mysql plugin: `%s' returned more than one row - "
437                                 "ignoring further results.", query);
438
439         mysql_free_result (res);
440
441         return (0);
442 } /* mysql_read_master_stats */
443
444 static int mysql_read_slave_stats (mysql_database_t *db, MYSQL *con)
445 {
446         MYSQL_RES *res;
447         MYSQL_ROW  row;
448
449         const char *query;
450         int         field_num;
451
452         /* WTF? libmysqlclient does not seem to provide any means to
453          * translate a column name to a column index ... :-/ */
454         const int READ_MASTER_LOG_POS_IDX   = 6;
455         const int SLAVE_IO_RUNNING_IDX      = 10;
456         const int SLAVE_SQL_RUNNING_IDX     = 11;
457         const int EXEC_MASTER_LOG_POS_IDX   = 21;
458         const int SECONDS_BEHIND_MASTER_IDX = 32;
459
460         query = "SHOW SLAVE STATUS";
461
462         res = exec_query (con, query);
463         if (res == NULL)
464                 return (-1);
465
466         row = mysql_fetch_row (res);
467         if (row == NULL)
468         {
469                 ERROR ("mysql plugin: Failed to get slave statistics: "
470                                 "`%s' did not return any rows.", query);
471                 mysql_free_result (res);
472                 return (-1);
473         }
474
475         field_num = mysql_num_fields (res);
476         if (field_num < 33)
477         {
478                 ERROR ("mysql plugin: Failed to get slave statistics: "
479                                 "`%s' returned less than 33 columns.", query);
480                 mysql_free_result (res);
481                 return (-1);
482         }
483
484         if (db->slave_stats)
485         {
486                 unsigned long long counter;
487                 double gauge;
488
489                 counter = atoll (row[READ_MASTER_LOG_POS_IDX]);
490                 counter_submit ("mysql_log_position", "slave-read", counter, db);
491
492                 counter = atoll (row[EXEC_MASTER_LOG_POS_IDX]);
493                 counter_submit ("mysql_log_position", "slave-exec", counter, db);
494
495                 if (row[SECONDS_BEHIND_MASTER_IDX] != NULL)
496                 {
497                         gauge = atof (row[SECONDS_BEHIND_MASTER_IDX]);
498                         gauge_submit ("time_offset", NULL, gauge, db);
499                 }
500         }
501
502         if (db->slave_notif)
503         {
504                 notification_t n = { 0, cdtime (), "", "",
505                         "mysql", "", "time_offset", "", NULL };
506
507                 char *io, *sql;
508
509                 io  = row[SLAVE_IO_RUNNING_IDX];
510                 sql = row[SLAVE_SQL_RUNNING_IDX];
511
512                 set_host (db, n.host, sizeof (n.host));
513
514                 /* Assured by "mysql_config_database" */
515                 assert (db->instance != NULL);
516                 sstrncpy (n.plugin_instance, db->instance, sizeof (n.plugin_instance));
517
518                 if (((io == NULL) || (strcasecmp (io, "yes") != 0))
519                                 && (db->slave_io_running))
520                 {
521                         n.severity = NOTIF_WARNING;
522                         ssnprintf (n.message, sizeof (n.message),
523                                         "slave I/O thread not started or not connected to master");
524                         plugin_dispatch_notification (&n);
525                         db->slave_io_running = 0;
526                 }
527                 else if (((io != NULL) && (strcasecmp (io, "yes") == 0))
528                                 && (! db->slave_io_running))
529                 {
530                         n.severity = NOTIF_OKAY;
531                         ssnprintf (n.message, sizeof (n.message),
532                                         "slave I/O thread started and connected to master");
533                         plugin_dispatch_notification (&n);
534                         db->slave_io_running = 1;
535                 }
536
537                 if (((sql == NULL) || (strcasecmp (sql, "yes") != 0))
538                                 && (db->slave_sql_running))
539                 {
540                         n.severity = NOTIF_WARNING;
541                         ssnprintf (n.message, sizeof (n.message),
542                                         "slave SQL thread not started");
543                         plugin_dispatch_notification (&n);
544                         db->slave_sql_running = 0;
545                 }
546                 else if (((sql != NULL) && (strcasecmp (sql, "yes") == 0))
547                                 && (! db->slave_sql_running))
548                 {
549                         n.severity = NOTIF_OKAY;
550                         ssnprintf (n.message, sizeof (n.message),
551                                         "slave SQL thread started");
552                         plugin_dispatch_notification (&n);
553                         db->slave_sql_running = 1;
554                 }
555         }
556
557         row = mysql_fetch_row (res);
558         if (row != NULL)
559                 WARNING ("mysql plugin: `%s' returned more than one row - "
560                                 "ignoring further results.", query);
561
562         mysql_free_result (res);
563
564         return (0);
565 } /* mysql_read_slave_stats */
566
567 static int mysql_read_innodb_stats (mysql_database_t *db, MYSQL *con)
568 {
569         MYSQL_RES *res;
570         MYSQL_ROW  row;
571
572         const char *query;
573         struct {
574                 const char *key;
575                 const char *type;
576                 int ds_type;
577         } metrics[] = {
578                 { "metadata_mem_pool_size",          "bytes",        DS_TYPE_GAUGE },
579                 { "lock_deadlocks",                  "mysql_locks",  DS_TYPE_DERIVE },
580                 { "lock_timeouts",                   "mysql_locks",  DS_TYPE_DERIVE },
581                 { "lock_row_lock_current_waits",     "mysql_locks",  DS_TYPE_DERIVE },
582                 { "buffer_pool_size",                "bytes",        DS_TYPE_GAUGE },
583
584                 { "buffer_pool_reads",               "operations",   DS_TYPE_DERIVE },
585                 { "buffer_pool_read_requests",       "operations",   DS_TYPE_DERIVE },
586                 { "buffer_pool_write_requests",      "operations",   DS_TYPE_DERIVE },
587                 { "buffer_pool_wait_free",           "operations",   DS_TYPE_DERIVE },
588                 { "buffer_pool_read_ahead",          "operations",   DS_TYPE_DERIVE },
589                 { "buffer_pool_read_ahead_evicted",  "operations",   DS_TYPE_DERIVE },
590
591                 { "buffer_pool_pages_total",         "gauge",        DS_TYPE_GAUGE },
592                 { "buffer_pool_pages_misc",          "gauge",        DS_TYPE_GAUGE },
593                 { "buffer_pool_pages_data",          "gauge",        DS_TYPE_GAUGE },
594                 { "buffer_pool_bytes_data",          "gauge",        DS_TYPE_GAUGE },
595                 { "buffer_pool_pages_dirty",         "gauge",        DS_TYPE_GAUGE },
596                 { "buffer_pool_bytes_dirty",         "gauge",        DS_TYPE_GAUGE },
597                 { "buffer_pool_pages_free",          "gauge",        DS_TYPE_GAUGE },
598
599                 { "buffer_pages_created",            "operations",   DS_TYPE_DERIVE },
600                 { "buffer_pages_written",            "operations",   DS_TYPE_DERIVE },
601                 { "buffer_pages_read",               "operations",   DS_TYPE_DERIVE },
602                 { "buffer_data_reads",               "operations",   DS_TYPE_DERIVE },
603                 { "buffer_data_written",             "operations",   DS_TYPE_DERIVE },
604
605                 { "os_data_reads",                   "operations",   DS_TYPE_DERIVE },
606                 { "os_data_writes",                  "operations",   DS_TYPE_DERIVE },
607                 { "os_data_fsyncs",                  "operations",   DS_TYPE_DERIVE },
608                 { "os_log_bytes_written",            "operations",   DS_TYPE_DERIVE },
609                 { "os_log_fsyncs",                   "operations",   DS_TYPE_DERIVE },
610                 { "os_log_pending_fsyncs",           "operations",   DS_TYPE_DERIVE },
611                 { "os_log_pending_writes",           "operations",   DS_TYPE_DERIVE },
612
613                 { "trx_rseg_history_len",            "gauge",        DS_TYPE_GAUGE },
614
615                 { "log_waits",                       "operations",   DS_TYPE_DERIVE },
616                 { "log_write_requests",              "operations",   DS_TYPE_DERIVE },
617                 { "log_writes",                      "operations",   DS_TYPE_DERIVE },
618                 { "adaptive_hash_searches",          "operations",   DS_TYPE_DERIVE },
619
620                 { "file_num_open_files",             "gauge",        DS_TYPE_GAUGE },
621
622                 { "ibuf_merges_insert",              "operations",   DS_TYPE_DERIVE },
623                 { "ibuf_merges_delete_mark",         "operations",   DS_TYPE_DERIVE },
624                 { "ibuf_merges_delete",              "operations",   DS_TYPE_DERIVE },
625                 { "ibuf_merges_discard_insert",      "operations",   DS_TYPE_DERIVE },
626                 { "ibuf_merges_discard_delete_mark", "operations",   DS_TYPE_DERIVE },
627                 { "ibuf_merges_discard_delete",      "operations",   DS_TYPE_DERIVE },
628                 { "ibuf_merges_discard_merges",      "operations",   DS_TYPE_DERIVE },
629                 { "ibuf_size",                       "bytes",        DS_TYPE_GAUGE },
630
631                 { "innodb_activity_count",           "gauge",        DS_TYPE_GAUGE },
632                 { "innodb_dblwr_writes",             "operations",   DS_TYPE_DERIVE },
633                 { "innodb_dblwr_pages_written",      "operations",   DS_TYPE_DERIVE },
634                 { "innodb_dblwr_page_size",          "gauge",        DS_TYPE_GAUGE },
635
636                 { "innodb_rwlock_s_spin_waits",      "operations",   DS_TYPE_DERIVE },
637                 { "innodb_rwlock_x_spin_waits",      "operations",   DS_TYPE_DERIVE },
638                 { "innodb_rwlock_s_spin_rounds",     "operations",   DS_TYPE_DERIVE },
639                 { "innodb_rwlock_x_spin_rounds",     "operations",   DS_TYPE_DERIVE },
640                 { "innodb_rwlock_s_os_waits",        "operations",   DS_TYPE_DERIVE },
641                 { "innodb_rwlock_x_os_waits",        "operations",   DS_TYPE_DERIVE },
642
643                 { "dml_reads",                       "operations",   DS_TYPE_DERIVE },
644                 { "dml_inserts",                     "operations",   DS_TYPE_DERIVE },
645                 { "dml_deletes",                     "operations",   DS_TYPE_DERIVE },
646                 { "dml_updates",                     "operations",   DS_TYPE_DERIVE },
647
648                 { NULL,                              NULL,           0}
649         };
650
651         query = "SELECT name, count, type FROM information_schema.innodb_metrics WHERE status = 'enabled'";
652
653         res = exec_query (con, query);
654         if (res == NULL)
655                 return (-1);
656
657         while ((row = mysql_fetch_row (res)))
658         {
659                 int i;
660                 char *key;
661                 unsigned long long val;
662
663                 key = row[0];
664                 val = atoll (row[1]);
665
666                 for (i = 0; metrics[i].key != NULL && strcmp(metrics[i].key, key) != 0; i++)
667                         ;
668
669                 if (metrics[i].key == NULL)
670                         continue;
671
672                 switch (metrics[i].ds_type) {
673                         case DS_TYPE_COUNTER:
674                                 counter_submit(metrics[i].type, key, (counter_t)val, db);
675                                 break;
676                         case DS_TYPE_GAUGE:
677                                 gauge_submit(metrics[i].type, key, (gauge_t)val, db);
678                                 break;
679                         case DS_TYPE_DERIVE:
680                                 derive_submit(metrics[i].type, key, (derive_t)val, db);
681                                 break;
682                 }
683         }
684
685         mysql_free_result(res);
686         return (0);
687 }
688
689 static int mysql_read (user_data_t *ud)
690 {
691         mysql_database_t *db;
692         MYSQL      *con;
693         MYSQL_RES  *res;
694         MYSQL_ROW   row;
695         const char *query;
696
697         derive_t qcache_hits          = 0;
698         derive_t qcache_inserts       = 0;
699         derive_t qcache_not_cached    = 0;
700         derive_t qcache_lowmem_prunes = 0;
701         gauge_t qcache_queries_in_cache = NAN;
702
703         gauge_t threads_running   = NAN;
704         gauge_t threads_connected = NAN;
705         gauge_t threads_cached    = NAN;
706         derive_t threads_created = 0;
707
708         unsigned long long traffic_incoming = 0ULL;
709         unsigned long long traffic_outgoing = 0ULL;
710         unsigned long mysql_version = 0ULL;
711
712         if ((ud == NULL) || (ud->data == NULL))
713         {
714                 ERROR ("mysql plugin: mysql_database_read: Invalid user data.");
715                 return (-1);
716         }
717
718         db = (mysql_database_t *) ud->data;
719
720         /* An error message will have been printed in this case */
721         if ((con = getconnection (db)) == NULL)
722                 return (-1);
723
724         mysql_version = mysql_get_server_version(con);
725
726         query = "SHOW STATUS";
727         if (mysql_version >= 50002)
728                 query = "SHOW GLOBAL STATUS";
729
730         res = exec_query (con, query);
731         if (res == NULL)
732                 return (-1);
733
734         while ((row = mysql_fetch_row (res)))
735         {
736                 char *key;
737                 unsigned long long val;
738
739                 key = row[0];
740                 val = atoll (row[1]);
741
742                 if (strncmp (key, "Com_", 
743                                   strlen ("Com_")) == 0)
744                 {
745                         if (val == 0ULL)
746                                 continue;
747
748                         /* Ignore `prepared statements' */
749                         if (strncmp (key, "Com_stmt_", strlen ("Com_stmt_")) != 0)
750                                 counter_submit ("mysql_commands", 
751                                                 key + strlen ("Com_"), 
752                                                 val, db);
753                 }
754                 else if (strncmp (key, "Handler_", 
755                                         strlen ("Handler_")) == 0)
756                 {
757                         if (val == 0ULL)
758                                 continue;
759
760                         counter_submit ("mysql_handler", 
761                                         key + strlen ("Handler_"), 
762                                         val, db);
763                 }
764                 else if (strncmp (key, "Qcache_",
765                                         strlen ("Qcache_")) == 0)
766                 {
767                         if (strcmp (key, "Qcache_hits") == 0)
768                                 qcache_hits = (derive_t) val;
769                         else if (strcmp (key, "Qcache_inserts") == 0)
770                                 qcache_inserts = (derive_t) val;
771                         else if (strcmp (key, "Qcache_not_cached") == 0)
772                                 qcache_not_cached = (derive_t) val;
773                         else if (strcmp (key, "Qcache_lowmem_prunes") == 0)
774                                 qcache_lowmem_prunes = (derive_t) val;
775                         else if (strcmp (key, "Qcache_queries_in_cache") == 0)
776                                 qcache_queries_in_cache = (gauge_t) val;
777                 }
778                 else if (strncmp (key, "Bytes_", 
779                                         strlen ("Bytes_")) == 0)
780                 {
781                         if (strcmp (key, "Bytes_received") == 0)
782                                 traffic_incoming += val;
783                         else if (strcmp (key, "Bytes_sent") == 0)
784                                 traffic_outgoing += val;
785                 }
786                 else if (strncmp (key, "Threads_", 
787                                         strlen ("Threads_")) == 0)
788                 {
789                         if (strcmp (key, "Threads_running") == 0)
790                                 threads_running = (gauge_t) val;
791                         else if (strcmp (key, "Threads_connected") == 0)
792                                 threads_connected = (gauge_t) val;
793                         else if (strcmp (key, "Threads_cached") == 0)
794                                 threads_cached = (gauge_t) val;
795                         else if (strcmp (key, "Threads_created") == 0)
796                                 threads_created = (derive_t) val;
797                 }
798                 else if (strncmp (key, "Table_locks_",
799                                         strlen ("Table_locks_")) == 0)
800                 {
801                         counter_submit ("mysql_locks",
802                                         key + strlen ("Table_locks_"),
803                                         val, db);
804                 }
805                 else if (db->innodb_stats && strncmp (key, "Innodb_", strlen ("Innodb_")) == 0)
806                 {
807                         /* buffer pool */
808                         if (strcmp (key, "Innodb_buffer_pool_pages_data") == 0)
809                                 gauge_submit ("mysql_bpool_pages", "data", val, db);
810                         else if (strcmp (key, "Innodb_buffer_pool_pages_dirty") == 0)
811                                 gauge_submit ("mysql_bpool_pages", "dirty", val, db);
812                         else if (strcmp (key, "Innodb_buffer_pool_pages_flushed") == 0)
813                                 counter_submit ("mysql_bpool_counters", "pages_flushed", val, db);
814                         else if (strcmp (key, "Innodb_buffer_pool_pages_free") == 0)
815                                 gauge_submit ("mysql_bpool_pages", "free", val, db);
816                         else if (strcmp (key, "Innodb_buffer_pool_pages_misc") == 0)
817                                 gauge_submit ("mysql_bpool_pages", "misc", val, db);
818                         else if (strcmp (key, "Innodb_buffer_pool_pages_total") == 0)
819                                 gauge_submit ("mysql_bpool_pages", "total", val, db);
820                         else if (strcmp (key, "Innodb_buffer_pool_read_ahead_rnd") == 0)
821                                 counter_submit ("mysql_bpool_counters", "read_ahead_rnd", val, db);
822                         else if (strcmp (key, "Innodb_buffer_pool_read_ahead") == 0)
823                                 counter_submit ("mysql_bpool_counters", "read_ahead", val, db);
824                         else if (strcmp (key, "Innodb_buffer_pool_read_ahead_evicted") == 0)
825                                 counter_submit ("mysql_bpool_counters", "read_ahead_evicted", val, db);
826                         else if (strcmp (key, "Innodb_buffer_pool_read_requests") == 0)
827                                 counter_submit ("mysql_bpool_counters", "read_requests", val, db);
828                         else if (strcmp (key, "Innodb_buffer_pool_reads") == 0)
829                                 counter_submit ("mysql_bpool_counters", "reads", val, db);
830                         else if (strcmp (key, "Innodb_buffer_pool_write_requests") == 0)
831                                 counter_submit ("mysql_bpool_counters", "write_requests", val, db);
832                         else if (strcmp (key, "Innodb_buffer_pool_bytes_data") == 0)
833                                 gauge_submit ("mysql_bpool_bytes", "data", val, db);
834                         else if (strcmp (key, "Innodb_buffer_pool_bytes_dirty") == 0)
835                                 gauge_submit ("mysql_bpool_bytes", "dirty", val, db);
836
837                         /* data */
838                         if (strcmp (key, "Innodb_data_fsyncs") == 0)
839                                 counter_submit ("mysql_innodb_data", "fsyncs", val, db);
840                         else if (strcmp (key, "Innodb_data_read") == 0)
841                                 counter_submit ("mysql_innodb_data", "read", val, db);
842                         else if (strcmp (key, "Innodb_data_reads") == 0)
843                                 counter_submit ("mysql_innodb_data", "reads", val, db);
844                         else if (strcmp (key, "Innodb_data_writes") == 0)
845                                 counter_submit ("mysql_innodb_data", "writes", val, db);
846                         else if (strcmp (key, "Innodb_data_written") == 0)
847                                 counter_submit ("mysql_innodb_data", "written", val, db);
848
849                         /* double write */
850                         else if (strcmp (key, "Innodb_dblwr_writes") == 0)
851                                 counter_submit ("mysql_innodb_dblwr", "writes", val, db);
852                         else if (strcmp (key, "Innodb_dblwr_pages_written") == 0)
853                                 counter_submit ("mysql_innodb_dblwr", "written", val, db);
854
855                         /* log */
856                         else if (strcmp (key, "Innodb_log_waits") == 0)
857                                 counter_submit ("mysql_innodb_log", "waits", val, db);
858                         else if (strcmp (key, "Innodb_log_write_requests") == 0)
859                                 counter_submit ("mysql_innodb_log", "write_requests", val, db);
860                         else if (strcmp (key, "Innodb_log_writes") == 0)
861                                 counter_submit ("mysql_innodb_log", "writes", val, db);
862                         else if (strcmp (key, "Innodb_os_log_fsyncs") == 0)
863                                 counter_submit ("mysql_innodb_log", "fsyncs", val, db);
864                         else if (strcmp (key, "Innodb_os_log_written") == 0)
865                                 counter_submit ("mysql_innodb_log", "written", val, db);
866
867                         /* pages */
868                         else if (strcmp (key, "Innodb_pages_created") == 0)
869                                 counter_submit ("mysql_innodb_pages", "created", val, db);
870                         else if (strcmp (key, "Innodb_pages_read") == 0)
871                                 counter_submit ("mysql_innodb_pages", "read", val, db);
872                         else if (strcmp (key, "Innodb_pages_written") == 0)
873                                 counter_submit ("mysql_innodb_pages", "written", val, db);
874
875                         /* row lock */
876                         else if (strcmp (key, "Innodb_row_lock_time") == 0)
877                                 counter_submit ("mysql_innodb_row_lock", "time", val, db);
878                         else if (strcmp (key, "Innodb_row_lock_waits") == 0)
879                                 counter_submit ("mysql_innodb_row_lock", "waits", val, db);
880
881                         /* rows */
882                         else if (strcmp (key, "Innodb_rows_deleted") == 0)
883                                 counter_submit ("mysql_innodb_rows", "deleted", val, db);
884                         else if (strcmp (key, "Innodb_rows_inserted") == 0)
885                                 counter_submit ("mysql_innodb_rows", "inserted", val, db);
886                         else if (strcmp (key, "Innodb_rows_read") == 0)
887                                 counter_submit ("mysql_innodb_rows", "read", val, db);
888                         else if (strcmp (key, "Innodb_rows_updated") == 0)
889                                 counter_submit ("mysql_innodb_rows", "updated", val, db);
890                 }
891                 else if (strncmp (key, "Select_", strlen ("Select_")) == 0)
892                 {
893                         counter_submit ("mysql_select", key + strlen ("Select_"),
894                                         val, db);
895                 }
896                 else if (strncmp (key, "Sort_", strlen ("Sort_")) == 0)
897                 {
898                         counter_submit ("mysql_sort", key + strlen ("Sort_"),
899                                         val, db);
900                 }
901         }
902         mysql_free_result (res); res = NULL;
903
904         if ((qcache_hits != 0)
905                         || (qcache_inserts != 0)
906                         || (qcache_not_cached != 0)
907                         || (qcache_lowmem_prunes != 0))
908         {
909                 derive_submit ("cache_result", "qcache-hits",
910                                 qcache_hits, db);
911                 derive_submit ("cache_result", "qcache-inserts",
912                                 qcache_inserts, db);
913                 derive_submit ("cache_result", "qcache-not_cached",
914                                 qcache_not_cached, db);
915                 derive_submit ("cache_result", "qcache-prunes",
916                                 qcache_lowmem_prunes, db);
917
918                 gauge_submit ("cache_size", "qcache",
919                                 qcache_queries_in_cache, db);
920         }
921
922         if (threads_created != 0)
923         {
924                 gauge_submit ("threads", "running",
925                                 threads_running, db);
926                 gauge_submit ("threads", "connected",
927                                 threads_connected, db);
928                 gauge_submit ("threads", "cached",
929                                 threads_cached, db);
930
931                 derive_submit ("total_threads", "created",
932                                 threads_created, db);
933         }
934
935         traffic_submit  (traffic_incoming, traffic_outgoing, db);
936
937         if (mysql_version >= 50600 && db->innodb_stats)
938                 mysql_read_innodb_stats (db, con);
939
940         if (db->master_stats)
941                 mysql_read_master_stats (db, con);
942
943         if ((db->slave_stats) || (db->slave_notif))
944                 mysql_read_slave_stats (db, con);
945
946         return (0);
947 } /* int mysql_read */
948
949 void module_register (void)
950 {
951         plugin_register_complex_config ("mysql", mysql_config);
952 } /* void module_register */