1 # -*- coding: utf-8 -*-
2 # Description: web log netdata python.d module
5 from base import LogService
8 from os import access, R_OK
9 from os.path import getsize
10 from collections import namedtuple
11 from copy import deepcopy
16 ORDER = ['response_statuses', 'response_codes', 'bandwidth', 'response_time', 'requests_per_url', 'http_method',
17 'requests_per_ipproto', 'clients', 'clients_all']
20 'options': [None, 'Response Codes', 'requests/s', 'responses', 'web_log.response_codes', 'stacked'],
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']
31 'options': [None, 'Bandwidth', 'KB/s', 'bandwidth', 'web_log.bandwidth', 'area'],
33 ['resp_length', 'received', 'incremental', 1, 1024],
34 ['bytes_sent', 'sent', 'incremental', -1, 1024]
37 'options': [None, 'Processing Time', 'milliseconds', 'timings', 'web_log.response_time', 'area'],
39 ['resp_time_min', 'min', 'incremental', 1, 1000],
40 ['resp_time_max', 'max', 'incremental', 1, 1000],
41 ['resp_time_avg', 'avg', 'incremental', 1, 1000]
44 'options': [None, 'Current Poll Unique Client IPs', 'unique ips', 'clients', 'web_log.clients', 'stacked'],
46 ['unique_cur_ipv4', 'ipv4', 'incremental', 1, 1],
47 ['unique_cur_ipv6', 'ipv6', 'incremental', 1, 1]
50 'options': [None, 'All Time Unique Client IPs', 'unique ips', 'clients', 'web_log.clients_all', 'stacked'],
52 ['unique_tot_ipv4', 'ipv4', 'absolute', 1, 1],
53 ['unique_tot_ipv6', 'ipv6', 'absolute', 1, 1]
56 'options': [None, 'Requests Per HTTP Method', 'requests/s', 'http methods', 'web_log.http_method', 'stacked'],
58 ['GET', 'GET', 'incremental', 1, 1]
60 'requests_per_ipproto': {
61 'options': [None, 'Requests Per IP Protocol', 'requests/s', 'ip protocols', 'web_log.requests_per_ipproto',
64 ['req_ipv4', 'ipv4', 'incremental', 1, 1],
65 ['req_ipv6', 'ipv6', 'incremental', 1, 1]
67 'response_statuses': {
68 'options': [None, 'Response Statuses', 'requests/s', 'responses', 'web_log.response_statuses',
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]
79 NAMED_URL_PATTERN = namedtuple('URL_PATTERN', ['description', 'pattern'])
82 class Service(LogService):
83 def __init__(self, configuration=None, name=None):
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.
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
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}
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"
114 if not self.log_path:
115 self.error('log path is not specified')
118 if not access(self.log_path, R_OK):
119 self.error('%s not readable or not exist' % self.log_path)
122 if not getsize(self.log_path):
123 self.error('%s is empty' % self.log_path)
126 # Read last line (or first if there is only one line)
127 with open(self.log_path, 'rb') as logs:
129 while logs.read(1) != b'\n':
133 last_line = logs.readline()
136 last_line = last_line.decode()
137 except UnicodeDecodeError:
139 last_line = last_line.decode(encoding='utf-8')
140 except (TypeError, UnicodeDecodeError) as error:
141 self.error(str(error))
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)
149 # Custom_log_format or predefined log format.
150 if self.custom_log_format:
151 match_dict, error = self.find_regex_custom(last_line)
153 match_dict, error = self.find_regex(last_line)
155 # "match_dict" is None if there are any problems
156 if match_dict is None:
157 self.error(str(error))
160 # self.url_pattern check
162 self.url_pattern = check_req_per_url_pattern('rpu', self.url_pattern)
164 self.create_access_charts(match_dict) # Create charts
165 self._get_data = self._get_access_data # _get_data assignment
167 self.error('Not implemented')
172 self.error('That can not happen, but it happened. "regex" is None')
174 self.info('Collected data: %s' % list(match_dict.keys()))
177 def find_regex_custom(self, last_line):
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
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
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")
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"
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)
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)
205 if not is_dict(self.custom_log_format):
206 return find_regex_return(msg='Custom log: "custom_log_format" is not a <dict>')
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>')
212 resp_time_func = self.custom_log_format.get('time_multiplier') or 0
214 if not isinstance(resp_time_func, int):
215 return find_regex_return(msg='Custom log: "time_multiplier" is not an integer')
218 regex = re.compile(pattern)
219 except re.error as error:
220 return find_regex_return(msg='Pattern compile error: %s' % str(error))
222 match = regex.search(last_line)
224 match_dict = match.groupdict() or None
226 return find_regex_return(msg='Custom log: pattern search FAILED')
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>)')
232 mandatory_dict = {'address': r'[\da-f.:]+',
233 'code': r'[1-9]\d{2}',
235 'bytes_sent': r'\d+|-'}
236 optional_dict = {'resp_length': r'\d+',
237 'resp_time': r'[\d.]+'}
239 mandatory_values = set(mandatory_dict) - set(match_dict)
241 return find_regex_return(msg='Custom log: search OK but some mandatory keys (%s) are missing'
242 % list(mandatory_values))
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]))
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]))
255 dot_in_time = '.' in match_dict.get('resp_time', '')
257 self.resp_time_func = lambda time: time * (resp_time_func or 1000000)
259 self.resp_time_func = lambda time: time * (resp_time_func or 1)
262 return find_regex_return(match_dict=match_dict)
264 def find_regex(self, last_line):
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.
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]+)'
279 r' (?P<code>[1-9]\d{2})'
280 r' (?P<bytes_sent>\d+|-)')
282 acs_apache_ext_insert = re.compile(r'(?P<address>[\da-f.:]+)'
283 r' -.*?"(?P<method>[A-Z]+)'
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+) ')
290 acs_apache_ext_append = re.compile(r'(?P<address>[\da-f.:]+)'
291 r' -.*?"(?P<method>[A-Z]+)'
293 r' (?P<code>[1-9]\d{2})'
294 r' (?P<bytes_sent>\d+|-)'
296 r' (?P<resp_length>\d+)'
297 r' (?P<resp_time>\d+)'
300 acs_nginx_ext_insert = re.compile(r'(?P<address>[\da-f.:]+)'
301 r' -.*?"(?P<method>[A-Z]+)'
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+) ')
308 acs_nginx_ext_append = re.compile(r'(?P<address>[\da-f.:]+)'
309 r' -.*?"(?P<method>[A-Z]+)'
311 r' (?P<code>[1-9]\d{2})'
312 r' (?P<bytes_sent>\d+)'
314 r' (?P<resp_length>\d+)'
315 r' (?P<resp_time>\d\.\d+)')
321 return time * 1000000
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)
329 for regex, function in regex_function:
330 match = regex.search(last_line)
333 self.resp_time_func = function
334 match_dict = match.groupdict()
337 return find_regex_return(match_dict=match_dict or None,
338 msg='Unknown log format. You need to use "custom_log_format" feature.')
340 def create_access_charts(self, match_dict):
342 :param match_dict: dict: regex.search.groupdict(). Ex. {'address': '127.0.0.1', 'code': '200', 'method': 'GET'}
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
348 def find_job_name(override_name, name):
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.
355 add_to_name = override_name or name
357 return '_'.join(['web_log', re.sub('\s+', '_', add_to_name)])
361 self.order = ORDER[:]
362 self.definitions = deepcopy(CHARTS)
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)
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',
387 # Add 'requests_per_url' chart if specified in the configuration
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:],
395 self.data.update({elem.description: 0})
396 self.data.update({'rpu_other': 0})
398 self.order.remove('requests_per_url')
400 def add_new_dimension(self, dimension, line_list, chart_string, key):
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
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)
414 chart += "%s %s\n" % ('DIMENSION', ' '.join(line_list))
418 def _get_access_data(self):
421 :return: dict OR None
422 None if _get_raw_data method fails.
423 In all other cases - dict.
425 raw = self._get_raw_data()
429 request_time, unique_current = list(), list()
430 request_counter = {'count': 0, 'sum': 0}
431 ip_address_counter = {'unique_cur_ip': 0}
433 match = self.regex.search(line)
435 match_dict = match.groupdict()
437 code = ''.join([match_dict['code'][0], 'xx'])
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'])
445 self._get_data_statuses(match_dict['code'])
448 self._get_data_per_url(match_dict['url'])
449 # requests per http method
450 self._get_data_http_method(match_dict['method'])
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
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
473 self.data['unmatched'] += 1
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])
482 def _get_data_detailed_response_codes(self, code):
484 :param code: str: CODE from parsed line. Ex.: '202, '499'
486 Calls add_new_dimension method If the value is found for the first time
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')
494 def _get_data_http_method(self, method):
496 :param method: str: METHOD from parsed line. Ex.: 'GET', 'POST'
498 Calls add_new_dimension method If the value is found for the first time
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
506 def _get_data_per_url(self, url):
508 :param url: str: URL from parsed line
510 Scan through string looking for the first location where patterns produce a match for all user
514 for elem in self.url_pattern:
515 if elem.pattern.search(url):
516 self.data[elem.description] += 1
520 self.data['rpu_other'] += 1
522 def _get_data_statuses(self, code):
524 :param code: str: response status code. Ex.: '202', '499'
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
537 self.data['other_requests'] += 1
540 def address_not_in_pool(pool, address, pool_size):
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.
547 index = bisect.bisect_left(pool, address)
548 if index < pool_size:
549 if pool[index] == address:
552 bisect.insort_left(pool, address)
555 bisect.insort_left(pool, address)
559 def find_regex_return(match_dict=None, msg='Generic error message'):
561 :param match_dict: dict: re.search.groupdict() or None
562 :param msg: str: error description
565 return match_dict, msg
568 def check_req_per_url_pattern(string, url_pattern):
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
575 if not is_dict(url_pattern):
580 def is_valid_pattern(pattern):
583 :return: re.compile(pattern) or None
585 if not isinstance(pattern, str):
589 compile_pattern = re.compile(pattern)
593 return compile_pattern
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))
600 return result or None
606 :return: True or False
607 obj can be <dict> or <OrderedDict>
611 except AttributeError: