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