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