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