]> arthur.barton.de Git - netdata.git/blob - python.d/web_log.chart.py
mongodb_plugin: mongo 2.4 compatibility #1
[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
13 priority = 60000
14 retries = 60
15
16 ORDER = ['response_statuses', 'response_codes', 'bandwidth', 'response_time', 'requests_per_url', 'http_method',
17          'requests_per_ipproto', 'clients', 'clients_all']
18 CHARTS = {
19     'response_codes': {
20         'options': [None, 'Response Codes', 'requests/s', 'responses', 'web_log.response_codes', 'stacked'],
21         'lines': [
22             ['2xx', '2xx', 'incremental'],
23             ['5xx', '5xx', 'incremental'],
24             ['3xx', '3xx', 'incremental'],
25             ['4xx', '4xx', 'incremental'],
26             ['1xx', '1xx', 'incremental'],
27             ['0xx', 'other', 'incremental'],
28             ['unmatched', 'unmatched', 'incremental']
29         ]},
30     'bandwidth': {
31         'options': [None, 'Bandwidth', 'KB/s', 'bandwidth', 'web_log.bandwidth', 'area'],
32         'lines': [
33             ['resp_length', 'received', 'incremental', 1, 1024],
34             ['bytes_sent', 'sent', 'incremental', -1, 1024]
35         ]},
36     'response_time': {
37         'options': [None, 'Processing Time', 'milliseconds', 'timings', 'web_log.response_time', 'area'],
38         'lines': [
39             ['resp_time_min', 'min', 'incremental', 1, 1000],
40             ['resp_time_max', 'max', 'incremental', 1, 1000],
41             ['resp_time_avg', 'avg', 'incremental', 1, 1000]
42         ]},
43     'clients': {
44         'options': [None, 'Current Poll Unique Client IPs', 'unique ips', 'clients', 'web_log.clients', 'stacked'],
45         'lines': [
46             ['unique_cur_ipv4', 'ipv4', 'incremental', 1, 1],
47             ['unique_cur_ipv6', 'ipv6', 'incremental', 1, 1]
48         ]},
49     'clients_all': {
50         'options': [None, 'All Time Unique Client IPs', 'unique ips', 'clients', 'web_log.clients_all', 'stacked'],
51         'lines': [
52             ['unique_tot_ipv4', 'ipv4', 'absolute', 1, 1],
53             ['unique_tot_ipv6', 'ipv6', 'absolute', 1, 1]
54         ]},
55     'http_method': {
56         'options': [None, 'Requests Per HTTP Method', 'requests/s', 'http methods', 'web_log.http_method', 'stacked'],
57         'lines': [
58             ['GET', 'GET', 'incremental', 1, 1]
59         ]},
60     'requests_per_ipproto': {
61         'options': [None, 'Requests Per IP Protocol', 'requests/s', 'ip protocols', 'web_log.requests_per_ipproto',
62                     'stacked'],
63         'lines': [
64             ['req_ipv4', 'ipv4', 'incremental', 1, 1],
65             ['req_ipv6', 'ipv6', 'incremental', 1, 1]
66         ]},
67     'response_statuses': {
68         'options': [None, 'Response Statuses', 'requests/s', 'responses', 'web_log.response_statuses',
69                     'stacked'],
70         'lines': [
71             ['successful_requests', 'success', 'incremental', 1, 1],
72             ['server_errors', 'error', 'incremental', 1, 1],
73             ['redirects', 'redirect', 'incremental', 1, 1],
74             ['bad_requests', 'bad', 'incremental', 1, 1],
75             ['other_requests', 'other', 'incremental', 1, 1]
76         ]}
77 }
78
79 NAMED_URL_PATTERN = namedtuple('URL_PATTERN', ['description', 'pattern'])
80
81
82 class Service(LogService):
83     def __init__(self, configuration=None, name=None):
84         """
85         :param configuration:
86         :param name:
87         # self._get_data = None  # will be assigned in 'check' method.
88         # self.order = None  # will be assigned in 'create_*_method' method.
89         # self.definitions = None  # will be assigned in 'create_*_method' method.
90         """
91         LogService.__init__(self, configuration=configuration, name=name)
92         # Variables from module configuration file
93         self.type = self.configuration.get('type', 'web_access')
94         self.log_path = self.configuration.get('path')
95         self.url_pattern = self.configuration.get('categories')  # dict
96         self.custom_log_format = self.configuration.get('custom_log_format')  # dict
97         # Instance variables
98         self.regex = None  # will be assigned in 'find_regex' or 'find_regex_custom' method
99         self.data = {'bytes_sent': 0, 'resp_length': 0, 'resp_time_min': 0, 'resp_time_max': 0,
100                      'resp_time_avg': 0, 'unique_cur_ipv4': 0, 'unique_cur_ipv6': 0, '2xx': 0,
101                      '5xx': 0, '3xx': 0, '4xx': 0, '1xx': 0, '0xx': 0, 'unmatched': 0, 'req_ipv4': 0,
102                      'req_ipv6': 0, 'unique_tot_ipv4': 0, 'unique_tot_ipv6': 0, 'successful_requests': 0,
103                      'redirects': 0, 'bad_requests': 0, 'server_errors': 0, 'other_requests': 0, 'GET': 0}
104
105     def check(self):
106         """
107         :return: bool
108
109         1. "log_path" is specified in the module configuration file
110         2. "log_path" must be readable by netdata user and must exist
111         3. "log_path' must not be empty. We need at least 1 line to find appropriate pattern to parse
112         4. other checks depends on log "type"
113         """
114         if not self.log_path:
115             self.error('log path is not specified')
116             return False
117
118         if not access(self.log_path, R_OK):
119             self.error('%s not readable or not exist' % self.log_path)
120             return False
121
122         if not getsize(self.log_path):
123             self.error('%s is empty' % self.log_path)
124             return False
125
126         # Read last line (or first if there is only one line)
127         with open(self.log_path, 'rb') as logs:
128             logs.seek(-2, 2)
129             while logs.read(1) != b'\n':
130                 logs.seek(-2, 1)
131                 if logs.tell() == 0:
132                     break
133             last_line = logs.readline()
134
135         try:
136             last_line = last_line.decode()
137         except UnicodeDecodeError:
138             try:
139                 last_line = last_line.decode(encoding='utf-8')
140             except (TypeError, UnicodeDecodeError) as error:
141                 self.error(str(error))
142                 return False
143
144         if self.type == 'web_access':
145             self.unique_all_time = list()  # sorted list of unique IPs
146             self.detailed_response_codes = self.configuration.get('detailed_response_codes', True)
147             self.all_time = self.configuration.get('all_time', True)
148
149             # Custom_log_format or predefined log format.
150             if self.custom_log_format:
151                 match_dict, error = self.find_regex_custom(last_line)
152             else:
153                 match_dict, error = self.find_regex(last_line)
154
155             # "match_dict" is None if there are any problems
156             if match_dict is None:
157                 self.error(str(error))
158                 return False
159
160             # self.url_pattern check
161             if self.url_pattern:
162                 self.url_pattern = check_req_per_url_pattern('rpu', self.url_pattern)
163
164             self.create_access_charts(match_dict)  # Create charts
165             self._get_data = self._get_access_data  # _get_data assignment
166         else:
167             self.error('Not implemented')
168             return False
169
170         # Double check
171         if not self.regex:
172             self.error('That can not happen, but it happened. "regex" is None')
173
174         self.info('Collected data: %s' % list(match_dict.keys()))
175         return True
176
177     def find_regex_custom(self, last_line):
178         """
179         :param last_line: str: literally last line from log file
180         :return: tuple where:
181         [0]: dict or None:  match_dict or None
182         [1]: str: error description
183
184         We are here only if "custom_log_format" is in logs. We need to make sure:
185         1. "custom_log_format" is a dict
186         2. "pattern" in "custom_log_format" and pattern is <str> instance
187         3. if "time_multiplier" is in "custom_log_format" it must be <int> instance
188
189         If all parameters is ok we need to make sure:
190         1. Pattern search is success
191         2. Pattern search contains named subgroups (?P<subgroup_name>) (= "match_dict")
192
193         If pattern search is success we need to make sure:
194         1. All mandatory keys ['address', 'code', 'bytes_sent', 'method', 'url'] are in "match_dict"
195
196         If this is True we need to make sure:
197         1. All mandatory key values from "match_dict" have the correct format
198          ("code" is integer, "method" is uppercase word, etc)
199
200         If non mandatory keys in "match_dict" we need to make sure:
201         1. All non mandatory key values from match_dict ['resp_length', 'resp_time'] have the correct format
202          ("resp_length" is integer or "-", "resp_time" is integer or float)
203
204         """
205         if not is_dict(self.custom_log_format):
206             return find_regex_return(msg='Custom log: "custom_log_format" is not a <dict>')
207
208         pattern = self.custom_log_format.get('pattern')
209         if not (pattern and isinstance(pattern, str)):
210             return find_regex_return(msg='Custom log: "pattern" option is not specified or type is not <str>')
211
212         resp_time_func = self.custom_log_format.get('time_multiplier') or 0
213
214         if not isinstance(resp_time_func, int):
215             return find_regex_return(msg='Custom log: "time_multiplier" is not an integer')
216
217         try:
218             regex = re.compile(pattern)
219         except re.error as error:
220             return find_regex_return(msg='Pattern compile error: %s' % str(error))
221
222         match = regex.search(last_line)
223         if match:
224             match_dict = match.groupdict() or None
225         else:
226             return find_regex_return(msg='Custom log: pattern search FAILED')
227
228         if match_dict is None:
229             find_regex_return(msg='Custom log: search OK but contains no named subgroups'
230                                   ' (you need to use ?P<subgroup_name>)')
231         else:
232             mandatory_dict = {'address': r'[\da-f.:]+',
233                               'code': r'[1-9]\d{2}',
234                               'method': r'[A-Z]+',
235                               'bytes_sent': r'\d+|-'}
236             optional_dict = {'resp_length': r'\d+',
237                              'resp_time': r'[\d.]+'}
238
239             mandatory_values = set(mandatory_dict) - set(match_dict)
240             if mandatory_values:
241                 return find_regex_return(msg='Custom log: search OK but some mandatory keys (%s) are missing'
242                                          % list(mandatory_values))
243             else:
244                 for key in mandatory_dict:
245                     if not re.search(mandatory_dict[key], match_dict[key]):
246                         return find_regex_return(msg='Custom log: can\'t parse "%s": %s'
247                                                      % (key, match_dict[key]))
248
249             optional_values = set(optional_dict) & set(match_dict)
250             for key in optional_values:
251                 if not re.search(optional_dict[key], match_dict[key]):
252                     return find_regex_return(msg='Custom log: can\'t parse "%s": %s'
253                                                  % (key, match_dict[key]))
254
255             dot_in_time = '.' in match_dict.get('resp_time', '')
256             if dot_in_time:
257                 self.resp_time_func = lambda time: time * (resp_time_func or 1000000)
258             else:
259                 self.resp_time_func = lambda time: time * (resp_time_func or 1)
260
261             self.regex = regex
262             return find_regex_return(match_dict=match_dict)
263
264     def find_regex(self, last_line):
265         """
266         :param last_line: str: literally last line from log file
267         :return: tuple where:
268         [0]: dict or None:  match_dict or None
269         [1]: str: error description
270         We need to find appropriate pattern for current log file
271         All logic is do a regex search through the string for all predefined patterns
272         until we find something or fail.
273         """
274         # REGEX: 1.IPv4 address 2.HTTP method 3. URL 4. Response code
275         # 5. Bytes sent 6. Response length 7. Response process time
276         acs_default = re.compile(r'(?P<address>[\da-f.:]+)'
277                                  r' -.*?"(?P<method>[A-Z]+)'
278                                  r' (?P<url>.*?)"'
279                                  r' (?P<code>[1-9]\d{2})'
280                                  r' (?P<bytes_sent>\d+|-)')
281
282         acs_apache_ext_insert = re.compile(r'(?P<address>[\da-f.:]+)'
283                                            r' -.*?"(?P<method>[A-Z]+)'
284                                            r' (?P<url>.*?)"'
285                                            r' (?P<code>[1-9]\d{2})'
286                                            r' (?P<bytes_sent>\d+|-)'
287                                            r' (?P<resp_length>\d+)'
288                                            r' (?P<resp_time>\d+) ')
289
290         acs_apache_ext_append = re.compile(r'(?P<address>[\da-f.:]+)'
291                                            r' -.*?"(?P<method>[A-Z]+)'
292                                            r' (?P<url>.*?)"'
293                                            r' (?P<code>[1-9]\d{2})'
294                                            r' (?P<bytes_sent>\d+|-)'
295                                            r' .*?'
296                                            r' (?P<resp_length>\d+)'
297                                            r' (?P<resp_time>\d+)'
298                                            r'(?: |$)')
299
300         acs_nginx_ext_insert = re.compile(r'(?P<address>[\da-f.:]+)'
301                                           r' -.*?"(?P<method>[A-Z]+)'
302                                           r' (?P<url>.*?)"'
303                                           r' (?P<code>[1-9]\d{2})'
304                                           r' (?P<bytes_sent>\d+)'
305                                           r' (?P<resp_length>\d+)'
306                                           r' (?P<resp_time>\d\.\d+) ')
307
308         acs_nginx_ext_append = re.compile(r'(?P<address>[\da-f.:]+)'
309                                           r' -.*?"(?P<method>[A-Z]+)'
310                                           r' (?P<url>.*?)"'
311                                           r' (?P<code>[1-9]\d{2})'
312                                           r' (?P<bytes_sent>\d+)'
313                                           r' .*?'
314                                           r' (?P<resp_length>\d+)'
315                                           r' (?P<resp_time>\d\.\d+)')
316
317         def func_usec(time):
318             return time
319
320         def func_sec(time):
321             return time * 1000000
322
323         r_regex = [acs_apache_ext_insert, acs_apache_ext_append, acs_nginx_ext_insert,
324                    acs_nginx_ext_append, acs_default]
325         r_function = [func_usec, func_usec, func_sec, func_sec, func_usec]
326         regex_function = zip(r_regex, r_function)
327
328         match_dict = dict()
329         for regex, function in regex_function:
330             match = regex.search(last_line)
331             if match:
332                 self.regex = regex
333                 self.resp_time_func = function
334                 match_dict = match.groupdict()
335                 break
336
337         return find_regex_return(match_dict=match_dict or None,
338                                  msg='Unknown log format. You need to use "custom_log_format" feature.')
339
340     def create_access_charts(self, match_dict):
341         """
342         :param match_dict: dict: regex.search.groupdict(). Ex. {'address': '127.0.0.1', 'code': '200', 'method': 'GET'}
343         :return:
344         Create additional charts depending on the 'match_dict' keys and configuration file options
345         1. 'time_response' chart is removed if there is no 'resp_time' in match_dict.
346         2. Other stuff is just remove/add chart depending on yes/no in conf
347         """
348         def find_job_name(override_name, name):
349             """
350             :param override_name: str: 'name' var from configuration file
351             :param name: str: 'job_name' from configuration file
352             :return: str: new job name
353             We need this for dynamic charts. Actually same logic as in python.d.plugin.
354             """
355             add_to_name = override_name or name
356             if add_to_name:
357                 return '_'.join(['web_log', re.sub('\s+', '_', add_to_name)])
358             else:
359                 return 'web_log'
360
361         self.order = ORDER[:]
362         self.definitions = deepcopy(CHARTS)
363
364         job_name = find_job_name(self.override_name, self.name)
365         self.detailed_chart = 'CHART %s.detailed_response_codes ""' \
366                               ' "Detailed Response Codes" requests/s responses' \
367                               ' web_log.detailed_response_codes stacked 1 %s\n' % (job_name, self.update_every)
368         self.http_method_chart = 'CHART %s.http_method' \
369                                  ' "" "Requests Per HTTP Method" requests/s "http methods"' \
370                                  ' web_log.http_method stacked 2 %s\n' \
371                                  'DIMENSION GET GET incremental\n' % (job_name, self.update_every)
372
373         # Remove 'request_time' chart from ORDER if resp_time not in match_dict
374         if 'resp_time' not in match_dict:
375             self.order.remove('response_time')
376         # Remove 'clients_all' chart from ORDER if specified in the configuration
377         if not self.all_time:
378             self.order.remove('clients_all')
379         # Add 'detailed_response_codes' chart if specified in the configuration
380         if self.detailed_response_codes:
381             self.order.append('detailed_response_codes')
382             self.definitions['detailed_response_codes'] = {'options': [None, 'Detailed Response Codes', 'requests/s',
383                                                                        'responses', 'web_log.detailed_response_codes',
384                                                                        'stacked'],
385                                                            'lines': []}
386
387         # Add 'requests_per_url' chart if specified in the configuration
388         if self.url_pattern:
389             self.definitions['requests_per_url'] = {'options': [None, 'Requests Per Url', 'requests/s',
390                                                                 'urls', 'web_log.requests_per_url', 'stacked'],
391                                                     'lines': [['rpu_other', 'other', 'incremental']]}
392             for elem in self.url_pattern:
393                 self.definitions['requests_per_url']['lines'].append([elem.description, elem.description[4:],
394                                                                       'incremental'])
395                 self.data.update({elem.description: 0})
396             self.data.update({'rpu_other': 0})
397         else:
398             self.order.remove('requests_per_url')
399
400     def add_new_dimension(self, dimension, line_list, chart_string, key):
401         """
402         :param dimension: str: response status code. Ex.: '202', '499'
403         :param line_list: list: Ex.: ['202', '202', 'incremental']
404         :param chart_string: Current string we need to pass to netdata to rebuild the chart
405         :param key: str: CHARTS dict key (chart name). Ex.: 'response_time'
406         :return: str: new chart string = previous + new dimensions
407         """
408         self.data.update({dimension: 0})
409         # SET method check if dim in _dimensions
410         self._dimensions.append(dimension)
411         # UPDATE method do SET only if dim in definitions
412         self.definitions[key]['lines'].append(line_list)
413         chart = chart_string
414         chart += "%s %s\n" % ('DIMENSION', ' '.join(line_list))
415         print(chart)
416         return chart
417
418     def _get_access_data(self):
419         """
420         Parse new log lines
421         :return: dict OR None
422         None if _get_raw_data method fails.
423         In all other cases - dict.
424         """
425         raw = self._get_raw_data()
426         if raw is None:
427             return None
428
429         request_time, unique_current = list(), list()
430         request_counter = {'count': 0, 'sum': 0}
431         ip_address_counter = {'unique_cur_ip': 0}
432         for line in raw:
433             match = self.regex.search(line)
434             if match:
435                 match_dict = match.groupdict()
436                 try:
437                     code = ''.join([match_dict['code'][0], 'xx'])
438                     self.data[code] += 1
439                 except KeyError:
440                     self.data['0xx'] += 1
441                 # detailed response code
442                 if self.detailed_response_codes:
443                     self._get_data_detailed_response_codes(match_dict['code'])
444                 # response statuses
445                 self._get_data_statuses(match_dict['code'])
446                 # requests per url
447                 if self.url_pattern:
448                     self._get_data_per_url(match_dict['url'])
449                 # requests per http method
450                 self._get_data_http_method(match_dict['method'])
451                 # bandwidth sent
452                 bytes_sent = match_dict['bytes_sent'] if '-' not in match_dict['bytes_sent'] else 0
453                 self.data['bytes_sent'] += int(bytes_sent)
454                 # request processing time and bandwidth received
455                 if 'resp_length' in match_dict:
456                     self.data['resp_length'] += int(match_dict['resp_length'])
457                 if 'resp_time' in match_dict:
458                     resp_time = self.resp_time_func(float(match_dict['resp_time']))
459                     bisect.insort_left(request_time, resp_time)
460                     request_counter['count'] += 1
461                     request_counter['sum'] += resp_time
462                 # requests per ip proto
463                 proto = 'ipv4' if '.' in match_dict['address'] else 'ipv6'
464                 self.data['req_' + proto] += 1
465                 # unique clients ips
466                 if address_not_in_pool(self.unique_all_time, match_dict['address'],
467                                        self.data['unique_tot_ipv4'] + self.data['unique_tot_ipv6']):
468                         self.data['unique_tot_' + proto] += 1
469                 if address_not_in_pool(unique_current, match_dict['address'], ip_address_counter['unique_cur_ip']):
470                         self.data['unique_cur_' + proto] += 1
471                         ip_address_counter['unique_cur_ip'] += 1
472             else:
473                 self.data['unmatched'] += 1
474
475         # timings
476         if request_time:
477             self.data['resp_time_min'] += int(request_time[0])
478             self.data['resp_time_avg'] += int(round(float(request_counter['sum']) / request_counter['count']))
479             self.data['resp_time_max'] += int(request_time[-1])
480         return self.data
481
482     def _get_data_detailed_response_codes(self, code):
483         """
484         :param code: str: CODE from parsed line. Ex.: '202, '499'
485         :return:
486         Calls add_new_dimension method If the value is found for the first time
487         """
488         if code not in self.data:
489             chart_string_copy = self.detailed_chart
490             self.detailed_chart = self.add_new_dimension(code, [code, code, 'incremental'],
491                                                          chart_string_copy, 'detailed_response_codes')
492         self.data[code] += 1
493
494     def _get_data_http_method(self, method):
495         """
496         :param method: str: METHOD from parsed line. Ex.: 'GET', 'POST'
497         :return:
498         Calls add_new_dimension method If the value is found for the first time
499         """
500         if method not in self.data:
501             chart_string_copy = self.http_method_chart
502             self.http_method_chart = self.add_new_dimension(method, [method, method, 'incremental'],
503                                                             chart_string_copy, 'http_method')
504         self.data[method] += 1
505
506     def _get_data_per_url(self, url):
507         """
508         :param url: str: URL from parsed line
509         :return:
510         Scan through string looking for the first location where patterns produce a match for all user
511         defined patterns
512         """
513         match = None
514         for elem in self.url_pattern:
515             if elem.pattern.search(url):
516                 self.data[elem.description] += 1
517                 match = True
518                 break
519         if not match:
520             self.data['rpu_other'] += 1
521
522     def _get_data_statuses(self, code):
523         """
524         :param code: str: response status code. Ex.: '202', '499'
525         :return:
526         """
527         code_class = code[0]
528         if code_class == '2' or code == '304' or code_class == '1':
529             self.data['successful_requests'] += 1
530         elif code_class == '3':
531             self.data['redirects'] += 1
532         elif code_class == '4':
533             self.data['bad_requests'] += 1
534         elif code_class == '5':
535             self.data['server_errors'] += 1
536         else:
537             self.data['other_requests'] += 1
538
539
540 def address_not_in_pool(pool, address, pool_size):
541     """
542     :param pool: list of ip addresses
543     :param address: ip address
544     :param pool_size: current pool size
545     :return: True if address not in pool. False if address in pool.
546     """
547     index = bisect.bisect_left(pool, address)
548     if index < pool_size:
549         if pool[index] == address:
550             return False
551         else:
552             bisect.insort_left(pool, address)
553             return True
554     else:
555         bisect.insort_left(pool, address)
556         return True
557
558
559 def find_regex_return(match_dict=None, msg='Generic error message'):
560     """
561     :param match_dict: dict: re.search.groupdict() or None
562     :param msg: str: error description
563     :return: tuple:
564     """
565     return match_dict, msg
566
567
568 def check_req_per_url_pattern(string, url_pattern):
569     """
570     :param string: str:
571     :param url_pattern: dict: ex. {'dim1': 'pattern1>', 'dim2': '<pattern2>'}
572     :return: list of named tuples or None:
573      We need to make sure all patterns are valid regular expressions
574     """
575     if not is_dict(url_pattern):
576         return None
577
578     result = list()
579
580     def is_valid_pattern(pattern):
581         """
582         :param pattern: str
583         :return: re.compile(pattern) or None
584         """
585         if not isinstance(pattern, str):
586             return False
587         else:
588             try:
589                 compile_pattern = re.compile(pattern)
590             except re.error:
591                 return False
592             else:
593                 return compile_pattern
594
595     for dimension, regex in url_pattern.items():
596         valid_pattern = is_valid_pattern(regex)
597         if isinstance(dimension, str) and valid_pattern:
598             result.append(NAMED_URL_PATTERN(description='_'.join([string, dimension]), pattern=valid_pattern))
599
600     return result or None
601
602
603 def is_dict(obj):
604     """
605     :param obj: dict:
606     :return: True or False
607     obj can be <dict> or <OrderedDict>
608     """
609     try:
610         obj.keys()
611     except AttributeError:
612         return False
613     else:
614         return True