##// END OF EJS Templates
integrations: webhook handle response errors and show response for easier debugging.
marcink -
r2581:dd15af20 default
parent child Browse files
Show More
@@ -1,390 +1,394 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2012-2018 RhodeCode GmbH
3 # Copyright (C) 2012-2018 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 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 from __future__ import unicode_literals
21 from __future__ import unicode_literals
22 import string
22 import string
23 from collections import OrderedDict
23 from collections import OrderedDict
24
24
25 import deform
25 import deform
26 import deform.widget
26 import deform.widget
27 import logging
27 import logging
28 import requests
28 import requests
29 import requests.adapters
29 import requests.adapters
30 import colander
30 import colander
31 from requests.packages.urllib3.util.retry import Retry
31 from requests.packages.urllib3.util.retry import Retry
32
32
33 import rhodecode
33 import rhodecode
34 from rhodecode import events
34 from rhodecode import events
35 from rhodecode.translation import _
35 from rhodecode.translation import _
36 from rhodecode.integrations.types.base import (
36 from rhodecode.integrations.types.base import (
37 IntegrationTypeBase, get_auth, get_url_vars)
37 IntegrationTypeBase, get_auth, get_url_vars)
38 from rhodecode.lib.celerylib import run_task, async_task, RequestContextTask
38 from rhodecode.lib.celerylib import run_task, async_task, RequestContextTask
39
39
40 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
41
41
42
42
43 # updating this required to update the `common_vars` passed in url calling func
43 # updating this required to update the `common_vars` passed in url calling func
44 WEBHOOK_URL_VARS = [
44 WEBHOOK_URL_VARS = [
45 'repo_name',
45 'repo_name',
46 'repo_type',
46 'repo_type',
47 'repo_id',
47 'repo_id',
48 'repo_url',
48 'repo_url',
49 # extra repo fields
49 # extra repo fields
50 'extra:<extra_key_name>',
50 'extra:<extra_key_name>',
51
51
52 # special attrs below that we handle, using multi-call
52 # special attrs below that we handle, using multi-call
53 'branch',
53 'branch',
54 'commit_id',
54 'commit_id',
55
55
56 # pr events vars
56 # pr events vars
57 'pull_request_id',
57 'pull_request_id',
58 'pull_request_url',
58 'pull_request_url',
59
59
60 # user who triggers the call
60 # user who triggers the call
61 'username',
61 'username',
62 'user_id',
62 'user_id',
63
63
64 ]
64 ]
65 URL_VARS = get_url_vars(WEBHOOK_URL_VARS)
65 URL_VARS = get_url_vars(WEBHOOK_URL_VARS)
66
66
67
67
68 class WebhookHandler(object):
68 class WebhookHandler(object):
69 def __init__(self, template_url, secret_token, headers):
69 def __init__(self, template_url, secret_token, headers):
70 self.template_url = template_url
70 self.template_url = template_url
71 self.secret_token = secret_token
71 self.secret_token = secret_token
72 self.headers = headers
72 self.headers = headers
73
73
74 def get_base_parsed_template(self, data):
74 def get_base_parsed_template(self, data):
75 """
75 """
76 initially parses the passed in template with some common variables
76 initially parses the passed in template with some common variables
77 available on ALL calls
77 available on ALL calls
78 """
78 """
79 # note: make sure to update the `WEBHOOK_URL_VARS` if this changes
79 # note: make sure to update the `WEBHOOK_URL_VARS` if this changes
80 common_vars = {
80 common_vars = {
81 'repo_name': data['repo']['repo_name'],
81 'repo_name': data['repo']['repo_name'],
82 'repo_type': data['repo']['repo_type'],
82 'repo_type': data['repo']['repo_type'],
83 'repo_id': data['repo']['repo_id'],
83 'repo_id': data['repo']['repo_id'],
84 'repo_url': data['repo']['url'],
84 'repo_url': data['repo']['url'],
85 'username': data['actor']['username'],
85 'username': data['actor']['username'],
86 'user_id': data['actor']['user_id']
86 'user_id': data['actor']['user_id']
87 }
87 }
88
88
89 extra_vars = {}
89 extra_vars = {}
90 for extra_key, extra_val in data['repo']['extra_fields'].items():
90 for extra_key, extra_val in data['repo']['extra_fields'].items():
91 extra_vars['extra__{}'.format(extra_key)] = extra_val
91 extra_vars['extra__{}'.format(extra_key)] = extra_val
92 common_vars.update(extra_vars)
92 common_vars.update(extra_vars)
93
93
94 template_url = self.template_url.replace('${extra:', '${extra__')
94 template_url = self.template_url.replace('${extra:', '${extra__')
95 return string.Template(template_url).safe_substitute(**common_vars)
95 return string.Template(template_url).safe_substitute(**common_vars)
96
96
97 def repo_push_event_handler(self, event, data):
97 def repo_push_event_handler(self, event, data):
98 url = self.get_base_parsed_template(data)
98 url = self.get_base_parsed_template(data)
99 url_cals = []
99 url_cals = []
100 branch_data = OrderedDict()
100 branch_data = OrderedDict()
101 for obj in data['push']['branches']:
101 for obj in data['push']['branches']:
102 branch_data[obj['name']] = obj
102 branch_data[obj['name']] = obj
103
103
104 branches_commits = OrderedDict()
104 branches_commits = OrderedDict()
105 for commit in data['push']['commits']:
105 for commit in data['push']['commits']:
106 if commit.get('git_ref_change'):
106 if commit.get('git_ref_change'):
107 # special case for GIT that allows creating tags,
107 # special case for GIT that allows creating tags,
108 # deleting branches without associated commit
108 # deleting branches without associated commit
109 continue
109 continue
110
110
111 if commit['branch'] not in branches_commits:
111 if commit['branch'] not in branches_commits:
112 branch_commits = {'branch': branch_data[commit['branch']],
112 branch_commits = {'branch': branch_data[commit['branch']],
113 'commits': []}
113 'commits': []}
114 branches_commits[commit['branch']] = branch_commits
114 branches_commits[commit['branch']] = branch_commits
115
115
116 branch_commits = branches_commits[commit['branch']]
116 branch_commits = branches_commits[commit['branch']]
117 branch_commits['commits'].append(commit)
117 branch_commits['commits'].append(commit)
118
118
119 if '${branch}' in url:
119 if '${branch}' in url:
120 # call it multiple times, for each branch if used in variables
120 # call it multiple times, for each branch if used in variables
121 for branch, commit_ids in branches_commits.items():
121 for branch, commit_ids in branches_commits.items():
122 branch_url = string.Template(url).safe_substitute(branch=branch)
122 branch_url = string.Template(url).safe_substitute(branch=branch)
123 # call further down for each commit if used
123 # call further down for each commit if used
124 if '${commit_id}' in branch_url:
124 if '${commit_id}' in branch_url:
125 for commit_data in commit_ids['commits']:
125 for commit_data in commit_ids['commits']:
126 commit_id = commit_data['raw_id']
126 commit_id = commit_data['raw_id']
127 commit_url = string.Template(branch_url).safe_substitute(
127 commit_url = string.Template(branch_url).safe_substitute(
128 commit_id=commit_id)
128 commit_id=commit_id)
129 # register per-commit call
129 # register per-commit call
130 log.debug(
130 log.debug(
131 'register webhook call(%s) to url %s', event, commit_url)
131 'register webhook call(%s) to url %s', event, commit_url)
132 url_cals.append((commit_url, self.secret_token, self.headers, data))
132 url_cals.append((commit_url, self.secret_token, self.headers, data))
133
133
134 else:
134 else:
135 # register per-branch call
135 # register per-branch call
136 log.debug(
136 log.debug(
137 'register webhook call(%s) to url %s', event, branch_url)
137 'register webhook call(%s) to url %s', event, branch_url)
138 url_cals.append((branch_url, self.secret_token, self.headers, data))
138 url_cals.append((branch_url, self.secret_token, self.headers, data))
139
139
140 else:
140 else:
141 log.debug(
141 log.debug(
142 'register webhook call(%s) to url %s', event, url)
142 'register webhook call(%s) to url %s', event, url)
143 url_cals.append((url, self.secret_token, self.headers, data))
143 url_cals.append((url, self.secret_token, self.headers, data))
144
144
145 return url_cals
145 return url_cals
146
146
147 def repo_create_event_handler(self, event, data):
147 def repo_create_event_handler(self, event, data):
148 url = self.get_base_parsed_template(data)
148 url = self.get_base_parsed_template(data)
149 log.debug(
149 log.debug(
150 'register webhook call(%s) to url %s', event, url)
150 'register webhook call(%s) to url %s', event, url)
151 return [(url, self.secret_token, self.headers, data)]
151 return [(url, self.secret_token, self.headers, data)]
152
152
153 def pull_request_event_handler(self, event, data):
153 def pull_request_event_handler(self, event, data):
154 url = self.get_base_parsed_template(data)
154 url = self.get_base_parsed_template(data)
155 log.debug(
155 log.debug(
156 'register webhook call(%s) to url %s', event, url)
156 'register webhook call(%s) to url %s', event, url)
157 url = string.Template(url).safe_substitute(
157 url = string.Template(url).safe_substitute(
158 pull_request_id=data['pullrequest']['pull_request_id'],
158 pull_request_id=data['pullrequest']['pull_request_id'],
159 pull_request_url=data['pullrequest']['url'])
159 pull_request_url=data['pullrequest']['url'])
160 return [(url, self.secret_token, self.headers, data)]
160 return [(url, self.secret_token, self.headers, data)]
161
161
162 def __call__(self, event, data):
162 def __call__(self, event, data):
163 if isinstance(event, events.RepoPushEvent):
163 if isinstance(event, events.RepoPushEvent):
164 return self.repo_push_event_handler(event, data)
164 return self.repo_push_event_handler(event, data)
165 elif isinstance(event, events.RepoCreateEvent):
165 elif isinstance(event, events.RepoCreateEvent):
166 return self.repo_create_event_handler(event, data)
166 return self.repo_create_event_handler(event, data)
167 elif isinstance(event, events.PullRequestEvent):
167 elif isinstance(event, events.PullRequestEvent):
168 return self.pull_request_event_handler(event, data)
168 return self.pull_request_event_handler(event, data)
169 else:
169 else:
170 raise ValueError('event type not supported: %s' % events)
170 raise ValueError('event type not supported: %s' % events)
171
171
172
172
173 class WebhookSettingsSchema(colander.Schema):
173 class WebhookSettingsSchema(colander.Schema):
174 url = colander.SchemaNode(
174 url = colander.SchemaNode(
175 colander.String(),
175 colander.String(),
176 title=_('Webhook URL'),
176 title=_('Webhook URL'),
177 description=
177 description=
178 _('URL to which Webhook should submit data. Following variables '
178 _('URL to which Webhook should submit data. Following variables '
179 'are allowed to be used: {vars}. Some of the variables would '
179 'are allowed to be used: {vars}. Some of the variables would '
180 'trigger multiple calls, like ${{branch}} or ${{commit_id}}. '
180 'trigger multiple calls, like ${{branch}} or ${{commit_id}}. '
181 'Webhook will be called as many times as unique objects in '
181 'Webhook will be called as many times as unique objects in '
182 'data in such cases.').format(vars=URL_VARS),
182 'data in such cases.').format(vars=URL_VARS),
183 missing=colander.required,
183 missing=colander.required,
184 required=True,
184 required=True,
185 validator=colander.url,
185 validator=colander.url,
186 widget=deform.widget.TextInputWidget(
186 widget=deform.widget.TextInputWidget(
187 placeholder='https://www.example.com/webhook'
187 placeholder='https://www.example.com/webhook'
188 ),
188 ),
189 )
189 )
190 secret_token = colander.SchemaNode(
190 secret_token = colander.SchemaNode(
191 colander.String(),
191 colander.String(),
192 title=_('Secret Token'),
192 title=_('Secret Token'),
193 description=_('Optional string used to validate received payloads. '
193 description=_('Optional string used to validate received payloads. '
194 'It will be sent together with event data in JSON'),
194 'It will be sent together with event data in JSON'),
195 default='',
195 default='',
196 missing='',
196 missing='',
197 widget=deform.widget.TextInputWidget(
197 widget=deform.widget.TextInputWidget(
198 placeholder='e.g. secret_token'
198 placeholder='e.g. secret_token'
199 ),
199 ),
200 )
200 )
201 username = colander.SchemaNode(
201 username = colander.SchemaNode(
202 colander.String(),
202 colander.String(),
203 title=_('Username'),
203 title=_('Username'),
204 description=_('Optional username to authenticate the call.'),
204 description=_('Optional username to authenticate the call.'),
205 default='',
205 default='',
206 missing='',
206 missing='',
207 widget=deform.widget.TextInputWidget(
207 widget=deform.widget.TextInputWidget(
208 placeholder='e.g. admin'
208 placeholder='e.g. admin'
209 ),
209 ),
210 )
210 )
211 password = colander.SchemaNode(
211 password = colander.SchemaNode(
212 colander.String(),
212 colander.String(),
213 title=_('Password'),
213 title=_('Password'),
214 description=_('Optional password to authenticate the call.'),
214 description=_('Optional password to authenticate the call.'),
215 default='',
215 default='',
216 missing='',
216 missing='',
217 widget=deform.widget.PasswordWidget(
217 widget=deform.widget.PasswordWidget(
218 placeholder='e.g. secret.',
218 placeholder='e.g. secret.',
219 redisplay=True,
219 redisplay=True,
220 ),
220 ),
221 )
221 )
222 custom_header_key = colander.SchemaNode(
222 custom_header_key = colander.SchemaNode(
223 colander.String(),
223 colander.String(),
224 title=_('Custom Header Key'),
224 title=_('Custom Header Key'),
225 description=_('Custom Header name to be set when calling endpoint.'),
225 description=_('Custom Header name to be set when calling endpoint.'),
226 default='',
226 default='',
227 missing='',
227 missing='',
228 widget=deform.widget.TextInputWidget(
228 widget=deform.widget.TextInputWidget(
229 placeholder='e.g.Authorization'
229 placeholder='e.g.Authorization'
230 ),
230 ),
231 )
231 )
232 custom_header_val = colander.SchemaNode(
232 custom_header_val = colander.SchemaNode(
233 colander.String(),
233 colander.String(),
234 title=_('Custom Header Value'),
234 title=_('Custom Header Value'),
235 description=_('Custom Header value to be set when calling endpoint.'),
235 description=_('Custom Header value to be set when calling endpoint.'),
236 default='',
236 default='',
237 missing='',
237 missing='',
238 widget=deform.widget.TextInputWidget(
238 widget=deform.widget.TextInputWidget(
239 placeholder='e.g. RcLogin auth=xxxx'
239 placeholder='e.g. RcLogin auth=xxxx'
240 ),
240 ),
241 )
241 )
242 method_type = colander.SchemaNode(
242 method_type = colander.SchemaNode(
243 colander.String(),
243 colander.String(),
244 title=_('Call Method'),
244 title=_('Call Method'),
245 description=_('Select if the Webhook call should be made '
245 description=_('Select if the Webhook call should be made '
246 'with POST or GET.'),
246 'with POST or GET.'),
247 default='post',
247 default='post',
248 missing='',
248 missing='',
249 widget=deform.widget.RadioChoiceWidget(
249 widget=deform.widget.RadioChoiceWidget(
250 values=[('get', 'GET'), ('post', 'POST')],
250 values=[('get', 'GET'), ('post', 'POST')],
251 inline=True
251 inline=True
252 ),
252 ),
253 )
253 )
254
254
255
255
256 class WebhookIntegrationType(IntegrationTypeBase):
256 class WebhookIntegrationType(IntegrationTypeBase):
257 key = 'webhook'
257 key = 'webhook'
258 display_name = _('Webhook')
258 display_name = _('Webhook')
259 description = _('Post json events to a Webhook endpoint')
259 description = _('Post json events to a Webhook endpoint')
260
260
261 @classmethod
261 @classmethod
262 def icon(cls):
262 def icon(cls):
263 return '''<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 256 239" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid"><g><path d="M119.540432,100.502743 C108.930124,118.338815 98.7646301,135.611455 88.3876025,152.753617 C85.7226696,157.154315 84.4040417,160.738531 86.5332204,166.333309 C92.4107024,181.787152 84.1193605,196.825836 68.5350381,200.908244 C53.8383677,204.759349 39.5192953,195.099955 36.6032893,179.365384 C34.0194114,165.437749 44.8274148,151.78491 60.1824106,149.608284 C61.4694072,149.424428 62.7821041,149.402681 64.944891,149.240571 C72.469175,136.623655 80.1773157,123.700312 88.3025935,110.073173 C73.611854,95.4654658 64.8677898,78.3885437 66.803227,57.2292132 C68.1712787,42.2715849 74.0527146,29.3462646 84.8033863,18.7517722 C105.393354,-1.53572199 136.805164,-4.82141828 161.048542,10.7510424 C184.333097,25.7086706 194.996783,54.8450075 185.906752,79.7822957 C179.052655,77.9239597 172.151111,76.049808 164.563565,73.9917997 C167.418285,60.1274266 165.306899,47.6765751 155.95591,37.0109123 C149.777932,29.9690049 141.850349,26.2780332 132.835442,24.9178894 C114.764113,22.1877169 97.0209573,33.7983633 91.7563309,51.5355878 C85.7800012,71.6669027 94.8245623,88.1111998 119.540432,100.502743 L119.540432,100.502743 Z" fill="#C73A63"></path><path d="M149.841194,79.4106285 C157.316054,92.5969067 164.905578,105.982857 172.427885,119.246236 C210.44865,107.483365 239.114472,128.530009 249.398582,151.063322 C261.81978,178.282014 253.328765,210.520191 228.933162,227.312431 C203.893073,244.551464 172.226236,241.605803 150.040866,219.46195 C155.694953,214.729124 161.376716,209.974552 167.44794,204.895759 C189.360489,219.088306 208.525074,218.420096 222.753207,201.614016 C234.885769,187.277151 234.622834,165.900356 222.138374,151.863988 C207.730339,135.66681 188.431321,135.172572 165.103273,150.721309 C155.426087,133.553447 145.58086,116.521995 136.210101,99.2295848 C133.05093,93.4015266 129.561608,90.0209366 122.440622,88.7873178 C110.547271,86.7253555 102.868785,76.5124151 102.408155,65.0698097 C101.955433,53.7537294 108.621719,43.5249733 119.04224,39.5394355 C129.363912,35.5914599 141.476705,38.7783085 148.419765,47.554004 C154.093621,54.7244134 155.896602,62.7943365 152.911402,71.6372484 C152.081082,74.1025091 151.00562,76.4886916 149.841194,79.4106285 L149.841194,79.4106285 Z" fill="#4B4B4B"></path><path d="M167.706921,187.209935 L121.936499,187.209935 C117.54964,205.253587 108.074103,219.821756 91.7464461,229.085759 C79.0544063,236.285822 65.3738898,238.72736 50.8136292,236.376762 C24.0061432,232.053165 2.08568567,207.920497 0.156179306,180.745298 C-2.02835403,149.962159 19.1309765,122.599149 47.3341915,116.452801 C49.2814904,123.524363 51.2485589,130.663141 53.1958579,137.716911 C27.3195169,150.919004 18.3639187,167.553089 25.6054984,188.352614 C31.9811726,206.657224 50.0900643,216.690262 69.7528413,212.809503 C89.8327554,208.847688 99.9567329,192.160226 98.7211371,165.37844 C117.75722,165.37844 136.809118,165.180745 155.847178,165.475311 C163.280522,165.591951 169.019617,164.820939 174.620326,158.267339 C183.840836,147.48306 200.811003,148.455721 210.741239,158.640984 C220.88894,169.049642 220.402609,185.79839 209.663799,195.768166 C199.302587,205.38802 182.933414,204.874012 173.240413,194.508846 C171.247644,192.37176 169.677943,189.835329 167.706921,187.209935 L167.706921,187.209935 Z" fill="#4A4A4A"></path></g></svg>'''
263 return '''<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 256 239" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid"><g><path d="M119.540432,100.502743 C108.930124,118.338815 98.7646301,135.611455 88.3876025,152.753617 C85.7226696,157.154315 84.4040417,160.738531 86.5332204,166.333309 C92.4107024,181.787152 84.1193605,196.825836 68.5350381,200.908244 C53.8383677,204.759349 39.5192953,195.099955 36.6032893,179.365384 C34.0194114,165.437749 44.8274148,151.78491 60.1824106,149.608284 C61.4694072,149.424428 62.7821041,149.402681 64.944891,149.240571 C72.469175,136.623655 80.1773157,123.700312 88.3025935,110.073173 C73.611854,95.4654658 64.8677898,78.3885437 66.803227,57.2292132 C68.1712787,42.2715849 74.0527146,29.3462646 84.8033863,18.7517722 C105.393354,-1.53572199 136.805164,-4.82141828 161.048542,10.7510424 C184.333097,25.7086706 194.996783,54.8450075 185.906752,79.7822957 C179.052655,77.9239597 172.151111,76.049808 164.563565,73.9917997 C167.418285,60.1274266 165.306899,47.6765751 155.95591,37.0109123 C149.777932,29.9690049 141.850349,26.2780332 132.835442,24.9178894 C114.764113,22.1877169 97.0209573,33.7983633 91.7563309,51.5355878 C85.7800012,71.6669027 94.8245623,88.1111998 119.540432,100.502743 L119.540432,100.502743 Z" fill="#C73A63"></path><path d="M149.841194,79.4106285 C157.316054,92.5969067 164.905578,105.982857 172.427885,119.246236 C210.44865,107.483365 239.114472,128.530009 249.398582,151.063322 C261.81978,178.282014 253.328765,210.520191 228.933162,227.312431 C203.893073,244.551464 172.226236,241.605803 150.040866,219.46195 C155.694953,214.729124 161.376716,209.974552 167.44794,204.895759 C189.360489,219.088306 208.525074,218.420096 222.753207,201.614016 C234.885769,187.277151 234.622834,165.900356 222.138374,151.863988 C207.730339,135.66681 188.431321,135.172572 165.103273,150.721309 C155.426087,133.553447 145.58086,116.521995 136.210101,99.2295848 C133.05093,93.4015266 129.561608,90.0209366 122.440622,88.7873178 C110.547271,86.7253555 102.868785,76.5124151 102.408155,65.0698097 C101.955433,53.7537294 108.621719,43.5249733 119.04224,39.5394355 C129.363912,35.5914599 141.476705,38.7783085 148.419765,47.554004 C154.093621,54.7244134 155.896602,62.7943365 152.911402,71.6372484 C152.081082,74.1025091 151.00562,76.4886916 149.841194,79.4106285 L149.841194,79.4106285 Z" fill="#4B4B4B"></path><path d="M167.706921,187.209935 L121.936499,187.209935 C117.54964,205.253587 108.074103,219.821756 91.7464461,229.085759 C79.0544063,236.285822 65.3738898,238.72736 50.8136292,236.376762 C24.0061432,232.053165 2.08568567,207.920497 0.156179306,180.745298 C-2.02835403,149.962159 19.1309765,122.599149 47.3341915,116.452801 C49.2814904,123.524363 51.2485589,130.663141 53.1958579,137.716911 C27.3195169,150.919004 18.3639187,167.553089 25.6054984,188.352614 C31.9811726,206.657224 50.0900643,216.690262 69.7528413,212.809503 C89.8327554,208.847688 99.9567329,192.160226 98.7211371,165.37844 C117.75722,165.37844 136.809118,165.180745 155.847178,165.475311 C163.280522,165.591951 169.019617,164.820939 174.620326,158.267339 C183.840836,147.48306 200.811003,148.455721 210.741239,158.640984 C220.88894,169.049642 220.402609,185.79839 209.663799,195.768166 C199.302587,205.38802 182.933414,204.874012 173.240413,194.508846 C171.247644,192.37176 169.677943,189.835329 167.706921,187.209935 L167.706921,187.209935 Z" fill="#4A4A4A"></path></g></svg>'''
264
264
265 valid_events = [
265 valid_events = [
266 events.PullRequestCloseEvent,
266 events.PullRequestCloseEvent,
267 events.PullRequestMergeEvent,
267 events.PullRequestMergeEvent,
268 events.PullRequestUpdateEvent,
268 events.PullRequestUpdateEvent,
269 events.PullRequestCommentEvent,
269 events.PullRequestCommentEvent,
270 events.PullRequestReviewEvent,
270 events.PullRequestReviewEvent,
271 events.PullRequestCreateEvent,
271 events.PullRequestCreateEvent,
272 events.RepoPushEvent,
272 events.RepoPushEvent,
273 events.RepoCreateEvent,
273 events.RepoCreateEvent,
274 ]
274 ]
275
275
276 def settings_schema(self):
276 def settings_schema(self):
277 schema = WebhookSettingsSchema()
277 schema = WebhookSettingsSchema()
278 schema.add(colander.SchemaNode(
278 schema.add(colander.SchemaNode(
279 colander.Set(),
279 colander.Set(),
280 widget=deform.widget.CheckboxChoiceWidget(
280 widget=deform.widget.CheckboxChoiceWidget(
281 values=sorted(
281 values=sorted(
282 [(e.name, e.display_name) for e in self.valid_events]
282 [(e.name, e.display_name) for e in self.valid_events]
283 )
283 )
284 ),
284 ),
285 description="Events activated for this integration",
285 description="Events activated for this integration",
286 name='events'
286 name='events'
287 ))
287 ))
288 return schema
288 return schema
289
289
290 def send_event(self, event):
290 def send_event(self, event):
291 log.debug('handling event %s with Webhook integration %s',
291 log.debug('handling event %s with Webhook integration %s',
292 event.name, self)
292 event.name, self)
293
293
294 if event.__class__ not in self.valid_events:
294 if event.__class__ not in self.valid_events:
295 log.debug('event not valid: %r' % event)
295 log.debug('event not valid: %r' % event)
296 return
296 return
297
297
298 if event.name not in self.settings['events']:
298 if event.name not in self.settings['events']:
299 log.debug('event ignored: %r' % event)
299 log.debug('event ignored: %r' % event)
300 return
300 return
301
301
302 data = event.as_dict()
302 data = event.as_dict()
303 template_url = self.settings['url']
303 template_url = self.settings['url']
304
304
305 headers = {}
305 headers = {}
306 head_key = self.settings.get('custom_header_key')
306 head_key = self.settings.get('custom_header_key')
307 head_val = self.settings.get('custom_header_val')
307 head_val = self.settings.get('custom_header_val')
308 if head_key and head_val:
308 if head_key and head_val:
309 headers = {head_key: head_val}
309 headers = {head_key: head_val}
310
310
311 handler = WebhookHandler(
311 handler = WebhookHandler(
312 template_url, self.settings['secret_token'], headers)
312 template_url, self.settings['secret_token'], headers)
313
313
314 url_calls = handler(event, data)
314 url_calls = handler(event, data)
315 log.debug('webhook: calling following urls: %s',
315 log.debug('webhook: calling following urls: %s',
316 [x[0] for x in url_calls])
316 [x[0] for x in url_calls])
317
317
318 run_task(post_to_webhook, url_calls, self.settings)
318 run_task(post_to_webhook, url_calls, self.settings)
319
319
320
320
321 @async_task(ignore_result=True, base=RequestContextTask)
321 @async_task(ignore_result=True, base=RequestContextTask)
322 def post_to_webhook(url_calls, settings):
322 def post_to_webhook(url_calls, settings):
323 """
323 """
324 Example data::
324 Example data::
325
325
326 {'actor': {'user_id': 2, 'username': u'admin'},
326 {'actor': {'user_id': 2, 'username': u'admin'},
327 'actor_ip': u'192.168.157.1',
327 'actor_ip': u'192.168.157.1',
328 'name': 'repo-push',
328 'name': 'repo-push',
329 'push': {'branches': [{'name': u'default',
329 'push': {'branches': [{'name': u'default',
330 'url': 'http://rc.local:8080/hg-repo/changelog?branch=default'}],
330 'url': 'http://rc.local:8080/hg-repo/changelog?branch=default'}],
331 'commits': [{'author': u'Marcin Kuzminski <marcin@rhodecode.com>',
331 'commits': [{'author': u'Marcin Kuzminski <marcin@rhodecode.com>',
332 'branch': u'default',
332 'branch': u'default',
333 'date': datetime.datetime(2017, 11, 30, 12, 59, 48),
333 'date': datetime.datetime(2017, 11, 30, 12, 59, 48),
334 'issues': [],
334 'issues': [],
335 'mentions': [],
335 'mentions': [],
336 'message': u'commit Thu 30 Nov 2017 13:59:48 CET',
336 'message': u'commit Thu 30 Nov 2017 13:59:48 CET',
337 'message_html': u'commit Thu 30 Nov 2017 13:59:48 CET',
337 'message_html': u'commit Thu 30 Nov 2017 13:59:48 CET',
338 'message_html_title': u'commit Thu 30 Nov 2017 13:59:48 CET',
338 'message_html_title': u'commit Thu 30 Nov 2017 13:59:48 CET',
339 'parents': [{'raw_id': '431b772a5353dad9974b810dd3707d79e3a7f6e0'}],
339 'parents': [{'raw_id': '431b772a5353dad9974b810dd3707d79e3a7f6e0'}],
340 'permalink_url': u'http://rc.local:8080/_7/changeset/a815cc738b9651eb5ffbcfb1ce6ccd7c701a5ddf',
340 'permalink_url': u'http://rc.local:8080/_7/changeset/a815cc738b9651eb5ffbcfb1ce6ccd7c701a5ddf',
341 'raw_id': 'a815cc738b9651eb5ffbcfb1ce6ccd7c701a5ddf',
341 'raw_id': 'a815cc738b9651eb5ffbcfb1ce6ccd7c701a5ddf',
342 'refs': {'bookmarks': [], 'branches': [u'default'], 'tags': [u'tip']},
342 'refs': {'bookmarks': [], 'branches': [u'default'], 'tags': [u'tip']},
343 'reviewers': [],
343 'reviewers': [],
344 'revision': 9L,
344 'revision': 9L,
345 'short_id': 'a815cc738b96',
345 'short_id': 'a815cc738b96',
346 'url': u'http://rc.local:8080/hg-repo/changeset/a815cc738b9651eb5ffbcfb1ce6ccd7c701a5ddf'}],
346 'url': u'http://rc.local:8080/hg-repo/changeset/a815cc738b9651eb5ffbcfb1ce6ccd7c701a5ddf'}],
347 'issues': {}},
347 'issues': {}},
348 'repo': {'extra_fields': '',
348 'repo': {'extra_fields': '',
349 'permalink_url': u'http://rc.local:8080/_7',
349 'permalink_url': u'http://rc.local:8080/_7',
350 'repo_id': 7,
350 'repo_id': 7,
351 'repo_name': u'hg-repo',
351 'repo_name': u'hg-repo',
352 'repo_type': u'hg',
352 'repo_type': u'hg',
353 'url': u'http://rc.local:8080/hg-repo'},
353 'url': u'http://rc.local:8080/hg-repo'},
354 'server_url': u'http://rc.local:8080',
354 'server_url': u'http://rc.local:8080',
355 'utc_timestamp': datetime.datetime(2017, 11, 30, 13, 0, 1, 569276)
355 'utc_timestamp': datetime.datetime(2017, 11, 30, 13, 0, 1, 569276)
356
356
357 """
357 """
358 max_retries = 3
358 max_retries = 3
359 retries = Retry(
359 retries = Retry(
360 total=max_retries,
360 total=max_retries,
361 backoff_factor=0.15,
361 backoff_factor=0.15,
362 status_forcelist=[500, 502, 503, 504])
362 status_forcelist=[500, 502, 503, 504])
363 call_headers = {
363 call_headers = {
364 'User-Agent': 'RhodeCode-webhook-caller/{}'.format(
364 'User-Agent': 'RhodeCode-webhook-caller/{}'.format(
365 rhodecode.__version__)
365 rhodecode.__version__)
366 } # updated below with custom ones, allows override
366 } # updated below with custom ones, allows override
367
367
368 for url, token, headers, data in url_calls:
368 for url, token, headers, data in url_calls:
369 req_session = requests.Session()
369 req_session = requests.Session()
370 req_session.mount( # retry max N times
370 req_session.mount( # retry max N times
371 'http://', requests.adapters.HTTPAdapter(max_retries=retries))
371 'http://', requests.adapters.HTTPAdapter(max_retries=retries))
372
372
373 method = settings.get('method_type') or 'post'
373 method = settings.get('method_type') or 'post'
374 call_method = getattr(req_session, method)
374 call_method = getattr(req_session, method)
375
375
376 headers = headers or {}
376 headers = headers or {}
377 call_headers.update(headers)
377 call_headers.update(headers)
378 auth = get_auth(settings)
378 auth = get_auth(settings)
379
379
380 log.debug('calling Webhook with method: %s, and auth:%s',
380 log.debug('calling Webhook with method: %s, and auth:%s',
381 call_method, auth)
381 call_method, auth)
382 if settings.get('log_data'):
382 if settings.get('log_data'):
383 log.debug('calling webhook with data: %s', data)
383 log.debug('calling webhook with data: %s', data)
384 resp = call_method(url, json={
384 resp = call_method(url, json={
385 'token': token,
385 'token': token,
386 'event': data
386 'event': data
387 }, headers=call_headers, auth=auth)
387 }, headers=call_headers, auth=auth)
388 log.debug('Got Webhook response: %s', resp)
388 log.debug('Got Webhook response: %s', resp)
389
389
390 resp.raise_for_status() # raise exception on a failed request
390 try:
391 resp.raise_for_status() # raise exception on a failed request
392 except Exception:
393 log.error(resp.text)
394 raise
General Comments 0
You need to be logged in to leave comments. Login now