]> arthur.barton.de Git - netdata.git/blob - python.d/mysql.chart.py
better debug messages. don't require specific python version
[netdata.git] / python.d / mysql.chart.py
1 # Description: MySQL netdata python.d plugin
2 # Author: Pawel Krupa (paulfantom)
3
4 import sys
5
6 NAME = "mysql.chart.py"
7
8 # import 3rd party library to handle MySQL communication
9 try:
10     import MySQLdb
11
12     # https://github.com/PyMySQL/mysqlclient-python
13     sys.stderr.write(NAME + ": using MySQLdb\n")
14 except ImportError:
15     try:
16         import pymysql as MySQLdb
17
18         # https://github.com/PyMySQL/PyMySQL
19         sys.stderr.write(NAME + ": using pymysql\n")
20     except ImportError:
21         sys.stderr.write(NAME + ": You need to install MySQLdb or PyMySQL module to use mysql.chart.py plugin\n")
22         raise ImportError
23
24 from base import BaseService
25
26 # default configuration (overridden by python.d.plugin)
27 config = {
28     'local': {
29         'user': 'root',
30         'password': '',
31         'socket': '/var/run/mysqld/mysqld.sock',
32         'update_every': 3,
33         'retries': 4,
34         'priority': 100
35     }
36 }
37
38 # default module values (can be overridden per job in `config`)
39 update_every = 3
40 priority = 90000
41 retries = 7
42
43 # query executed on MySQL server
44 QUERY = "SHOW GLOBAL STATUS"
45
46 # charts order (can be overridden if you want less charts, or different order)
47 ORDER = ['net',
48          'queries',
49          'handlers',
50          'table_locks',
51          'join_issues',
52          'sort_issues',
53          'tmp',
54          'connections',
55          'binlog_cache',
56          'threads',
57          'thread_cache_misses',
58          'innodb_io',
59          'innodb_io_ops',
60          'innodb_io_pending_ops',
61          'innodb_log',
62          'innodb_os_log',
63          'innodb_os_log_io',
64          'innodb_cur_row_lock',
65          'innodb_rows',
66          'innodb_buffer_pool_pages',
67          'innodb_buffer_pool_bytes',
68          'innodb_buffer_pool_read_ahead',
69          'innodb_buffer_pool_reqs',
70          'innodb_buffer_pool_ops',
71          'qcache_ops',
72          'qcache',
73          'qcache_freemem',
74          'qcache_memblocks',
75          'key_blocks',
76          'key_requests',
77          'key_disk_ops',
78          'files',
79          'files_rate',
80          'binlog_stmt_cache',
81          'connection_errors']
82
83 # charts definitions in format:
84 # CHARTS = {
85 #    'chart_name_in_netdata': (
86 #        "parameters defining chart (passed to CHART statement)",
87 #        [ # dimensions (lines) definitions
88 #            ("dimension_name", "dimension parameters (passed to DIMENSION statement)")
89 #        ])
90 #    }
91
92 CHARTS = {
93     'net': (
94         "'' 'mysql Bandwidth' 'kilobits/s' bandwidth mysql.net area",
95         [
96             ("Bytes_received", "in incremental 8 1024"),
97             ("Bytes_sent", "out incremental -8 1024")
98         ]),
99     'queries': (
100         "'' 'mysql Queries' 'queries/s' queries mysql.queries line",
101         [
102             ("Queries", "queries incremental 1 1"),
103             ("Questions", "questions incremental 1 1"),
104             ("Slow_queries", "slow_queries incremental -1 1")
105         ]),
106     'handlers': (
107         "'' 'mysql Handlers' 'handlers/s' handlers mysql.handlers line",
108         [
109             ("Handler_commit", "commit incremental 1 1"),
110             ("Handler_delete", "delete incremental 1 1"),
111             ("Handler_prepare", "prepare incremental 1 1"),
112             ("Handler_read_first", "read_first incremental 1 1"),
113             ("Handler_read_key", "read_key incremental 1 1"),
114             ("Handler_read_next", "read_next incremental 1 1"),
115             ("Handler_read_prev", "read_prev incremental 1 1"),
116             ("Handler_read_rnd", "read_rnd incremental 1 1"),
117             ("Handler_read_rnd_next", "read_rnd_next incremental 1 1"),
118             ("Handler_rollback", "rollback incremental 1 1"),
119             ("Handler_savepoint", "savepoint incremental 1 1"),
120             ("Handler_savepoint_rollback", "savepoint_rollback incremental 1 1"),
121             ("Handler_update", "update incremental 1 1"),
122             ("Handler_write", "write incremental 1 1")
123         ]),
124     'table_locks': (
125         "'' 'mysql Tables Locks' 'locks/s' locks mysql.table_locks line",
126         [
127             ("Table_locks_immediate", "immediate incremental 1 1"),
128             ("Table_locks_waited", "waited incremental -1 1")
129         ]),
130     'join_issues': (
131         "'' 'mysql Select Join Issues' 'joins/s' issues mysql.join_issues line",
132         [
133             ("Select_full_join", "full_join incremental 1 1"),
134             ("Select_full_range_join", "full_range_join incremental 1 1"),
135             ("Select_range", "range incremental 1 1"),
136             ("Select_range_check", "range_check incremental 1 1"),
137             ("Select_scan", "scan incremental 1 1"),
138         ]),
139     'sort_issues': (
140         "'' 'mysql Sort Issues' 'issues/s' issues mysql.sort.issues line",
141         [
142             ("Sort_merge_passes", "merge_passes incremental 1 1"),
143             ("Sort_range", "range incremental 1 1"),
144             ("Sort_scan", "scan incremental 1 1"),
145         ]),
146     'tmp': (
147         "'' 'mysql Tmp Operations' 'counter' temporaries mysql.tmp line",
148         [
149             ("Created_tmp_disk_tables", "disk_tables incremental 1 1"),
150             ("Created_tmp_files", "files incremental 1 1"),
151             ("Created_tmp_tables", "tables incremental 1 1"),
152         ]),
153     'connections': (
154         "'' 'mysql Connections' 'connections/s' connections mysql.connections line",
155         [
156             ("Connections", "all incremental 1 1"),
157             ("Aborted_connects", "aborted incremental 1 1"),
158         ]),
159     'binlog_cache': (
160         "'' 'mysql Binlog Cache' 'transactions/s' binlog mysql.binlog_cache line",
161         [
162             ("Binlog_cache_disk_use", "disk incremental 1 1"),
163             ("Binlog_cache_use", "all incremental 1 1"),
164         ]),
165     'threads': (
166         "'' 'mysql Threads' 'threads' threads mysql.threads line",
167         [
168             ("Threads_connected", "connected absolute 1 1"),
169             ("Threads_created", "created incremental 1 1"),
170             ("Threads_cached", "cached absolute -1 1"),
171             ("Threads_running", "running absolute 1 1"),
172         ]),
173     'thread_cache_misses': (
174         "'' 'mysql Threads Cache Misses' 'misses' threads mysql.thread_cache_misses area",
175         [
176             ("Thread_cache_misses", "misses misses absolute 1 100"),
177         ]),
178     'innodb_io': (
179         "'' 'mysql InnoDB I/O Bandwidth' 'kilobytes/s' innodb mysql.innodb_io area",
180         [
181             ("Innodb_data_read", "read incremental 1 1024"),
182             ("Innodb_data_written", "write incremental -1 1024"),
183         ]),
184     'innodb_io_ops': (
185         "'' 'mysql InnoDB I/O Operations' 'operations/s' innodb mysql.innodb_io_ops line",
186         [
187             ("Innodb_data_reads", "reads incremental 1 1"),
188             ("Innodb_data_writes", "writes incremental -1 1"),
189             ("Innodb_data_fsyncs", "fsyncs incremental 1 1"),
190         ]),
191     'innodb_io_pending_ops': (
192         "'' 'mysql InnoDB Pending I/O Operations' 'operations' innodb mysql.innodb_io_pending_ops line",
193         [
194             ("Innodb_data_pending_reads", "reads absolute 1 1"),
195             ("Innodb_data_pending_writes", "writes absolute -1 1"),
196             ("Innodb_data_pending_fsyncs", "fsyncs absolute 1 1"),
197         ]),
198     'innodb_log': (
199         "'' 'mysql InnoDB Log Operations' 'operations/s' innodb mysql.innodb_log line",
200         [
201             ("Innodb_log_waits", "waits incremental 1 1"),
202             ("Innodb_log_write_requests", "write_requests incremental -1 1"),
203             ("Innodb_log_writes", "incremental -1 1"),
204         ]),
205     'innodb_os_log': (
206         "'' 'mysql InnoDB OS Log Operations' 'operations' innodb mysql.innodb_os_log line",
207         [
208             ("Innodb_os_log_fsyncs", "fsyncs incremental 1 1"),
209             ("Innodb_os_log_pending_fsyncs", "pending_fsyncs absolute 1 1"),
210             ("Innodb_os_log_pending_writes", "pending_writes absolute -1 1"),
211         ]),
212     'innodb_os_log_io': (
213         "'' 'mysql InnoDB OS Log Bandwidth' 'kilobytes/s' innodb mysql.innodb_os_log_io area",
214         [
215             ("Innodb_os_log_written", "write incremental -1 1024"),
216         ]),
217     'innodb_cur_row_lock': (
218         "'' 'mysql InnoDB Current Row Locks' 'operations' innodb mysql.innodb_cur_row_lock area",
219         [
220             ("Innodb_row_lock_current_waits", "current_waits absolute 1 1"),
221         ]),
222     'innodb_rows': (
223         "'' 'mysql InnoDB Row Operations' 'operations/s' innodb mysql.innodb_rows area",
224         [
225             ("Innodb_rows_inserted", "read incremental 1 1"),
226             ("Innodb_rows_read", "deleted incremental -1 1"),
227             ("Innodb_rows_updated", "inserted incremental 1 1"),
228             ("Innodb_rows_deleted", "updated incremental -1 1"),
229         ]),
230     'innodb_buffer_pool_pages': (
231         "'' 'mysql InnoDB Buffer Pool Pages' 'pages' innodb mysql.innodb_buffer_pool_pages line",
232         [
233             ("Innodb_buffer_pool_pages_data", "data absolute 1 1"),
234             ("Innodb_buffer_pool_pages_dirty", "dirty absolute -1 1"),
235             ("Innodb_buffer_pool_pages_free", "free absolute 1 1"),
236             ("Innodb_buffer_pool_pages_flushed", "flushed incremental -1 1"),
237             ("Innodb_buffer_pool_pages_misc", "misc absolute -1 1"),
238             ("Innodb_buffer_pool_pages_total", "total absolute 1 1"),
239         ]),
240     'innodb_buffer_pool_bytes': (
241         "'' 'mysql InnoDB Buffer Pool Bytes' 'MB' innodb mysql.innodb_buffer_pool_bytes area",
242         [
243             ("Innodb_buffer_pool_bytes_data", "data absolute 1"),
244             ("Innodb_buffer_pool_bytes_dirty", "dirty absolute -1"),
245         ]),
246     'innodb_buffer_pool_read_ahead': (
247         "'' 'mysql InnoDB Buffer Pool Read Ahead' 'operations/s' innodb mysql.innodb_buffer_pool_read_ahead area",
248         [
249             ("Innodb_buffer_pool_read_ahead", "all incremental 1 1"),
250             ("Innodb_buffer_pool_read_ahead_evicted", "evicted incremental -1 1"),
251             ("Innodb_buffer_pool_read_ahead_rnd", "random incremental 1 1"),
252         ]),
253     'innodb_buffer_pool_reqs': (
254         "'' 'mysql InnoDB Buffer Pool Requests' 'requests/s' innodb mysql.innodb_buffer_pool_reqs area",
255         [
256             ("Innodb_buffer_pool_read_requests", "reads incremental 1 1"),
257             ("Innodb_buffer_pool_write_requests", "writes incremental -1 1"),
258         ]),
259     'innodb_buffer_pool_ops': (
260         "'' 'mysql InnoDB Buffer Pool Operations' 'operations/s' innodb mysql.innodb_buffer_pool_ops area",
261         [
262             ("Innodb_buffer_pool_reads", "'disk reads' incremental 1 1"),
263             ("Innodb_buffer_pool_wait_free", "'wait free' incremental -1 1"),
264         ]),
265     'qcache_ops': (
266         "'' 'mysql QCache Operations' 'queries/s' qcache mysql.qcache_ops line",
267         [
268             ("Qcache_hits", "hits incremental 1 1"),
269             ("Qcache_lowmem_prunes", "'lowmem prunes' incremental -1 1"),
270             ("Qcache_inserts", "inserts incremental 1 1"),
271             ("Qcache_not_cached", "'not cached' incremental -1 1"),
272         ]),
273     'qcache': (
274         "'' 'mysql QCache Queries in Cache' 'queries' qcache mysql.qcache line",
275         [
276             ("Qcache_queries_in_cache", "queries absolute 1 1"),
277         ]),
278     'qcache_freemem': (
279         "'' 'mysql QCache Free Memory' 'MB' qcache mysql.qcache_freemem area",
280         [
281             ("Qcache_free_memory", "free absolute 1"),
282         ]),
283     'qcache_memblocks': (
284         "'' 'mysql QCache Memory Blocks' 'blocks' qcache mysql.qcache_memblocks line",
285         [
286             ("Qcache_free_blocks", "free absolute 1"),
287             ("Qcache_total_blocks", "total absolute 1 1"),
288         ]),
289     'key_blocks': (
290         "'' 'mysql MyISAM Key Cache Blocks' 'blocks' myisam mysql.key_blocks line",
291         [
292             ("Key_blocks_unused", "unused absolute 1 1"),
293             ("Key_blocks_used", "used absolute -1 1"),
294             ("Key_blocks_not_flushed", "'not flushed' absolute 1 1"),
295         ]),
296     'key_requests': (
297         "'' 'mysql MyISAM Key Cache Requests' 'requests/s' myisam mysql.key_requests area",
298         [
299             ("Key_read_requests", "reads incremental 1 1"),
300             ("Key_write_requests", "writes incremental -1 1"),
301         ]),
302     'key_disk_ops': (
303         "'' 'mysql MyISAM Key Cache Disk Operations' 'operations/s' myisam mysql.key_disk_ops area",
304         [
305             ("Key_reads", "reads incremental 1 1"),
306             ("Key_writes", "writes incremental -1 1"),
307         ]),
308     'files': (
309         "'' 'mysql Open Files' 'files' files mysql.files line",
310         [
311             ("Open_files", "files absolute 1 1"),
312         ]),
313     'files_rate': (
314         "'' 'mysql Opened Files Rate' 'files/s' files mysql.files_rate line",
315         [
316             ("Opened_files", "files incremental 1 1"),
317         ]),
318     'binlog_stmt_cache': (
319         "'' 'mysql Binlog Statement Cache' 'statements/s' binlog mysql.binlog_stmt_cache line",
320         [
321             ("Binlog_stmt_cache_disk_use", "disk incremental 1 1"),
322             ("Binlog_stmt_cache_use", "all incremental 1 1"),
323         ]),
324     'connection_errors': (
325         "'' 'mysql Connection Errors' 'connections/s' connections mysql.connection_errors line",
326         [
327             ("Connection_errors_accept", "accept incremental 1 1"),
328             ("Connection_errors_internal", "internal incremental 1 1"),
329             ("Connection_errors_max_connections", "max incremental 1 1"),
330             ("Connection_errors_peer_address", "peer_addr incremental 1 1"),
331             ("Connection_errors_select", "select incremental 1 1"),
332             ("Connection_errors_tcpwrap", "tcpwrap incremental 1 1")
333         ])
334 }
335
336
337 class Service(BaseService):
338     def __init__(self, configuration=None, name=None):
339         super(self.__class__, self).__init__(configuration=configuration, name=name)
340         self.configuration = self._parse_config(configuration)
341         self.connection = None
342         self.defs = {}
343
344     def _parse_config(self, configuration):
345         """
346         Parse configuration to collect data from MySQL server
347         :param configuration: dict
348         :return: dict
349         """
350         if self.name is None:
351             self.name = 'local'
352         if 'user' not in configuration:
353             configuration['user'] = 'root'
354         if 'password' not in configuration:
355             configuration['password'] = ''
356         if 'my.cnf' in configuration:
357             configuration['socket'] = ''
358             configuration['host'] = ''
359             configuration['port'] = 0
360         elif 'socket' in configuration:
361             configuration['my.cnf'] = ''
362             configuration['host'] = ''
363             configuration['port'] = 0
364         elif 'host' in configuration:
365             configuration['my.cnf'] = ''
366             configuration['socket'] = ''
367             if 'port' in configuration:
368                 configuration['port'] = int(configuration['port'])
369             else:
370                 configuration['port'] = 3306
371
372         return configuration
373
374     def _connect(self):
375         """
376         Try to connect to MySQL server
377         """
378         try:
379             self.connection = MySQLdb.connect(user=self.configuration['user'],
380                                               passwd=self.configuration['password'],
381                                               read_default_file=self.configuration['my.cnf'],
382                                               unix_socket=self.configuration['socket'],
383                                               host=self.configuration['host'],
384                                               port=self.configuration['port'],
385                                               connect_timeout=self.configuration['update_every'])
386         except Exception as e:
387             self.error(NAME + " has problem connecting to server:", e)
388             raise RuntimeError
389
390     def _get_data(self):
391         """
392         Get raw data from MySQL server
393         :return: dict
394         """
395         if self.connection is None:
396             try:
397                 self._connect()
398             except RuntimeError:
399                 return None
400         try:
401             with self.connection.cursor() as cursor:
402                 cursor.execute(QUERY)
403                 raw_data = cursor.fetchall()
404         except Exception as e:
405             self.error(NAME + ": cannot execute query.", e)
406             self.connection.close()
407             self.connection = None
408             return None
409
410         return dict(raw_data)
411
412     def check(self):
413         """
414         Check if service is able to connect to server
415         :return: boolean
416         """
417         try:
418             self.connection = self._connect()
419             return True
420         except RuntimeError:
421             self.connection = None
422             return False
423
424     def create(self):
425         """
426         Create graphs
427         :return: boolean
428         """
429         for name in ORDER:
430             self.defs[name] = []
431             for line in CHARTS[name][1]:
432                 self.defs[name].append(line[0])
433
434         idx = 0
435         data = self._get_data()
436         for name in ORDER:
437             header = "CHART mysql_" + \
438                      str(self.name) + "." + \
439                      name + " " + \
440                      CHARTS[name][0] + " " + \
441                      str(self.priority + idx) + " " + \
442                      str(self.update_every)
443             content = ""
444             # check if server has this data point
445             for line in CHARTS[name][1]:
446                 if line[0] in data:
447                     content += "DIMENSION " + line[0] + " " + line[1] + "\n"
448             if len(content) > 0:
449                 print(header)
450                 print(content)
451                 idx += 1
452
453         if idx == 0:
454             return False
455         return True
456
457     def update(self, interval):
458         """
459         Update data on graphs
460         :param interval: int
461         :return: boolean
462         """
463         data = self._get_data()
464         if data is None:
465             return False
466         try:
467             data['Thread cache misses'] = int(int(data['Threads_created']) * 10000 / int(data['Connections']))
468         except Exception:
469             pass
470         for chart, dimensions in self.defs.items():
471             header = "BEGIN mysql_" + str(self.name) + "." + chart + " " + str(interval) + '\n'
472             lines = ""
473             for d in dimensions:
474                 try:
475                     lines += "SET " + d + " = " + data[d] + '\n'
476                 except KeyError:
477                     pass
478             if len(lines) > 0:
479                 print(header + lines + "END")
480
481         return True