##// END OF EJS Templates
logging: fix logging for webhooks
ergo -
Show More
@@ -1,143 +1,143 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # AppEnlight Enterprise Edition, including its added features, Support
19 19 # services, and proprietary license terms, please see
20 20 # https://rhodecode.com/licenses/
21 21
22 22 import logging
23 23
24 24 import requests
25 25
26 26 from appenlight.models.integrations import (IntegrationBase,
27 27 IntegrationException)
28 28 from appenlight.models.alert_channel import AlertChannel
29 29 from appenlight.lib.ext_json import json
30 30
31 31 _ = str
32 32
33 33 log = logging.getLogger(__name__)
34 34
35 35
36 36 class NotFoundException(Exception):
37 37 pass
38 38
39 39
40 40 class WebhooksIntegration(IntegrationBase):
41 41 __mapper_args__ = {
42 42 'polymorphic_identity': 'webhooks'
43 43 }
44 44 front_visible = False
45 45 as_alert_channel = True
46 46 supports_report_alerting = True
47 47 action_notification = True
48 48 integration_action = 'Message via Webhooks'
49 49
50 50 @classmethod
51 51 def create_client(cls, url):
52 52 client = WebhooksClient(url)
53 53 return client
54 54
55 55
56 56 class WebhooksClient(object):
57 57 def __init__(self, url):
58 58 self.api_url = url
59 59
60 60 def make_request(self, url, method='get', data=None):
61 61 headers = {
62 62 'Content-Type': 'application/json',
63 63 'User-Agent': 'appenlight-webhooks',
64 64 }
65 65 try:
66 66 if data:
67 67 data = json.dumps(data)
68 68 resp = getattr(requests, method)(url, data=data, headers=headers,
69 69 timeout=3)
70 70 except Exception as e:
71 71 raise IntegrationException(
72 _('Error communicating with Webhooks: %s').format(e))
72 _('Error communicating with Webhooks: {}').format(e))
73 73 if resp.status_code > 299:
74 74 raise IntegrationException(
75 'Error communicating with Webhooks - status code: %s'.format(
75 'Error communicating with Webhooks - status code: {}'.format(
76 76 resp.status_code))
77 77 return resp
78 78
79 79 def send_to_hook(self, payload):
80 80 return self.make_request(self.api_url, method='post',
81 81 data=payload).json()
82 82
83 83
84 84 class WebhooksAlertChannel(AlertChannel):
85 85 __mapper_args__ = {
86 86 'polymorphic_identity': 'webhooks'
87 87 }
88 88
89 89 def notify_reports(self, **kwargs):
90 90 """
91 91 Notify user of individual reports
92 92
93 93 kwargs:
94 94 application: application that the event applies for,
95 95 user: user that should be notified
96 96 request: request object
97 97 since_when: reports are newer than this time value,
98 98 reports: list of reports to render
99 99
100 100 """
101 101 template_vars = self.get_notification_basic_vars(kwargs)
102 102 payload = []
103 103 include_keys = ('id', 'http_status', 'report_type', 'resource_name',
104 104 'front_url', 'resource_id', 'error', 'url_path',
105 105 'tags', 'duration')
106 106
107 107 for occurences, report in kwargs['reports']:
108 108 r_dict = report.last_report_ref.get_dict(kwargs['request'],
109 109 include_keys=include_keys)
110 110 r_dict['group']['occurences'] = occurences
111 111 payload.append(r_dict)
112 112 client = WebhooksIntegration.create_client(
113 113 self.integration.config['reports_webhook'])
114 114 client.send_to_hook(payload)
115 115
116 116 def notify_alert(self, **kwargs):
117 117 """
118 118 Notify user of report or uptime threshold events based on events alert type
119 119
120 120 Kwargs:
121 121 application: application that the event applies for,
122 122 event: event that is notified,
123 123 user: user that should be notified
124 124 request: request object
125 125
126 126 """
127 127 payload = {
128 128 'alert_action': kwargs['event'].unified_alert_action(),
129 129 'alert_name': kwargs['event'].unified_alert_name(),
130 130 'event_time': kwargs['event'].end_date or kwargs[
131 131 'event'].start_date,
132 132 'resource_name': None,
133 133 'resource_id': None
134 134 }
135 135 if kwargs['event'].values and kwargs['event'].values.get('reports'):
136 136 payload['reports'] = kwargs['event'].values.get('reports', [])
137 137 if 'application' in kwargs:
138 138 payload['resource_name'] = kwargs['application'].resource_name
139 139 payload['resource_id'] = kwargs['application'].resource_id
140 140
141 141 client = WebhooksIntegration.create_client(
142 142 self.integration.config['alerts_webhook'])
143 143 client.send_to_hook(payload)
General Comments 0
You need to be logged in to leave comments. Login now