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