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