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