]> arthur.barton.de Git - netdata.git/blobdiff - python.d/web_log.chart.py
postgres_plugin: remove sensitive information from error
[netdata.git] / python.d / web_log.chart.py
index adeabc8cdb3d03a1d46714f7613060ebe762a3fd..afe45531d80793e8da2f8feb1447e39d93bb0e23 100644 (file)
@@ -14,7 +14,7 @@ priority = 60000
 retries = 60
 
 ORDER = ['response_statuses', 'response_codes', 'bandwidth', 'response_time', 'requests_per_url', 'http_method',
-         'requests_per_ipproto', 'clients', 'clients_all']
+         'http_version', 'requests_per_ipproto', 'clients', 'clients_all']
 CHARTS = {
     'response_codes': {
         'options': [None, 'Response Codes', 'requests/s', 'responses', 'web_log.response_codes', 'stacked'],
@@ -55,7 +55,12 @@ CHARTS = {
     'http_method': {
         'options': [None, 'Requests Per HTTP Method', 'requests/s', 'http methods', 'web_log.http_method', 'stacked'],
         'lines': [
+            ['GET', 'GET', 'incremental', 1, 1]
         ]},
+    'http_version': {
+        'options': [None, 'Requests Per HTTP Version', 'requests/s', 'http versions',
+                    'web_log.http_version', 'stacked'],
+        'lines': []},
     'requests_per_ipproto': {
         'options': [None, 'Requests Per IP Protocol', 'requests/s', 'ip protocols', 'web_log.requests_per_ipproto',
                     'stacked'],
@@ -86,38 +91,38 @@ class Service(LogService):
         # self._get_data = None  # will be assigned in 'check' method.
         # self.order = None  # will be assigned in 'create_*_method' method.
         # self.definitions = None  # will be assigned in 'create_*_method' method.
-        # self.detailed_chart = None  # will be assigned in 'create_*_method' method.
-        # self.http_method_chart = None  # will be assigned in 'create_*_method' method.
         """
         LogService.__init__(self, configuration=configuration, name=name)
         # Variables from module configuration file
+        self.type = self.configuration.get('type', 'web_access')
         self.log_path = self.configuration.get('path')
-        self.detailed_response_codes = self.configuration.get('detailed_response_codes', True)
-        self.all_time = self.configuration.get('all_time', True)
         self.url_pattern = self.configuration.get('categories')  # dict
         self.custom_log_format = self.configuration.get('custom_log_format')  # dict
         # Instance variables
-        self.unique_all_time = list()  # sorted list of unique IPs
         self.regex = None  # will be assigned in 'find_regex' or 'find_regex_custom' method
-        self.resp_time_func = None  # will be assigned in 'find_regex' or 'find_regex_custom' method
-        # if there is no new logs this dict  returned to netdata
         self.data = {'bytes_sent': 0, 'resp_length': 0, 'resp_time_min': 0, 'resp_time_max': 0,
                      'resp_time_avg': 0, 'unique_cur_ipv4': 0, 'unique_cur_ipv6': 0, '2xx': 0,
                      '5xx': 0, '3xx': 0, '4xx': 0, '1xx': 0, '0xx': 0, 'unmatched': 0, 'req_ipv4': 0,
                      'req_ipv6': 0, 'unique_tot_ipv4': 0, 'unique_tot_ipv6': 0, 'successful_requests': 0,
-                     'redirects': 0, 'bad_requests': 0, 'server_errors': 0, 'other_requests': 0}
+                     'redirects': 0, 'bad_requests': 0, 'server_errors': 0, 'other_requests': 0, 'GET': 0}
 
     def check(self):
+        """
+        :return: bool
+
+        1. "log_path" is specified in the module configuration file
+        2. "log_path" must be readable by netdata user and must exist
+        3. "log_path' must not be empty. We need at least 1 line to find appropriate pattern to parse
+        4. other checks depends on log "type"
+        """
         if not self.log_path:
             self.error('log path is not specified')
             return False
 
-        # log_path must be readable
         if not access(self.log_path, R_OK):
             self.error('%s not readable or not exist' % self.log_path)
             return False
 
-        # log_path file should not be empty
         if not getsize(self.log_path):
             self.error('%s is empty' % self.log_path)
             return False
@@ -140,35 +145,45 @@ class Service(LogService):
                 self.error(str(error))
                 return False
 
-        # Custom_log_format is preferable
-        if self.custom_log_format:
-            match_dict, log_name, error = self.find_regex_custom(last_line)
-        else:
-            match_dict, log_name, error = self.find_regex(last_line)
+        if self.type == 'web_access':
+            self.unique_all_time = list()  # sorted list of unique IPs
+            self.detailed_response_codes = self.configuration.get('detailed_response_codes', True)
+            self.all_time = self.configuration.get('all_time', True)
 
-        if match_dict is None:
-            self.error(str(error))
-            return False
+            # Custom_log_format or predefined log format.
+            if self.custom_log_format:
+                match_dict, error = self.find_regex_custom(last_line)
+            else:
+                match_dict, error = self.find_regex(last_line)
 
-        if not (self.regex and self.resp_time_func):
-            self.error('That can not happen, but it happened. "regex" or "resp_time_func" is None')
+            # "match_dict" is None if there are any problems
+            if match_dict is None:
+                self.error(str(error))
+                return False
+
+            # self.url_pattern check
+            if self.url_pattern:
+                self.url_pattern = check_req_per_url_pattern('rpu', self.url_pattern)
 
-        if log_name == 'web_access':
             self.create_access_charts(match_dict)  # Create charts
-            self._get_data = self._get_access_data
-            self.info('Collected data: %s' % list(match_dict.keys()))
-            return True
+            self._get_data = self._get_access_data  # _get_data assignment
         else:
-            # If it's not access_logs.. Not used at the moment
+            self.error('Not implemented')
             return False
 
+        # Double check
+        if not self.regex:
+            self.error('That can not happen, but it happened. "regex" is None')
+
+        self.info('Collected data: %s' % list(match_dict.keys()))
+        return True
+
     def find_regex_custom(self, last_line):
         """
         :param last_line: str: literally last line from log file
         :return: tuple where:
         [0]: dict or None:  match_dict or None
-        [1]: str or None: log_name or None
-        [2]: str: error description
+        [1]: str: error description
 
         We are here only if "custom_log_format" is in logs. We need to make sure:
         1. "custom_log_format" is a dict
@@ -191,68 +206,72 @@ class Service(LogService):
          ("resp_length" is integer or "-", "resp_time" is integer or float)
 
         """
-        try:
-            self.custom_log_format.keys()
-        except AttributeError:
-            return None, None, 'Custom log: "custom_log_format" is not a <dict>'
+        if not is_dict(self.custom_log_format):
+            return find_regex_return(msg='Custom log: "custom_log_format" is not a <dict>')
 
         pattern = self.custom_log_format.get('pattern')
         if not (pattern and isinstance(pattern, str)):
-            return None, None, 'Custom log: "pattern" option is not specified or type is not <str>'
+            return find_regex_return(msg='Custom log: "pattern" option is not specified or type is not <str>')
 
         resp_time_func = self.custom_log_format.get('time_multiplier') or 0
 
         if not isinstance(resp_time_func, int):
-            return None, None, 'Custom log: "time_multiplier" is not an integer'
+            return find_regex_return(msg='Custom log: "time_multiplier" is not an integer')
+
+        try:
+            regex = re.compile(pattern)
+        except re.error as error:
+            return find_regex_return(msg='Pattern compile error: %s' % str(error))
 
-        regex = re.compile(pattern)
         match = regex.search(last_line)
         if match:
             match_dict = match.groupdict() or None
         else:
-            return None, None, 'Custom log: pattern search FAILED'
+            return find_regex_return(msg='Custom log: pattern search FAILED')
 
         if match_dict is None:
-            return None, None, 'Custom log: search OK but contains no named subgroups' \
-                               ' (you need to use ?P<subgroup_name>)'
+            find_regex_return(msg='Custom log: search OK but contains no named subgroups'
+                                  ' (you need to use ?P<subgroup_name>)')
         else:
-            basic_values = {'address', 'method', 'url', 'code', 'bytes_sent'} - set(match_dict)
-
-            if basic_values:
-                return None, None, 'Custom log: search OK but some mandatory keys (%s) are missing' % list(basic_values)
+            mandatory_dict = {'address': r'[\da-f.:]+',
+                              'code': r'[1-9]\d{2}',
+                              'method': r'[A-Z]+',
+                              'bytes_sent': r'\d+|-'}
+            optional_dict = {'resp_length': r'\d+',
+                             'resp_time': r'[\d.]+',
+                             'http_version': r'\d\.\d'}
+
+            mandatory_values = set(mandatory_dict) - set(match_dict)
+            if mandatory_values:
+                return find_regex_return(msg='Custom log: search OK but some mandatory keys (%s) are missing'
+                                         % list(mandatory_values))
+            else:
+                for key in mandatory_dict:
+                    if not re.search(mandatory_dict[key], match_dict[key]):
+                        return find_regex_return(msg='Custom log: can\'t parse "%s": %s'
+                                                     % (key, match_dict[key]))
+
+            optional_values = set(optional_dict) & set(match_dict)
+            for key in optional_values:
+                if not re.search(optional_dict[key], match_dict[key]):
+                    return find_regex_return(msg='Custom log: can\'t parse "%s": %s'
+                                                 % (key, match_dict[key]))
+
+            dot_in_time = '.' in match_dict.get('resp_time', '')
+            if dot_in_time:
+                self.resp_time_func = lambda time: time * (resp_time_func or 1000000)
             else:
-                if not re.search(r'[\da-f.:]+', match_dict['address']):
-                    return None, None, 'Custom log: can\'t parse "address": %s' % match_dict['address']
-                if not re.search(r'[1-9]\d{2}', match_dict['code']):
-                    return None, None, 'Custom log: can\'t parse "code": %s' % match_dict['code']
-                if not re.search(r'[A-Z]+', match_dict['method']):
-                    return None, None, 'Custom log: can\'t parse "method": %s' % match_dict['method']
-                if not re.search(r'\d+|-', match_dict['bytes_sent']):
-                    return None, None, 'Custom log: can\'t parse "bytes_sent": %s' % match_dict['bytes_sent']
-
-            if 'resp_length' in match_dict:
-                if not re.search(r'\d+', match_dict.get('resp_length', '')):
-                    return None, None, 'Custom log: can\'t parse "resp_length": %s' % match_dict['resp_length']
-
-            if 'resp_time' in match_dict:
-                if not re.search(r'[\d.]+', match_dict.get('resp_length', '')):
-                    return None, None, 'Custom log: can\'t parse "resp_time": %s' % match_dict['resp_time']
-                else:
-                    if '.' in match_dict['resp_time']:
-                        self.resp_time_func = lambda time: time * (resp_time_func or 1000000)
-                    else:
-                        self.resp_time_func = lambda time: time * (resp_time_func or 1)
+                self.resp_time_func = lambda time: time * (resp_time_func or 1)
 
             self.regex = regex
-            return match_dict, 'web_access', 'Custom log: we are fine'
+            return find_regex_return(match_dict=match_dict)
 
     def find_regex(self, last_line):
         """
         :param last_line: str: literally last line from log file
         :return: tuple where:
         [0]: dict or None:  match_dict or None
-        [1]: str or None: log_name or None
-        [2]: str: error description
+        [1]: str: error description
         We need to find appropriate pattern for current log file
         All logic is do a regex search through the string for all predefined patterns
         until we find something or fail.
@@ -261,13 +280,15 @@ class Service(LogService):
         # 5. Bytes sent 6. Response length 7. Response process time
         acs_default = re.compile(r'(?P<address>[\da-f.:]+)'
                                  r' -.*?"(?P<method>[A-Z]+)'
-                                 r' (?P<url>.*?)"'
+                                 r' (?P<url>[^ ]+)'
+                                 r' [A-Z]+/(?P<http_version>\d\.\d)"'
                                  r' (?P<code>[1-9]\d{2})'
                                  r' (?P<bytes_sent>\d+|-)')
 
         acs_apache_ext_insert = re.compile(r'(?P<address>[\da-f.:]+)'
                                            r' -.*?"(?P<method>[A-Z]+)'
-                                           r' (?P<url>.*?)"'
+                                           r' (?P<url>[^ ]+)'
+                                           r' [A-Z]+/(?P<http_version>\d\.\d)"'
                                            r' (?P<code>[1-9]\d{2})'
                                            r' (?P<bytes_sent>\d+|-)'
                                            r' (?P<resp_length>\d+)'
@@ -275,7 +296,8 @@ class Service(LogService):
 
         acs_apache_ext_append = re.compile(r'(?P<address>[\da-f.:]+)'
                                            r' -.*?"(?P<method>[A-Z]+)'
-                                           r' (?P<url>.*?)"'
+                                           r' (?P<url>[^ ]+)'
+                                           r' [A-Z]+/(?P<http_version>\d\.\d)"'
                                            r' (?P<code>[1-9]\d{2})'
                                            r' (?P<bytes_sent>\d+|-)'
                                            r' .*?'
@@ -285,7 +307,8 @@ class Service(LogService):
 
         acs_nginx_ext_insert = re.compile(r'(?P<address>[\da-f.:]+)'
                                           r' -.*?"(?P<method>[A-Z]+)'
-                                          r' (?P<url>.*?)"'
+                                          r' (?P<url>[^ ]+)'
+                                          r' [A-Z]+/(?P<http_version>\d\.\d)"'
                                           r' (?P<code>[1-9]\d{2})'
                                           r' (?P<bytes_sent>\d+)'
                                           r' (?P<resp_length>\d+)'
@@ -293,7 +316,8 @@ class Service(LogService):
 
         acs_nginx_ext_append = re.compile(r'(?P<address>[\da-f.:]+)'
                                           r' -.*?"(?P<method>[A-Z]+)'
-                                          r' (?P<url>.*?)"'
+                                          r' (?P<url>[^ ]+)'
+                                          r' [A-Z]+/(?P<http_version>\d\.\d)"'
                                           r' (?P<code>[1-9]\d{2})'
                                           r' (?P<bytes_sent>\d+)'
                                           r' .*?'
@@ -320,8 +344,8 @@ class Service(LogService):
                 match_dict = match.groupdict()
                 break
 
-        return match_dict or None, 'web_access', 'Unknown log format. Plugin still can work for you.' \
-                                                 ' Read about the "custom_log_format" feature in the conf file'
+        return find_regex_return(match_dict=match_dict or None,
+                                 msg='Unknown log format. You need to use "custom_log_format" feature.')
 
     def create_access_charts(self, match_dict):
         """
@@ -353,7 +377,11 @@ class Service(LogService):
                               ' web_log.detailed_response_codes stacked 1 %s\n' % (job_name, self.update_every)
         self.http_method_chart = 'CHART %s.http_method' \
                                  ' "" "Requests Per HTTP Method" requests/s "http methods"' \
-                                 ' web_log.http_method stacked 2 %s\n' % (job_name, self.update_every)
+                                 ' web_log.http_method stacked 2 %s\n' \
+                                 'DIMENSION GET GET incremental\n' % (job_name, self.update_every)
+        self.http_version_chart = 'CHART %s.http_version' \
+                                  ' "" "Requests Per HTTP Version" requests/s "http versions"' \
+                                  ' web_log.http_version stacked 3 %s\n' % (job_name, self.update_every)
 
         # Remove 'request_time' chart from ORDER if resp_time not in match_dict
         if 'resp_time' not in match_dict:
@@ -371,16 +399,14 @@ class Service(LogService):
 
         # Add 'requests_per_url' chart if specified in the configuration
         if self.url_pattern:
-            self.url_pattern = [NAMED_URL_PATTERN(description=k, pattern=re.compile(v)) for k, v
-                                in self.url_pattern.items()]
             self.definitions['requests_per_url'] = {'options': [None, 'Requests Per Url', 'requests/s',
                                                                 'urls', 'web_log.requests_per_url', 'stacked'],
-                                                    'lines': [['other_url', 'other', 'incremental']]}
+                                                    'lines': [['rpu_other', 'other', 'incremental']]}
             for elem in self.url_pattern:
-                self.definitions['requests_per_url']['lines'].append([elem.description, elem.description,
+                self.definitions['requests_per_url']['lines'].append([elem.description, elem.description[4:],
                                                                       'incremental'])
                 self.data.update({elem.description: 0})
-            self.data.update({'other_url': 0})
+            self.data.update({'rpu_other': 0})
         else:
             self.order.remove('requests_per_url')
 
@@ -435,8 +461,12 @@ class Service(LogService):
                     self._get_data_per_url(match_dict['url'])
                 # requests per http method
                 self._get_data_http_method(match_dict['method'])
+                # requests per http version
+                if 'http_version' in match_dict:
+                    self._get_data_http_version(match_dict['http_version'])
                 # bandwidth sent
-                self.data['bytes_sent'] += int(match_dict['bytes_sent'] if '-' not in match_dict['bytes_sent'] else 0)
+                bytes_sent = match_dict['bytes_sent'] if '-' not in match_dict['bytes_sent'] else 0
+                self.data['bytes_sent'] += int(bytes_sent)
                 # request processing time and bandwidth received
                 if 'resp_length' in match_dict:
                     self.data['resp_length'] += int(match_dict['resp_length'])
@@ -489,6 +519,20 @@ class Service(LogService):
                                                             chart_string_copy, 'http_method')
         self.data[method] += 1
 
+    def _get_data_http_version(self, http_version):
+        """
+        :param http_version: str: METHOD from parsed line. Ex.: '1.1', '1.0'
+        :return:
+        Calls add_new_dimension method If the value is found for the first time
+        """
+        http_version_dim_id = http_version.replace('.', '_')
+        if http_version_dim_id not in self.data:
+            chart_string_copy = self.http_version_chart
+            self.http_version_chart = self.add_new_dimension(http_version_dim_id,
+                                                             [http_version_dim_id, http_version, 'incremental'],
+                                                             chart_string_copy, 'http_version')
+        self.data[http_version_dim_id] += 1
+
     def _get_data_per_url(self, url):
         """
         :param url: str: URL from parsed line
@@ -503,7 +547,7 @@ class Service(LogService):
                 match = True
                 break
         if not match:
-            self.data['other_url'] += 1
+            self.data['rpu_other'] += 1
 
     def _get_data_statuses(self, code):
         """
@@ -527,8 +571,8 @@ def address_not_in_pool(pool, address, pool_size):
     """
     :param pool: list of ip addresses
     :param address: ip address
-    :param pool_size: current size of pool
-    :return: True if address not in pool. False if address in pool
+    :param pool_size: current pool size
+    :return: True if address not in pool. False if address in pool.
     """
     index = bisect.bisect_left(pool, address)
     if index < pool_size:
@@ -540,3 +584,61 @@ def address_not_in_pool(pool, address, pool_size):
     else:
         bisect.insort_left(pool, address)
         return True
+
+
+def find_regex_return(match_dict=None, msg='Generic error message'):
+    """
+    :param match_dict: dict: re.search.groupdict() or None
+    :param msg: str: error description
+    :return: tuple:
+    """
+    return match_dict, msg
+
+
+def check_req_per_url_pattern(string, url_pattern):
+    """
+    :param string: str:
+    :param url_pattern: dict: ex. {'dim1': 'pattern1>', 'dim2': '<pattern2>'}
+    :return: list of named tuples or None:
+     We need to make sure all patterns are valid regular expressions
+    """
+    if not is_dict(url_pattern):
+        return None
+
+    result = list()
+
+    def is_valid_pattern(pattern):
+        """
+        :param pattern: str
+        :return: re.compile(pattern) or None
+        """
+        if not isinstance(pattern, str):
+            return False
+        else:
+            try:
+                compile_pattern = re.compile(pattern)
+            except re.error:
+                return False
+            else:
+                return compile_pattern
+
+    for dimension, regex in url_pattern.items():
+        valid_pattern = is_valid_pattern(regex)
+        if isinstance(dimension, str) and valid_pattern:
+            result.append(NAMED_URL_PATTERN(description='_'.join([string, dimension]), pattern=valid_pattern))
+
+    return result or None
+
+
+def is_dict(obj):
+    """
+    :param obj: dict:
+    :return: True or False
+    obj can be <dict> or <OrderedDict>
+    """
+    try:
+        obj.keys()
+    except AttributeError:
+        return False
+    else:
+        return True