]> arthur.barton.de Git - netdata.git/blob - python.d/web_log.chart.py
web_log plugin: reponse statuses chart 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 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_statuses', 'response_codes', 'bandwidth', 'response_time', 'requests_per_url', 'http_method',
21          'requests_per_ipproto', 'clients', 'clients_all']
22 CHARTS = {
23     'response_codes': {
24         'options': [None, 'Response Codes', 'requests/s', 'responses', 'web_log.response_codes', 'stacked'],
25         'lines': [
26             ['2xx', '2xx', 'incremental'],
27             ['5xx', '5xx', 'incremental'],
28             ['3xx', '3xx', 'incremental'],
29             ['4xx', '4xx', 'incremental'],
30             ['1xx', '1xx', 'incremental'],
31             ['0xx', 'other', 'incremental'],
32             ['unmatched', 'unmatched', 'incremental']
33         ]},
34     'bandwidth': {
35         'options': [None, 'Bandwidth', 'KB/s', 'bandwidth', 'web_log.bandwidth', 'area'],
36         'lines': [
37             ['resp_length', 'received', 'incremental', 1, 1024],
38             ['bytes_sent', 'sent', 'incremental', -1, 1024]
39         ]},
40     'response_time': {
41         'options': [None, 'Processing Time', 'milliseconds', 'timings', 'web_log.response_time', 'area'],
42         'lines': [
43             ['resp_time_min', 'min', 'incremental', 1, 1000],
44             ['resp_time_max', 'max', 'incremental', 1, 1000],
45             ['resp_time_avg', 'avg', 'incremental', 1, 1000]
46         ]},
47     'clients': {
48         'options': [None, 'Current Poll Unique Client IPs', 'unique ips', 'clients', 'web_log.clients', 'stacked'],
49         'lines': [
50             ['unique_cur_ipv4', 'ipv4', 'incremental', 1, 1],
51             ['unique_cur_ipv6', 'ipv6', 'incremental', 1, 1]
52         ]},
53     'clients_all': {
54         'options': [None, 'All Time Unique Client IPs', 'unique ips', 'clients', 'web_log.clients_all', 'stacked'],
55         'lines': [
56             ['unique_tot_ipv4', 'ipv4', 'absolute', 1, 1],
57             ['unique_tot_ipv6', 'ipv6', 'absolute', 1, 1]
58         ]},
59     'http_method': {
60         'options': [None, 'Requests Per HTTP Method', 'requests/s', 'http methods', 'web_log.http_method', 'stacked'],
61         'lines': [
62         ]},
63     'requests_per_ipproto': {
64         'options': [None, 'Requests Per IP Protocol', 'requests/s', 'ip protocols', 'web_log.requests_per_ipproto',
65                     'stacked'],
66         'lines': [
67             ['req_ipv4', 'ipv4', 'incremental', 1, 1],
68             ['req_ipv6', 'ipv6', 'incremental', 1, 1]
69         ]},
70     'response_statuses': {
71         'options': [None, 'Response Statuses', 'requests/s', 'responses', 'web_log.response_statuses',
72                     'stacked'],
73         'lines': [
74             ['successful_requests', 'successful', 'incremental', 1, 1],
75             ['redirects', None, 'incremental', 1, 1],
76             ['bad_requests', 'bad', 'incremental', 1, 1],
77             ['server_errors', None, 'incremental', 1, 1]
78         ]}
79 }
80
81 NAMED_URL_PATTERN = namedtuple('URL_PATTERN', ['description', 'pattern'])
82
83
84 class Service(LogService):
85     def __init__(self, configuration=None, name=None):
86         LogService.__init__(self, configuration=configuration, name=name)
87         # Variables from module configuration file
88         self.log_path = self.configuration.get('path')
89         self.detailed_response_codes = self.configuration.get('detailed_response_codes', True)
90         self.all_time = self.configuration.get('all_time', True)
91         self.url_pattern = self.configuration.get('categories')  # dict
92         self.regex = None  # will be assigned in 'find_regex' method
93         self.resp_time_func = None  # will be assigned in 'find_regex' method
94         self._get_data = None  # will be assigned in 'check' method.
95         self.order = None  # will be assigned in 'create_*_method' method.
96         self.definitions = None  # will be assigned in 'create_*_method' method.
97         self.detailed_chart = None  # will be assigned in 'create_*_method' method.
98         self.http_method_chart = None  # will be assigned in 'create_*_method' method.
99         # sorted list of unique IPs
100         self.unique_all_time = list()
101         # if there is no new logs this dict  returned to netdata
102         self.data = {'bytes_sent': 0, 'resp_length': 0, 'resp_time_min': 0, 'resp_time_max': 0,
103                      'resp_time_avg': 0, 'unique_cur_ipv4': 0, 'unique_cur_ipv6': 0, '2xx': 0,
104                      '5xx': 0, '3xx': 0, '4xx': 0, '1xx': 0, '0xx': 0, 'unmatched': 0, 'req_ipv4': 0,
105                      'req_ipv6': 0, 'unique_tot_ipv4': 0, 'unique_tot_ipv6': 0, 'successful_requests': 0,
106                      'redirects': 0, 'bad_requests': 0, 'server_errors': 0}
107
108     def check(self):
109         if not self.log_path:
110             self.error('log path is not specified')
111             return False
112
113         # log_path must be readable
114         if not access(self.log_path, R_OK):
115             self.error('%s not readable or not exist' % self.log_path)
116             return False
117
118         # log_path file should not be empty
119         if not getsize(self.log_path):
120             self.error('%s is empty' % self.log_path)
121             return False
122
123         # Read last line (or first if there is only one line)
124         with open(self.log_path, 'rb') as logs:
125             logs.seek(-2, 2)
126             while logs.read(1) != b'\n':
127                 logs.seek(-2, 1)
128                 if logs.tell() == 0:
129                     break
130             last_line = logs.readline().decode(encoding='utf-8')
131
132         # Parse last line
133         regex_name = self.find_regex(last_line)
134         if not regex_name:
135             self.error('Can\'t parse %s' % self.log_path)
136             return False
137
138         if regex_name.startswith('acs_'):
139             self.create_access_charts(regex_name)
140             if regex_name == 'acs_default':
141                 self.info('Not all data collected. You need to modify LogFormat.')
142             self._get_data = self._get_access_data
143             self.info('Used regex: %s' % regex_name)
144             return True
145         else:
146             # If it's not access_logs.. Not used at the moment
147             return False
148
149     def find_regex(self, last_line):
150         """
151         :param last_line: str: literally last line from log file
152         :return: regex_name
153         It's sad but different web servers has different logs formats
154         We need to find appropriate regex for current log file
155         All logic is do a regex search through the string for all patterns
156         until we find something or fail.
157         """
158         # REGEX: 1.IPv4 address 2.HTTP method 3. URL 4. Response code
159         # 5. Bytes sent 6. Response length 7. Response process time
160         acs_default = re.compile(r'([\da-f.:]+)'
161                                  r' -.*?"([A-Z]+)'
162                                  r' (.*?)"'
163                                  r' ([1-9]\d{2})'
164                                  r' (\d+|-)')
165
166         acs_apache_ext_insert = re.compile(r'([\da-f.:]+)'
167                                            r' -.*?"([A-Z]+)'
168                                            r' (.*?)"'
169                                            r' ([1-9]\d{2})'
170                                            r' (\d+|-)'
171                                            r' (\d+)'
172                                            r' (\d+) ')
173
174         acs_apache_ext_append = re.compile(r'([\da-f.:]+)'
175                                            r' -.*?"([A-Z]+)'
176                                            r' (.*?)"'
177                                            r' ([1-9]\d{2})'
178                                            r' (\d+|-)'
179                                            r' .*?'
180                                            r' (\d+)'
181                                            r' (\d+)'
182                                            r'(?: |$)')
183
184         acs_nginx_ext_insert = re.compile(r'([\da-f.:]+)'
185                                           r' -.*?"([A-Z]+)'
186                                           r' (.*?)"'
187                                           r' ([1-9]\d{2})'
188                                           r' (\d+)'
189                                           r' (\d+)'
190                                           r' (\d\.\d+) ')
191
192         acs_nginx_ext_append = re.compile(r'([\da-f.:]+)'
193                                           r' -.*?"([A-Z]+)'
194                                           r' (.*?)"'
195                                           r' ([1-9]\d{2})'
196                                           r' (\d+)'
197                                           r' .*?'
198                                           r' (\d+)'
199                                           r' (\d\.\d+)')
200
201         r_regex = [acs_apache_ext_insert, acs_apache_ext_append, acs_nginx_ext_insert,
202                    acs_nginx_ext_append, acs_default]
203         r_function = [lambda x: x, lambda x: x, lambda x: x * 1000000, lambda x: x * 1000000, lambda x: x]
204         r_name = ['acs_apache_ext_insert', 'acs_apache_ext_append', 'acs_nginx_ext_insert',
205                   'acs_nginx_ext_append', 'acs_default']
206         regex_function_name = zip(r_regex, r_function, r_name)
207
208         regex_name = None
209         for regex, function, name in regex_function_name:
210             if regex.search(last_line):
211                 self.regex = regex
212                 self.resp_time_func = function
213                 regex_name = name
214                 break
215         return regex_name
216
217     def create_access_charts(self, regex_name):
218         """
219         :param regex_name: str: regex name from 'find_regex' method. Ex.: 'apache_extended', 'nginx_extended'
220         :return:
221         Create additional charts depending on the 'find_regex' result (parsed_line) and configuration file
222         1. 'time_response' chart is removed if there is no 'time_response' in logs.
223         2. Other stuff is just remove/add chart depending on yes/no in conf
224         """
225         def find_job_name(override_name, name):
226             """
227             :param override_name: str: 'name' var from configuration file
228             :param name: str: 'job_name' from configuration file
229             :return: str: new job name
230             We need this for dynamic charts. Actually same logic as in python.d.plugin.
231             """
232             add_to_name = override_name or name
233             if add_to_name:
234                 return '_'.join(['web_log', re.sub('\s+', '_', add_to_name)])
235             else:
236                 return 'web_log'
237
238         self.order = ORDER[:]
239         self.definitions = deepcopy(CHARTS)
240
241         job_name = find_job_name(self.override_name, self.name)
242         self.detailed_chart = 'CHART %s.detailed_response_codes ""' \
243                               ' "Detailed Response Codes" requests/s responses' \
244                               ' web_log.detailed_response_codes stacked 1 %s\n' % (job_name, self.update_every)
245         self.http_method_chart = 'CHART %s.http_method' \
246                                  ' "" "Requests Per HTTP Method" requests/s "http methods"' \
247                                  ' web_log.http_method stacked 2 %s\n' % (job_name, self.update_every)
248
249         # Remove 'request_time' chart from ORDER if request_time not in logs
250         if regex_name == 'acs_default':
251             self.order.remove('response_time')
252         # Remove 'clients_all' chart from ORDER if specified in the configuration
253         if not self.all_time:
254             self.order.remove('clients_all')
255         # Add 'detailed_response_codes' chart if specified in the configuration
256         if self.detailed_response_codes:
257             self.order.append('detailed_response_codes')
258             self.definitions['detailed_response_codes'] = {'options': [None, 'Detailed Response Codes', 'requests/s',
259                                                                        'responses', 'web_log.detailed_response_codes',
260                                                                        'stacked'],
261                                                            'lines': []}
262
263         # Add 'requests_per_url' chart if specified in the configuration
264         if self.url_pattern:
265             self.url_pattern = [NAMED_URL_PATTERN(description=k, pattern=re.compile(v)) for k, v
266                                 in self.url_pattern.items()]
267             self.definitions['requests_per_url'] = {'options': [None, 'Requests Per Url', 'requests/s',
268                                                                 'urls', 'web_log.requests_per_url', 'stacked'],
269                                                     'lines': [['other_url', 'other', 'incremental']]}
270             for elem in self.url_pattern:
271                 self.definitions['requests_per_url']['lines'].append([elem.description, elem.description,
272                                                                       'incremental'])
273                 self.data.update({elem.description: 0})
274             self.data.update({'other_url': 0})
275         else:
276             self.order.remove('requests_per_url')
277
278     def add_new_dimension(self, dimension, line_list, chart_string, key):
279         """
280         :param dimension: str: response status code. Ex.: '202', '499'
281         :param line_list: list: Ex.: ['202', '202', 'incremental']
282         :param chart_string: Current string we need to pass to netdata to rebuild the chart
283         :param key: str: CHARTS dict key (chart name). Ex.: 'response_time'
284         :return: str: new chart string = previous + new dimensions
285         """
286         self.data.update({dimension: 0})
287         # SET method check if dim in _dimensions
288         self._dimensions.append(dimension)
289         # UPDATE method do SET only if dim in definitions
290         self.definitions[key]['lines'].append(line_list)
291         chart = chart_string
292         chart += "%s %s\n" % ('DIMENSION', ' '.join(line_list))
293         print(chart)
294         return chart
295
296     def _get_access_data(self):
297         """
298         Parse new log lines
299         :return: dict OR None
300         None if _get_raw_data method fails.
301         In all other cases - dict.
302         """
303         raw = self._get_raw_data()
304         if raw is None:
305             return None
306
307         request_time, unique_current = list(), list()
308         request_counter = {'count': 0, 'sum': 0}
309         ip_address_counter = {'unique_cur_ip': 0}
310         for line in raw:
311             match = self.regex.search(line)
312             if match:
313                 match_dict = dict(zip_longest('address method url code sent resp_length resp_time'.split(),
314                                               match.groups()))
315                 try:
316                     code = ''.join([match_dict['code'][0], 'xx'])
317                     self.data[code] += 1
318                 except KeyError:
319                     self.data['0xx'] += 1
320                 # detailed response code
321                 if self.detailed_response_codes:
322                     self._get_data_detailed_response_codes(match_dict['code'])
323                 # response statuses
324                 self._get_data_statuses(match_dict['code'])
325                 # requests per url
326                 if self.url_pattern:
327                     self._get_data_per_url(match_dict['url'])
328                 # requests per http method
329                 self._get_data_http_method(match_dict['method'])
330                 # bandwidth sent
331                 self.data['bytes_sent'] += int(match_dict['sent'] if '-' not in match_dict['sent'] else 0)
332                 # request processing time and bandwidth received
333                 if match_dict['resp_length'] and match_dict['resp_time']:
334                     self.data['resp_length'] += int(match_dict['resp_length'])
335                     resp_time = self.resp_time_func(float(match_dict['resp_time']))
336                     bisect.insort_left(request_time, resp_time)
337                     request_counter['count'] += 1
338                     request_counter['sum'] += resp_time
339                 # requests per ip proto
340                 proto = 'ipv4' if '.' in match_dict['address'] else 'ipv6'
341                 self.data['req_' + proto] += 1
342                 # unique clients ips
343                 if address_not_in_pool(self.unique_all_time, match_dict['address'],
344                                        self.data['unique_tot_ipv4'] + self.data['unique_tot_ipv6']):
345                         self.data['unique_tot_' + proto] += 1
346                 if address_not_in_pool(unique_current, match_dict['address'], ip_address_counter['unique_cur_ip']):
347                         self.data['unique_cur_' + proto] += 1
348                         ip_address_counter['unique_cur_ip'] += 1
349             else:
350                 self.data['unmatched'] += 1
351
352         # timings
353         if request_time:
354             self.data['resp_time_min'] += int(request_time[0])
355             self.data['resp_time_avg'] += int(round(float(request_counter['sum']) / request_counter['count']))
356             self.data['resp_time_max'] += int(request_time[-1])
357         return self.data
358
359     def _get_data_detailed_response_codes(self, code):
360         """
361         :param code: str: CODE from parsed line. Ex.: '202, '499'
362         :return:
363         Calls add_new_dimension method If the value is found for the first time
364         """
365         if code not in self.data:
366             chart_string_copy = self.detailed_chart
367             self.detailed_chart = self.add_new_dimension(code, [code, code, 'incremental'],
368                                                          chart_string_copy, 'detailed_response_codes')
369         self.data[code] += 1
370
371     def _get_data_http_method(self, method):
372         """
373         :param method: str: METHOD from parsed line. Ex.: 'GET', 'POST'
374         :return:
375         Calls add_new_dimension method If the value is found for the first time
376         """
377         if method not in self.data:
378             chart_string_copy = self.http_method_chart
379             self.http_method_chart = self.add_new_dimension(method, [method, method, 'incremental'],
380                                                             chart_string_copy, 'http_method')
381         self.data[method] += 1
382
383     def _get_data_per_url(self, url):
384         """
385         :param url: str: URL from parsed line
386         :return:
387         Scan through string looking for the first location where patterns produce a match for all user
388         defined patterns
389         """
390         match = None
391         for elem in self.url_pattern:
392             if elem.pattern.search(url):
393                 self.data[elem.description] += 1
394                 match = True
395                 break
396         if not match:
397             self.data['other_url'] += 1
398
399     def _get_data_statuses(self, code):
400         """
401         :param code: str: response status code. Ex.: '202', '499'
402         :return:
403         """
404         if code[0] == '2' or code == '304' or code[0] == '1':
405             self.data['successful_requests'] += 1
406         elif code[0] == '3':
407             self.data['redirects'] += 1
408         elif code[0] == '4':
409             self.data['bad_requests'] += 1
410         elif code[0] == '5':
411             self.data['server_errors'] += 1
412
413
414 def address_not_in_pool(pool, address, pool_size):
415     """
416     :param pool: list of ip addresses
417     :param address: ip address
418     :param pool_size: current size of pool
419     :return: True if address not in pool. False if address in pool
420     """
421     index = bisect.bisect_left(pool, address)
422     if index < pool_size:
423         if pool[index] == address:
424             return False
425         else:
426             bisect.insort_left(pool, address)
427             return True
428     else:
429         bisect.insort_left(pool, address)
430         return True