]> arthur.barton.de Git - netdata.git/blob - python.d/web_log.chart.py
web_log plugin: support for apache non default (+ %I %D) added
[netdata.git] / python.d / web_log.chart.py
1 # -*- coding: utf-8 -*-
2 # Description: web log netdata python.d module
3 # Author: l2isbad
4
5 from base import LogService
6 import re
7 import bisect
8 from os import access, R_OK
9 from os.path import getsize
10 from collections import defaultdict, namedtuple
11 from copy import deepcopy
12 try:
13     from itertools import zip_longest
14 except ImportError:
15     from itertools import izip_longest as zip_longest
16
17 priority = 60000
18 retries = 60
19
20 ORDER = ['response_codes', 'response_time', 'requests_per_url', 'http_method', 'bandwidth', 'clients', 'clients_all']
21 CHARTS = {
22     'response_codes': {
23         'options': [None, 'Response Codes', 'requests/s', 'responses', 'web_log.response_codes', 'stacked'],
24         'lines': [
25             ['2xx', '2xx', 'absolute'],
26             ['5xx', '5xx', 'absolute'],
27             ['3xx', '3xx', 'absolute'],
28             ['4xx', '4xx', 'absolute'],
29             ['1xx', '1xx', 'absolute'],
30             ['0xx', 'other', 'absolute'],
31             ['unmatched', 'unmatched', 'absolute']
32         ]},
33     'bandwidth': {
34         'options': [None, 'Bandwidth', 'KB/s', 'bandwidth', 'web_log.bandwidth', 'area'],
35         'lines': [
36             ['resp_length', 'received', 'absolute', 1, 1024],
37             ['bytes_sent', 'sent', 'absolute', -1, 1024]
38         ]},
39     'response_time': {
40         'options': [None, 'Processing Time', 'milliseconds', 'timings', 'web_log.response_time', 'area'],
41         'lines': [
42             ['resp_time_min', 'min', 'absolute', 1, 1],
43             ['resp_time_max', 'max', 'absolute', 1, 1],
44             ['resp_time_avg', 'avg', 'absolute', 1, 1]
45         ]},
46     'clients': {
47         'options': [None, 'Current Poll Unique Client IPs', 'unique ips', 'unique clients', 'web_log.clients', 'line'],
48         'lines': [
49             ['unique_cur_ipv4', 'ipv4', 'absolute', 1, 1],
50             ['unique_cur_ipv6', 'ipv6', 'absolute', 1, 1]
51         ]},
52     'clients_all': {
53         'options': [None, 'All Time Unique Client IPs', 'unique ips', 'unique clients', 'web_log.clients_all', 'line'],
54         'lines': [
55             ['unique_tot_ipv4', 'ipv4', 'absolute', 1, 1],
56             ['unique_tot_ipv6', 'ipv6', 'absolute', 1, 1]
57         ]},
58     'http_method': {
59         'options': [None, 'Requests Per HTTP Method', 'requests/s', 'requests', 'web_log.http_method', 'stacked'],
60         'lines': [
61         ]}
62 }
63
64 NAMED_URL_PATTERN = namedtuple('URL_PATTERN', ['description', 'pattern'])
65
66
67 class Service(LogService):
68     def __init__(self, configuration=None, name=None):
69         LogService.__init__(self, configuration=configuration, name=name)
70         # Vars from module configuration file
71         self.log_path = self.configuration.get('path')
72         self.detailed_response_codes = self.configuration.get('detailed_response_codes', True)
73         self.all_time = self.configuration.get('all_time', True)
74         self.url_pattern = self.configuration.get('categories')  # dict
75         self.regex = None
76         # sorted list of unique IPs
77         self.unique_all_time = list()
78         # dict for values that should not be zeroed every poll
79         self.storage = {'unique_tot_ipv4': 0, 'unique_tot_ipv6': 0}
80         # if there is no new logs this dict + self.storage returned to netdata
81         self.data = {'bytes_sent': 0, 'resp_length': 0, 'resp_time_min': 0,
82                      'resp_time_max': 0, 'resp_time_avg': 0, 'unique_cur_ipv4': 0,
83                      'unique_cur_ipv6': 0, '2xx': 0, '5xx': 0, '3xx': 0, '4xx': 0,
84                      '1xx': 0, '0xx': 0, 'unmatched': 0}
85
86     def check(self):
87         if not self.log_path:
88             self.error('log path is not specified')
89             return False
90
91         # log_path must be readable
92         if not access(self.log_path, R_OK):
93             self.error('%s not readable or not exist' % self.log_path)
94             return False
95
96         # log_path file should not be empty
97         if not getsize(self.log_path):
98             self.error('%s is empty' % self.log_path)
99             return False
100
101         # Read last line (or first if there is only one line)
102         with open(self.log_path, 'rb') as logs:
103             logs.seek(-2, 2)
104             while logs.read(1) != b'\n':
105                 logs.seek(-2, 1)
106                 if logs.tell() == 0:
107                     break
108             last_line = logs.readline().decode(encoding='utf-8')
109
110         # Parse last line
111         parsed_line, regex_name = self.find_regex(last_line)
112         if not parsed_line:
113             self.error('Can\'t parse output')
114             return False
115
116         self.create_charts(parsed_line[0], regex_name)
117         if len(parsed_line[0]) == 5:
118             self.info('Not all data collected. You need to modify LogFormat.')
119         return True
120
121     def find_regex(self, last_line):
122         # REGEX: 1.IPv4 address 2.HTTP method 3. URL 4. Response code
123         # 5. Bytes sent 6. Response length 7. Response process time
124         default = re.compile(r'([\da-f.:]+)'
125                              r' -.*?"([A-Z]+)'
126                              r' (.*?)"'
127                              r' ([1-9]\d{2})'
128                              r' (\d+)')
129
130         apache_extended = re.compile(r'([\da-f.:]+)'
131                                     r' -.*?"([A-Z]+)'
132                                     r' (.*?)"'
133                                     r' ([1-9]\d{2})'
134                                     r' (\d+)'
135                                     r' (\d+)'
136                                     r' (\d+) ')
137
138         nginx_extended = re.compile(r'([\da-f.:]+)'
139                                     r' -.*?"([A-Z]+)'
140                                     r' (.*?)"'
141                                     r' ([1-9]\d{2})'
142                                     r' (\d+)'
143                                     r' (\d+)'
144                                     r' ([\d.]+) ')
145
146         regex_function = zip([apache_extended, nginx_extended, default],
147                              [lambda x: x, lambda x: x * 1000, lambda x: x],
148                              ['apache_extended', 'nginx_extended', 'default'])
149
150         for regex, function, name in regex_function:
151             if regex.search(last_line):
152                 self.regex = regex
153                 self.resp_time_func = function
154                 regex_name = name
155                 break
156
157         if self.regex:
158             return self.regex.findall(last_line), regex_name
159         else:
160             return None, None
161
162     def create_charts(self, parsed_line, regex_name):
163         def find_job_name(override_name, name):
164             add_to_name = override_name or name
165             if add_to_name:
166                 return '_'.join(['web_log', add_to_name])
167             else:
168                 return 'web_log'
169
170         job_name = find_job_name(self.override_name, self.name)
171         self.detailed_chart = 'CHART %s.detailed_response_codes ""' \
172                               ' "Response Codes" requests/s responses' \
173                               ' web_log.detailed_resp stacked 1 %s\n' % (job_name, self.update_every)
174         self.http_method_chart = 'CHART %s.http_method' \
175                                  ' "" "HTTP Methods" requests/s requests' \
176                                  ' web_log.http_method stacked 2 %s\n' % (job_name, self.update_every)
177         self.order = ORDER[:]
178         self.definitions = deepcopy(CHARTS)
179         if 'apache' in regex_name:
180             self.definitions['response_time']['lines'][0][4] = 1000
181             self.definitions['response_time']['lines'][1][4] = 1000
182             self.definitions['response_time']['lines'][2][4] = 1000
183
184         # Remove 'request_time' chart from ORDER if request_time not in logs
185         if len(parsed_line) < 7:
186             self.order.remove('response_time')
187         # Remove 'clients_all' chart from ORDER if specified in the configuration
188         if not self.all_time:
189             self.order.remove('clients_all')
190         # Add 'detailed_response_codes' chart if specified in the configuration
191         if self.detailed_response_codes:
192             self.order.append('detailed_response_codes')
193             self.definitions['detailed_response_codes'] = {'options': [None, 'Detailed Response Codes', 'requests/s',
194                                                                        'responses', 'web_log.detailed_resp', 'stacked'],
195                                                            'lines': []}
196
197         # Add 'requests_per_url' chart if specified in the configuration
198         if self.url_pattern:
199             self.url_pattern = [NAMED_URL_PATTERN(description=k, pattern=re.compile(v)) for k, v in self.url_pattern.items()]
200             self.definitions['requests_per_url'] = {'options': [None, 'Requests Per Url', 'requests/s',
201                                                                 'requests', 'web_log.url_pattern', 'stacked'],
202                                                     'lines': [['other_url', 'other', 'absolute']]}
203             for elem in self.url_pattern:
204                 self.definitions['requests_per_url']['lines'].append([elem.description, elem.description, 'absolute'])
205                 self.data.update({elem.description: 0})
206             self.data.update({'other_url': 0})
207         else:
208             self.order.remove('requests_per_url')
209
210     def add_new_dimension(self, dimension, line_list, chart_string, key):
211         self.storage.update({dimension: 0})
212         # SET method check if dim in _dimensions
213         self._dimensions.append(dimension)
214         # UPDATE method do SET only if dim in definitions
215         self.definitions[key]['lines'].append(line_list)
216         chart = chart_string
217         chart += "%s %s\n" % ('DIMENSION', ' '.join(line_list))
218         print(chart)
219         return chart
220
221     def _get_data(self):
222         """
223         Parse new log lines
224         :return: dict
225         """
226         raw = self._get_raw_data()
227         if raw is None:
228             return None
229
230         request_time, unique_current = list(), list()
231         request_counter = {'count': 0, 'sum': 0}
232         to_netdata = dict()
233         to_netdata.update(self.data)
234         default_dict = defaultdict(lambda: 0)
235
236         for line in raw:
237             match = self.regex.findall(line)
238             if match:
239                 match_dict = dict(zip_longest('address method url code sent resp_length resp_time'.split(), match[0]))
240                 try:
241                     code = ''.join([match_dict['code'][0], 'xx'])
242                     to_netdata[code] += 1
243                 except KeyError:
244                     to_netdata['0xx'] += 1
245                 # detailed response code
246                 if self.detailed_response_codes:
247                     self._get_data_detailed_response_codes(match_dict['code'], default_dict)
248                 # requests per url
249                 if self.url_pattern:
250                     self._get_data_per_url(match_dict['url'], default_dict)
251                 # requests per http method
252                 self._get_data_http_method(match_dict['method'], default_dict)
253
254                 to_netdata['bytes_sent'] += int(match_dict['sent'])
255
256                 if match_dict['resp_length'] and match_dict['resp_time']:
257                     to_netdata['resp_length'] += int(match_dict['resp_length'])
258                     resp_time = self.resp_time_func(float(match_dict['resp_time']))
259                     bisect.insort_left(request_time, resp_time)
260                     request_counter['count'] += 1
261                     request_counter['sum'] += resp_time
262                 # unique clients ips
263                 if address_not_in_pool(self.unique_all_time, match_dict['address'],
264                                        self.storage['unique_tot_ipv4'] + self.storage['unique_tot_ipv6']):
265                     if '.' in match_dict['address']:
266                         self.storage['unique_tot_ipv4'] += 1
267                     else:
268                         self.storage['unique_tot_ipv6'] += 1
269                 if address_not_in_pool(unique_current, match_dict['address'],
270                                        to_netdata['unique_cur_ipv4'] + to_netdata['unique_cur_ipv6']):
271                     if '.' in match_dict['address']:
272                         to_netdata['unique_cur_ipv4'] += 1
273                     else:
274                         to_netdata['unique_cur_ipv6'] += 1
275             else:
276                 to_netdata['unmatched'] += 1
277         # timings
278         if request_time:
279             to_netdata['resp_time_min'] = request_time[0]
280             to_netdata['resp_time_avg'] = float(request_counter['sum']) / request_counter['count']
281             to_netdata['resp_time_max'] = request_time[-1]
282         to_netdata.update(self.storage)
283         to_netdata.update(default_dict)
284         return to_netdata
285
286     def _get_data_detailed_response_codes(self, code, default_dict):
287         if code not in self.storage:
288             chart_string_copy = self.detailed_chart
289             self.detailed_chart = self.add_new_dimension(code, [code, code, 'absolute'],
290                                                          chart_string_copy, 'detailed_response_codes')
291         default_dict[code] += 1
292
293     def _get_data_http_method(self, method, default_dict):
294         if method not in self.storage:
295             chart_string_copy = self.http_method_chart
296             self.http_method_chart = self.add_new_dimension(method, [method, method, 'absolute'],
297                                                             chart_string_copy, 'http_method')
298         default_dict[method] += 1
299
300     def _get_data_per_url(self, url, default_dict):
301         match = None
302         for elem in self.url_pattern:
303             if elem.pattern.search(url):
304                 default_dict[elem.description] += 1
305                 match = True
306                 break
307         if not match:
308             default_dict['other_url'] += 1
309
310
311 def address_not_in_pool(pool, address, pool_size):
312     index = bisect.bisect_left(pool, address)
313     if index < pool_size:
314         if pool[index] == address:
315             return False
316         else:
317             bisect.insort_left(pool, address)
318             return True
319     else:
320         bisect.insort_left(pool, address)
321         return True