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