##// END OF EJS Templates
elasticsearch: migrate to ES 5.x
ergo -
Show More
@@ -1,708 +1,707 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 import bisect
18 18 import collections
19 19 import math
20 20 from datetime import datetime, timedelta
21 21
22 22 import sqlalchemy as sa
23 23 import elasticsearch.exceptions
24 24 import elasticsearch.helpers
25 25
26 26 from celery.utils.log import get_task_logger
27 27 from zope.sqlalchemy import mark_changed
28 28 from pyramid.threadlocal import get_current_request, get_current_registry
29 29 from ziggurat_foundations.models.services.resource import ResourceService
30 30
31 31 from appenlight.celery import celery
32 32 from appenlight.models.report_group import ReportGroup
33 33 from appenlight.models import DBSession, Datastores
34 34 from appenlight.models.report import Report
35 35 from appenlight.models.log import Log
36 36 from appenlight.models.metric import Metric
37 37 from appenlight.models.event import Event
38 38
39 39 from appenlight.models.services.application import ApplicationService
40 40 from appenlight.models.services.event import EventService
41 41 from appenlight.models.services.log import LogService
42 42 from appenlight.models.services.report import ReportService
43 43 from appenlight.models.services.report_group import ReportGroupService
44 44 from appenlight.models.services.user import UserService
45 45 from appenlight.models.tag import Tag
46 46 from appenlight.lib import print_traceback
47 47 from appenlight.lib.utils import parse_proto, in_batches
48 48 from appenlight.lib.ext_json import json
49 49 from appenlight.lib.redis_keys import REDIS_KEYS
50 50 from appenlight.lib.enums import ReportType
51 51
52 52 log = get_task_logger(__name__)
53 53
54 54 sample_boundries = (
55 55 list(range(100, 1000, 100))
56 56 + list(range(1000, 10000, 1000))
57 57 + list(range(10000, 100000, 5000))
58 58 )
59 59
60 60
61 61 def pick_sample(total_occurences, report_type=None):
62 62 every = 1.0
63 63 position = bisect.bisect_left(sample_boundries, total_occurences)
64 64 if position > 0:
65 65 if report_type == ReportType.not_found:
66 66 divide = 10.0
67 67 else:
68 68 divide = 100.0
69 69 every = sample_boundries[position - 1] / divide
70 70 return total_occurences % every == 0
71 71
72 72
73 73 @celery.task(queue="default", default_retry_delay=1, max_retries=2)
74 74 def test_exception_task():
75 75 log.error("test celery log", extra={"location": "celery"})
76 76 log.warning("test celery log", extra={"location": "celery"})
77 77 raise Exception("Celery exception test")
78 78
79 79
80 80 @celery.task(queue="default", default_retry_delay=1, max_retries=2)
81 81 def test_retry_exception_task():
82 82 try:
83 83 import time
84 84
85 85 time.sleep(1.3)
86 86 log.error("test retry celery log", extra={"location": "celery"})
87 87 log.warning("test retry celery log", extra={"location": "celery"})
88 88 raise Exception("Celery exception test")
89 89 except Exception as exc:
90 90 if celery.conf["CELERY_EAGER_PROPAGATES_EXCEPTIONS"]:
91 91 raise
92 92 test_retry_exception_task.retry(exc=exc)
93 93
94 94
95 95 @celery.task(queue="reports", default_retry_delay=600, max_retries=144)
96 96 def add_reports(resource_id, request_params, dataset, **kwargs):
97 97 proto_version = parse_proto(request_params.get("protocol_version", ""))
98 98 current_time = datetime.utcnow().replace(second=0, microsecond=0)
99 99 try:
100 100 # we will store solr docs here for single insert
101 101 es_report_docs = {}
102 102 es_report_group_docs = {}
103 103 resource = ApplicationService.by_id(resource_id)
104 104
105 105 tags = []
106 106 es_slow_calls_docs = {}
107 107 es_reports_stats_rows = {}
108 108 for report_data in dataset:
109 109 # build report details for later
110 110 added_details = 0
111 111 report = Report()
112 112 report.set_data(report_data, resource, proto_version)
113 113 report._skip_ft_index = True
114 114
115 115 # find latest group in this months partition
116 116 report_group = ReportGroupService.by_hash_and_resource(
117 117 report.resource_id,
118 118 report.grouping_hash,
119 119 since_when=datetime.utcnow().date().replace(day=1),
120 120 )
121 121 occurences = report_data.get("occurences", 1)
122 122 if not report_group:
123 123 # total reports will be +1 moment later
124 124 report_group = ReportGroup(
125 125 grouping_hash=report.grouping_hash,
126 126 occurences=0,
127 127 total_reports=0,
128 128 last_report=0,
129 129 priority=report.priority,
130 130 error=report.error,
131 131 first_timestamp=report.start_time,
132 132 )
133 133 report_group._skip_ft_index = True
134 134 report_group.report_type = report.report_type
135 135 report.report_group_time = report_group.first_timestamp
136 136 add_sample = pick_sample(
137 137 report_group.occurences, report_type=report_group.report_type
138 138 )
139 139 if add_sample:
140 140 resource.report_groups.append(report_group)
141 141 report_group.reports.append(report)
142 142 added_details += 1
143 143 DBSession.flush()
144 144 if report.partition_id not in es_report_docs:
145 145 es_report_docs[report.partition_id] = []
146 146 es_report_docs[report.partition_id].append(report.es_doc())
147 147 tags.extend(list(report.tags.items()))
148 148 slow_calls = report.add_slow_calls(report_data, report_group)
149 149 DBSession.flush()
150 150 for s_call in slow_calls:
151 151 if s_call.partition_id not in es_slow_calls_docs:
152 152 es_slow_calls_docs[s_call.partition_id] = []
153 153 es_slow_calls_docs[s_call.partition_id].append(s_call.es_doc())
154 154 # try generating new stat rows if needed
155 155 else:
156 156 # required for postprocessing to not fail later
157 157 report.report_group = report_group
158 158
159 159 stat_row = ReportService.generate_stat_rows(report, resource, report_group)
160 160 if stat_row.partition_id not in es_reports_stats_rows:
161 161 es_reports_stats_rows[stat_row.partition_id] = []
162 162 es_reports_stats_rows[stat_row.partition_id].append(stat_row.es_doc())
163 163
164 164 # see if we should mark 10th occurence of report
165 165 last_occurences_10 = int(math.floor(report_group.occurences / 10))
166 166 curr_occurences_10 = int(
167 167 math.floor((report_group.occurences + report.occurences) / 10)
168 168 )
169 169 last_occurences_100 = int(math.floor(report_group.occurences / 100))
170 170 curr_occurences_100 = int(
171 171 math.floor((report_group.occurences + report.occurences) / 100)
172 172 )
173 173 notify_occurences_10 = last_occurences_10 != curr_occurences_10
174 174 notify_occurences_100 = last_occurences_100 != curr_occurences_100
175 175 report_group.occurences = ReportGroup.occurences + occurences
176 176 report_group.last_timestamp = report.start_time
177 177 report_group.summed_duration = ReportGroup.summed_duration + report.duration
178 178 summed_duration = ReportGroup.summed_duration + report.duration
179 179 summed_occurences = ReportGroup.occurences + occurences
180 180 report_group.average_duration = summed_duration / summed_occurences
181 181 report_group.run_postprocessing(report)
182 182 if added_details:
183 183 report_group.total_reports = ReportGroup.total_reports + 1
184 184 report_group.last_report = report.id
185 185 report_group.set_notification_info(
186 186 notify_10=notify_occurences_10, notify_100=notify_occurences_100
187 187 )
188 188 DBSession.flush()
189 189 report_group.get_report().notify_channel(report_group)
190 190 if report_group.partition_id not in es_report_group_docs:
191 191 es_report_group_docs[report_group.partition_id] = []
192 192 es_report_group_docs[report_group.partition_id].append(
193 193 report_group.es_doc()
194 194 )
195 195
196 196 action = "REPORT"
197 197 log_msg = "%s: %s %s, client: %s, proto: %s" % (
198 198 action,
199 199 report_data.get("http_status", "unknown"),
200 200 str(resource),
201 201 report_data.get("client"),
202 202 proto_version,
203 203 )
204 204 log.info(log_msg)
205 205 total_reports = len(dataset)
206 206 redis_pipeline = Datastores.redis.pipeline(transaction=False)
207 207 key = REDIS_KEYS["counters"]["reports_per_minute"].format(current_time)
208 208 redis_pipeline.incr(key, total_reports)
209 209 redis_pipeline.expire(key, 3600 * 24)
210 210 key = REDIS_KEYS["counters"]["events_per_minute_per_user"].format(
211 211 resource.owner_user_id, current_time
212 212 )
213 213 redis_pipeline.incr(key, total_reports)
214 214 redis_pipeline.expire(key, 3600)
215 215 key = REDIS_KEYS["counters"]["reports_per_hour_per_app"].format(
216 216 resource_id, current_time.replace(minute=0)
217 217 )
218 218 redis_pipeline.incr(key, total_reports)
219 219 redis_pipeline.expire(key, 3600 * 24 * 7)
220 220 redis_pipeline.sadd(
221 221 REDIS_KEYS["apps_that_got_new_data_per_hour"].format(
222 222 current_time.replace(minute=0)
223 223 ),
224 224 resource_id,
225 225 )
226 226 redis_pipeline.execute()
227 227
228 228 add_reports_es(es_report_group_docs, es_report_docs)
229 229 add_reports_slow_calls_es(es_slow_calls_docs)
230 230 add_reports_stats_rows_es(es_reports_stats_rows)
231 231 return True
232 232 except Exception as exc:
233 233 print_traceback(log)
234 234 if celery.conf["CELERY_EAGER_PROPAGATES_EXCEPTIONS"]:
235 235 raise
236 236 add_reports.retry(exc=exc)
237 237
238 238
239 239 @celery.task(queue="es", default_retry_delay=600, max_retries=144)
240 240 def add_reports_es(report_group_docs, report_docs):
241 241 for k, v in report_group_docs.items():
242 242 to_update = {"_index": k, "_type": "report_group"}
243 243 [i.update(to_update) for i in v]
244 244 elasticsearch.helpers.bulk(Datastores.es, v)
245 245 for k, v in report_docs.items():
246 246 to_update = {"_index": k, "_type": "report"}
247 247 [i.update(to_update) for i in v]
248 248 elasticsearch.helpers.bulk(Datastores.es, v)
249 249
250 250
251 251 @celery.task(queue="es", default_retry_delay=600, max_retries=144)
252 252 def add_reports_slow_calls_es(es_docs):
253 253 for k, v in es_docs.items():
254 254 to_update = {"_index": k, "_type": "log"}
255 255 [i.update(to_update) for i in v]
256 256 elasticsearch.helpers.bulk(Datastores.es, v)
257 257
258 258
259 259 @celery.task(queue="es", default_retry_delay=600, max_retries=144)
260 260 def add_reports_stats_rows_es(es_docs):
261 261 for k, v in es_docs.items():
262 262 to_update = {"_index": k, "_type": "log"}
263 263 [i.update(to_update) for i in v]
264 264 elasticsearch.helpers.bulk(Datastores.es, v)
265 265
266 266
267 267 @celery.task(queue="logs", default_retry_delay=600, max_retries=144)
268 268 def add_logs(resource_id, request_params, dataset, **kwargs):
269 269 proto_version = request_params.get("protocol_version")
270 270 current_time = datetime.utcnow().replace(second=0, microsecond=0)
271 271
272 272 try:
273 273 es_docs = collections.defaultdict(list)
274 274 resource = ApplicationService.by_id_cached()(resource_id)
275 275 resource = DBSession.merge(resource, load=False)
276 276 ns_pairs = []
277 277 for entry in dataset:
278 278 # gather pk and ns so we can remove older versions of row later
279 279 if entry["primary_key"] is not None:
280 280 ns_pairs.append({"pk": entry["primary_key"], "ns": entry["namespace"]})
281 281 log_entry = Log()
282 282 log_entry.set_data(entry, resource=resource)
283 283 log_entry._skip_ft_index = True
284 284 resource.logs.append(log_entry)
285 285 DBSession.flush()
286 286 # insert non pk rows first
287 287 if entry["primary_key"] is None:
288 288 es_docs[log_entry.partition_id].append(log_entry.es_doc())
289 289
290 290 # 2nd pass to delete all log entries from db foe same pk/ns pair
291 291 if ns_pairs:
292 292 ids_to_delete = []
293 293 es_docs = collections.defaultdict(list)
294 294 es_docs_to_delete = collections.defaultdict(list)
295 295 found_pkey_logs = LogService.query_by_primary_key_and_namespace(
296 296 list_of_pairs=ns_pairs
297 297 )
298 298 log_dict = {}
299 299 for log_entry in found_pkey_logs:
300 300 log_key = (log_entry.primary_key, log_entry.namespace)
301 301 if log_key not in log_dict:
302 302 log_dict[log_key] = []
303 303 log_dict[log_key].append(log_entry)
304 304
305 305 for ns, entry_list in log_dict.items():
306 306 entry_list = sorted(entry_list, key=lambda x: x.timestamp)
307 307 # newest row needs to be indexed in es
308 308 log_entry = entry_list[-1]
309 309 # delete everything from pg and ES, leave the last row in pg
310 310 for e in entry_list[:-1]:
311 311 ids_to_delete.append(e.log_id)
312 312 es_docs_to_delete[e.partition_id].append(e.delete_hash)
313 313
314 314 es_docs_to_delete[log_entry.partition_id].append(log_entry.delete_hash)
315 315
316 316 es_docs[log_entry.partition_id].append(log_entry.es_doc())
317 317
318 318 if ids_to_delete:
319 319 query = DBSession.query(Log).filter(Log.log_id.in_(ids_to_delete))
320 320 query.delete(synchronize_session=False)
321 321 if es_docs_to_delete:
322 322 # batch this to avoid problems with default ES bulk limits
323 323 for es_index in es_docs_to_delete.keys():
324 324 for batch in in_batches(es_docs_to_delete[es_index], 20):
325 325 query = {"query": {"terms": {"delete_hash": batch}}}
326 326
327 327 try:
328 Datastores.es.transport.perform_request(
329 "DELETE",
330 "/{}/{}/_query".format(es_index, "log"),
331 body=query,
328 Datastores.es.delete_by_query(
329 index=es_index, doc_type="log",
330 body=query, conflicts="proceed"
332 331 )
333 332 except elasticsearch.exceptions.NotFoundError as exc:
334 333 msg = "skipping index {}".format(es_index)
335 334 log.info(msg)
336 335
337 336 total_logs = len(dataset)
338 337
339 338 log_msg = "LOG_NEW: %s, entries: %s, proto:%s" % (
340 339 str(resource),
341 340 total_logs,
342 341 proto_version,
343 342 )
344 343 log.info(log_msg)
345 344 # mark_changed(session)
346 345 redis_pipeline = Datastores.redis.pipeline(transaction=False)
347 346 key = REDIS_KEYS["counters"]["logs_per_minute"].format(current_time)
348 347 redis_pipeline.incr(key, total_logs)
349 348 redis_pipeline.expire(key, 3600 * 24)
350 349 key = REDIS_KEYS["counters"]["events_per_minute_per_user"].format(
351 350 resource.owner_user_id, current_time
352 351 )
353 352 redis_pipeline.incr(key, total_logs)
354 353 redis_pipeline.expire(key, 3600)
355 354 key = REDIS_KEYS["counters"]["logs_per_hour_per_app"].format(
356 355 resource_id, current_time.replace(minute=0)
357 356 )
358 357 redis_pipeline.incr(key, total_logs)
359 358 redis_pipeline.expire(key, 3600 * 24 * 7)
360 359 redis_pipeline.sadd(
361 360 REDIS_KEYS["apps_that_got_new_data_per_hour"].format(
362 361 current_time.replace(minute=0)
363 362 ),
364 363 resource_id,
365 364 )
366 365 redis_pipeline.execute()
367 366 add_logs_es(es_docs)
368 367 return True
369 368 except Exception as exc:
370 369 print_traceback(log)
371 370 if celery.conf["CELERY_EAGER_PROPAGATES_EXCEPTIONS"]:
372 371 raise
373 372 add_logs.retry(exc=exc)
374 373
375 374
376 375 @celery.task(queue="es", default_retry_delay=600, max_retries=144)
377 376 def add_logs_es(es_docs):
378 377 for k, v in es_docs.items():
379 378 to_update = {"_index": k, "_type": "log"}
380 379 [i.update(to_update) for i in v]
381 380 elasticsearch.helpers.bulk(Datastores.es, v)
382 381
383 382
384 383 @celery.task(queue="metrics", default_retry_delay=600, max_retries=144)
385 384 def add_metrics(resource_id, request_params, dataset, proto_version):
386 385 current_time = datetime.utcnow().replace(second=0, microsecond=0)
387 386 try:
388 387 resource = ApplicationService.by_id_cached()(resource_id)
389 388 resource = DBSession.merge(resource, load=False)
390 389 es_docs = []
391 390 rows = []
392 391 for metric in dataset:
393 392 tags = dict(metric["tags"])
394 393 server_n = tags.get("server_name", metric["server_name"]).lower()
395 394 tags["server_name"] = server_n or "unknown"
396 395 new_metric = Metric(
397 396 timestamp=metric["timestamp"],
398 397 resource_id=resource.resource_id,
399 398 namespace=metric["namespace"],
400 399 tags=tags,
401 400 )
402 401 rows.append(new_metric)
403 402 es_docs.append(new_metric.es_doc())
404 403 session = DBSession()
405 404 session.bulk_save_objects(rows)
406 405 session.flush()
407 406
408 407 action = "METRICS"
409 408 metrics_msg = "%s: %s, metrics: %s, proto:%s" % (
410 409 action,
411 410 str(resource),
412 411 len(dataset),
413 412 proto_version,
414 413 )
415 414 log.info(metrics_msg)
416 415
417 416 mark_changed(session)
418 417 redis_pipeline = Datastores.redis.pipeline(transaction=False)
419 418 key = REDIS_KEYS["counters"]["metrics_per_minute"].format(current_time)
420 419 redis_pipeline.incr(key, len(rows))
421 420 redis_pipeline.expire(key, 3600 * 24)
422 421 key = REDIS_KEYS["counters"]["events_per_minute_per_user"].format(
423 422 resource.owner_user_id, current_time
424 423 )
425 424 redis_pipeline.incr(key, len(rows))
426 425 redis_pipeline.expire(key, 3600)
427 426 key = REDIS_KEYS["counters"]["metrics_per_hour_per_app"].format(
428 427 resource_id, current_time.replace(minute=0)
429 428 )
430 429 redis_pipeline.incr(key, len(rows))
431 430 redis_pipeline.expire(key, 3600 * 24 * 7)
432 431 redis_pipeline.sadd(
433 432 REDIS_KEYS["apps_that_got_new_data_per_hour"].format(
434 433 current_time.replace(minute=0)
435 434 ),
436 435 resource_id,
437 436 )
438 437 redis_pipeline.execute()
439 438 add_metrics_es(es_docs)
440 439 return True
441 440 except Exception as exc:
442 441 print_traceback(log)
443 442 if celery.conf["CELERY_EAGER_PROPAGATES_EXCEPTIONS"]:
444 443 raise
445 444 add_metrics.retry(exc=exc)
446 445
447 446
448 447 @celery.task(queue="es", default_retry_delay=600, max_retries=144)
449 448 def add_metrics_es(es_docs):
450 449 for doc in es_docs:
451 450 partition = "rcae_m_%s" % doc["timestamp"].strftime("%Y_%m_%d")
452 451 Datastores.es.index(partition, "log", doc)
453 452
454 453
455 454 @celery.task(queue="default", default_retry_delay=5, max_retries=2)
456 455 def check_user_report_notifications(resource_id):
457 456 since_when = datetime.utcnow()
458 457 try:
459 458 request = get_current_request()
460 459 application = ApplicationService.by_id(resource_id)
461 460 if not application:
462 461 return
463 462 error_key = REDIS_KEYS["reports_to_notify_per_type_per_app"].format(
464 463 ReportType.error, resource_id
465 464 )
466 465 slow_key = REDIS_KEYS["reports_to_notify_per_type_per_app"].format(
467 466 ReportType.slow, resource_id
468 467 )
469 468 error_group_ids = Datastores.redis.smembers(error_key)
470 469 slow_group_ids = Datastores.redis.smembers(slow_key)
471 470 Datastores.redis.delete(error_key)
472 471 Datastores.redis.delete(slow_key)
473 472 err_gids = [int(g_id) for g_id in error_group_ids]
474 473 slow_gids = [int(g_id) for g_id in list(slow_group_ids)]
475 474 group_ids = err_gids + slow_gids
476 475 occurence_dict = {}
477 476 for g_id in group_ids:
478 477 key = REDIS_KEYS["counters"]["report_group_occurences"].format(g_id)
479 478 val = Datastores.redis.get(key)
480 479 Datastores.redis.delete(key)
481 480 if val:
482 481 occurence_dict[g_id] = int(val)
483 482 else:
484 483 occurence_dict[g_id] = 1
485 484 report_groups = ReportGroupService.by_ids(group_ids)
486 485 report_groups.options(sa.orm.joinedload(ReportGroup.last_report_ref))
487 486
488 487 ApplicationService.check_for_groups_alert(
489 488 application,
490 489 "alert",
491 490 report_groups=report_groups,
492 491 occurence_dict=occurence_dict,
493 492 )
494 493 users = set(
495 494 [p.user for p in ResourceService.users_for_perm(application, "view")]
496 495 )
497 496 report_groups = report_groups.all()
498 497 for user in users:
499 498 UserService.report_notify(
500 499 user,
501 500 request,
502 501 application,
503 502 report_groups=report_groups,
504 503 occurence_dict=occurence_dict,
505 504 )
506 505 for group in report_groups:
507 506 # marks report_groups as notified
508 507 if not group.notified:
509 508 group.notified = True
510 509 except Exception as exc:
511 510 print_traceback(log)
512 511 raise
513 512
514 513
515 514 @celery.task(queue="default", default_retry_delay=5, max_retries=2)
516 515 def check_alerts(resource_id):
517 516 since_when = datetime.utcnow()
518 517 try:
519 518 request = get_current_request()
520 519 application = ApplicationService.by_id(resource_id)
521 520 if not application:
522 521 return
523 522 error_key = REDIS_KEYS["reports_to_notify_per_type_per_app_alerting"].format(
524 523 ReportType.error, resource_id
525 524 )
526 525 slow_key = REDIS_KEYS["reports_to_notify_per_type_per_app_alerting"].format(
527 526 ReportType.slow, resource_id
528 527 )
529 528 error_group_ids = Datastores.redis.smembers(error_key)
530 529 slow_group_ids = Datastores.redis.smembers(slow_key)
531 530 Datastores.redis.delete(error_key)
532 531 Datastores.redis.delete(slow_key)
533 532 err_gids = [int(g_id) for g_id in error_group_ids]
534 533 slow_gids = [int(g_id) for g_id in list(slow_group_ids)]
535 534 group_ids = err_gids + slow_gids
536 535 occurence_dict = {}
537 536 for g_id in group_ids:
538 537 key = REDIS_KEYS["counters"]["report_group_occurences_alerting"].format(
539 538 g_id
540 539 )
541 540 val = Datastores.redis.get(key)
542 541 Datastores.redis.delete(key)
543 542 if val:
544 543 occurence_dict[g_id] = int(val)
545 544 else:
546 545 occurence_dict[g_id] = 1
547 546 report_groups = ReportGroupService.by_ids(group_ids)
548 547 report_groups.options(sa.orm.joinedload(ReportGroup.last_report_ref))
549 548
550 549 ApplicationService.check_for_groups_alert(
551 550 application,
552 551 "alert",
553 552 report_groups=report_groups,
554 553 occurence_dict=occurence_dict,
555 554 since_when=since_when,
556 555 )
557 556 except Exception as exc:
558 557 print_traceback(log)
559 558 raise
560 559
561 560
562 561 @celery.task(queue="default", default_retry_delay=1, max_retries=2)
563 562 def close_alerts():
564 563 log.warning("Checking alerts")
565 564 since_when = datetime.utcnow()
566 565 try:
567 566 event_types = [
568 567 Event.types["error_report_alert"],
569 568 Event.types["slow_report_alert"],
570 569 ]
571 570 statuses = [Event.statuses["active"]]
572 571 # get events older than 5 min
573 572 events = EventService.by_type_and_status(
574 573 event_types, statuses, older_than=(since_when - timedelta(minutes=5))
575 574 )
576 575 for event in events:
577 576 # see if we can close them
578 577 event.validate_or_close(since_when=(since_when - timedelta(minutes=1)))
579 578 except Exception as exc:
580 579 print_traceback(log)
581 580 raise
582 581
583 582
584 583 @celery.task(queue="default", default_retry_delay=600, max_retries=144)
585 584 def update_tag_counter(tag_name, tag_value, count):
586 585 try:
587 586 query = (
588 587 DBSession.query(Tag)
589 588 .filter(Tag.name == tag_name)
590 589 .filter(
591 590 sa.cast(Tag.value, sa.types.TEXT)
592 591 == sa.cast(json.dumps(tag_value), sa.types.TEXT)
593 592 )
594 593 )
595 594 query.update(
596 595 {"times_seen": Tag.times_seen + count, "last_timestamp": datetime.utcnow()},
597 596 synchronize_session=False,
598 597 )
599 598 session = DBSession()
600 599 mark_changed(session)
601 600 return True
602 601 except Exception as exc:
603 602 print_traceback(log)
604 603 if celery.conf["CELERY_EAGER_PROPAGATES_EXCEPTIONS"]:
605 604 raise
606 605 update_tag_counter.retry(exc=exc)
607 606
608 607
609 608 @celery.task(queue="default")
610 609 def update_tag_counters():
611 610 """
612 611 Sets task to update counters for application tags
613 612 """
614 613 tags = Datastores.redis.lrange(REDIS_KEYS["seen_tag_list"], 0, -1)
615 614 Datastores.redis.delete(REDIS_KEYS["seen_tag_list"])
616 615 c = collections.Counter(tags)
617 616 for t_json, count in c.items():
618 617 tag_info = json.loads(t_json)
619 618 update_tag_counter.delay(tag_info[0], tag_info[1], count)
620 619
621 620
622 621 @celery.task(queue="default")
623 622 def daily_digest():
624 623 """
625 624 Sends daily digest with top 50 error reports
626 625 """
627 626 request = get_current_request()
628 627 apps = Datastores.redis.smembers(REDIS_KEYS["apps_that_had_reports"])
629 628 Datastores.redis.delete(REDIS_KEYS["apps_that_had_reports"])
630 629 since_when = datetime.utcnow() - timedelta(hours=8)
631 630 log.warning("Generating daily digests")
632 631 for resource_id in apps:
633 632 resource_id = resource_id.decode("utf8")
634 633 end_date = datetime.utcnow().replace(microsecond=0, second=0)
635 634 filter_settings = {
636 635 "resource": [resource_id],
637 636 "tags": [{"name": "type", "value": ["error"], "op": None}],
638 637 "type": "error",
639 638 "start_date": since_when,
640 639 "end_date": end_date,
641 640 }
642 641
643 642 reports = ReportGroupService.get_trending(
644 643 request, filter_settings=filter_settings, limit=50
645 644 )
646 645
647 646 application = ApplicationService.by_id(resource_id)
648 647 if application:
649 648 users = set(
650 649 [p.user for p in ResourceService.users_for_perm(application, "view")]
651 650 )
652 651 for user in users:
653 652 user.send_digest(
654 653 request, application, reports=reports, since_when=since_when
655 654 )
656 655
657 656
658 657 @celery.task(queue="default")
659 658 def notifications_reports():
660 659 """
661 660 Loop that checks redis for info and then issues new tasks to celery to
662 661 issue notifications
663 662 """
664 663 apps = Datastores.redis.smembers(REDIS_KEYS["apps_that_had_reports"])
665 664 Datastores.redis.delete(REDIS_KEYS["apps_that_had_reports"])
666 665 for app in apps:
667 666 log.warning("Notify for app: %s" % app)
668 667 check_user_report_notifications.delay(app.decode("utf8"))
669 668
670 669
671 670 @celery.task(queue="default")
672 671 def alerting_reports():
673 672 """
674 673 Loop that checks redis for info and then issues new tasks to celery to
675 674 perform the following:
676 675 - which applications should have new alerts opened
677 676 """
678 677
679 678 apps = Datastores.redis.smembers(REDIS_KEYS["apps_that_had_reports_alerting"])
680 679 Datastores.redis.delete(REDIS_KEYS["apps_that_had_reports_alerting"])
681 680 for app in apps:
682 681 log.warning("Notify for app: %s" % app)
683 682 check_alerts.delay(app.decode("utf8"))
684 683
685 684
686 685 @celery.task(
687 686 queue="default", soft_time_limit=3600 * 4, hard_time_limit=3600 * 4, max_retries=144
688 687 )
689 688 def logs_cleanup(resource_id, filter_settings):
690 689 request = get_current_request()
691 690 request.tm.begin()
692 691 es_query = {
693 692 "query": {
694 693 "bool": {"filter": [{"term": {"resource_id": resource_id}}]}
695 694 }
696 695 }
697 696
698 697 query = DBSession.query(Log).filter(Log.resource_id == resource_id)
699 698 if filter_settings["namespace"]:
700 699 query = query.filter(Log.namespace == filter_settings["namespace"][0])
701 700 es_query["query"]["bool"]["filter"].append(
702 701 {"term": {"namespace": filter_settings["namespace"][0]}}
703 702 )
704 703 query.delete(synchronize_session=False)
705 704 request.tm.commit()
706 Datastores.es.transport.perform_request(
707 "DELETE", "/{}/{}/_query".format("rcae_l_*", "log"), body=es_query
705 Datastores.es.delete_by_query(
706 index="rcae_l_*", doc_type="log", body=es_query, conflicts="proceed"
708 707 )
@@ -1,529 +1,529 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 from datetime import datetime, timedelta
18 18 import math
19 19 import uuid
20 20 import hashlib
21 21 import copy
22 22 import urllib.parse
23 23 import logging
24 24 import sqlalchemy as sa
25 25
26 26 from appenlight.models import Base, Datastores
27 27 from appenlight.lib.utils.date_utils import convert_date
28 28 from appenlight.lib.utils import convert_es_type
29 29 from appenlight.models.slow_call import SlowCall
30 30 from appenlight.lib.utils import channelstream_request
31 31 from appenlight.lib.enums import ReportType, Language
32 32 from pyramid.threadlocal import get_current_registry, get_current_request
33 33 from sqlalchemy.dialects.postgresql import JSON
34 34 from ziggurat_foundations.models.base import BaseModel
35 35
36 36 log = logging.getLogger(__name__)
37 37
38 38 REPORT_TYPE_MATRIX = {
39 39 "http_status": {"type": "int", "ops": ("eq", "ne", "ge", "le")},
40 40 "group:priority": {"type": "int", "ops": ("eq", "ne", "ge", "le")},
41 41 "duration": {"type": "float", "ops": ("ge", "le")},
42 42 "url_domain": {
43 43 "type": "unicode",
44 44 "ops": ("eq", "ne", "startswith", "endswith", "contains"),
45 45 },
46 46 "url_path": {
47 47 "type": "unicode",
48 48 "ops": ("eq", "ne", "startswith", "endswith", "contains"),
49 49 },
50 50 "error": {
51 51 "type": "unicode",
52 52 "ops": ("eq", "ne", "startswith", "endswith", "contains"),
53 53 },
54 54 "tags:server_name": {
55 55 "type": "unicode",
56 56 "ops": ("eq", "ne", "startswith", "endswith", "contains"),
57 57 },
58 58 "traceback": {"type": "unicode", "ops": ("contains",)},
59 59 "group:occurences": {"type": "int", "ops": ("eq", "ne", "ge", "le")},
60 60 }
61 61
62 62
63 63 class Report(Base, BaseModel):
64 64 __tablename__ = "reports"
65 65 __table_args__ = {"implicit_returning": False}
66 66
67 67 id = sa.Column(sa.Integer, nullable=False, primary_key=True)
68 68 group_id = sa.Column(
69 69 sa.BigInteger,
70 70 sa.ForeignKey("reports_groups.id", ondelete="cascade", onupdate="cascade"),
71 71 )
72 72 resource_id = sa.Column(sa.Integer(), nullable=False, index=True)
73 73 report_type = sa.Column(sa.Integer(), nullable=False, index=True)
74 74 error = sa.Column(sa.UnicodeText(), index=True)
75 75 extra = sa.Column(JSON(), default={})
76 76 request = sa.Column(JSON(), nullable=False, default={})
77 77 ip = sa.Column(sa.String(39), index=True, default="")
78 78 username = sa.Column(sa.Unicode(255), default="")
79 79 user_agent = sa.Column(sa.Unicode(255), default="")
80 80 url = sa.Column(sa.UnicodeText(), index=True)
81 81 request_id = sa.Column(sa.Text())
82 82 request_stats = sa.Column(JSON(), nullable=False, default={})
83 83 traceback = sa.Column(JSON(), nullable=False, default=None)
84 84 traceback_hash = sa.Column(sa.Text())
85 85 start_time = sa.Column(
86 86 sa.DateTime(), default=datetime.utcnow, server_default=sa.func.now()
87 87 )
88 88 end_time = sa.Column(sa.DateTime())
89 89 duration = sa.Column(sa.Float, default=0)
90 90 http_status = sa.Column(sa.Integer, index=True)
91 91 url_domain = sa.Column(sa.Unicode(100), index=True)
92 92 url_path = sa.Column(sa.Unicode(255), index=True)
93 93 tags = sa.Column(JSON(), nullable=False, default={})
94 94 language = sa.Column(sa.Integer(), default=0)
95 95 # this is used to determine partition for the report
96 96 report_group_time = sa.Column(
97 97 sa.DateTime(), default=datetime.utcnow, server_default=sa.func.now()
98 98 )
99 99
100 100 logs = sa.orm.relationship(
101 101 "Log",
102 102 lazy="dynamic",
103 103 passive_deletes=True,
104 104 passive_updates=True,
105 105 primaryjoin="and_(Report.request_id==Log.request_id, "
106 106 "Log.request_id != None, Log.request_id != '')",
107 107 foreign_keys="[Log.request_id]",
108 108 )
109 109
110 110 slow_calls = sa.orm.relationship(
111 111 "SlowCall",
112 112 backref="detail",
113 113 cascade="all, delete-orphan",
114 114 passive_deletes=True,
115 115 passive_updates=True,
116 116 order_by="SlowCall.timestamp",
117 117 )
118 118
119 119 def set_data(self, data, resource, protocol_version=None):
120 120 self.http_status = data["http_status"]
121 121 self.priority = data["priority"]
122 122 self.error = data["error"]
123 123 report_language = data.get("language", "").lower()
124 124 self.language = getattr(Language, report_language, Language.unknown)
125 125 # we need temp holder here to decide later
126 126 # if we want to to commit the tags if report is marked for creation
127 127 self.tags = {"server_name": data["server"], "view_name": data["view_name"]}
128 128 if data.get("tags"):
129 129 for tag_tuple in data["tags"]:
130 130 self.tags[tag_tuple[0]] = tag_tuple[1]
131 131 self.traceback = data["traceback"]
132 132 stripped_traceback = self.stripped_traceback()
133 133 tb_repr = repr(stripped_traceback).encode("utf8")
134 134 self.traceback_hash = hashlib.sha1(tb_repr).hexdigest()
135 135 url_info = urllib.parse.urlsplit(data.get("url", ""), allow_fragments=False)
136 136 self.url_domain = url_info.netloc[:128]
137 137 self.url_path = url_info.path[:2048]
138 138 self.occurences = data["occurences"]
139 139 if self.error:
140 140 self.report_type = ReportType.error
141 141 else:
142 142 self.report_type = ReportType.slow
143 143
144 144 # but if its status 404 its 404 type
145 145 if self.http_status in [404, "404"] or self.error == "404 Not Found":
146 146 self.report_type = ReportType.not_found
147 147 self.error = ""
148 148
149 149 self.generate_grouping_hash(
150 150 data.get("appenlight.group_string", data.get("group_string")),
151 151 resource.default_grouping,
152 152 protocol_version,
153 153 )
154 154
155 155 # details
156 156 if data["http_status"] in [404, "404"]:
157 157 data = {
158 158 "username": data["username"],
159 159 "ip": data["ip"],
160 160 "url": data["url"],
161 161 "user_agent": data["user_agent"],
162 162 }
163 163 if data.get("HTTP_REFERER") or data.get("http_referer"):
164 164 data["HTTP_REFERER"] = data.get("HTTP_REFERER", "") or data.get(
165 165 "http_referer", ""
166 166 )
167 167
168 168 self.resource_id = resource.resource_id
169 169 self.username = data["username"]
170 170 self.user_agent = data["user_agent"]
171 171 self.ip = data["ip"]
172 172 self.extra = {}
173 173 if data.get("extra"):
174 174 for extra_tuple in data["extra"]:
175 175 self.extra[extra_tuple[0]] = extra_tuple[1]
176 176
177 177 self.url = data["url"]
178 178 self.request_id = data.get("request_id", "").replace("-", "") or str(
179 179 uuid.uuid4()
180 180 )
181 181 request_data = data.get("request", {})
182 182
183 183 self.request = request_data
184 184 self.request_stats = data.get("request_stats") or {}
185 185 traceback = data.get("traceback")
186 186 if not traceback:
187 187 traceback = data.get("frameinfo")
188 188 self.traceback = traceback
189 189 start_date = convert_date(data.get("start_time"))
190 190 if not self.start_time or self.start_time < start_date:
191 191 self.start_time = start_date
192 192
193 193 self.end_time = convert_date(data.get("end_time"), False)
194 194 self.duration = 0
195 195
196 196 if self.start_time and self.end_time:
197 197 d = self.end_time - self.start_time
198 198 self.duration = d.total_seconds()
199 199
200 200 # update tags with other vars
201 201 if self.username:
202 202 self.tags["user_name"] = self.username
203 203 self.tags["report_language"] = Language.key_from_value(self.language)
204 204
205 205 def add_slow_calls(self, data, report_group):
206 206 slow_calls = []
207 207 for call in data.get("slow_calls", []):
208 208 sc_inst = SlowCall()
209 209 sc_inst.set_data(
210 210 call, resource_id=self.resource_id, report_group=report_group
211 211 )
212 212 slow_calls.append(sc_inst)
213 213 self.slow_calls.extend(slow_calls)
214 214 return slow_calls
215 215
216 216 def get_dict(self, request, details=False, exclude_keys=None, include_keys=None):
217 217 from appenlight.models.services.report_group import ReportGroupService
218 218
219 219 instance_dict = super(Report, self).get_dict()
220 220 instance_dict["req_stats"] = self.req_stats()
221 221 instance_dict["group"] = {}
222 222 instance_dict["group"]["id"] = self.report_group.id
223 223 instance_dict["group"]["total_reports"] = self.report_group.total_reports
224 224 instance_dict["group"]["last_report"] = self.report_group.last_report
225 225 instance_dict["group"]["priority"] = self.report_group.priority
226 226 instance_dict["group"]["occurences"] = self.report_group.occurences
227 227 instance_dict["group"]["last_timestamp"] = self.report_group.last_timestamp
228 228 instance_dict["group"]["first_timestamp"] = self.report_group.first_timestamp
229 229 instance_dict["group"]["public"] = self.report_group.public
230 230 instance_dict["group"]["fixed"] = self.report_group.fixed
231 231 instance_dict["group"]["read"] = self.report_group.read
232 232 instance_dict["group"]["average_duration"] = self.report_group.average_duration
233 233
234 234 instance_dict["resource_name"] = self.report_group.application.resource_name
235 235 instance_dict["report_type"] = self.report_type
236 236
237 237 if instance_dict["http_status"] == 404 and not instance_dict["error"]:
238 238 instance_dict["error"] = "404 Not Found"
239 239
240 240 if details:
241 241 instance_dict[
242 242 "affected_users_count"
243 243 ] = ReportGroupService.affected_users_count(self.report_group)
244 244 instance_dict["top_affected_users"] = [
245 245 {"username": u.username, "count": u.count}
246 246 for u in ReportGroupService.top_affected_users(self.report_group)
247 247 ]
248 248 instance_dict["application"] = {"integrations": []}
249 249 for integration in self.report_group.application.integrations:
250 250 if integration.front_visible:
251 251 instance_dict["application"]["integrations"].append(
252 252 {
253 253 "name": integration.integration_name,
254 254 "action": integration.integration_action,
255 255 }
256 256 )
257 257 instance_dict["comments"] = [
258 258 c.get_dict() for c in self.report_group.comments
259 259 ]
260 260
261 261 instance_dict["group"]["next_report"] = None
262 262 instance_dict["group"]["previous_report"] = None
263 263 next_in_group = self.get_next_in_group(request)
264 264 previous_in_group = self.get_previous_in_group(request)
265 265 if next_in_group:
266 266 instance_dict["group"]["next_report"] = next_in_group
267 267 if previous_in_group:
268 268 instance_dict["group"]["previous_report"] = previous_in_group
269 269
270 270 # slow call ordering
271 271 def find_parent(row, data):
272 272 for r in reversed(data):
273 273 try:
274 274 if (
275 275 row["timestamp"] > r["timestamp"]
276 276 and row["end_time"] < r["end_time"]
277 277 ):
278 278 return r
279 279 except TypeError as e:
280 280 log.warning("reports_view.find_parent: %s" % e)
281 281 return None
282 282
283 283 new_calls = []
284 284 calls = [c.get_dict() for c in self.slow_calls]
285 285 while calls:
286 286 # start from end
287 287 for x in range(len(calls) - 1, -1, -1):
288 288 parent = find_parent(calls[x], calls)
289 289 if parent:
290 290 parent["children"].append(calls[x])
291 291 else:
292 292 # no parent at all? append to new calls anyways
293 293 new_calls.append(calls[x])
294 294 # print 'append', calls[x]
295 295 del calls[x]
296 296 break
297 297 instance_dict["slow_calls"] = new_calls
298 298
299 299 instance_dict["front_url"] = self.get_public_url(request)
300 300
301 301 exclude_keys_list = exclude_keys or []
302 302 include_keys_list = include_keys or []
303 303 for k in list(instance_dict.keys()):
304 304 if k == "group":
305 305 continue
306 306 if k in exclude_keys_list or (k not in include_keys_list and include_keys):
307 307 del instance_dict[k]
308 308 return instance_dict
309 309
310 310 def get_previous_in_group(self, request):
311 311 query = {
312 312 "size": 1,
313 313 "query": {
314 314 "bool": {
315 315 "filter": [
316 316 {"term": {"group_id": self.group_id}},
317 317 {"range": {"pg_id": {"lt": self.id}}},
318 318 ]
319 319 }
320 320 },
321 321 "sort": [{"_doc": {"order": "desc"}}],
322 322 }
323 323 result = request.es_conn.search(
324 324 body=query, index=self.partition_id, doc_type="report"
325 325 )
326 326 if result["hits"]["total"]:
327 327 return result["hits"]["hits"][0]["_source"]["pg_id"]
328 328
329 329 def get_next_in_group(self, request):
330 330 query = {
331 331 "size": 1,
332 332 "query": {
333 333 "bool": {
334 334 "filter": [
335 335 {"term": {"group_id": self.group_id}},
336 336 {"range": {"pg_id": {"gt": self.id}}},
337 337 ]
338 338 }
339 339 },
340 340 "sort": [{"_doc": {"order": "asc"}}],
341 341 }
342 342 result = request.es_conn.search(
343 343 body=query, index=self.partition_id, doc_type="report"
344 344 )
345 345 if result["hits"]["total"]:
346 346 return result["hits"]["hits"][0]["_source"]["pg_id"]
347 347
348 348 def get_public_url(self, request=None, report_group=None, _app_url=None):
349 349 """
350 350 Returns url that user can use to visit specific report
351 351 """
352 352 if not request:
353 353 request = get_current_request()
354 354 url = request.route_url("/", _app_url=_app_url)
355 355 if report_group:
356 356 return (url + "ui/report/%s/%s") % (report_group.id, self.id)
357 357 return (url + "ui/report/%s/%s") % (self.group_id, self.id)
358 358
359 359 def req_stats(self):
360 360 stats = self.request_stats.copy()
361 361 stats["percentages"] = {}
362 362 stats["percentages"]["main"] = 100.0
363 363 main = stats.get("main", 0.0)
364 364 if not main:
365 365 return None
366 366 for name, call_time in stats.items():
367 367 if "calls" not in name and "main" not in name and "percentages" not in name:
368 368 stats["main"] -= call_time
369 369 stats["percentages"][name] = math.floor((call_time / main * 100.0))
370 370 stats["percentages"]["main"] -= stats["percentages"][name]
371 371 if stats["percentages"]["main"] < 0.0:
372 372 stats["percentages"]["main"] = 0.0
373 373 stats["main"] = 0.0
374 374 return stats
375 375
376 376 def generate_grouping_hash(
377 377 self, hash_string=None, default_grouping=None, protocol_version=None
378 378 ):
379 379 """
380 380 Generates SHA1 hash that will be used to group reports together
381 381 """
382 382 if not hash_string:
383 383 location = self.tags.get("view_name") or self.url_path
384 384 server_name = self.tags.get("server_name") or ""
385 385 if default_grouping == "url_traceback":
386 386 hash_string = "%s_%s_%s" % (self.traceback_hash, location, self.error)
387 387 if self.language == Language.javascript:
388 388 hash_string = "%s_%s" % (self.traceback_hash, self.error)
389 389
390 390 elif default_grouping == "traceback_server":
391 391 hash_string = "%s_%s" % (self.traceback_hash, server_name)
392 392 if self.language == Language.javascript:
393 393 hash_string = "%s_%s" % (self.traceback_hash, server_name)
394 394 else:
395 395 hash_string = "%s_%s" % (self.error, location)
396 396 month = datetime.utcnow().date().replace(day=1)
397 397 hash_string = "{}_{}".format(month, hash_string)
398 398 binary_string = hash_string.encode("utf8")
399 399 self.grouping_hash = hashlib.sha1(binary_string).hexdigest()
400 400 return self.grouping_hash
401 401
402 402 def stripped_traceback(self):
403 403 """
404 404 Traceback without local vars
405 405 """
406 406 stripped_traceback = copy.deepcopy(self.traceback)
407 407
408 408 if isinstance(stripped_traceback, list):
409 409 for row in stripped_traceback:
410 410 row.pop("vars", None)
411 411 return stripped_traceback
412 412
413 413 def notify_channel(self, report_group):
414 414 """
415 415 Sends notification to websocket channel
416 416 """
417 417 settings = get_current_registry().settings
418 418 log.info("notify channelstream")
419 419 if self.report_type != ReportType.error:
420 420 return
421 421 payload = {
422 422 "type": "message",
423 423 "user": "__system__",
424 424 "channel": "app_%s" % self.resource_id,
425 425 "message": {
426 426 "topic": "front_dashboard.new_topic",
427 427 "report": {
428 428 "group": {
429 429 "priority": report_group.priority,
430 430 "first_timestamp": report_group.first_timestamp,
431 431 "last_timestamp": report_group.last_timestamp,
432 432 "average_duration": report_group.average_duration,
433 433 "occurences": report_group.occurences,
434 434 },
435 435 "report_id": self.id,
436 436 "group_id": self.group_id,
437 437 "resource_id": self.resource_id,
438 438 "http_status": self.http_status,
439 439 "url_domain": self.url_domain,
440 440 "url_path": self.url_path,
441 441 "error": self.error or "",
442 442 "server": self.tags.get("server_name"),
443 443 "view_name": self.tags.get("view_name"),
444 444 "front_url": self.get_public_url(),
445 445 },
446 446 },
447 447 }
448 448 channelstream_request(
449 449 settings["cometd.secret"],
450 450 "/message",
451 451 [payload],
452 452 servers=[settings["cometd_servers"]],
453 453 )
454 454
455 455 def es_doc(self):
456 456 tags = {}
457 457 tag_list = []
458 458 for name, value in self.tags.items():
459 459 name = name.replace(".", "_")
460 460 tag_list.append(name)
461 461 tags[name] = {
462 462 "values": convert_es_type(value),
463 463 "numeric_values": value
464 464 if (isinstance(value, (int, float)) and not isinstance(value, bool))
465 465 else None,
466 466 }
467 467
468 468 if "user_name" not in self.tags and self.username:
469 469 tags["user_name"] = {"value": [self.username], "numeric_value": None}
470 470 return {
471 471 "_id": str(self.id),
472 472 "pg_id": str(self.id),
473 473 "resource_id": self.resource_id,
474 474 "http_status": self.http_status or "",
475 475 "start_time": self.start_time,
476 476 "end_time": self.end_time,
477 477 "url_domain": self.url_domain if self.url_domain else "",
478 478 "url_path": self.url_path if self.url_path else "",
479 479 "duration": self.duration,
480 480 "error": self.error if self.error else "",
481 481 "report_type": self.report_type,
482 482 "request_id": self.request_id,
483 483 "ip": self.ip,
484 484 "group_id": str(self.group_id),
485 485 "_parent": str(self.group_id),
486 486 "tags": tags,
487 487 "tag_list": tag_list,
488 488 }
489 489
490 490 @property
491 491 def partition_id(self):
492 492 return "rcae_r_%s" % self.report_group_time.strftime("%Y_%m")
493 493
494 494 def partition_range(self):
495 495 start_date = self.report_group_time.date().replace(day=1)
496 496 end_date = start_date + timedelta(days=40)
497 497 end_date = end_date.replace(day=1)
498 498 return start_date, end_date
499 499
500 500
501 501 def after_insert(mapper, connection, target):
502 502 if not hasattr(target, "_skip_ft_index"):
503 503 data = target.es_doc()
504 504 data.pop("_id", None)
505 505 Datastores.es.index(
506 506 target.partition_id, "report", data, parent=target.group_id, id=target.id
507 507 )
508 508
509 509
510 510 def after_update(mapper, connection, target):
511 511 if not hasattr(target, "_skip_ft_index"):
512 512 data = target.es_doc()
513 513 data.pop("_id", None)
514 514 Datastores.es.index(
515 515 target.partition_id, "report", data, parent=target.group_id, id=target.id
516 516 )
517 517
518 518
519 519 def after_delete(mapper, connection, target):
520 520 if not hasattr(target, "_skip_ft_index"):
521 521 query = {"query": {"term": {"pg_id": target.id}}}
522 Datastores.es.transport.perform_request(
523 "DELETE", "/{}/{}/_query".format(target.partition_id, "report"), body=query
522 Datastores.es.delete_by_query(
523 index=target.partition_id, doc_type="report", body=query, conflicts="proceed"
524 524 )
525 525
526 526
527 527 sa.event.listen(Report, "after_insert", after_insert)
528 528 sa.event.listen(Report, "after_update", after_update)
529 529 sa.event.listen(Report, "after_delete", after_delete)
@@ -1,287 +1,285 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 import logging
18 18 import sqlalchemy as sa
19 19
20 20 from datetime import datetime, timedelta
21 21
22 22 from pyramid.threadlocal import get_current_request
23 23 from sqlalchemy.dialects.postgresql import JSON
24 24 from ziggurat_foundations.models.base import BaseModel
25 25
26 26 from appenlight.models import Base, get_db_session, Datastores
27 27 from appenlight.lib.enums import ReportType
28 28 from appenlight.lib.rule import Rule
29 29 from appenlight.lib.redis_keys import REDIS_KEYS
30 30 from appenlight.models.report import REPORT_TYPE_MATRIX
31 31
32 32 log = logging.getLogger(__name__)
33 33
34 34
35 35 class ReportGroup(Base, BaseModel):
36 36 __tablename__ = "reports_groups"
37 37 __table_args__ = {"implicit_returning": False}
38 38
39 39 id = sa.Column(sa.BigInteger(), nullable=False, primary_key=True)
40 40 resource_id = sa.Column(
41 41 sa.Integer(),
42 42 sa.ForeignKey(
43 43 "applications.resource_id", onupdate="CASCADE", ondelete="CASCADE"
44 44 ),
45 45 nullable=False,
46 46 index=True,
47 47 )
48 48 priority = sa.Column(
49 49 sa.Integer, nullable=False, index=True, default=5, server_default="5"
50 50 )
51 51 first_timestamp = sa.Column(
52 52 sa.DateTime(), default=datetime.utcnow, server_default=sa.func.now()
53 53 )
54 54 last_timestamp = sa.Column(
55 55 sa.DateTime(), default=datetime.utcnow, server_default=sa.func.now()
56 56 )
57 57 error = sa.Column(sa.UnicodeText(), index=True)
58 58 grouping_hash = sa.Column(sa.String(40), default="")
59 59 triggered_postprocesses_ids = sa.Column(JSON(), nullable=False, default=list)
60 60 report_type = sa.Column(sa.Integer, default=1)
61 61 total_reports = sa.Column(sa.Integer, default=1)
62 62 last_report = sa.Column(sa.Integer)
63 63 occurences = sa.Column(sa.Integer, default=1)
64 64 average_duration = sa.Column(sa.Float, default=0)
65 65 summed_duration = sa.Column(sa.Float, default=0)
66 66 read = sa.Column(sa.Boolean(), index=True, default=False)
67 67 fixed = sa.Column(sa.Boolean(), index=True, default=False)
68 68 notified = sa.Column(sa.Boolean(), index=True, default=False)
69 69 public = sa.Column(sa.Boolean(), index=True, default=False)
70 70
71 71 reports = sa.orm.relationship(
72 72 "Report",
73 73 lazy="dynamic",
74 74 backref="report_group",
75 75 cascade="all, delete-orphan",
76 76 passive_deletes=True,
77 77 passive_updates=True,
78 78 )
79 79
80 80 comments = sa.orm.relationship(
81 81 "ReportComment",
82 82 lazy="dynamic",
83 83 backref="report",
84 84 cascade="all, delete-orphan",
85 85 passive_deletes=True,
86 86 passive_updates=True,
87 87 order_by="ReportComment.comment_id",
88 88 )
89 89
90 90 assigned_users = sa.orm.relationship(
91 91 "User",
92 92 backref=sa.orm.backref(
93 93 "assigned_reports_relation",
94 94 lazy="dynamic",
95 95 order_by=sa.desc(sa.text("reports_groups.id")),
96 96 ),
97 97 passive_deletes=True,
98 98 passive_updates=True,
99 99 secondary="reports_assignments",
100 100 order_by="User.user_name",
101 101 )
102 102
103 103 stats = sa.orm.relationship(
104 104 "ReportStat",
105 105 lazy="dynamic",
106 106 backref="report",
107 107 passive_deletes=True,
108 108 passive_updates=True,
109 109 )
110 110
111 111 last_report_ref = sa.orm.relationship(
112 112 "Report",
113 113 uselist=False,
114 114 primaryjoin="ReportGroup.last_report " "== Report.id",
115 115 foreign_keys="Report.id",
116 116 cascade="all, delete-orphan",
117 117 passive_deletes=True,
118 118 passive_updates=True,
119 119 )
120 120
121 121 def __repr__(self):
122 122 return "<ReportGroup id:{}>".format(self.id)
123 123
124 124 def get_report(self, report_id=None, public=False):
125 125 """
126 126 Gets report with specific id or latest report if id was not specified
127 127 """
128 128 from .report import Report
129 129
130 130 if not report_id:
131 131 return self.last_report_ref
132 132 else:
133 133 return self.reports.filter(Report.id == report_id).first()
134 134
135 135 def get_public_url(self, request, _app_url=None):
136 136 url = request.route_url("/", _app_url=_app_url)
137 137 return (url + "ui/report/%s") % self.id
138 138
139 139 def run_postprocessing(self, report):
140 140 """
141 141 Alters report group priority based on postprocessing configuration
142 142 """
143 143 request = get_current_request()
144 144 get_db_session(None, self).flush()
145 145 for action in self.application.postprocess_conf:
146 146 get_db_session(None, self).flush()
147 147 rule_obj = Rule(action.rule, REPORT_TYPE_MATRIX)
148 148 report_dict = report.get_dict(request)
149 149 # if was not processed yet
150 150 if (
151 151 rule_obj.match(report_dict)
152 152 and action.pkey not in self.triggered_postprocesses_ids
153 153 ):
154 154 action.postprocess(self)
155 155 # this way sqla can track mutation of list
156 156 self.triggered_postprocesses_ids = self.triggered_postprocesses_ids + [
157 157 action.pkey
158 158 ]
159 159
160 160 get_db_session(None, self).flush()
161 161 # do not go out of bounds
162 162 if self.priority < 1:
163 163 self.priority = 1
164 164 if self.priority > 10:
165 165 self.priority = 10
166 166
167 167 def get_dict(self, request):
168 168 instance_dict = super(ReportGroup, self).get_dict()
169 169 instance_dict["server_name"] = self.get_report().tags.get("server_name")
170 170 instance_dict["view_name"] = self.get_report().tags.get("view_name")
171 171 instance_dict["resource_name"] = self.application.resource_name
172 172 instance_dict["report_type"] = self.get_report().report_type
173 173 instance_dict["url_path"] = self.get_report().url_path
174 174 instance_dict["front_url"] = self.get_report().get_public_url(request)
175 175 del instance_dict["triggered_postprocesses_ids"]
176 176 return instance_dict
177 177
178 178 def es_doc(self):
179 179 return {
180 180 "_id": str(self.id),
181 181 "pg_id": str(self.id),
182 182 "resource_id": self.resource_id,
183 183 "error": self.error,
184 184 "fixed": self.fixed,
185 185 "public": self.public,
186 186 "read": self.read,
187 187 "priority": self.priority,
188 188 "occurences": self.occurences,
189 189 "average_duration": self.average_duration,
190 190 "summed_duration": self.summed_duration,
191 191 "first_timestamp": self.first_timestamp,
192 192 "last_timestamp": self.last_timestamp,
193 193 }
194 194
195 195 def set_notification_info(self, notify_10=False, notify_100=False):
196 196 """
197 197 Update redis notification maps for notification job
198 198 """
199 199 current_time = datetime.utcnow().replace(second=0, microsecond=0)
200 200 # global app counter
201 201 key = REDIS_KEYS["counters"]["reports_per_type"].format(
202 202 self.report_type, current_time
203 203 )
204 204 redis_pipeline = Datastores.redis.pipeline()
205 205 redis_pipeline.incr(key)
206 206 redis_pipeline.expire(key, 3600 * 24)
207 207 # detailed app notification for alerts and notifications
208 208 redis_pipeline.sadd(REDIS_KEYS["apps_that_had_reports"], self.resource_id)
209 209 redis_pipeline.sadd(
210 210 REDIS_KEYS["apps_that_had_reports_alerting"], self.resource_id
211 211 )
212 212 # only notify for exceptions here
213 213 if self.report_type == ReportType.error:
214 214 redis_pipeline.sadd(REDIS_KEYS["apps_that_had_reports"], self.resource_id)
215 215 redis_pipeline.sadd(
216 216 REDIS_KEYS["apps_that_had_error_reports_alerting"], self.resource_id
217 217 )
218 218 key = REDIS_KEYS["counters"]["report_group_occurences"].format(self.id)
219 219 redis_pipeline.incr(key)
220 220 redis_pipeline.expire(key, 3600 * 24)
221 221 key = REDIS_KEYS["counters"]["report_group_occurences_alerting"].format(self.id)
222 222 redis_pipeline.incr(key)
223 223 redis_pipeline.expire(key, 3600 * 24)
224 224
225 225 if notify_10:
226 226 key = REDIS_KEYS["counters"]["report_group_occurences_10th"].format(self.id)
227 227 redis_pipeline.setex(key, 3600 * 24, 1)
228 228 if notify_100:
229 229 key = REDIS_KEYS["counters"]["report_group_occurences_100th"].format(
230 230 self.id
231 231 )
232 232 redis_pipeline.setex(key, 3600 * 24, 1)
233 233
234 234 key = REDIS_KEYS["reports_to_notify_per_type_per_app"].format(
235 235 self.report_type, self.resource_id
236 236 )
237 237 redis_pipeline.sadd(key, self.id)
238 238 redis_pipeline.expire(key, 3600 * 24)
239 239 key = REDIS_KEYS["reports_to_notify_per_type_per_app_alerting"].format(
240 240 self.report_type, self.resource_id
241 241 )
242 242 redis_pipeline.sadd(key, self.id)
243 243 redis_pipeline.expire(key, 3600 * 24)
244 244 redis_pipeline.execute()
245 245
246 246 @property
247 247 def partition_id(self):
248 248 return "rcae_r_%s" % self.first_timestamp.strftime("%Y_%m")
249 249
250 250 def partition_range(self):
251 251 start_date = self.first_timestamp.date().replace(day=1)
252 252 end_date = start_date + timedelta(days=40)
253 253 end_date = end_date.replace(day=1)
254 254 return start_date, end_date
255 255
256 256
257 257 def after_insert(mapper, connection, target):
258 258 if not hasattr(target, "_skip_ft_index"):
259 259 data = target.es_doc()
260 260 data.pop("_id", None)
261 261 Datastores.es.index(target.partition_id, "report_group", data, id=target.id)
262 262
263 263
264 264 def after_update(mapper, connection, target):
265 265 if not hasattr(target, "_skip_ft_index"):
266 266 data = target.es_doc()
267 267 data.pop("_id", None)
268 268 Datastores.es.index(target.partition_id, "report_group", data, id=target.id)
269 269
270 270
271 271 def after_delete(mapper, connection, target):
272 272 query = {"query": {"term": {"group_id": target.id}}}
273 273 # delete by query
274 Datastores.es.transport.perform_request(
275 "DELETE", "/{}/{}/_query".format(target.partition_id, "report"), body=query
274 Datastores.es.delete_by_query(
275 index=target.partition_id, doc_type="report", body=query, conflicts="proceed"
276 276 )
277 277 query = {"query": {"term": {"pg_id": target.id}}}
278 Datastores.es.transport.perform_request(
279 "DELETE",
280 "/{}/{}/_query".format(target.partition_id, "report_group"),
281 body=query,
278 Datastores.es.delete_by_query(
279 index=target.partition_id, doc_type="report_group", body=query, conflicts="proceed"
282 280 )
283 281
284 282
285 283 sa.event.listen(ReportGroup, "after_insert", after_insert)
286 284 sa.event.listen(ReportGroup, "after_update", after_update)
287 285 sa.event.listen(ReportGroup, "after_delete", after_delete)
@@ -1,519 +1,521 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 import logging
18 18 import paginate
19 19 import sqlalchemy as sa
20 20 import appenlight.lib.helpers as h
21 21
22 22 from datetime import datetime
23 23
24 24 from appenlight.models import get_db_session, Datastores
25 25 from appenlight.models.report import Report
26 26 from appenlight.models.report_group import ReportGroup
27 27 from appenlight.models.report_comment import ReportComment
28 28 from appenlight.models.user import User
29 29 from appenlight.models.services.base import BaseService
30 30 from appenlight.lib.enums import ReportType
31 31 from appenlight.lib.utils import es_index_name_limiter
32 32
33 33 log = logging.getLogger(__name__)
34 34
35 35
36 36 class ReportGroupService(BaseService):
37 37 @classmethod
38 38 def get_trending(cls, request, filter_settings, limit=15, db_session=None):
39 39 """
40 40 Returns report groups trending for specific time interval
41 41 """
42 42 db_session = get_db_session(db_session)
43 43
44 44 tags = []
45 45 if filter_settings.get("tags"):
46 46 for tag in filter_settings["tags"]:
47 47 tags.append(
48 48 {"terms": {"tags.{}.values".format(tag["name"]): tag["value"]}}
49 49 )
50 50
51 51 index_names = es_index_name_limiter(
52 52 start_date=filter_settings["start_date"],
53 53 end_date=filter_settings["end_date"],
54 54 ixtypes=["reports"],
55 55 )
56 56
57 57 if not index_names or not filter_settings["resource"]:
58 58 return []
59 59
60 60 es_query = {
61 61 "aggs": {
62 62 "parent_agg": {
63 63 "aggs": {
64 64 "groups": {
65 65 "aggs": {
66 66 "sub_agg": {
67 "value_count": {"field": "tags.group_id.values"}
67 "value_count": {"field": "tags.group_id.values.keyword"}
68 68 }
69 69 },
70 70 "filter": {"exists": {"field": "tags.group_id.values"}},
71 71 }
72 72 },
73 "terms": {"field": "tags.group_id.values", "size": limit},
73 "terms": {"field": "tags.group_id.values.keyword", "size": limit},
74 74 }
75 75 },
76 76 "query": {
77 77 "bool": {
78 78 "filter": [
79 79 {
80 80 "terms": {
81 81 "resource_id": [filter_settings["resource"][0]]
82 82 }
83 83 },
84 84 {
85 85 "range": {
86 86 "timestamp": {
87 87 "gte": filter_settings["start_date"],
88 88 "lte": filter_settings["end_date"],
89 89 }
90 90 }
91 91 },
92 92 ]
93 93 }
94 94 },
95 95 }
96 96 if tags:
97 97 es_query["query"]["bool"]["filter"].extend(tags)
98 98
99 99 result = Datastores.es.search(
100 100 body=es_query, index=index_names, doc_type="log", size=0
101 101 )
102 102 series = []
103 103 for bucket in result["aggregations"]["parent_agg"]["buckets"]:
104 104 series.append(
105 105 {"key": bucket["key"], "groups": bucket["groups"]["sub_agg"]["value"]}
106 106 )
107 107
108 108 report_groups_d = {}
109 109 for g in series:
110 110 report_groups_d[int(g["key"])] = g["groups"] or 0
111 111
112 112 query = db_session.query(ReportGroup)
113 113 query = query.filter(ReportGroup.id.in_(list(report_groups_d.keys())))
114 114 query = query.options(sa.orm.joinedload(ReportGroup.last_report_ref))
115 115 results = [(report_groups_d[group.id], group) for group in query]
116 116 return sorted(results, reverse=True, key=lambda x: x[0])
117 117
118 118 @classmethod
119 119 def get_search_iterator(
120 120 cls,
121 121 app_ids=None,
122 122 page=1,
123 123 items_per_page=50,
124 124 order_by=None,
125 125 filter_settings=None,
126 126 limit=None,
127 127 ):
128 128 if not app_ids:
129 129 return {}
130 130 if not filter_settings:
131 131 filter_settings = {}
132 132
133 133 query = {
134 134 "size": 0,
135 135 "query": {
136 136 "bool": {
137 137 "must": [],
138 138 "should": [],
139 139 "filter": [{"terms": {"resource_id": list(app_ids)}}]
140 140 }
141 141 },
142 142 "aggs": {
143 143 "top_groups": {
144 144 "terms": {
145 145 "size": 5000,
146 "field": "_parent",
146 "field": "_parent#report_group",
147 147 "order": {"newest": "desc"},
148 148 },
149 149 "aggs": {
150 150 "top_reports_hits": {
151 151 "top_hits": {"size": 1, "sort": {"start_time": "desc"}}
152 152 },
153 153 "newest": {"max": {"field": "start_time"}},
154 154 },
155 155 }
156 156 },
157 157 }
158 158
159 159 start_date = filter_settings.get("start_date")
160 160 end_date = filter_settings.get("end_date")
161 161 filter_part = query["query"]["bool"]["filter"]
162 162 date_range = {"range": {"start_time": {}}}
163 163 if start_date:
164 164 date_range["range"]["start_time"]["gte"] = start_date
165 165 if end_date:
166 166 date_range["range"]["start_time"]["lte"] = end_date
167 167 if start_date or end_date:
168 168 filter_part.append(date_range)
169 169
170 170 priorities = filter_settings.get("priority")
171 171
172 172 for tag in filter_settings.get("tags", []):
173 173 tag_values = [v.lower() for v in tag["value"]]
174 174 key = "tags.%s.values" % tag["name"].replace(".", "_")
175 175 filter_part.append({"terms": {key: tag_values}})
176 176
177 177 if priorities:
178 178 filter_part.append(
179 179 {
180 180 "has_parent": {
181 181 "parent_type": "report_group",
182 182 "query": {"terms": {"priority": priorities}},
183 183 }
184 184 }
185 185 )
186 186
187 187 min_occurences = filter_settings.get("min_occurences")
188 188 if min_occurences:
189 189 filter_part.append(
190 190 {
191 191 "has_parent": {
192 192 "parent_type": "report_group",
193 193 "query": {"range": {"occurences": {"gte": min_occurences[0]}}},
194 194 }
195 195 }
196 196 )
197 197
198 198 min_duration = filter_settings.get("min_duration")
199 199 max_duration = filter_settings.get("max_duration")
200 200
201 201 request_ids = filter_settings.get("request_id")
202 202 if request_ids:
203 203 filter_part.append({"terms": {"request_id": request_ids}})
204 204
205 205 duration_range = {"range": {"average_duration": {}}}
206 206 if min_duration:
207 207 duration_range["range"]["average_duration"]["gte"] = min_duration[0]
208 208 if max_duration:
209 209 duration_range["range"]["average_duration"]["lte"] = max_duration[0]
210 210 if min_duration or max_duration:
211 211 filter_part.append(
212 212 {"has_parent": {"parent_type": "report_group", "query": duration_range}}
213 213 )
214 214
215 215 http_status = filter_settings.get("http_status")
216 216 report_type = filter_settings.get("report_type", [ReportType.error])
217 217 # set error report type if http status is not found
218 218 # and we are dealing with slow reports
219 219 if not http_status or ReportType.slow in report_type:
220 220 filter_part.append({"terms": {"report_type": report_type}})
221 221 if http_status:
222 222 filter_part.append({"terms": {"http_status": http_status}})
223 223
224 224 messages = filter_settings.get("message")
225 225 if messages:
226 226 condition = {"match": {"message": " ".join(messages)}}
227 227 query["query"]["bool"]["must"].append(condition)
228 228 errors = filter_settings.get("error")
229 229 if errors:
230 230 condition = {"match": {"error": " ".join(errors)}}
231 231 query["query"]["bool"]["must"].append(condition)
232 232 url_domains = filter_settings.get("url_domain")
233 233 if url_domains:
234 234 condition = {"terms": {"url_domain": url_domains}}
235 235 query["query"]["bool"]["must"].append(condition)
236 236 url_paths = filter_settings.get("url_path")
237 237 if url_paths:
238 238 condition = {"terms": {"url_path": url_paths}}
239 239 query["query"]["bool"]["must"].append(condition)
240 240
241 241 if filter_settings.get("report_status"):
242 242 for status in filter_settings.get("report_status"):
243 243 if status == "never_reviewed":
244 244 filter_part.append(
245 245 {
246 246 "has_parent": {
247 247 "parent_type": "report_group",
248 248 "query": {"term": {"read": False}},
249 249 }
250 250 }
251 251 )
252 252 elif status == "reviewed":
253 253 filter_part.append(
254 254 {
255 255 "has_parent": {
256 256 "parent_type": "report_group",
257 257 "query": {"term": {"read": True}},
258 258 }
259 259 }
260 260 )
261 261 elif status == "public":
262 262 filter_part.append(
263 263 {
264 264 "has_parent": {
265 265 "parent_type": "report_group",
266 266 "query": {"term": {"public": True}},
267 267 }
268 268 }
269 269 )
270 270 elif status == "fixed":
271 271 filter_part.append(
272 272 {
273 273 "has_parent": {
274 274 "parent_type": "report_group",
275 275 "query": {"term": {"fixed": True}},
276 276 }
277 277 }
278 278 )
279 279
280 280 # logging.getLogger('pyelasticsearch').setLevel(logging.DEBUG)
281 281 index_names = es_index_name_limiter(
282 282 filter_settings.get("start_date"),
283 283 filter_settings.get("end_date"),
284 284 ixtypes=["reports"],
285 285 )
286 286 if index_names:
287 287 results = Datastores.es.search(
288 288 body=query,
289 289 index=index_names,
290 290 doc_type=["report", "report_group"],
291 291 size=0,
292 292 )
293 293 else:
294 294 return []
295 295 return results["aggregations"]
296 296
297 297 @classmethod
298 298 def get_paginator_by_app_ids(
299 299 cls,
300 300 app_ids=None,
301 301 page=1,
302 302 item_count=None,
303 303 items_per_page=50,
304 304 order_by=None,
305 305 filter_settings=None,
306 306 exclude_columns=None,
307 307 db_session=None,
308 308 ):
309 309 if not filter_settings:
310 310 filter_settings = {}
311 311 results = cls.get_search_iterator(
312 312 app_ids, page, items_per_page, order_by, filter_settings
313 313 )
314 314
315 315 ordered_ids = []
316 316 if results:
317 317 for item in results["top_groups"]["buckets"]:
318 318 pg_id = item["top_reports_hits"]["hits"]["hits"][0]["_source"]["pg_id"]
319 319 ordered_ids.append(pg_id)
320 320 log.info(filter_settings)
321 321 paginator = paginate.Page(
322 322 ordered_ids, items_per_page=items_per_page, **filter_settings
323 323 )
324 324 sa_items = ()
325 325 if paginator.items:
326 326 db_session = get_db_session(db_session)
327 327 # latest report detail
328 328 query = db_session.query(Report)
329 329 query = query.options(sa.orm.joinedload(Report.report_group))
330 330 query = query.filter(Report.id.in_(paginator.items))
331 331 if filter_settings.get("order_col"):
332 332 order_col = filter_settings.get("order_col")
333 333 if filter_settings.get("order_dir") == "dsc":
334 334 sort_on = "desc"
335 335 else:
336 336 sort_on = "asc"
337 337 if order_col == "when":
338 338 order_col = "last_timestamp"
339 339 query = query.order_by(
340 340 getattr(sa, sort_on)(getattr(ReportGroup, order_col))
341 341 )
342 342 sa_items = query.all()
343 343 sorted_instance_list = []
344 344 for i_id in ordered_ids:
345 345 for report in sa_items:
346 346 if str(report.id) == i_id and report not in sorted_instance_list:
347 347 sorted_instance_list.append(report)
348 348 paginator.sa_items = sorted_instance_list
349 349 return paginator
350 350
351 351 @classmethod
352 352 def by_app_ids(cls, app_ids=None, order_by=True, db_session=None):
353 353 db_session = get_db_session(db_session)
354 354 q = db_session.query(ReportGroup)
355 355 if app_ids:
356 356 q = q.filter(ReportGroup.resource_id.in_(app_ids))
357 357 if order_by:
358 358 q = q.order_by(sa.desc(ReportGroup.id))
359 359 return q
360 360
361 361 @classmethod
362 362 def by_id(cls, group_id, app_ids=None, db_session=None):
363 363 db_session = get_db_session(db_session)
364 364 q = db_session.query(ReportGroup).filter(ReportGroup.id == int(group_id))
365 365 if app_ids:
366 366 q = q.filter(ReportGroup.resource_id.in_(app_ids))
367 367 return q.first()
368 368
369 369 @classmethod
370 370 def by_ids(cls, group_ids=None, db_session=None):
371 371 db_session = get_db_session(db_session)
372 372 query = db_session.query(ReportGroup)
373 373 query = query.filter(ReportGroup.id.in_(group_ids))
374 374 return query
375 375
376 376 @classmethod
377 377 def by_hash_and_resource(
378 378 cls, resource_id, grouping_hash, since_when=None, db_session=None
379 379 ):
380 380 db_session = get_db_session(db_session)
381 381 q = db_session.query(ReportGroup)
382 382 q = q.filter(ReportGroup.resource_id == resource_id)
383 383 q = q.filter(ReportGroup.grouping_hash == grouping_hash)
384 384 q = q.filter(ReportGroup.fixed == False)
385 385 if since_when:
386 386 q = q.filter(ReportGroup.first_timestamp >= since_when)
387 387 return q.first()
388 388
389 389 @classmethod
390 390 def users_commenting(cls, report_group, exclude_user_id=None, db_session=None):
391 391 db_session = get_db_session(None, report_group)
392 392 query = db_session.query(User).distinct()
393 393 query = query.filter(User.id == ReportComment.owner_id)
394 394 query = query.filter(ReportComment.group_id == report_group.id)
395 395 if exclude_user_id:
396 396 query = query.filter(ReportComment.owner_id != exclude_user_id)
397 397 return query
398 398
399 399 @classmethod
400 400 def affected_users_count(cls, report_group, db_session=None):
401 401 db_session = get_db_session(db_session)
402 402 query = db_session.query(sa.func.count(Report.username))
403 403 query = query.filter(Report.group_id == report_group.id)
404 404 query = query.filter(Report.username != "")
405 405 query = query.filter(Report.username != None)
406 406 query = query.group_by(Report.username)
407 407 return query.count()
408 408
409 409 @classmethod
410 410 def top_affected_users(cls, report_group, db_session=None):
411 411 db_session = get_db_session(db_session)
412 412 count_label = sa.func.count(Report.username).label("count")
413 413 query = db_session.query(Report.username, count_label)
414 414 query = query.filter(Report.group_id == report_group.id)
415 415 query = query.filter(Report.username != None)
416 416 query = query.filter(Report.username != "")
417 417 query = query.group_by(Report.username)
418 418 query = query.order_by(sa.desc(count_label))
419 419 query = query.limit(50)
420 420 return query
421 421
422 422 @classmethod
423 423 def get_report_stats(cls, request, filter_settings):
424 424 """
425 425 Gets report dashboard graphs
426 426 Returns information for BAR charts with occurences/interval information
427 427 detailed means version that returns time intervals - non detailed
428 428 returns total sum
429 429 """
430 430 delta = filter_settings["end_date"] - filter_settings["start_date"]
431 431 if delta < h.time_deltas.get("12h")["delta"]:
432 432 interval = "1m"
433 433 elif delta <= h.time_deltas.get("3d")["delta"]:
434 434 interval = "5m"
435 435 elif delta >= h.time_deltas.get("2w")["delta"]:
436 436 interval = "24h"
437 437 else:
438 438 interval = "1h"
439 439
440 440 group_id = filter_settings.get("group_id")
441 441
442 442 es_query = {
443 443 "aggs": {
444 444 "parent_agg": {
445 445 "aggs": {
446 446 "types": {
447 447 "aggs": {
448 "sub_agg": {"terms": {"field": "tags.type.values"}}
448 "sub_agg": {"terms": {"field": "tags.type.values.keyword"}}
449 449 },
450 450 "filter": {
451 "and": [{"exists": {"field": "tags.type.values"}}]
451 "bool": {
452 "filter": [{"exists": {"field": "tags.type.values"}}]
453 }
452 454 },
453 455 }
454 456 },
455 457 "date_histogram": {
456 458 "extended_bounds": {
457 459 "max": filter_settings["end_date"],
458 460 "min": filter_settings["start_date"],
459 461 },
460 462 "field": "timestamp",
461 463 "interval": interval,
462 464 "min_doc_count": 0,
463 465 },
464 466 }
465 467 },
466 468 "query": {
467 469 "bool": {
468 470 "filter": [
469 471 {
470 472 "terms": {
471 473 "resource_id": [filter_settings["resource"][0]]
472 474 }
473 475 },
474 476 {
475 477 "range": {
476 478 "timestamp": {
477 479 "gte": filter_settings["start_date"],
478 480 "lte": filter_settings["end_date"],
479 481 }
480 482 }
481 483 },
482 484 ]
483 485 }
484 486 },
485 487 }
486 488 if group_id:
487 489 parent_agg = es_query["aggs"]["parent_agg"]
488 filters = parent_agg["aggs"]["types"]["filter"]["and"]
490 filters = parent_agg["aggs"]["types"]["filter"]["bool"]["filter"]
489 491 filters.append({"terms": {"tags.group_id.values": [group_id]}})
490 492
491 493 index_names = es_index_name_limiter(
492 494 start_date=filter_settings["start_date"],
493 495 end_date=filter_settings["end_date"],
494 496 ixtypes=["reports"],
495 497 )
496 498
497 499 if not index_names:
498 500 return []
499 501
500 502 result = Datastores.es.search(
501 503 body=es_query, index=index_names, doc_type="log", size=0
502 504 )
503 505 series = []
504 506 for bucket in result["aggregations"]["parent_agg"]["buckets"]:
505 507 point = {
506 508 "x": datetime.utcfromtimestamp(int(bucket["key"]) / 1000),
507 509 "report": 0,
508 510 "not_found": 0,
509 511 "slow_report": 0,
510 512 }
511 513 for subbucket in bucket["types"]["sub_agg"]["buckets"]:
512 514 if subbucket["key"] == "slow":
513 515 point["slow_report"] = subbucket["doc_count"]
514 516 elif subbucket["key"] == "error":
515 517 point["report"] = subbucket["doc_count"]
516 518 elif subbucket["key"] == "not_found":
517 519 point["not_found"] = subbucket["doc_count"]
518 520 series.append(point)
519 521 return series
@@ -1,61 +1,63 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 from appenlight.models import Datastores
18 18 from appenlight.models.services.base import BaseService
19 19 from appenlight.lib.enums import ReportType
20 20 from appenlight.lib.utils import es_index_name_limiter
21 21
22 22
23 23 class ReportStatService(BaseService):
24 24 @classmethod
25 25 def count_by_type(cls, report_type, resource_id, since_when):
26 26 report_type = ReportType.key_from_value(report_type)
27 27
28 28 index_names = es_index_name_limiter(start_date=since_when, ixtypes=["reports"])
29 29
30 30 es_query = {
31 31 "aggs": {
32 32 "reports": {
33 33 "aggs": {
34 34 "sub_agg": {"value_count": {"field": "tags.group_id.values"}}
35 35 },
36 36 "filter": {
37 "and": [
37 "bool": {
38 "filter": [
38 39 {"terms": {"resource_id": [resource_id]}},
39 40 {"exists": {"field": "tags.group_id.values"}},
40 41 ]
42 }
41 43 },
42 44 }
43 45 },
44 46 "query": {
45 47 "bool": {
46 48 "filter": [
47 49 {"terms": {"resource_id": [resource_id]}},
48 50 {"terms": {"tags.type.values": [report_type]}},
49 51 {"range": {"timestamp": {"gte": since_when}}},
50 52 ]
51 53 }
52 54 },
53 55 }
54 56
55 57 if index_names:
56 58 result = Datastores.es.search(
57 59 body=es_query, index=index_names, doc_type="log", size=0
58 60 )
59 61 return result["aggregations"]["reports"]["sub_agg"]["value"]
60 62 else:
61 63 return 0
@@ -1,607 +1,612 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 from datetime import datetime
18 18
19 19 import appenlight.lib.helpers as h
20 20 from appenlight.models import get_db_session, Datastores
21 21 from appenlight.models.services.base import BaseService
22 22 from appenlight.lib.enums import ReportType
23 23 from appenlight.lib.utils import es_index_name_limiter
24 24
25 25 try:
26 26 from ae_uptime_ce.models.services.uptime_metric import UptimeMetricService
27 27 except ImportError:
28 28 UptimeMetricService = None
29 29
30 30
31 31 def check_key(key, stats, uptime, total_seconds):
32 32 if key not in stats:
33 33 stats[key] = {
34 34 "name": key,
35 35 "requests": 0,
36 36 "errors": 0,
37 37 "tolerated_requests": 0,
38 38 "frustrating_requests": 0,
39 39 "satisfying_requests": 0,
40 40 "total_minutes": total_seconds / 60.0,
41 41 "uptime": uptime,
42 42 "apdex": 0,
43 43 "rpm": 0,
44 44 "response_time": 0,
45 45 "avg_response_time": 0,
46 46 }
47 47
48 48
49 49 class RequestMetricService(BaseService):
50 50 @classmethod
51 51 def get_metrics_stats(cls, request, filter_settings, db_session=None):
52 52 delta = filter_settings["end_date"] - filter_settings["start_date"]
53 53 if delta < h.time_deltas.get("12h")["delta"]:
54 54 interval = "1m"
55 55 elif delta <= h.time_deltas.get("3d")["delta"]:
56 56 interval = "5m"
57 57 elif delta >= h.time_deltas.get("2w")["delta"]:
58 58 interval = "24h"
59 59 else:
60 60 interval = "1h"
61 61
62 62 filter_settings["namespace"] = ["appenlight.request_metric"]
63 63
64 64 es_query = {
65 65 "aggs": {
66 66 "parent_agg": {
67 67 "aggs": {
68 68 "custom": {
69 69 "aggs": {
70 70 "sub_agg": {
71 71 "sum": {"field": "tags.custom.numeric_values"}
72 72 }
73 73 },
74 74 "filter": {
75 75 "exists": {"field": "tags.custom.numeric_values"}
76 76 },
77 77 },
78 78 "main": {
79 79 "aggs": {
80 80 "sub_agg": {
81 81 "sum": {"field": "tags.main.numeric_values"}
82 82 }
83 83 },
84 84 "filter": {"exists": {"field": "tags.main.numeric_values"}},
85 85 },
86 86 "nosql": {
87 87 "aggs": {
88 88 "sub_agg": {
89 89 "sum": {"field": "tags.nosql.numeric_values"}
90 90 }
91 91 },
92 92 "filter": {
93 93 "exists": {"field": "tags.nosql.numeric_values"}
94 94 },
95 95 },
96 96 "remote": {
97 97 "aggs": {
98 98 "sub_agg": {
99 99 "sum": {"field": "tags.remote.numeric_values"}
100 100 }
101 101 },
102 102 "filter": {
103 103 "exists": {"field": "tags.remote.numeric_values"}
104 104 },
105 105 },
106 106 "requests": {
107 107 "aggs": {
108 108 "sub_agg": {
109 109 "sum": {"field": "tags.requests.numeric_values"}
110 110 }
111 111 },
112 112 "filter": {
113 113 "exists": {"field": "tags.requests.numeric_values"}
114 114 },
115 115 },
116 116 "sql": {
117 117 "aggs": {
118 118 "sub_agg": {"sum": {"field": "tags.sql.numeric_values"}}
119 119 },
120 120 "filter": {"exists": {"field": "tags.sql.numeric_values"}},
121 121 },
122 122 "tmpl": {
123 123 "aggs": {
124 124 "sub_agg": {
125 125 "sum": {"field": "tags.tmpl.numeric_values"}
126 126 }
127 127 },
128 128 "filter": {"exists": {"field": "tags.tmpl.numeric_values"}},
129 129 },
130 130 },
131 131 "date_histogram": {
132 132 "extended_bounds": {
133 133 "max": filter_settings["end_date"],
134 134 "min": filter_settings["start_date"],
135 135 },
136 136 "field": "timestamp",
137 137 "interval": interval,
138 138 "min_doc_count": 0,
139 139 },
140 140 }
141 141 },
142 142 "query": {
143 143 "bool": {
144 144 "filter": [
145 145 {
146 146 "terms": {
147 147 "resource_id": [filter_settings["resource"][0]]
148 148 }
149 149 },
150 150 {
151 151 "range": {
152 152 "timestamp": {
153 153 "gte": filter_settings["start_date"],
154 154 "lte": filter_settings["end_date"],
155 155 }
156 156 }
157 157 },
158 158 {"terms": {"namespace": ["appenlight.request_metric"]}},
159 159 ]
160 160 }
161 161 },
162 162 }
163 163
164 164 index_names = es_index_name_limiter(
165 165 start_date=filter_settings["start_date"],
166 166 end_date=filter_settings["end_date"],
167 167 ixtypes=["metrics"],
168 168 )
169 169 if not index_names:
170 170 return []
171 171
172 172 result = Datastores.es.search(
173 173 body=es_query, index=index_names, doc_type="log", size=0
174 174 )
175 175
176 176 plot_data = []
177 177 for item in result["aggregations"]["parent_agg"]["buckets"]:
178 178 x_time = datetime.utcfromtimestamp(int(item["key"]) / 1000)
179 179 point = {"x": x_time}
180 180 for key in ["custom", "main", "nosql", "remote", "requests", "sql", "tmpl"]:
181 181 value = item[key]["sub_agg"]["value"]
182 182 point[key] = round(value, 3) if value else 0
183 183 plot_data.append(point)
184 184
185 185 return plot_data
186 186
187 187 @classmethod
188 188 def get_requests_breakdown(cls, request, filter_settings, db_session=None):
189 189 db_session = get_db_session(db_session)
190 190
191 191 # fetch total time of all requests in this time range
192 192 index_names = es_index_name_limiter(
193 193 start_date=filter_settings["start_date"],
194 194 end_date=filter_settings["end_date"],
195 195 ixtypes=["metrics"],
196 196 )
197 197
198 198 if index_names and filter_settings["resource"]:
199 199 es_query = {
200 200 "aggs": {
201 201 "main": {
202 202 "aggs": {
203 203 "sub_agg": {"sum": {"field": "tags.main.numeric_values"}}
204 204 },
205 205 "filter": {"exists": {"field": "tags.main.numeric_values"}},
206 206 }
207 207 },
208 208 "query": {
209 209 "bool": {
210 210 "filter": [
211 211 {
212 212 "terms": {
213 213 "resource_id": [filter_settings["resource"][0]]
214 214 }
215 215 },
216 216 {
217 217 "range": {
218 218 "timestamp": {
219 219 "gte": filter_settings["start_date"],
220 220 "lte": filter_settings["end_date"],
221 221 }
222 222 }
223 223 },
224 224 {"terms": {"namespace": ["appenlight.request_metric"]}},
225 225 ]
226 226 }
227 227 },
228 228 }
229 229 result = Datastores.es.search(
230 230 body=es_query, index=index_names, doc_type="log", size=0
231 231 )
232 232 total_time_spent = result["aggregations"]["main"]["sub_agg"]["value"]
233 233 else:
234 234 total_time_spent = 0
235 235 script_text = "doc['tags.main.numeric_values'].value / {}".format(
236 236 total_time_spent
237 237 )
238 if total_time_spent == 0:
239 script_text = '0'
238 240
239 241 if index_names and filter_settings["resource"]:
240 242 es_query = {
241 243 "aggs": {
242 244 "parent_agg": {
243 245 "aggs": {
244 246 "main": {
245 247 "aggs": {
246 248 "sub_agg": {
247 249 "sum": {"field": "tags.main.numeric_values"}
248 250 }
249 251 },
250 252 "filter": {
251 253 "exists": {"field": "tags.main.numeric_values"}
252 254 },
253 255 },
254 256 "percentage": {
255 257 "aggs": {
256 258 "sub_agg": {
257 259 "sum": {
258 "lang": "expression",
259 260 "script": script_text,
260 261 }
261 262 }
262 263 },
263 264 "filter": {
264 265 "exists": {"field": "tags.main.numeric_values"}
265 266 },
266 267 },
267 268 "requests": {
268 269 "aggs": {
269 270 "sub_agg": {
270 271 "sum": {"field": "tags.requests.numeric_values"}
271 272 }
272 273 },
273 274 "filter": {
274 275 "exists": {"field": "tags.requests.numeric_values"}
275 276 },
276 277 },
277 278 },
278 279 "terms": {
279 "field": "tags.view_name.values",
280 "field": "tags.view_name.values.keyword",
280 281 "order": {"percentage>sub_agg": "desc"},
281 282 "size": 15,
282 283 },
283 284 }
284 285 },
285 286 "query": {
286 287 "bool": {
287 288 "filter": [
288 289 {
289 290 "terms": {
290 291 "resource_id": [filter_settings["resource"][0]]
291 292 }
292 293 },
293 294 {
294 295 "range": {
295 296 "timestamp": {
296 297 "gte": filter_settings["start_date"],
297 298 "lte": filter_settings["end_date"],
298 299 }
299 300 }
300 301 },
301 302 ]
302 303 }
303 304 },
304 305 }
305 306 result = Datastores.es.search(
306 307 body=es_query, index=index_names, doc_type="log", size=0
307 308 )
308 309 series = result["aggregations"]["parent_agg"]["buckets"]
309 310 else:
310 311 series = []
311 312
312 313 and_part = [
313 314 {"term": {"resource_id": filter_settings["resource"][0]}},
314 315 {"terms": {"tags.view_name.values": [row["key"] for row in series]}},
315 316 {"term": {"report_type": str(ReportType.slow)}},
316 317 ]
317 318 query = {
318 319 "aggs": {
319 320 "top_reports": {
320 "terms": {"field": "tags.view_name.values", "size": len(series)},
321 "terms": {"field": "tags.view_name.values.keyword", "size": len(series)},
321 322 "aggs": {
322 323 "top_calls_hits": {
323 324 "top_hits": {"sort": {"start_time": "desc"}, "size": 5}
324 325 }
325 326 },
326 327 }
327 328 },
328 329 "query": {"bool": {"filter": and_part}},
329 330 }
330 331 details = {}
331 332 index_names = es_index_name_limiter(ixtypes=["reports"])
332 333 if index_names and series:
333 334 result = Datastores.es.search(
334 335 body=query, doc_type="report", size=0, index=index_names
335 336 )
336 337 for bucket in result["aggregations"]["top_reports"]["buckets"]:
337 338 details[bucket["key"]] = []
338 339
339 340 for hit in bucket["top_calls_hits"]["hits"]["hits"]:
340 341 details[bucket["key"]].append(
341 342 {
342 343 "report_id": hit["_source"]["pg_id"],
343 344 "group_id": hit["_source"]["group_id"],
344 345 }
345 346 )
346 347
347 348 results = []
348 349 for row in series:
349 350 result = {
350 351 "key": row["key"],
351 352 "main": row["main"]["sub_agg"]["value"],
352 353 "requests": row["requests"]["sub_agg"]["value"],
353 354 }
354 355 # es can return 'infinity'
355 356 try:
356 357 result["percentage"] = float(row["percentage"]["sub_agg"]["value"])
357 358 except ValueError:
358 359 result["percentage"] = 0
359 360
360 361 result["latest_details"] = details.get(row["key"]) or []
361 362 results.append(result)
362 363
363 364 return results
364 365
365 366 @classmethod
366 367 def get_apdex_stats(cls, request, filter_settings, threshold=1, db_session=None):
367 368 """
368 369 Returns information and calculates APDEX score per server for dashboard
369 370 server information (upper right stats boxes)
370 371 """
371 372 # Apdex t = (Satisfied Count + Tolerated Count / 2) / Total Samples
372 373 db_session = get_db_session(db_session)
373 374 index_names = es_index_name_limiter(
374 375 start_date=filter_settings["start_date"],
375 376 end_date=filter_settings["end_date"],
376 377 ixtypes=["metrics"],
377 378 )
378 379
379 380 requests_series = []
380 381
381 382 if index_names and filter_settings["resource"]:
382 383 es_query = {
383 384 "aggs": {
384 385 "parent_agg": {
385 386 "aggs": {
386 387 "frustrating": {
387 388 "aggs": {
388 389 "sub_agg": {
389 390 "sum": {"field": "tags.requests.numeric_values"}
390 391 }
391 392 },
392 393 "filter": {
393 "and": [
394 "bool": {
395 "filter": [
394 396 {
395 397 "range": {
396 398 "tags.main.numeric_values": {"gte": "4"}
397 399 }
398 400 },
399 401 {
400 402 "exists": {
401 403 "field": "tags.requests.numeric_values"
402 404 }
403 405 },
404 406 ]
407 }
405 408 },
406 409 },
407 410 "main": {
408 411 "aggs": {
409 412 "sub_agg": {
410 413 "sum": {"field": "tags.main.numeric_values"}
411 414 }
412 415 },
413 416 "filter": {
414 417 "exists": {"field": "tags.main.numeric_values"}
415 418 },
416 419 },
417 420 "requests": {
418 421 "aggs": {
419 422 "sub_agg": {
420 423 "sum": {"field": "tags.requests.numeric_values"}
421 424 }
422 425 },
423 426 "filter": {
424 427 "exists": {"field": "tags.requests.numeric_values"}
425 428 },
426 429 },
427 430 "tolerated": {
428 431 "aggs": {
429 432 "sub_agg": {
430 433 "sum": {"field": "tags.requests.numeric_values"}
431 434 }
432 435 },
433 436 "filter": {
434 "and": [
437 "bool": {"filter": [
435 438 {
436 439 "range": {
437 440 "tags.main.numeric_values": {"gte": "1"}
438 441 }
439 442 },
440 443 {
441 444 "range": {
442 445 "tags.main.numeric_values": {"lt": "4"}
443 446 }
444 447 },
445 448 {
446 449 "exists": {
447 450 "field": "tags.requests.numeric_values"
448 451 }
449 452 },
450 ]
453 ]}
451 454 },
452 455 },
453 456 },
454 "terms": {"field": "tags.server_name.values", "size": 999999},
457 "terms": {"field": "tags.server_name.values.keyword", "size": 999999},
455 458 }
456 459 },
457 460 "query": {
458 461 "bool": {
459 462 "filter": [
460 463 {
461 464 "terms": {
462 465 "resource_id": [filter_settings["resource"][0]]
463 466 }
464 467 },
465 468 {
466 469 "range": {
467 470 "timestamp": {
468 471 "gte": filter_settings["start_date"],
469 472 "lte": filter_settings["end_date"],
470 473 }
471 474 }
472 475 },
473 476 {"terms": {"namespace": ["appenlight.request_metric"]}},
474 477 ]
475 478 }
476 479 },
477 480 }
478 481
479 482 result = Datastores.es.search(
480 483 body=es_query, index=index_names, doc_type="log", size=0
481 484 )
482 485 for bucket in result["aggregations"]["parent_agg"]["buckets"]:
483 486 requests_series.append(
484 487 {
485 488 "frustrating": bucket["frustrating"]["sub_agg"]["value"],
486 489 "main": bucket["main"]["sub_agg"]["value"],
487 490 "requests": bucket["requests"]["sub_agg"]["value"],
488 491 "tolerated": bucket["tolerated"]["sub_agg"]["value"],
489 492 "key": bucket["key"],
490 493 }
491 494 )
492 495
493 496 since_when = filter_settings["start_date"]
494 497 until = filter_settings["end_date"]
495 498
496 499 # total errors
497 500
498 501 index_names = es_index_name_limiter(
499 502 start_date=filter_settings["start_date"],
500 503 end_date=filter_settings["end_date"],
501 504 ixtypes=["reports"],
502 505 )
503 506
504 507 report_series = []
505 508 if index_names and filter_settings["resource"]:
506 509 report_type = ReportType.key_from_value(ReportType.error)
507 510 es_query = {
508 511 "aggs": {
509 512 "parent_agg": {
510 513 "aggs": {
511 514 "errors": {
512 515 "aggs": {
513 516 "sub_agg": {
514 517 "sum": {
515 518 "field": "tags.occurences.numeric_values"
516 519 }
517 520 }
518 521 },
519 522 "filter": {
520 "and": [
523 "bool": {
524 "filter": [
521 525 {"terms": {"tags.type.values": [report_type]}},
522 526 {
523 527 "exists": {
524 528 "field": "tags.occurences.numeric_values"
525 529 }
526 530 },
527 531 ]
532 }
528 533 },
529 534 }
530 535 },
531 "terms": {"field": "tags.server_name.values", "size": 999999},
536 "terms": {"field": "tags.server_name.values.keyword", "size": 999999},
532 537 }
533 538 },
534 539 "query": {
535 540 "bool": {
536 541 "filter": [
537 542 {
538 543 "terms": {
539 544 "resource_id": [filter_settings["resource"][0]]
540 545 }
541 546 },
542 547 {
543 548 "range": {
544 549 "timestamp": {
545 550 "gte": filter_settings["start_date"],
546 551 "lte": filter_settings["end_date"],
547 552 }
548 553 }
549 554 },
550 555 {"terms": {"namespace": ["appenlight.error"]}},
551 556 ]
552 557 }
553 558 },
554 559 }
555 560 result = Datastores.es.search(
556 561 body=es_query, index=index_names, doc_type="log", size=0
557 562 )
558 563 for bucket in result["aggregations"]["parent_agg"]["buckets"]:
559 564 report_series.append(
560 565 {
561 566 "key": bucket["key"],
562 567 "errors": bucket["errors"]["sub_agg"]["value"],
563 568 }
564 569 )
565 570
566 571 stats = {}
567 572 if UptimeMetricService is not None:
568 573 uptime = UptimeMetricService.get_uptime_by_app(
569 574 filter_settings["resource"][0], since_when=since_when, until=until
570 575 )
571 576 else:
572 577 uptime = 0
573 578
574 579 total_seconds = (until - since_when).total_seconds()
575 580
576 581 for stat in requests_series:
577 582 check_key(stat["key"], stats, uptime, total_seconds)
578 583 stats[stat["key"]]["requests"] = int(stat["requests"])
579 584 stats[stat["key"]]["response_time"] = stat["main"]
580 585 stats[stat["key"]]["tolerated_requests"] = stat["tolerated"]
581 586 stats[stat["key"]]["frustrating_requests"] = stat["frustrating"]
582 587 for server in report_series:
583 588 check_key(server["key"], stats, uptime, total_seconds)
584 589 stats[server["key"]]["errors"] = server["errors"]
585 590
586 591 server_stats = list(stats.values())
587 592 for stat in server_stats:
588 593 stat["satisfying_requests"] = (
589 594 stat["requests"]
590 595 - stat["errors"]
591 596 - stat["frustrating_requests"]
592 597 - stat["tolerated_requests"]
593 598 )
594 599 if stat["satisfying_requests"] < 0:
595 600 stat["satisfying_requests"] = 0
596 601
597 602 if stat["requests"]:
598 603 stat["avg_response_time"] = round(
599 604 stat["response_time"] / stat["requests"], 3
600 605 )
601 606 qual_requests = (
602 607 stat["satisfying_requests"] + stat["tolerated_requests"] / 2.0
603 608 )
604 609 stat["apdex"] = round((qual_requests / stat["requests"]) * 100, 2)
605 610 stat["rpm"] = round(stat["requests"] / stat["total_minutes"], 2)
606 611
607 612 return sorted(server_stats, key=lambda x: x["name"])
@@ -1,182 +1,182 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 from appenlight.models import get_db_session, Datastores
18 18 from appenlight.models.report import Report
19 19 from appenlight.models.services.base import BaseService
20 20 from appenlight.lib.utils import es_index_name_limiter
21 21
22 22
23 23 class SlowCallService(BaseService):
24 24 @classmethod
25 25 def get_time_consuming_calls(cls, request, filter_settings, db_session=None):
26 26 db_session = get_db_session(db_session)
27 27 # get slow calls from older partitions too
28 28 index_names = es_index_name_limiter(
29 29 start_date=filter_settings["start_date"],
30 30 end_date=filter_settings["end_date"],
31 31 ixtypes=["slow_calls"],
32 32 )
33 33 if index_names and filter_settings["resource"]:
34 34 # get longest time taking hashes
35 35 es_query = {
36 36 "aggs": {
37 37 "parent_agg": {
38 38 "aggs": {
39 39 "duration": {
40 40 "aggs": {
41 41 "sub_agg": {
42 42 "sum": {"field": "tags.duration.numeric_values"}
43 43 }
44 44 },
45 45 "filter": {
46 46 "exists": {"field": "tags.duration.numeric_values"}
47 47 },
48 48 },
49 49 "total": {
50 50 "aggs": {
51 51 "sub_agg": {
52 52 "value_count": {
53 "field": "tags.statement_hash.values"
53 "field": "tags.statement_hash.values.keyword"
54 54 }
55 55 }
56 56 },
57 57 "filter": {
58 58 "exists": {"field": "tags.statement_hash.values"}
59 59 },
60 60 },
61 61 },
62 62 "terms": {
63 "field": "tags.statement_hash.values",
63 "field": "tags.statement_hash.values.keyword",
64 64 "order": {"duration>sub_agg": "desc"},
65 65 "size": 15,
66 66 },
67 67 }
68 68 },
69 69 "query": {
70 70 "bool": {
71 71 "filter": [
72 72 {
73 73 "terms": {
74 74 "resource_id": [filter_settings["resource"][0]]
75 75 }
76 76 },
77 77 {
78 78 "range": {
79 79 "timestamp": {
80 80 "gte": filter_settings["start_date"],
81 81 "lte": filter_settings["end_date"],
82 82 }
83 83 }
84 84 },
85 85 ]
86 86 }
87 87 },
88 88 }
89 89 result = Datastores.es.search(
90 90 body=es_query, index=index_names, doc_type="log", size=0
91 91 )
92 92 results = result["aggregations"]["parent_agg"]["buckets"]
93 93 else:
94 94 return []
95 95 hashes = [i["key"] for i in results]
96 96
97 97 # get queries associated with hashes
98 98 calls_query = {
99 99 "aggs": {
100 100 "top_calls": {
101 "terms": {"field": "tags.statement_hash.values", "size": 15},
101 "terms": {"field": "tags.statement_hash.values.keyword", "size": 15},
102 102 "aggs": {
103 103 "top_calls_hits": {
104 104 "top_hits": {"sort": {"timestamp": "desc"}, "size": 5}
105 105 }
106 106 },
107 107 }
108 108 },
109 109 "query": {
110 110 "bool": {
111 111 "filter": [
112 112 {
113 113 "terms": {
114 114 "resource_id": [filter_settings["resource"][0]]
115 115 }
116 116 },
117 117 {"terms": {"tags.statement_hash.values": hashes}},
118 118 {
119 119 "range": {
120 120 "timestamp": {
121 121 "gte": filter_settings["start_date"],
122 122 "lte": filter_settings["end_date"],
123 123 }
124 124 }
125 125 },
126 126 ]
127 127 }
128 128 },
129 129 }
130 130 calls = Datastores.es.search(
131 131 body=calls_query, index=index_names, doc_type="log", size=0
132 132 )
133 133 call_results = {}
134 134 report_ids = []
135 135 for call in calls["aggregations"]["top_calls"]["buckets"]:
136 136 hits = call["top_calls_hits"]["hits"]["hits"]
137 137 call_results[call["key"]] = [i["_source"] for i in hits]
138 138 report_ids.extend(
139 139 [i["_source"]["tags"]["report_id"]["values"] for i in hits]
140 140 )
141 141 if report_ids:
142 142 r_query = db_session.query(Report.group_id, Report.id)
143 143 r_query = r_query.filter(Report.id.in_(report_ids))
144 144 r_query = r_query.filter(Report.start_time >= filter_settings["start_date"])
145 145 else:
146 146 r_query = []
147 147 reports_reversed = {}
148 148 for report in r_query:
149 149 reports_reversed[report.id] = report.group_id
150 150
151 151 final_results = []
152 152 for item in results:
153 153 if item["key"] not in call_results:
154 154 continue
155 155 call = call_results[item["key"]][0]
156 156 row = {
157 157 "occurences": item["total"]["sub_agg"]["value"],
158 158 "total_duration": round(item["duration"]["sub_agg"]["value"]),
159 159 "statement": call["message"],
160 160 "statement_type": call["tags"]["type"]["values"],
161 161 "statement_subtype": call["tags"]["subtype"]["values"],
162 162 "statement_hash": item["key"],
163 163 "latest_details": [],
164 164 }
165 165 if row["statement_type"] in ["tmpl", " remote"]:
166 166 params = (
167 167 call["tags"]["parameters"]["values"]
168 168 if "parameters" in call["tags"]
169 169 else ""
170 170 )
171 171 row["statement"] = "{} ({})".format(call["message"], params)
172 172 for call in call_results[item["key"]]:
173 173 report_id = call["tags"]["report_id"]["values"]
174 174 group_id = reports_reversed.get(report_id)
175 175 if group_id:
176 176 row["latest_details"].append(
177 177 {"group_id": group_id, "report_id": report_id}
178 178 )
179 179
180 180 final_results.append(row)
181 181
182 182 return final_results
@@ -1,437 +1,458 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 import argparse
18 18 import datetime
19 19 import logging
20 20
21 21 import sqlalchemy as sa
22 22 import elasticsearch.exceptions
23 23 import elasticsearch.helpers
24 24
25 25 from collections import defaultdict
26 26 from pyramid.paster import setup_logging
27 27 from pyramid.paster import bootstrap
28 28 from appenlight.models import DBSession, Datastores, metadata
29 29 from appenlight.lib import get_callable
30 30 from appenlight.models.report_group import ReportGroup
31 31 from appenlight.models.report import Report
32 32 from appenlight.models.report_stat import ReportStat
33 33 from appenlight.models.log import Log
34 34 from appenlight.models.slow_call import SlowCall
35 35 from appenlight.models.metric import Metric
36 36
37 37
38 38 log = logging.getLogger(__name__)
39 39
40 40 tables = {
41 41 "slow_calls_p_": [],
42 42 "reports_stats_p_": [],
43 43 "reports_p_": [],
44 44 "reports_groups_p_": [],
45 45 "logs_p_": [],
46 46 "metrics_p_": [],
47 47 }
48 48
49 49
50 50 def detect_tables(table_prefix):
51 51 found_tables = []
52 52 db_tables_query = """
53 53 SELECT tablename FROM pg_tables WHERE tablename NOT LIKE 'pg_%' AND
54 54 tablename NOT LIKE 'sql_%' ORDER BY tablename ASC;"""
55 55
56 56 for table in DBSession.execute(db_tables_query).fetchall():
57 57 tablename = table.tablename
58 58 if tablename.startswith(table_prefix):
59 59 t = sa.Table(
60 60 tablename, metadata, autoload=True, autoload_with=DBSession.bind.engine
61 61 )
62 62 found_tables.append(t)
63 63 return found_tables
64 64
65 65
66 66 def main():
67 67 """
68 68 Recreates Elasticsearch indexes
69 69 Performs reindex of whole db to Elasticsearch
70 70
71 71 """
72 72
73 73 # need parser twice because we first need to load ini file
74 74 # bootstrap pyramid and then load plugins
75 75 pre_parser = argparse.ArgumentParser(
76 76 description="Reindex AppEnlight data", add_help=False
77 77 )
78 78 pre_parser.add_argument(
79 79 "-c", "--config", required=True, help="Configuration ini file of application"
80 80 )
81 81 pre_parser.add_argument("-h", "--help", help="Show help", nargs="?")
82 82 pre_parser.add_argument(
83 83 "-t", "--types", nargs="+", help="Which parts of database should get reindexed"
84 84 )
85 85 args = pre_parser.parse_args()
86 86
87 87 config_uri = args.config
88 88 setup_logging(config_uri)
89 89 log.setLevel(logging.INFO)
90 90 env = bootstrap(config_uri)
91 91 parser = argparse.ArgumentParser(description="Reindex AppEnlight data")
92 92 choices = {
93 93 "reports": "appenlight.scripts.reindex_elasticsearch:reindex_reports",
94 94 "logs": "appenlight.scripts.reindex_elasticsearch:reindex_logs",
95 95 "metrics": "appenlight.scripts.reindex_elasticsearch:reindex_metrics",
96 96 "slow_calls": "appenlight.scripts.reindex_elasticsearch:reindex_slow_calls",
97 97 "template": "appenlight.scripts.reindex_elasticsearch:update_template",
98 98 }
99 99 for k, v in env["registry"].appenlight_plugins.items():
100 100 if v.get("fulltext_indexer"):
101 101 choices[k] = v["fulltext_indexer"]
102 102 parser.add_argument(
103 103 "-t",
104 104 "--types",
105 105 nargs="*",
106 106 choices=["all"] + list(choices.keys()),
107 107 default=[],
108 108 help="Which parts of database should get reindexed",
109 109 )
110 110 parser.add_argument(
111 111 "-c", "--config", required=True, help="Configuration ini file of application"
112 112 )
113 113 args = parser.parse_args()
114 114
115 115 if "all" in args.types:
116 116 args.types = list(choices.keys())
117 117
118 118 print("Selected types to reindex: {}".format(args.types))
119 119
120 120 log.info("settings {}".format(args.types))
121 121
122 122 if "template" in args.types:
123 123 get_callable(choices["template"])()
124 124 args.types.remove("template")
125 125 for selected in args.types:
126 126 get_callable(choices[selected])()
127 127
128 128
129 129 def update_template():
130 130 try:
131 131 Datastores.es.indices.delete_template("rcae")
132 132 except elasticsearch.exceptions.NotFoundError as e:
133 133 log.error(e)
134 134 log.info("updating elasticsearch template")
135 135 tag_templates = [
136 136 {
137 137 "values": {
138 138 "path_match": "tags.*",
139 139 "mapping": {
140 140 "type": "object",
141 141 "properties": {
142 "values": {"type": "string", "analyzer": "tag_value"},
142 "values": {"type": "text", "analyzer": "tag_value",
143 "fields": {
144 "keyword": {
145 "type": "keyword",
146 "ignore_above": 256
147 }
148 }},
143 149 "numeric_values": {"type": "float"},
144 150 },
145 151 },
146 152 }
147 153 }
148 154 ]
149 155
150 156 template_schema = {
151 157 "template": "rcae_*",
152 158 "settings": {
153 159 "index": {
154 160 "refresh_interval": "5s",
155 161 "translog": {"sync_interval": "5s", "durability": "async"},
156 162 },
157 163 "number_of_shards": 5,
158 164 "analysis": {
159 165 "analyzer": {
160 166 "url_path": {
161 167 "type": "custom",
162 168 "char_filter": [],
163 169 "tokenizer": "path_hierarchy",
164 170 "filter": [],
165 171 },
166 172 "tag_value": {
167 173 "type": "custom",
168 174 "char_filter": [],
169 175 "tokenizer": "keyword",
170 176 "filter": ["lowercase"],
171 177 },
172 178 }
173 179 },
174 180 },
175 181 "mappings": {
176 182 "report_group": {
177 183 "_all": {"enabled": False},
178 184 "dynamic_templates": tag_templates,
179 185 "properties": {
180 "pg_id": {"type": "string", "index": "not_analyzed"},
186 "pg_id": {"type": "keyword", "index": True},
181 187 "resource_id": {"type": "integer"},
182 188 "priority": {"type": "integer"},
183 "error": {"type": "string", "analyzer": "simple"},
189 "error": {"type": "text", "analyzer": "simple"},
184 190 "read": {"type": "boolean"},
185 191 "occurences": {"type": "integer"},
186 192 "fixed": {"type": "boolean"},
187 193 "first_timestamp": {"type": "date"},
188 194 "last_timestamp": {"type": "date"},
189 195 "average_duration": {"type": "float"},
190 196 "summed_duration": {"type": "float"},
191 197 "public": {"type": "boolean"},
192 198 },
193 199 },
194 200 "report": {
195 201 "_all": {"enabled": False},
196 202 "dynamic_templates": tag_templates,
197 203 "properties": {
198 "pg_id": {"type": "string", "index": "not_analyzed"},
204 "pg_id": {"type": "keyword", "index": True},
199 205 "resource_id": {"type": "integer"},
200 "group_id": {"type": "string"},
206 "group_id": {"type": "keyword"},
201 207 "http_status": {"type": "integer"},
202 "ip": {"type": "string", "index": "not_analyzed"},
203 "url_domain": {"type": "string", "analyzer": "simple"},
204 "url_path": {"type": "string", "analyzer": "url_path"},
205 "error": {"type": "string", "analyzer": "simple"},
208 "ip": {"type": "keyword", "index": True},
209 "url_domain": {"type": "text", "analyzer": "simple"},
210 "url_path": {"type": "text", "analyzer": "url_path"},
211 "error": {"type": "text", "analyzer": "simple"},
206 212 "report_type": {"type": "integer"},
207 213 "start_time": {"type": "date"},
208 "request_id": {"type": "string", "index": "not_analyzed"},
214 "request_id": {"type": "keyword", "index": True},
209 215 "end_time": {"type": "date"},
210 216 "duration": {"type": "float"},
211 217 "tags": {"type": "object"},
212 "tag_list": {"type": "string", "analyzer": "tag_value"},
218 "tag_list": {"type": "text", "analyzer": "tag_value",
219 "fields": {
220 "keyword": {
221 "type": "keyword",
222 "ignore_above": 256
223 }
224 }},
213 225 "extra": {"type": "object"},
214 226 },
215 227 "_parent": {"type": "report_group"},
216 228 },
217 229 "log": {
218 230 "_all": {"enabled": False},
219 231 "dynamic_templates": tag_templates,
220 232 "properties": {
221 "pg_id": {"type": "string", "index": "not_analyzed"},
222 "delete_hash": {"type": "string", "index": "not_analyzed"},
233 "pg_id": {"type": "keyword", "index": True},
234 "delete_hash": {"type": "keyword", "index": True},
223 235 "resource_id": {"type": "integer"},
224 236 "timestamp": {"type": "date"},
225 237 "permanent": {"type": "boolean"},
226 "request_id": {"type": "string", "index": "not_analyzed"},
227 "log_level": {"type": "string", "analyzer": "simple"},
228 "message": {"type": "string", "analyzer": "simple"},
229 "namespace": {"type": "string", "index": "not_analyzed"},
238 "request_id": {"type": "keyword", "index": True},
239 "log_level": {"type": "text", "analyzer": "simple"},
240 "message": {"type": "text", "analyzer": "simple"},
241 "namespace": {
242 "type": "text",
243 "fields": {"keyword": {"type": "keyword", "ignore_above": 256}},
244 },
230 245 "tags": {"type": "object"},
231 "tag_list": {"type": "string", "analyzer": "tag_value"},
246 "tag_list": {"type": "text", "analyzer": "tag_value",
247 "fields": {
248 "keyword": {
249 "type": "keyword",
250 "ignore_above": 256
251 }
252 }},
232 253 },
233 254 },
234 255 },
235 256 }
236 257
237 258 Datastores.es.indices.put_template("rcae", body=template_schema)
238 259
239 260
240 261 def reindex_reports():
241 262 reports_groups_tables = detect_tables("reports_groups_p_")
242 263 try:
243 264 Datastores.es.indices.delete("rcae_r*")
244 265 except elasticsearch.exceptions.NotFoundError as e:
245 266 log.error(e)
246 267
247 268 log.info("reindexing report groups")
248 269 i = 0
249 270 task_start = datetime.datetime.now()
250 271 for partition_table in reports_groups_tables:
251 272 conn = DBSession.connection().execution_options(stream_results=True)
252 273 result = conn.execute(partition_table.select())
253 274 while True:
254 275 chunk = result.fetchmany(2000)
255 276 if not chunk:
256 277 break
257 278 es_docs = defaultdict(list)
258 279 for row in chunk:
259 280 i += 1
260 281 item = ReportGroup(**dict(list(row.items())))
261 282 d_range = item.partition_id
262 283 es_docs[d_range].append(item.es_doc())
263 284 if es_docs:
264 285 name = partition_table.name
265 286 log.info("round {}, {}".format(i, name))
266 287 for k, v in es_docs.items():
267 288 to_update = {"_index": k, "_type": "report_group"}
268 289 [i.update(to_update) for i in v]
269 290 elasticsearch.helpers.bulk(Datastores.es, v)
270 291
271 292 log.info("total docs {} {}".format(i, datetime.datetime.now() - task_start))
272 293
273 294 i = 0
274 295 log.info("reindexing reports")
275 296 task_start = datetime.datetime.now()
276 297 reports_tables = detect_tables("reports_p_")
277 298 for partition_table in reports_tables:
278 299 conn = DBSession.connection().execution_options(stream_results=True)
279 300 result = conn.execute(partition_table.select())
280 301 while True:
281 302 chunk = result.fetchmany(2000)
282 303 if not chunk:
283 304 break
284 305 es_docs = defaultdict(list)
285 306 for row in chunk:
286 307 i += 1
287 308 item = Report(**dict(list(row.items())))
288 309 d_range = item.partition_id
289 310 es_docs[d_range].append(item.es_doc())
290 311 if es_docs:
291 312 name = partition_table.name
292 313 log.info("round {}, {}".format(i, name))
293 314 for k, v in es_docs.items():
294 315 to_update = {"_index": k, "_type": "report"}
295 316 [i.update(to_update) for i in v]
296 317 elasticsearch.helpers.bulk(Datastores.es, v)
297 318
298 319 log.info("total docs {} {}".format(i, datetime.datetime.now() - task_start))
299 320
300 321 log.info("reindexing reports stats")
301 322 i = 0
302 323 task_start = datetime.datetime.now()
303 324 reports_stats_tables = detect_tables("reports_stats_p_")
304 325 for partition_table in reports_stats_tables:
305 326 conn = DBSession.connection().execution_options(stream_results=True)
306 327 result = conn.execute(partition_table.select())
307 328 while True:
308 329 chunk = result.fetchmany(2000)
309 330 if not chunk:
310 331 break
311 332 es_docs = defaultdict(list)
312 333 for row in chunk:
313 334 rd = dict(list(row.items()))
314 335 # remove legacy columns
315 336 # TODO: remove the column later
316 337 rd.pop("size", None)
317 338 item = ReportStat(**rd)
318 339 i += 1
319 340 d_range = item.partition_id
320 341 es_docs[d_range].append(item.es_doc())
321 342 if es_docs:
322 343 name = partition_table.name
323 344 log.info("round {}, {}".format(i, name))
324 345 for k, v in es_docs.items():
325 346 to_update = {"_index": k, "_type": "log"}
326 347 [i.update(to_update) for i in v]
327 348 elasticsearch.helpers.bulk(Datastores.es, v)
328 349
329 350 log.info("total docs {} {}".format(i, datetime.datetime.now() - task_start))
330 351
331 352
332 353 def reindex_logs():
333 354 try:
334 355 Datastores.es.indices.delete("rcae_l*")
335 356 except elasticsearch.exceptions.NotFoundError as e:
336 357 log.error(e)
337 358
338 359 # logs
339 360 log.info("reindexing logs")
340 361 i = 0
341 362 task_start = datetime.datetime.now()
342 363 log_tables = detect_tables("logs_p_")
343 364 for partition_table in log_tables:
344 365 conn = DBSession.connection().execution_options(stream_results=True)
345 366 result = conn.execute(partition_table.select())
346 367 while True:
347 368 chunk = result.fetchmany(2000)
348 369 if not chunk:
349 370 break
350 371 es_docs = defaultdict(list)
351 372
352 373 for row in chunk:
353 374 i += 1
354 375 item = Log(**dict(list(row.items())))
355 376 d_range = item.partition_id
356 377 es_docs[d_range].append(item.es_doc())
357 378 if es_docs:
358 379 name = partition_table.name
359 380 log.info("round {}, {}".format(i, name))
360 381 for k, v in es_docs.items():
361 382 to_update = {"_index": k, "_type": "log"}
362 383 [i.update(to_update) for i in v]
363 384 elasticsearch.helpers.bulk(Datastores.es, v)
364 385
365 386 log.info("total docs {} {}".format(i, datetime.datetime.now() - task_start))
366 387
367 388
368 389 def reindex_metrics():
369 390 try:
370 391 Datastores.es.indices.delete("rcae_m*")
371 392 except elasticsearch.exceptions.NotFoundError as e:
372 393 log.error(e)
373 394
374 395 log.info("reindexing applications metrics")
375 396 i = 0
376 397 task_start = datetime.datetime.now()
377 398 metric_tables = detect_tables("metrics_p_")
378 399 for partition_table in metric_tables:
379 400 conn = DBSession.connection().execution_options(stream_results=True)
380 401 result = conn.execute(partition_table.select())
381 402 while True:
382 403 chunk = result.fetchmany(2000)
383 404 if not chunk:
384 405 break
385 406 es_docs = defaultdict(list)
386 407 for row in chunk:
387 408 i += 1
388 409 item = Metric(**dict(list(row.items())))
389 410 d_range = item.partition_id
390 411 es_docs[d_range].append(item.es_doc())
391 412 if es_docs:
392 413 name = partition_table.name
393 414 log.info("round {}, {}".format(i, name))
394 415 for k, v in es_docs.items():
395 416 to_update = {"_index": k, "_type": "log"}
396 417 [i.update(to_update) for i in v]
397 418 elasticsearch.helpers.bulk(Datastores.es, v)
398 419
399 420 log.info("total docs {} {}".format(i, datetime.datetime.now() - task_start))
400 421
401 422
402 423 def reindex_slow_calls():
403 424 try:
404 425 Datastores.es.indices.delete("rcae_sc*")
405 426 except elasticsearch.exceptions.NotFoundError as e:
406 427 log.error(e)
407 428
408 429 log.info("reindexing slow calls")
409 430 i = 0
410 431 task_start = datetime.datetime.now()
411 432 slow_calls_tables = detect_tables("slow_calls_p_")
412 433 for partition_table in slow_calls_tables:
413 434 conn = DBSession.connection().execution_options(stream_results=True)
414 435 result = conn.execute(partition_table.select())
415 436 while True:
416 437 chunk = result.fetchmany(2000)
417 438 if not chunk:
418 439 break
419 440 es_docs = defaultdict(list)
420 441 for row in chunk:
421 442 i += 1
422 443 item = SlowCall(**dict(list(row.items())))
423 444 d_range = item.partition_id
424 445 es_docs[d_range].append(item.es_doc())
425 446 if es_docs:
426 447 name = partition_table.name
427 448 log.info("round {}, {}".format(i, name))
428 449 for k, v in es_docs.items():
429 450 to_update = {"_index": k, "_type": "log"}
430 451 [i.update(to_update) for i in v]
431 452 elasticsearch.helpers.bulk(Datastores.es, v)
432 453
433 454 log.info("total docs {} {}".format(i, datetime.datetime.now() - task_start))
434 455
435 456
436 457 if __name__ == "__main__":
437 458 main()
@@ -1,220 +1,220 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors
4 4 #
5 5 # Licensed under the Apache License, Version 2.0 (the "License");
6 6 # you may not use this file except in compliance with the License.
7 7 # You may obtain a copy of the License at
8 8 #
9 9 # http://www.apache.org/licenses/LICENSE-2.0
10 10 #
11 11 # Unless required by applicable law or agreed to in writing, software
12 12 # distributed under the License is distributed on an "AS IS" BASIS,
13 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 14 # See the License for the specific language governing permissions and
15 15 # limitations under the License.
16 16
17 17 import logging
18 18 from datetime import datetime, timedelta
19 19
20 20 from pyramid.view import view_config
21 21 from pyramid.httpexceptions import HTTPUnprocessableEntity
22 22 from appenlight.models import Datastores, Log
23 23 from appenlight.models.services.log import LogService
24 24 from appenlight.lib.utils import (
25 25 build_filter_settings_from_query_dict,
26 26 es_index_name_limiter,
27 27 )
28 28 from appenlight.lib.helpers import gen_pagination_headers
29 29 from appenlight.celery.tasks import logs_cleanup
30 30
31 31 log = logging.getLogger(__name__)
32 32
33 33 section_filters_key = "appenlight:logs:filter:%s"
34 34
35 35
36 36 @view_config(route_name="logs_no_id", renderer="json", permission="authenticated")
37 37 def fetch_logs(request):
38 38 """
39 39 Returns list of log entries from Elasticsearch
40 40 """
41 41
42 42 filter_settings = build_filter_settings_from_query_dict(
43 43 request, request.GET.mixed()
44 44 )
45 45 logs_paginator = LogService.get_paginator_by_app_ids(
46 46 app_ids=filter_settings["resource"],
47 47 page=filter_settings["page"],
48 48 filter_settings=filter_settings,
49 49 )
50 50 headers = gen_pagination_headers(request, logs_paginator)
51 51 request.response.headers.update(headers)
52 52
53 53 return [l.get_dict() for l in logs_paginator.sa_items]
54 54
55 55
56 56 @view_config(
57 57 route_name="section_view",
58 58 match_param=["section=logs_section", "view=fetch_series"],
59 59 renderer="json",
60 60 permission="authenticated",
61 61 )
62 62 def logs_fetch_series(request):
63 63 """
64 64 Handles metric dashboard graphs
65 65 Returns information for time/tier breakdown
66 66 """
67 67 filter_settings = build_filter_settings_from_query_dict(
68 68 request, request.GET.mixed()
69 69 )
70 70 paginator = LogService.get_paginator_by_app_ids(
71 71 app_ids=filter_settings["resource"],
72 72 page=1,
73 73 filter_settings=filter_settings,
74 74 items_per_page=1,
75 75 )
76 76 now = datetime.utcnow().replace(microsecond=0, second=0)
77 77 delta = timedelta(days=7)
78 78 if paginator.sa_items:
79 79 start_date = paginator.sa_items[-1].timestamp.replace(microsecond=0, second=0)
80 80 filter_settings["start_date"] = start_date - delta
81 81 else:
82 82 filter_settings["start_date"] = now - delta
83 83 filter_settings["end_date"] = filter_settings["start_date"] + timedelta(days=7)
84 84
85 85 @request.registry.cache_regions.redis_sec_30.cache_on_arguments("logs_graphs")
86 86 def cached(apps, search_params, delta, now):
87 87 data = LogService.get_time_series_aggregate(
88 88 filter_settings["resource"], filter_settings
89 89 )
90 90 if not data:
91 91 return []
92 92 buckets = data["aggregations"]["events_over_time"]["buckets"]
93 93 return [
94 94 {
95 95 "x": datetime.utcfromtimestamp(item["key"] / 1000),
96 96 "logs": item["doc_count"],
97 97 }
98 98 for item in buckets
99 99 ]
100 100
101 101 return cached(filter_settings, request.GET.mixed(), delta, now)
102 102
103 103
104 104 @view_config(
105 105 route_name="logs_no_id",
106 106 renderer="json",
107 107 request_method="DELETE",
108 108 permission="authenticated",
109 109 )
110 110 def logs_mass_delete(request):
111 111 params = request.GET.mixed()
112 112 if "resource" not in params:
113 113 raise HTTPUnprocessableEntity()
114 114 # this might be '' and then colander will not validate the schema
115 115 if not params.get("namespace"):
116 116 params.pop("namespace", None)
117 117 filter_settings = build_filter_settings_from_query_dict(
118 118 request, params, resource_permissions=["update_reports"]
119 119 )
120 120
121 121 resource_id = list(filter_settings["resource"])[0]
122 122 # filter settings returns list of all of users applications
123 123 # if app is not matching - normally we would not care as its used for search
124 124 # but here user playing with params would possibly wipe out their whole data
125 125 if int(resource_id) != int(params["resource"]):
126 126 raise HTTPUnprocessableEntity()
127 127
128 128 logs_cleanup.delay(resource_id, filter_settings)
129 129 msg = (
130 130 "Log cleanup process started - it may take a while for "
131 131 "everything to get removed"
132 132 )
133 133 request.session.flash(msg)
134 134 return {}
135 135
136 136
137 137 @view_config(
138 138 route_name="section_view",
139 139 match_param=("view=common_tags", "section=logs_section"),
140 140 renderer="json",
141 141 permission="authenticated",
142 142 )
143 143 def common_tags(request):
144 144 config = request.GET.mixed()
145 145 filter_settings = build_filter_settings_from_query_dict(request, config)
146 146
147 147 resources = list(filter_settings["resource"])
148 148 query = {
149 149 "query": {
150 150 "bool": {
151 151 "filter": [{"terms": {"resource_id": list(resources)}}]
152 152 }
153 153 }
154 154 }
155 155 start_date = filter_settings.get("start_date")
156 156 end_date = filter_settings.get("end_date")
157 157 filter_part = query["query"]["bool"]["filter"]
158 158
159 159 date_range = {"range": {"timestamp": {}}}
160 160 if start_date:
161 161 date_range["range"]["timestamp"]["gte"] = start_date
162 162 if end_date:
163 163 date_range["range"]["timestamp"]["lte"] = end_date
164 164 if start_date or end_date:
165 165 filter_part.append(date_range)
166 166
167 167 levels = filter_settings.get("level")
168 168 if levels:
169 169 filter_part.append({"terms": {"log_level": levels}})
170 170 namespaces = filter_settings.get("namespace")
171 171 if namespaces:
172 172 filter_part.append({"terms": {"namespace": namespaces}})
173 173
174 query["aggs"] = {"sub_agg": {"terms": {"field": "tag_list", "size": 50}}}
174 query["aggs"] = {"sub_agg": {"terms": {"field": "tag_list.keyword", "size": 50}}}
175 175 # tags
176 176 index_names = es_index_name_limiter(ixtypes=[config.get("datasource", "logs")])
177 177 result = Datastores.es.search(body=query, index=index_names, doc_type="log", size=0)
178 178 tag_buckets = result["aggregations"]["sub_agg"].get("buckets", [])
179 179 # namespaces
180 query["aggs"] = {"sub_agg": {"terms": {"field": "namespace", "size": 50}}}
180 query["aggs"] = {"sub_agg": {"terms": {"field": "namespace.keyword", "size": 50}}}
181 181 result = Datastores.es.search(body=query, index=index_names, doc_type="log", size=0)
182 182 namespaces_buckets = result["aggregations"]["sub_agg"].get("buckets", [])
183 183 return {
184 184 "tags": [item["key"] for item in tag_buckets],
185 185 "namespaces": [item["key"] for item in namespaces_buckets],
186 186 }
187 187
188 188
189 189 @view_config(
190 190 route_name="section_view",
191 191 match_param=("view=common_values", "section=logs_section"),
192 192 renderer="json",
193 193 permission="authenticated",
194 194 )
195 195 def common_values(request):
196 196 config = request.GET.mixed()
197 197 datasource = config.pop("datasource", "logs")
198 198 filter_settings = build_filter_settings_from_query_dict(request, config)
199 199 resources = list(filter_settings["resource"])
200 200 tag_name = filter_settings["tags"][0]["value"][0]
201 201
202 202 and_part = [
203 203 {"terms": {"resource_id": list(resources)}},
204 204 ]
205 205 if filter_settings["namespace"]:
206 206 and_part.append({"terms": {"namespace": filter_settings["namespace"]}})
207 207 query = {
208 208 "query": {
209 209 "bool": {
210 210 "filter": and_part
211 211 }
212 212 }
213 213 }
214 214 query["aggs"] = {
215 215 "sub_agg": {"terms": {"field": "tags.{}.values".format(tag_name), "size": 50}}
216 216 }
217 217 index_names = es_index_name_limiter(ixtypes=[datasource])
218 218 result = Datastores.es.search(body=query, index=index_names, doc_type="log", size=0)
219 219 values_buckets = result["aggregations"]["sub_agg"].get("buckets", [])
220 220 return {"values": [item["key"] for item in values_buckets]}
General Comments 4
Under Review
author

Auto status change to "Under Review"

Under Review
author

Auto status change to "Under Review"

You need to be logged in to leave comments. Login now