##// END OF EJS Templates
application: add all() method to service
ergo -
Show More
@@ -1,193 +1,198 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # AppEnlight Enterprise Edition, including its added features, Support
18 # AppEnlight Enterprise Edition, including its added features, Support
19 # services, and proprietary license terms, please see
19 # services, and proprietary license terms, please see
20 # https://rhodecode.com/licenses/
20 # https://rhodecode.com/licenses/
21
21
22 import logging
22 import logging
23 import urllib.parse
23 import urllib.parse
24
24
25 import sqlalchemy as sa
25 import sqlalchemy as sa
26 from pyramid.threadlocal import get_current_request
26 from pyramid.threadlocal import get_current_request
27
27
28 from appenlight.lib.cache_regions import get_region
28 from appenlight.lib.cache_regions import get_region
29 from appenlight.lib.enums import ReportType
29 from appenlight.lib.enums import ReportType
30 from appenlight.models import get_db_session
30 from appenlight.models import get_db_session
31 from appenlight.models.report_group import ReportGroup
31 from appenlight.models.report_group import ReportGroup
32 from appenlight.models.application import Application
32 from appenlight.models.application import Application
33 from appenlight.models.event import Event
33 from appenlight.models.event import Event
34 from appenlight.models.services.base import BaseService
34 from appenlight.models.services.base import BaseService
35 from appenlight.models.services.event import EventService
35 from appenlight.models.services.event import EventService
36
36
37 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
38
38
39
39
40 # cache_memory_min_1 = get_region('memory_min_1')
41
42 class ApplicationService(BaseService):
40 class ApplicationService(BaseService):
41
42 @classmethod
43 def all(cls, db_session=None):
44 db_session = get_db_session(db_session)
45 q = db_session.query(Application)
46 return q
47
43 @classmethod
48 @classmethod
44 def by_api_key(cls, api_key, db_session=None):
49 def by_api_key(cls, api_key, db_session=None):
45 db_session = get_db_session(db_session)
50 db_session = get_db_session(db_session)
46 q = db_session.query(Application)
51 q = db_session.query(Application)
47 q = q.filter(Application.api_key == api_key)
52 q = q.filter(Application.api_key == api_key)
48 q = q.options(sa.orm.eagerload(Application.owner))
53 q = q.options(sa.orm.eagerload(Application.owner))
49 return q.first()
54 return q.first()
50
55
51 @classmethod
56 @classmethod
52 def by_api_key_cached(cls, db_session=None):
57 def by_api_key_cached(cls, db_session=None):
53 db_session = get_db_session(db_session)
58 db_session = get_db_session(db_session)
54 cache_region = get_region('redis_min_1')
59 cache_region = get_region('redis_min_1')
55
60
56 @cache_region.cache_on_arguments('ApplicationService.by_api_key')
61 @cache_region.cache_on_arguments('ApplicationService.by_api_key')
57 def cached(*args, **kwargs):
62 def cached(*args, **kwargs):
58 app = cls.by_api_key(*args, db_session=db_session, **kwargs)
63 app = cls.by_api_key(*args, db_session=db_session, **kwargs)
59 if app:
64 if app:
60 db_session.expunge(app)
65 db_session.expunge(app)
61 return app
66 return app
62
67
63 return cached
68 return cached
64
69
65 @classmethod
70 @classmethod
66 def by_public_api_key(cls, api_key, db_session=None, from_cache=False,
71 def by_public_api_key(cls, api_key, db_session=None, from_cache=False,
67 request=None):
72 request=None):
68 db_session = get_db_session(db_session)
73 db_session = get_db_session(db_session)
69 cache_region = get_region('redis_min_1')
74 cache_region = get_region('redis_min_1')
70
75
71 def uncached(api_key):
76 def uncached(api_key):
72 q = db_session.query(Application)
77 q = db_session.query(Application)
73 q = q.filter(Application.public_key == api_key)
78 q = q.filter(Application.public_key == api_key)
74 q = q.options(sa.orm.eagerload(Application.owner))
79 q = q.options(sa.orm.eagerload(Application.owner))
75 return q.first()
80 return q.first()
76
81
77 if from_cache:
82 if from_cache:
78 @cache_region.cache_on_arguments(
83 @cache_region.cache_on_arguments(
79 'ApplicationService.by_public_api_key')
84 'ApplicationService.by_public_api_key')
80 def cached(api_key):
85 def cached(api_key):
81 app = uncached(api_key)
86 app = uncached(api_key)
82 if app:
87 if app:
83 db_session.expunge(app)
88 db_session.expunge(app)
84 return app
89 return app
85
90
86 app = cached(api_key)
91 app = cached(api_key)
87 else:
92 else:
88 app = uncached(api_key)
93 app = uncached(api_key)
89 return app
94 return app
90
95
91 @classmethod
96 @classmethod
92 def by_id(cls, db_id, db_session=None):
97 def by_id(cls, db_id, db_session=None):
93 db_session = get_db_session(db_session)
98 db_session = get_db_session(db_session)
94 q = db_session.query(Application)
99 q = db_session.query(Application)
95 q = q.filter(Application.resource_id == db_id)
100 q = q.filter(Application.resource_id == db_id)
96 return q.first()
101 return q.first()
97
102
98 @classmethod
103 @classmethod
99 def by_id_cached(cls, db_session=None):
104 def by_id_cached(cls, db_session=None):
100 db_session = get_db_session(db_session)
105 db_session = get_db_session(db_session)
101 cache_region = get_region('redis_min_1')
106 cache_region = get_region('redis_min_1')
102
107
103 @cache_region.cache_on_arguments('ApplicationService.by_id')
108 @cache_region.cache_on_arguments('ApplicationService.by_id')
104 def cached(*args, **kwargs):
109 def cached(*args, **kwargs):
105 app = cls.by_id(*args, db_session=db_session, **kwargs)
110 app = cls.by_id(*args, db_session=db_session, **kwargs)
106 if app:
111 if app:
107 db_session.expunge(app)
112 db_session.expunge(app)
108 return app
113 return app
109
114
110 return cached
115 return cached
111
116
112 @classmethod
117 @classmethod
113 def by_ids(cls, db_ids, db_session=None):
118 def by_ids(cls, db_ids, db_session=None):
114 db_session = get_db_session(db_session)
119 db_session = get_db_session(db_session)
115 query = db_session.query(Application)
120 query = db_session.query(Application)
116 query = query.filter(Application.resource_id.in_(db_ids))
121 query = query.filter(Application.resource_id.in_(db_ids))
117 return query
122 return query
118
123
119 @classmethod
124 @classmethod
120 def by_http_referer(cls, referer_string, db_session=None):
125 def by_http_referer(cls, referer_string, db_session=None):
121 db_session = get_db_session(db_session)
126 db_session = get_db_session(db_session)
122 domain = urllib.parse.urlsplit(
127 domain = urllib.parse.urlsplit(
123 referer_string, allow_fragments=False).netloc
128 referer_string, allow_fragments=False).netloc
124 if domain:
129 if domain:
125 if domain.startswith('www.'):
130 if domain.startswith('www.'):
126 domain = domain[4:]
131 domain = domain[4:]
127 q = db_session.query(Application).filter(Application.domain == domain)
132 q = db_session.query(Application).filter(Application.domain == domain)
128 return q.first()
133 return q.first()
129
134
130 @classmethod
135 @classmethod
131 def last_updated(cls, since_when, exclude_status=None, db_session=None):
136 def last_updated(cls, since_when, exclude_status=None, db_session=None):
132 db_session = get_db_session(db_session)
137 db_session = get_db_session(db_session)
133 q = db_session.query(Application)
138 q = db_session.query(Application)
134 q2 = ReportGroup.last_updated(
139 q2 = ReportGroup.last_updated(
135 since_when, exclude_status=exclude_status, db_session=db_session)
140 since_when, exclude_status=exclude_status, db_session=db_session)
136 q2 = q2.from_self(ReportGroup.resource_id)
141 q2 = q2.from_self(ReportGroup.resource_id)
137 q2 = q2.group_by(ReportGroup.resource_id)
142 q2 = q2.group_by(ReportGroup.resource_id)
138 q = q.filter(Application.resource_id.in_(q2))
143 q = q.filter(Application.resource_id.in_(q2))
139 return q
144 return q
140
145
141 @classmethod
146 @classmethod
142 def check_for_groups_alert(cls, resource, event_type, *args, **kwargs):
147 def check_for_groups_alert(cls, resource, event_type, *args, **kwargs):
143 """ Check for open alerts depending on group type.
148 """ Check for open alerts depending on group type.
144 Create new one if nothing is found and send alerts """
149 Create new one if nothing is found and send alerts """
145 db_session = get_db_session(kwargs.get('db_session'))
150 db_session = get_db_session(kwargs.get('db_session'))
146 request = get_current_request()
151 request = get_current_request()
147 report_groups = kwargs['report_groups']
152 report_groups = kwargs['report_groups']
148 occurence_dict = kwargs['occurence_dict']
153 occurence_dict = kwargs['occurence_dict']
149
154
150 error_reports = 0
155 error_reports = 0
151 slow_reports = 0
156 slow_reports = 0
152 for group in report_groups:
157 for group in report_groups:
153 occurences = occurence_dict.get(group.id, 1)
158 occurences = occurence_dict.get(group.id, 1)
154 if group.get_report().report_type == ReportType.error:
159 if group.get_report().report_type == ReportType.error:
155 error_reports += occurences
160 error_reports += occurences
156 elif group.get_report().report_type == ReportType.slow:
161 elif group.get_report().report_type == ReportType.slow:
157 slow_reports += occurences
162 slow_reports += occurences
158
163
159 log_msg = 'LIMIT INFO: %s : %s error reports. %s slow_reports' % (
164 log_msg = 'LIMIT INFO: %s : %s error reports. %s slow_reports' % (
160 resource,
165 resource,
161 error_reports,
166 error_reports,
162 slow_reports)
167 slow_reports)
163 logging.warning(log_msg)
168 logging.warning(log_msg)
164 threshold = 10
169 threshold = 10
165 for event_type in ['error_report_alert', 'slow_report_alert']:
170 for event_type in ['error_report_alert', 'slow_report_alert']:
166 if (error_reports < resource.error_report_threshold and
171 if (error_reports < resource.error_report_threshold and
167 event_type == 'error_report_alert'):
172 event_type == 'error_report_alert'):
168 continue
173 continue
169 elif (slow_reports <= resource.slow_report_threshold and
174 elif (slow_reports <= resource.slow_report_threshold and
170 event_type == 'slow_report_alert'):
175 event_type == 'slow_report_alert'):
171 continue
176 continue
172 if event_type == 'error_report_alert':
177 if event_type == 'error_report_alert':
173 amount = error_reports
178 amount = error_reports
174 threshold = resource.error_report_threshold
179 threshold = resource.error_report_threshold
175 elif event_type == 'slow_report_alert':
180 elif event_type == 'slow_report_alert':
176 amount = slow_reports
181 amount = slow_reports
177 threshold = resource.slow_report_threshold
182 threshold = resource.slow_report_threshold
178
183
179 event = EventService.for_resource([resource.resource_id],
184 event = EventService.for_resource([resource.resource_id],
180 event_type=Event.types[
185 event_type=Event.types[
181 event_type],
186 event_type],
182 status=Event.statuses['active'])
187 status=Event.statuses['active'])
183 if event.first():
188 if event.first():
184 log.info('ALERT: PROGRESS: %s %s' % (event_type, resource))
189 log.info('ALERT: PROGRESS: %s %s' % (event_type, resource))
185 else:
190 else:
186 log.warning('ALERT: OPEN: %s %s' % (event_type, resource))
191 log.warning('ALERT: OPEN: %s %s' % (event_type, resource))
187 new_event = Event(resource_id=resource.resource_id,
192 new_event = Event(resource_id=resource.resource_id,
188 event_type=Event.types[event_type],
193 event_type=Event.types[event_type],
189 status=Event.statuses['active'],
194 status=Event.statuses['active'],
190 values={'reports': amount,
195 values={'reports': amount,
191 'threshold': threshold})
196 'threshold': threshold})
192 db_session.add(new_event)
197 db_session.add(new_event)
193 new_event.send_alerts(request=request, resource=resource)
198 new_event.send_alerts(request=request, resource=resource)
General Comments 0
You need to be logged in to leave comments. Login now