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