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