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