]> arthur.barton.de Git - netdata.git/blob - python.d/varnish.chart.py
9d2c780e973eda08a33c9cc271752e153a5704d2
[netdata.git] / python.d / varnish.chart.py
1 # -*- coding: utf-8 -*-
2 # Description:  varnish netdata python.d module
3 # Author: l2isbad
4
5 from base import SimpleService
6 from re import compile
7 from os import access as is_executable, X_OK
8 from subprocess import Popen, PIPE
9
10
11 # default module values (can be overridden per job in `config`)
12 # update_every = 2
13 priority = 60000
14 retries = 60
15
16 ORDER = ['session', 'hit_rate', 'chit_rate', 'expunge', 'threads', 'backend_health', 'memory_usage', 'bad', 'uptime']
17
18 CHARTS = {'backend_health': 
19              {'lines': [['backend_conn', 'conn', 'incremental', 1, 1],
20                        ['backend_unhealthy', 'unhealthy', 'incremental', 1, 1],
21                        ['backend_busy', 'busy', 'incremental', 1, 1],
22                        ['backend_fail', 'fail', 'incremental', 1, 1],
23                        ['backend_reuse', 'reuse', 'incremental', 1, 1],
24                        ['backend_recycle', 'resycle', 'incremental', 1, 1],
25                        ['backend_toolate', 'toolate', 'incremental', 1, 1],
26                        ['backend_retry', 'retry', 'incremental', 1, 1],
27                        ['backend_req', 'req', 'incremental', 1, 1]],
28               'options': [None, 'Backend health', 'connections', 'Backend health', 'varnish.backend_traf', 'line']},
29           'bad': 
30              {'lines': [['sess_drop_b', None, 'incremental', 1, 1],
31                        ['backend_unhealthy_b', None, 'incremental', 1, 1],
32                        ['fetch_failed', None, 'incremental', 1, 1],
33                        ['backend_busy_b', None, 'incremental', 1, 1],
34                        ['threads_failed_b', None, 'incremental', 1, 1],
35                        ['threads_limited_b', None, 'incremental', 1, 1],
36                        ['threads_destroyed_b', None, 'incremental', 1, 1],
37                        ['thread_queue_len_b', 'queue_len', 'absolute', 1, 1],
38                        ['losthdr_b', None, 'incremental', 1, 1],
39                        ['esi_errors_b', None, 'incremental', 1, 1],
40                        ['esi_warnings_b', None, 'incremental', 1, 1],
41                        ['sess_fail_b', None, 'incremental', 1, 1],
42                        ['sess_pipe_overflow_b', None, 'incremental', 1, 1]],
43               'options': [None, 'Misbehavior', 'problems', 'Problems summary', 'varnish.bad', 'line']},
44           'expunge':
45              {'lines': [['n_expired', 'expired', 'incremental', 1, 1],
46                        ['n_lru_nuked', 'lru_nuked', 'incremental', 1, 1]],
47               'options': [None, 'Object expunging', 'objects', 'Cache performance', 'varnish.expunge', 'line']},
48           'hit_rate': 
49              {'lines': [['cache_hit_perc', 'hit', 'absolute', 1, 100],
50                        ['cache_miss_perc', 'miss', 'absolute', 1, 100],
51                        ['cache_hitpass_perc', 'hitpass', 'absolute', 1, 100]],
52               'options': [None, 'All history hit rate ratio','percent', 'Cache performance', 'varnish.hit_rate', 'stacked']},
53           'chit_rate': 
54              {'lines': [['cache_hit_cperc', 'hit', 'absolute', 1, 100],
55                        ['cache_miss_cperc', 'miss', 'absolute', 1, 100],
56                        ['cache_hitpass_cperc', 'hitpass', 'absolute', 1, 100]],
57               'options': [None, 'Current poll hit rate ratio','percent', 'Cache performance', 'varnish.chit_rate', 'stacked']},
58           'memory_usage': 
59              {'lines': [['s0.g_space', 'available', 'absolute', 1, 1048576],
60                        ['s0.g_bytes', 'allocated', 'absolute', -1, 1048576]],
61               'options': [None, 'Memory usage', 'megabytes', 'Memory usage', 'varnish.memory_usage', 'stacked']},
62           'session': 
63              {'lines': [['sess_conn', 'conn', 'incremental', 1, 1],
64                        ['client_req', 'requests', 'incremental', 1, 1],
65                        ['sess_dropped', 'dropped', 'incremental', 1, 1]],
66               'options': [None, 'Sessions', 'units', 'Client metrics', 'varnish.session', 'line']},
67           'threads': 
68              {'lines': [['threads', None, 'absolute', 1, 1],
69                        ['threads_created', 'created', 'incremental', 1, 1],
70                        ['threads_failed', 'failed', 'incremental', 1, 1],
71                        ['threads_limited', 'limited', 'incremental', 1, 1],
72                        ['thread_queue_len', 'queue_len', 'incremental', 1, 1],
73                        ['sess_queued', 'sess_queued', 'incremental', 1, 1]],
74               'options': [None, 'Thread status', 'threads', 'Thread-related metrics', 'varnish.threads', 'line']},
75           'uptime': 
76              {'lines': [['uptime', None, 'absolute', 1, 1]],
77               'options': [None, 'Varnish uptime', 'seconds', 'Uptime', 'varnish.uptime', 'line']}
78 }
79
80 DIRECTORIES = ['/bin/', '/usr/bin/', '/sbin/', '/usr/sbin/']
81
82
83 class Service(SimpleService):
84     def __init__(self, configuration=None, name=None):
85         SimpleService.__init__(self, configuration=configuration, name=name)
86         try:
87             self.varnish = [''.join([directory, 'varnishstat']) for directory in DIRECTORIES
88                          if is_executable(''.join([directory, 'varnishstat']), X_OK)][0]
89         except IndexError:
90             self.varnish = False
91         self.rgx_all = compile(r'([A-Z]+\.)([\d\w_.]+)\s+(\d+)')
92         # Could be
93         # VBE.boot.super_backend.pipe_hdrbyte (new)
94         # or
95         # VBE.default2(127.0.0.2,,81).bereq_bodybytes (old)
96         # Regex result: [('super_backend', 'beresp_hdrbytes', '0'), ('super_backend', 'beresp_bodybytes', '0')]
97         self.rgx_bck = (compile(r'VBE.([\d\w_.]+)\(.*?\).(beresp[\w_]+)\s+(\d+)'),
98                         compile(r'VBE\.[\d\w-]+\.([\w\d_]+).(beresp[\w_]+)\s+(\d+)'))
99         self.cache_prev = list()
100
101     def check(self):
102         # Cant start without 'varnishstat' command
103         if not self.varnish:
104             self.error('\'varnishstat\' command was not found in %s or not executable by netdata' % DIRECTORIES)
105             return False
106
107         # If command is present and we can execute it we need to make sure..
108         # 1. STDOUT is not empty
109         reply = self._get_raw_data()
110         if not reply:
111             self.error('No output from \'varnishstat\' (not enough privileges?)')
112             return False
113
114         # 2. Output is parsable (list is not empty after regex findall)
115         is_parsable = self.rgx_all.findall(reply)
116         if not is_parsable:
117             self.error('Cant parse output (only varnish version 4+ supported)')
118             return False
119
120         # We need to find the right regex for backend parse
121         self.backend_list = self.rgx_bck[0].findall(reply)[::2]
122         if self.backend_list:
123             self.rgx_bck = self.rgx_bck[0]
124         else:
125             self.backend_list = self.rgx_bck[1].findall(reply)[::2]
126             self.rgx_bck = self.rgx_back[1]
127
128         # We are about to start!
129         self.create_charts()
130
131         self.info('Plugin was started successfully')
132         return True
133      
134     def _get_raw_data(self):
135         try:
136             reply = Popen([self.varnish, '-1'], stdout=PIPE, stderr=PIPE, shell=False)
137         except OSError:
138             return None
139
140         raw_data = reply.communicate()[0]
141
142         if not raw_data:
143             return None
144
145         return raw_data
146
147     def _get_data(self):
148         """
149         Format data received from shell command
150         :return: dict
151         """
152         raw_data = self._get_raw_data()
153         data_all = self.rgx_all.findall(raw_data)
154         data_backend = self.rgx_bck.findall(raw_data)
155
156         if not data_all:
157             return None
158
159         # 1. ALL data from 'varnishstat -1'. t - type(MAIN, MEMPOOL etc)
160         to_netdata = {k: int(v) for t, k, v in data_all}
161         
162         # 2. ADD backend statistics
163         to_netdata.update({'_'.join([n, k]): int(v) for n, k, v in data_backend})
164
165         # 3. ADD additional keys to dict
166         # 3.1 Cache hit/miss/hitpass OVERALL in percent
167         cache_summary = sum([to_netdata.get('cache_hit', 0), to_netdata.get('cache_miss', 0),
168                              to_netdata.get('cache_hitpass', 0)])
169         to_netdata['cache_hit_perc'] = find_percent(to_netdata.get('cache_hit', 0), cache_summary, 10000)
170         to_netdata['cache_miss_perc'] = find_percent(to_netdata.get('cache_miss', 0), cache_summary, 10000)
171         to_netdata['cache_hitpass_perc'] = find_percent(to_netdata.get('cache_hitpass', 0), cache_summary, 10000)
172
173         # 3.2 Cache hit/miss/hitpass CURRENT in percent
174         if self.cache_prev:
175             cache_summary = sum([to_netdata.get('cache_hit', 0), to_netdata.get('cache_miss', 0),
176                                  to_netdata.get('cache_hitpass', 0)]) - sum(self.cache_prev)
177             to_netdata['cache_hit_cperc'] = find_percent(to_netdata.get('cache_hit', 0) - self.cache_prev[0], cache_summary, 10000)
178             to_netdata['cache_miss_cperc'] = find_percent(to_netdata.get('cache_miss', 0) - self.cache_prev[1], cache_summary, 10000)
179             to_netdata['cache_hitpass_cperc'] = find_percent(to_netdata.get('cache_hitpass', 0) - self.cache_prev[2], cache_summary, 10000)
180         else:
181             to_netdata['cache_hit_cperc'] = 0
182             to_netdata['cache_miss_cperc'] = 0
183             to_netdata['cache_hitpass_cperc'] = 0
184
185         self.cache_prev = [to_netdata.get('cache_hit', 0), to_netdata.get('cache_miss', 0), to_netdata.get('cache_hitpass', 0)]
186
187         # 3.3 Problems summary chart
188         for elem in ['backend_busy', 'backend_unhealthy', 'esi_errors', 'esi_warnings', 'losthdr', 'sess_drop',
189                      'sess_fail', 'sess_pipe_overflow', 'threads_destroyed', 'threads_failed', 'threads_limited', 'thread_queue_len']:
190             to_netdata[''.join([elem, '_b'])] = to_netdata.get(elem, 0)
191
192         # Ready steady go!
193         return to_netdata
194
195     def create_charts(self):
196         # If 'all_charts' is true...ALL charts are displayed. If no only default + 'extra_charts'
197         #if self.configuration.get('all_charts'):
198         #    self.order = EXTRA_ORDER
199         #else:
200         #    try:
201         #        extra_charts = list(filter(lambda chart: chart in EXTRA_ORDER, self.extra_charts.split()))
202         #    except (AttributeError, NameError, ValueError):
203         #        self.error('Extra charts disabled.')
204         #        extra_charts = []
205     
206         self.order = ORDER[:]
207         #self.order.extend(extra_charts)
208
209         # Create static charts
210         self.definitions = {chart: values for chart, values in CHARTS.items() if chart in self.order}
211  
212         # Create dynamic backend charts
213         if self.backend_list:
214             for backend in self.backend_list:
215                 self.order.insert(0, ''.join([backend[0], '_resp_stats']))
216                 self.definitions.update({''.join([backend[0], '_resp_stats']): {
217                     'options': [None,
218                                 '%s response statistics' % backend[0].capitalize(),
219                                 "kilobit/s",
220                                 'Backend response',
221                                 'varnish.backend',
222                                 'area'],
223                     'lines': [[''.join([backend[0], '_beresp_hdrbytes']),
224                                'header', 'incremental', 8, 1000],
225                               [''.join([backend[0], '_beresp_bodybytes']),
226                                'body', 'incremental', -8, 1000]]}})
227
228
229 def find_percent(value1, value2, multiply):
230     # If value2 is 0 return 0
231     if not value2:
232         return 0
233     else:
234         return round(float(value1) / float(value2) * multiply)