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