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 defaultdict, namedtuple
11 from copy import deepcopy
13 from itertools import zip_longest
15 from itertools import izip_longest as zip_longest
20 ORDER = ['response_codes', 'response_time', 'requests_per_url', 'http_method', 'bandwidth', 'clients', 'clients_all']
23 'options': [None, 'Response Codes', 'requests/s', 'responses', 'web_log.response_codes', 'stacked'],
25 ['2xx', '2xx', 'absolute'],
26 ['5xx', '5xx', 'absolute'],
27 ['3xx', '3xx', 'absolute'],
28 ['4xx', '4xx', 'absolute'],
29 ['1xx', '1xx', 'absolute'],
30 ['0xx', 'other', 'absolute'],
31 ['unmatched', 'unmatched', 'absolute']
34 'options': [None, 'Bandwidth', 'KB/s', 'bandwidth', 'web_log.bandwidth', 'area'],
36 ['resp_length', 'received', 'absolute', 1, 1024],
37 ['bytes_sent', 'sent', 'absolute', -1, 1024]
40 'options': [None, 'Processing Time', 'milliseconds', 'timings', 'web_log.response_time', 'area'],
42 ['resp_time_min', 'min', 'absolute', 1, 1],
43 ['resp_time_max', 'max', 'absolute', 1, 1],
44 ['resp_time_avg', 'avg', 'absolute', 1, 1]
47 'options': [None, 'Current Poll Unique Client IPs', 'unique ips', 'unique clients', 'web_log.clients', 'line'],
49 ['unique_cur_ipv4', 'ipv4', 'absolute', 1, 1],
50 ['unique_cur_ipv6', 'ipv6', 'absolute', 1, 1]
53 'options': [None, 'All Time Unique Client IPs', 'unique ips', 'unique clients', 'web_log.clients_all', 'line'],
55 ['unique_tot_ipv4', 'ipv4', 'absolute', 1, 1],
56 ['unique_tot_ipv6', 'ipv6', 'absolute', 1, 1]
59 'options': [None, 'Requests Per HTTP Method', 'requests/s', 'requests', 'web_log.http_method', 'stacked'],
64 NAMED_URL_PATTERN = namedtuple('URL_PATTERN', ['description', 'pattern'])
67 class Service(LogService):
68 def __init__(self, configuration=None, name=None):
69 LogService.__init__(self, configuration=configuration, name=name)
70 # Vars from module configuration file
71 self.log_path = self.configuration.get('path')
72 self.detailed_response_codes = self.configuration.get('detailed_response_codes', True)
73 self.all_time = self.configuration.get('all_time', True)
74 self.url_pattern = self.configuration.get('categories') # dict
76 # sorted list of unique IPs
77 self.unique_all_time = list()
78 # dict for values that should not be zeroed every poll
79 self.storage = {'unique_tot_ipv4': 0, 'unique_tot_ipv6': 0}
80 # if there is no new logs this dict + self.storage returned to netdata
81 self.data = {'bytes_sent': 0, 'resp_length': 0, 'resp_time_min': 0,
82 'resp_time_max': 0, 'resp_time_avg': 0, 'unique_cur_ipv4': 0,
83 'unique_cur_ipv6': 0, '2xx': 0, '5xx': 0, '3xx': 0, '4xx': 0,
84 '1xx': 0, '0xx': 0, 'unmatched': 0}
88 self.error('log path is not specified')
91 # log_path must be readable
92 if not access(self.log_path, R_OK):
93 self.error('%s not readable or not exist' % self.log_path)
96 # log_path file should not be empty
97 if not getsize(self.log_path):
98 self.error('%s is empty' % self.log_path)
101 # Read last line (or first if there is only one line)
102 with open(self.log_path, 'rb') as logs:
104 while logs.read(1) != b'\n':
108 last_line = logs.readline().decode(encoding='utf-8')
111 parsed_line, regex_name = self.find_regex(last_line)
113 self.error('Can\'t parse output')
116 self.create_charts(parsed_line[0], regex_name)
117 if len(parsed_line[0]) == 5:
118 self.info('Not all data collected. You need to modify LogFormat.')
121 def find_regex(self, last_line):
122 # REGEX: 1.IPv4 address 2.HTTP method 3. URL 4. Response code
123 # 5. Bytes sent 6. Response length 7. Response process time
124 default = re.compile(r'([\da-f.:]+)'
130 apache_extended = re.compile(r'([\da-f.:]+)'
138 nginx_extended = re.compile(r'([\da-f.:]+)'
146 regex_function = zip([apache_extended, nginx_extended, default],
147 [lambda x: x, lambda x: x * 1000, lambda x: x],
148 ['apache_extended', 'nginx_extended', 'default'])
150 for regex, function, name in regex_function:
151 if regex.search(last_line):
153 self.resp_time_func = function
158 return self.regex.findall(last_line), regex_name
162 def create_charts(self, parsed_line, regex_name):
163 def find_job_name(override_name, name):
164 add_to_name = override_name or name
166 return '_'.join(['web_log', add_to_name])
170 job_name = find_job_name(self.override_name, self.name)
171 self.detailed_chart = 'CHART %s.detailed_response_codes ""' \
172 ' "Response Codes" requests/s responses' \
173 ' web_log.detailed_resp stacked 1 %s\n' % (job_name, self.update_every)
174 self.http_method_chart = 'CHART %s.http_method' \
175 ' "" "HTTP Methods" requests/s requests' \
176 ' web_log.http_method stacked 2 %s\n' % (job_name, self.update_every)
177 self.order = ORDER[:]
178 self.definitions = deepcopy(CHARTS)
179 if 'apache' in regex_name:
180 self.definitions['response_time']['lines'][0][4] = 1000
181 self.definitions['response_time']['lines'][1][4] = 1000
182 self.definitions['response_time']['lines'][2][4] = 1000
184 # Remove 'request_time' chart from ORDER if request_time not in logs
185 if len(parsed_line) < 7:
186 self.order.remove('response_time')
187 # Remove 'clients_all' chart from ORDER if specified in the configuration
188 if not self.all_time:
189 self.order.remove('clients_all')
190 # Add 'detailed_response_codes' chart if specified in the configuration
191 if self.detailed_response_codes:
192 self.order.append('detailed_response_codes')
193 self.definitions['detailed_response_codes'] = {'options': [None, 'Detailed Response Codes', 'requests/s',
194 'responses', 'web_log.detailed_resp', 'stacked'],
197 # Add 'requests_per_url' chart if specified in the configuration
199 self.url_pattern = [NAMED_URL_PATTERN(description=k, pattern=re.compile(v)) for k, v in self.url_pattern.items()]
200 self.definitions['requests_per_url'] = {'options': [None, 'Requests Per Url', 'requests/s',
201 'requests', 'web_log.url_pattern', 'stacked'],
202 'lines': [['other_url', 'other', 'absolute']]}
203 for elem in self.url_pattern:
204 self.definitions['requests_per_url']['lines'].append([elem.description, elem.description, 'absolute'])
205 self.data.update({elem.description: 0})
206 self.data.update({'other_url': 0})
208 self.order.remove('requests_per_url')
210 def add_new_dimension(self, dimension, line_list, chart_string, key):
211 self.storage.update({dimension: 0})
212 # SET method check if dim in _dimensions
213 self._dimensions.append(dimension)
214 # UPDATE method do SET only if dim in definitions
215 self.definitions[key]['lines'].append(line_list)
217 chart += "%s %s\n" % ('DIMENSION', ' '.join(line_list))
226 raw = self._get_raw_data()
230 request_time, unique_current = list(), list()
231 request_counter = {'count': 0, 'sum': 0}
233 to_netdata.update(self.data)
234 default_dict = defaultdict(lambda: 0)
237 match = self.regex.findall(line)
239 match_dict = dict(zip_longest('address method url code sent resp_length resp_time'.split(), match[0]))
241 code = ''.join([match_dict['code'][0], 'xx'])
242 to_netdata[code] += 1
244 to_netdata['0xx'] += 1
245 # detailed response code
246 if self.detailed_response_codes:
247 self._get_data_detailed_response_codes(match_dict['code'], default_dict)
250 self._get_data_per_url(match_dict['url'], default_dict)
251 # requests per http method
252 self._get_data_http_method(match_dict['method'], default_dict)
254 to_netdata['bytes_sent'] += int(match_dict['sent'])
256 if match_dict['resp_length'] and match_dict['resp_time']:
257 to_netdata['resp_length'] += int(match_dict['resp_length'])
258 resp_time = self.resp_time_func(float(match_dict['resp_time']))
259 bisect.insort_left(request_time, resp_time)
260 request_counter['count'] += 1
261 request_counter['sum'] += resp_time
263 if address_not_in_pool(self.unique_all_time, match_dict['address'],
264 self.storage['unique_tot_ipv4'] + self.storage['unique_tot_ipv6']):
265 if '.' in match_dict['address']:
266 self.storage['unique_tot_ipv4'] += 1
268 self.storage['unique_tot_ipv6'] += 1
269 if address_not_in_pool(unique_current, match_dict['address'],
270 to_netdata['unique_cur_ipv4'] + to_netdata['unique_cur_ipv6']):
271 if '.' in match_dict['address']:
272 to_netdata['unique_cur_ipv4'] += 1
274 to_netdata['unique_cur_ipv6'] += 1
276 to_netdata['unmatched'] += 1
279 to_netdata['resp_time_min'] = request_time[0]
280 to_netdata['resp_time_avg'] = float(request_counter['sum']) / request_counter['count']
281 to_netdata['resp_time_max'] = request_time[-1]
282 to_netdata.update(self.storage)
283 to_netdata.update(default_dict)
286 def _get_data_detailed_response_codes(self, code, default_dict):
287 if code not in self.storage:
288 chart_string_copy = self.detailed_chart
289 self.detailed_chart = self.add_new_dimension(code, [code, code, 'absolute'],
290 chart_string_copy, 'detailed_response_codes')
291 default_dict[code] += 1
293 def _get_data_http_method(self, method, default_dict):
294 if method not in self.storage:
295 chart_string_copy = self.http_method_chart
296 self.http_method_chart = self.add_new_dimension(method, [method, method, 'absolute'],
297 chart_string_copy, 'http_method')
298 default_dict[method] += 1
300 def _get_data_per_url(self, url, default_dict):
302 for elem in self.url_pattern:
303 if elem.pattern.search(url):
304 default_dict[elem.description] += 1
308 default_dict['other_url'] += 1
311 def address_not_in_pool(pool, address, pool_size):
312 index = bisect.bisect_left(pool, address)
313 if index < pool_size:
314 if pool[index] == address:
317 bisect.insort_left(pool, address)
320 bisect.insort_left(pool, address)