]> arthur.barton.de Git - netdata.git/blob - python.d/bind_rndc.chart.py
mongodb_plugin: oplog window and "optimeDate" diff between nodes charts added
[netdata.git] / python.d / bind_rndc.chart.py
1 # -*- coding: utf-8 -*-
2 # Description: bind rndc netdata python.d module
3 # Author: l2isbad
4
5 from base import SimpleService
6 from re import compile, findall
7 from os.path import getsize, split
8 from os import access as is_accessible, R_OK
9 from subprocess import Popen
10
11 priority = 60000
12 retries = 60
13 update_every = 30
14
15 NMS = ['requests', 'responses', 'success', 'auth_answer', 'nonauth_answer', 'nxrrset', 'failure',
16        'nxdomain', 'recursion', 'duplicate', 'rejections']
17 QUERIES = ['RESERVED0', 'A', 'NS', 'CNAME', 'SOA', 'PTR', 'MX', 'TXT', 'X25', 'AAAA', 'SRV', 'NAPTR',
18            'A6', 'DS', 'RRSIG', 'DNSKEY', 'SPF', 'ANY', 'DLV']
19
20
21 class Service(SimpleService):
22     def __init__(self, configuration=None, name=None):
23         SimpleService.__init__(self, configuration=configuration, name=name)
24         self.named_stats_path = self.configuration.get('named_stats_path', '/var/log/bind/named.stats')
25         self.regex_values = compile(r'([0-9]+) ([^\n]+)')
26         # self.options = ['Incoming Requests', 'Incoming Queries', 'Outgoing Queries',
27         # 'Name Server Statistics', 'Zone Maintenance Statistics', 'Resolver Statistics',
28         # 'Cache DB RRsets', 'Socket I/O Statistics']
29         self.options = ['Name Server Statistics', 'Incoming Queries', 'Outgoing Queries']
30         self.regex_options = [r'(%s(?= \+\+)) \+\+([^\+]+)' % option for option in self.options]
31         self.rndc = self.find_binary('rndc')
32
33     def check(self):
34         # We cant start without 'rndc' command
35         if not self.rndc:
36             self.error('Can\'t locate \'rndc\' binary or binary is not executable by netdata')
37             return False
38
39         # We cant start if stats file is not exist or not readable by netdata user
40         if not is_accessible(self.named_stats_path, R_OK):
41             self.error('Cannot access file %s' % self.named_stats_path)
42             return False
43
44         size_before = getsize(self.named_stats_path)
45         run_rndc = Popen([self.rndc, 'stats'], shell=False)
46         run_rndc.wait()
47         size_after = getsize(self.named_stats_path)
48
49         # We cant start if netdata user has no permissions to run 'rndc stats'
50         if not run_rndc.returncode:
51             # 'rndc' was found, stats file is exist and readable and we can run 'rndc stats'. Lets go!
52             self.create_charts()
53             
54             # BIND APPEND dump on every run 'rndc stats'
55             # that is why stats file size can be VERY large if update_interval too small
56             dump_size_24hr = round(86400 / self.update_every * (int(size_after) - int(size_before)) / 1048576, 3)
57             
58             # If update_every too small we should WARN user
59             if self.update_every < 30:
60                 self.info('Update_every %s is NOT recommended for use. Increase the value to > 30' % self.update_every)
61             
62             self.info('With current update_interval it will be + %s MB every 24hr. '
63                       'Don\'t forget to create logrotate conf file for %s' % (dump_size_24hr, self.named_stats_path))
64
65             self.info('Plugin was started successfully.')
66
67             return True
68         else:
69             self.error('Not enough permissions to run "%s stats"' % self.rndc)
70             return False
71
72     def _get_raw_data(self):
73         """
74         Run 'rndc stats' and read last dump from named.stats
75         :return: tuple(
76                        file.read() obj,
77                        named.stats file size
78                       )
79         """
80
81         try:
82             current_size = getsize(self.named_stats_path)
83         except OSError:
84             return None, None
85         
86         run_rndc = Popen([self.rndc, 'stats'], shell=False)
87         run_rndc.wait()
88
89         if run_rndc.returncode:     
90             return None, None
91
92         try:
93             with open(self.named_stats_path) as bind_rndc:
94                 bind_rndc.seek(current_size)
95                 result = bind_rndc.read()
96         except OSError:
97             return None, None
98         else:
99             return result, current_size
100
101     def _get_data(self):
102         """
103         Parse data from _get_raw_data()
104         :return: dict
105         """
106
107         raw_data, size = self._get_raw_data()
108
109         if raw_data is None:
110             return None
111
112         rndc_stats = dict()
113         
114         # Result: dict.
115         # topic = Cache DB RRsets; body = A 178303 NS 86790 ... ; desc = A; value = 178303
116         # {'Cache DB RRsets': [('A', 178303), ('NS', 286790), ...],
117         # {Incoming Queries': [('RESERVED0', 8), ('A', 4557317680), ...],
118         # ......
119         for regex in self.regex_options:
120             rndc_stats.update({topic: [(desc, int(value)) for value, desc in self.regex_values.findall(body)]
121                                for topic, body in findall(regex, raw_data)})
122         
123         nms = dict(rndc_stats.get('Name Server Statistics', []))
124
125         inc_queries = {'i' + k: 0 for k in QUERIES}
126         inc_queries.update({'i' + k: v for k, v in rndc_stats.get('Incoming Queries', [])})
127         out_queries = {'o' + k: 0 for k in QUERIES}
128         out_queries.update({'o' + k: v for k, v in rndc_stats.get('Outgoing Queries', [])})
129         
130         to_netdata = dict()
131         to_netdata['requests'] = sum([v for k, v in nms.items() if 'request' in k and 'received' in k])
132         to_netdata['responses'] = sum([v for k, v in nms.items() if 'responses' in k and 'sent' in k])
133         to_netdata['success'] = nms.get('queries resulted in successful answer', 0)
134         to_netdata['auth_answer'] = nms.get('queries resulted in authoritative answer', 0)
135         to_netdata['nonauth_answer'] = nms.get('queries resulted in non authoritative answer', 0)
136         to_netdata['nxrrset'] = nms.get('queries resulted in nxrrset', 0)
137         to_netdata['failure'] = sum([nms.get('queries resulted in SERVFAIL', 0), nms.get('other query failures', 0)])
138         to_netdata['nxdomain'] = nms.get('queries resulted in NXDOMAIN', 0)
139         to_netdata['recursion'] = nms.get('queries caused recursion', 0)
140         to_netdata['duplicate'] = nms.get('duplicate queries received', 0)
141         to_netdata['rejections'] = nms.get('recursive queries rejected', 0)
142         to_netdata['stats_size'] = size
143         
144         to_netdata.update(inc_queries)
145         to_netdata.update(out_queries)
146         return to_netdata
147
148     def create_charts(self):
149         self.order = ['stats_size', 'bind_stats', 'incoming_q', 'outgoing_q']
150         self.definitions = {
151             'bind_stats': {
152                 'options': [None, 'Name Server Statistics', 'stats', 'Name Server Statistics', 'bind_rndc.stats', 'line'],
153                 'lines': [
154                          ]},
155             'incoming_q': {
156                 'options': [None, 'Incoming queries', 'queries','Incoming queries', 'bind_rndc.incq', 'line'],
157                 'lines': [
158                         ]},
159             'outgoing_q': {
160                 'options': [None, 'Outgoing queries', 'queries','Outgoing queries', 'bind_rndc.outq', 'line'],
161                 'lines': [
162                         ]},
163             'stats_size': {
164                 'options': [None, '%s file size' % split(self.named_stats_path)[1].capitalize(), 'megabytes',
165                             '%s size' % split(self.named_stats_path)[1].capitalize(), 'bind_rndc.size', 'line'],
166                 'lines': [
167                          ["stats_size", None, "absolute", 1, 1048576]
168                         ]}
169                      }
170         for elem in QUERIES:
171             self.definitions['incoming_q']['lines'].append(['i' + elem, elem, 'incremental'])
172             self.definitions['outgoing_q']['lines'].append(['o' + elem, elem, 'incremental'])
173
174         for elem in NMS:
175             self.definitions['bind_stats']['lines'].append([elem, None, 'incremental'])