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