##// END OF EJS Templates
logging: fix logging for webhooks
ergo -
Show More
@@ -1,143 +1,143 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
23
24 import requests
24 import requests
25
25
26 from appenlight.models.integrations import (IntegrationBase,
26 from appenlight.models.integrations import (IntegrationBase,
27 IntegrationException)
27 IntegrationException)
28 from appenlight.models.alert_channel import AlertChannel
28 from appenlight.models.alert_channel import AlertChannel
29 from appenlight.lib.ext_json import json
29 from appenlight.lib.ext_json import json
30
30
31 _ = str
31 _ = str
32
32
33 log = logging.getLogger(__name__)
33 log = logging.getLogger(__name__)
34
34
35
35
36 class NotFoundException(Exception):
36 class NotFoundException(Exception):
37 pass
37 pass
38
38
39
39
40 class WebhooksIntegration(IntegrationBase):
40 class WebhooksIntegration(IntegrationBase):
41 __mapper_args__ = {
41 __mapper_args__ = {
42 'polymorphic_identity': 'webhooks'
42 'polymorphic_identity': 'webhooks'
43 }
43 }
44 front_visible = False
44 front_visible = False
45 as_alert_channel = True
45 as_alert_channel = True
46 supports_report_alerting = True
46 supports_report_alerting = True
47 action_notification = True
47 action_notification = True
48 integration_action = 'Message via Webhooks'
48 integration_action = 'Message via Webhooks'
49
49
50 @classmethod
50 @classmethod
51 def create_client(cls, url):
51 def create_client(cls, url):
52 client = WebhooksClient(url)
52 client = WebhooksClient(url)
53 return client
53 return client
54
54
55
55
56 class WebhooksClient(object):
56 class WebhooksClient(object):
57 def __init__(self, url):
57 def __init__(self, url):
58 self.api_url = url
58 self.api_url = url
59
59
60 def make_request(self, url, method='get', data=None):
60 def make_request(self, url, method='get', data=None):
61 headers = {
61 headers = {
62 'Content-Type': 'application/json',
62 'Content-Type': 'application/json',
63 'User-Agent': 'appenlight-webhooks',
63 'User-Agent': 'appenlight-webhooks',
64 }
64 }
65 try:
65 try:
66 if data:
66 if data:
67 data = json.dumps(data)
67 data = json.dumps(data)
68 resp = getattr(requests, method)(url, data=data, headers=headers,
68 resp = getattr(requests, method)(url, data=data, headers=headers,
69 timeout=3)
69 timeout=3)
70 except Exception as e:
70 except Exception as e:
71 raise IntegrationException(
71 raise IntegrationException(
72 _('Error communicating with Webhooks: %s').format(e))
72 _('Error communicating with Webhooks: {}').format(e))
73 if resp.status_code > 299:
73 if resp.status_code > 299:
74 raise IntegrationException(
74 raise IntegrationException(
75 'Error communicating with Webhooks - status code: %s'.format(
75 'Error communicating with Webhooks - status code: {}'.format(
76 resp.status_code))
76 resp.status_code))
77 return resp
77 return resp
78
78
79 def send_to_hook(self, payload):
79 def send_to_hook(self, payload):
80 return self.make_request(self.api_url, method='post',
80 return self.make_request(self.api_url, method='post',
81 data=payload).json()
81 data=payload).json()
82
82
83
83
84 class WebhooksAlertChannel(AlertChannel):
84 class WebhooksAlertChannel(AlertChannel):
85 __mapper_args__ = {
85 __mapper_args__ = {
86 'polymorphic_identity': 'webhooks'
86 'polymorphic_identity': 'webhooks'
87 }
87 }
88
88
89 def notify_reports(self, **kwargs):
89 def notify_reports(self, **kwargs):
90 """
90 """
91 Notify user of individual reports
91 Notify user of individual reports
92
92
93 kwargs:
93 kwargs:
94 application: application that the event applies for,
94 application: application that the event applies for,
95 user: user that should be notified
95 user: user that should be notified
96 request: request object
96 request: request object
97 since_when: reports are newer than this time value,
97 since_when: reports are newer than this time value,
98 reports: list of reports to render
98 reports: list of reports to render
99
99
100 """
100 """
101 template_vars = self.get_notification_basic_vars(kwargs)
101 template_vars = self.get_notification_basic_vars(kwargs)
102 payload = []
102 payload = []
103 include_keys = ('id', 'http_status', 'report_type', 'resource_name',
103 include_keys = ('id', 'http_status', 'report_type', 'resource_name',
104 'front_url', 'resource_id', 'error', 'url_path',
104 'front_url', 'resource_id', 'error', 'url_path',
105 'tags', 'duration')
105 'tags', 'duration')
106
106
107 for occurences, report in kwargs['reports']:
107 for occurences, report in kwargs['reports']:
108 r_dict = report.last_report_ref.get_dict(kwargs['request'],
108 r_dict = report.last_report_ref.get_dict(kwargs['request'],
109 include_keys=include_keys)
109 include_keys=include_keys)
110 r_dict['group']['occurences'] = occurences
110 r_dict['group']['occurences'] = occurences
111 payload.append(r_dict)
111 payload.append(r_dict)
112 client = WebhooksIntegration.create_client(
112 client = WebhooksIntegration.create_client(
113 self.integration.config['reports_webhook'])
113 self.integration.config['reports_webhook'])
114 client.send_to_hook(payload)
114 client.send_to_hook(payload)
115
115
116 def notify_alert(self, **kwargs):
116 def notify_alert(self, **kwargs):
117 """
117 """
118 Notify user of report or uptime threshold events based on events alert type
118 Notify user of report or uptime threshold events based on events alert type
119
119
120 Kwargs:
120 Kwargs:
121 application: application that the event applies for,
121 application: application that the event applies for,
122 event: event that is notified,
122 event: event that is notified,
123 user: user that should be notified
123 user: user that should be notified
124 request: request object
124 request: request object
125
125
126 """
126 """
127 payload = {
127 payload = {
128 'alert_action': kwargs['event'].unified_alert_action(),
128 'alert_action': kwargs['event'].unified_alert_action(),
129 'alert_name': kwargs['event'].unified_alert_name(),
129 'alert_name': kwargs['event'].unified_alert_name(),
130 'event_time': kwargs['event'].end_date or kwargs[
130 'event_time': kwargs['event'].end_date or kwargs[
131 'event'].start_date,
131 'event'].start_date,
132 'resource_name': None,
132 'resource_name': None,
133 'resource_id': None
133 'resource_id': None
134 }
134 }
135 if kwargs['event'].values and kwargs['event'].values.get('reports'):
135 if kwargs['event'].values and kwargs['event'].values.get('reports'):
136 payload['reports'] = kwargs['event'].values.get('reports', [])
136 payload['reports'] = kwargs['event'].values.get('reports', [])
137 if 'application' in kwargs:
137 if 'application' in kwargs:
138 payload['resource_name'] = kwargs['application'].resource_name
138 payload['resource_name'] = kwargs['application'].resource_name
139 payload['resource_id'] = kwargs['application'].resource_id
139 payload['resource_id'] = kwargs['application'].resource_id
140
140
141 client = WebhooksIntegration.create_client(
141 client = WebhooksIntegration.create_client(
142 self.integration.config['alerts_webhook'])
142 self.integration.config['alerts_webhook'])
143 client.send_to_hook(payload)
143 client.send_to_hook(payload)
General Comments 0
You need to be logged in to leave comments. Login now