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