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