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