##// END OF EJS Templates
integrations: webhook, allow to set a custom header. Fixes #5384
marcink -
r2086:d7985951 default
parent child Browse files
Show More
@@ -1,276 +1,316 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2012-2017 RhodeCode GmbH
3 # Copyright (C) 2012-2017 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 logging
26 import logging
27 import requests
27 import requests
28 import colander
28 import colander
29 from celery.task import task
29 from celery.task import task
30 from requests.packages.urllib3.util.retry import Retry
30 from requests.packages.urllib3.util.retry import Retry
31
31
32 import rhodecode
32 from rhodecode import events
33 from rhodecode import events
33 from rhodecode.translation import _
34 from rhodecode.translation import _
34 from rhodecode.integrations.types.base import IntegrationTypeBase
35 from rhodecode.integrations.types.base import IntegrationTypeBase
35
36
36 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
37
38
38 # updating this required to update the `common_vars` passed in url calling func
39 # updating this required to update the `common_vars` passed in url calling func
39 WEBHOOK_URL_VARS = [
40 WEBHOOK_URL_VARS = [
40 'repo_name',
41 'repo_name',
41 'repo_type',
42 'repo_type',
42 'repo_id',
43 'repo_id',
43 'repo_url',
44 'repo_url',
44 # extra repo fields
45 # extra repo fields
45 'extra:<extra_key_name>',
46 'extra:<extra_key_name>',
46
47
47 # special attrs below that we handle, using multi-call
48 # special attrs below that we handle, using multi-call
48 'branch',
49 'branch',
49 'commit_id',
50 'commit_id',
50
51
51 # pr events vars
52 # pr events vars
52 'pull_request_id',
53 'pull_request_id',
53 'pull_request_url',
54 'pull_request_url',
54
55
55 # user who triggers the call
56 # user who triggers the call
56 'username',
57 'username',
57 'user_id',
58 'user_id',
58
59
59 ]
60 ]
60 URL_VARS = ', '.join('${' + x + '}' for x in WEBHOOK_URL_VARS)
61 URL_VARS = ', '.join('${' + x + '}' for x in WEBHOOK_URL_VARS)
61
62
62
63
63 class WebhookHandler(object):
64 class WebhookHandler(object):
64 def __init__(self, template_url, secret_token):
65 def __init__(self, template_url, secret_token, headers):
65 self.template_url = template_url
66 self.template_url = template_url
66 self.secret_token = secret_token
67 self.secret_token = secret_token
68 self.headers = headers
67
69
68 def get_base_parsed_template(self, data):
70 def get_base_parsed_template(self, data):
69 """
71 """
70 initially parses the passed in template with some common variables
72 initially parses the passed in template with some common variables
71 available on ALL calls
73 available on ALL calls
72 """
74 """
73 # note: make sure to update the `WEBHOOK_URL_VARS` if this changes
75 # note: make sure to update the `WEBHOOK_URL_VARS` if this changes
74 common_vars = {
76 common_vars = {
75 'repo_name': data['repo']['repo_name'],
77 'repo_name': data['repo']['repo_name'],
76 'repo_type': data['repo']['repo_type'],
78 'repo_type': data['repo']['repo_type'],
77 'repo_id': data['repo']['repo_id'],
79 'repo_id': data['repo']['repo_id'],
78 'repo_url': data['repo']['url'],
80 'repo_url': data['repo']['url'],
79 'username': data['actor']['username'],
81 'username': data['actor']['username'],
80 'user_id': data['actor']['user_id']
82 'user_id': data['actor']['user_id']
81 }
83 }
82 extra_vars = {}
84 extra_vars = {}
83 for extra_key, extra_val in data['repo']['extra_fields'].items():
85 for extra_key, extra_val in data['repo']['extra_fields'].items():
84 extra_vars['extra:{}'.format(extra_key)] = extra_val
86 extra_vars['extra:{}'.format(extra_key)] = extra_val
85 common_vars.update(extra_vars)
87 common_vars.update(extra_vars)
86
88
87 return string.Template(
89 return string.Template(
88 self.template_url).safe_substitute(**common_vars)
90 self.template_url).safe_substitute(**common_vars)
89
91
90 def repo_push_event_handler(self, event, data):
92 def repo_push_event_handler(self, event, data):
91 url = self.get_base_parsed_template(data)
93 url = self.get_base_parsed_template(data)
92 url_cals = []
94 url_cals = []
93 branch_data = OrderedDict()
95 branch_data = OrderedDict()
94 for obj in data['push']['branches']:
96 for obj in data['push']['branches']:
95 branch_data[obj['name']] = obj
97 branch_data[obj['name']] = obj
96
98
97 branches_commits = OrderedDict()
99 branches_commits = OrderedDict()
98 for commit in data['push']['commits']:
100 for commit in data['push']['commits']:
99 if commit['branch'] not in branches_commits:
101 if commit['branch'] not in branches_commits:
100 branch_commits = {'branch': branch_data[commit['branch']],
102 branch_commits = {'branch': branch_data[commit['branch']],
101 'commits': []}
103 'commits': []}
102 branches_commits[commit['branch']] = branch_commits
104 branches_commits[commit['branch']] = branch_commits
103
105
104 branch_commits = branches_commits[commit['branch']]
106 branch_commits = branches_commits[commit['branch']]
105 branch_commits['commits'].append(commit)
107 branch_commits['commits'].append(commit)
106
108
107 if '${branch}' in url:
109 if '${branch}' in url:
108 # call it multiple times, for each branch if used in variables
110 # call it multiple times, for each branch if used in variables
109 for branch, commit_ids in branches_commits.items():
111 for branch, commit_ids in branches_commits.items():
110 branch_url = string.Template(url).safe_substitute(branch=branch)
112 branch_url = string.Template(url).safe_substitute(branch=branch)
111 # call further down for each commit if used
113 # call further down for each commit if used
112 if '${commit_id}' in branch_url:
114 if '${commit_id}' in branch_url:
113 for commit_data in commit_ids['commits']:
115 for commit_data in commit_ids['commits']:
114 commit_id = commit_data['raw_id']
116 commit_id = commit_data['raw_id']
115 commit_url = string.Template(branch_url).safe_substitute(
117 commit_url = string.Template(branch_url).safe_substitute(
116 commit_id=commit_id)
118 commit_id=commit_id)
117 # register per-commit call
119 # register per-commit call
118 log.debug(
120 log.debug(
119 'register webhook call(%s) to url %s', event, commit_url)
121 'register webhook call(%s) to url %s', event, commit_url)
120 url_cals.append((commit_url, self.secret_token, data))
122 url_cals.append((commit_url, self.secret_token, self.headers, data))
121
123
122 else:
124 else:
123 # register per-branch call
125 # register per-branch call
124 log.debug(
126 log.debug(
125 'register webhook call(%s) to url %s', event, branch_url)
127 'register webhook call(%s) to url %s', event, branch_url)
126 url_cals.append((branch_url, self.secret_token, data))
128 url_cals.append((branch_url, self.secret_token, self.headers, data))
127
129
128 else:
130 else:
129 log.debug(
131 log.debug(
130 'register webhook call(%s) to url %s', event, url)
132 'register webhook call(%s) to url %s', event, url)
131 url_cals.append((url, self.secret_token, data))
133 url_cals.append((url, self.secret_token, self.headers, data))
132
134
133 return url_cals
135 return url_cals
134
136
135 def repo_create_event_handler(self, event, data):
137 def repo_create_event_handler(self, event, data):
136 url = self.get_base_parsed_template(data)
138 url = self.get_base_parsed_template(data)
137 log.debug(
139 log.debug(
138 'register webhook call(%s) to url %s', event, url)
140 'register webhook call(%s) to url %s', event, url)
139 return [(url, self.secret_token, data)]
141 return [(url, self.secret_token, self.headers, data)]
140
142
141 def pull_request_event_handler(self, event, data):
143 def pull_request_event_handler(self, event, data):
142 url = self.get_base_parsed_template(data)
144 url = self.get_base_parsed_template(data)
143 log.debug(
145 log.debug(
144 'register webhook call(%s) to url %s', event, url)
146 'register webhook call(%s) to url %s', event, url)
145 url = string.Template(url).safe_substitute(
147 url = string.Template(url).safe_substitute(
146 pull_request_id=data['pullrequest']['pull_request_id'],
148 pull_request_id=data['pullrequest']['pull_request_id'],
147 pull_request_url=data['pullrequest']['url'])
149 pull_request_url=data['pullrequest']['url'])
148 return [(url, self.secret_token, data)]
150 return [(url, self.secret_token, self.headers, data)]
149
151
150 def __call__(self, event, data):
152 def __call__(self, event, data):
151 if isinstance(event, events.RepoPushEvent):
153 if isinstance(event, events.RepoPushEvent):
152 return self.repo_push_event_handler(event, data)
154 return self.repo_push_event_handler(event, data)
153 elif isinstance(event, events.RepoCreateEvent):
155 elif isinstance(event, events.RepoCreateEvent):
154 return self.repo_create_event_handler(event, data)
156 return self.repo_create_event_handler(event, data)
155 elif isinstance(event, events.PullRequestEvent):
157 elif isinstance(event, events.PullRequestEvent):
156 return self.pull_request_event_handler(event, data)
158 return self.pull_request_event_handler(event, data)
157 else:
159 else:
158 raise ValueError('event type not supported: %s' % events)
160 raise ValueError('event type not supported: %s' % events)
159
161
160
162
161 class WebhookSettingsSchema(colander.Schema):
163 class WebhookSettingsSchema(colander.Schema):
162 url = colander.SchemaNode(
164 url = colander.SchemaNode(
163 colander.String(),
165 colander.String(),
164 title=_('Webhook URL'),
166 title=_('Webhook URL'),
165 description=
167 description=
166 _('URL of the webhook to receive POST event. Following variables '
168 _('URL of the webhook to receive POST event. Following variables '
167 'are allowed to be used: {vars}. Some of the variables would '
169 'are allowed to be used: {vars}. Some of the variables would '
168 'trigger multiple calls, like ${{branch}} or ${{commit_id}}. '
170 'trigger multiple calls, like ${{branch}} or ${{commit_id}}. '
169 'Webhook will be called as many times as unique objects in '
171 'Webhook will be called as many times as unique objects in '
170 'data in such cases.').format(vars=URL_VARS),
172 'data in such cases.').format(vars=URL_VARS),
171 missing=colander.required,
173 missing=colander.required,
172 required=True,
174 required=True,
173 validator=colander.url,
175 validator=colander.url,
174 widget=deform.widget.TextInputWidget(
176 widget=deform.widget.TextInputWidget(
175 placeholder='https://www.example.com/webhook'
177 placeholder='https://www.example.com/webhook'
176 ),
178 ),
177 )
179 )
178 secret_token = colander.SchemaNode(
180 secret_token = colander.SchemaNode(
179 colander.String(),
181 colander.String(),
180 title=_('Secret Token'),
182 title=_('Secret Token'),
181 description=_('String used to validate received payloads.'),
183 description=_('String used to validate received payloads. It will be '
184 'sent together with event data in JSON'),
182 default='',
185 default='',
183 missing='',
186 missing='',
184 widget=deform.widget.TextInputWidget(
187 widget=deform.widget.TextInputWidget(
185 placeholder='secret_token'
188 placeholder='e.g. secret_token'
189 ),
190 )
191 custom_header_key = colander.SchemaNode(
192 colander.String(),
193 title=_('Custom Header Key'),
194 description=_('Custom Header name to be set when calling endpoint.'),
195 default='',
196 missing='',
197 widget=deform.widget.TextInputWidget(
198 placeholder='e.g.Authorization'
199 ),
200 )
201 custom_header_val = colander.SchemaNode(
202 colander.String(),
203 title=_('Custom Header Value'),
204 description=_('Custom Header value to be set when calling endpoint.'),
205 default='',
206 missing='',
207 widget=deform.widget.TextInputWidget(
208 placeholder='e.g. RcLogin auth=xxxx'
186 ),
209 ),
187 )
210 )
188 method_type = colander.SchemaNode(
211 method_type = colander.SchemaNode(
189 colander.String(),
212 colander.String(),
190 title=_('Call Method'),
213 title=_('Call Method'),
191 description=_('Select if the webhook call should be made '
214 description=_('Select if the webhook call should be made '
192 'with POST or GET.'),
215 'with POST or GET.'),
193 default='post',
216 default='post',
194 missing='',
217 missing='',
195 widget=deform.widget.RadioChoiceWidget(
218 widget=deform.widget.RadioChoiceWidget(
196 values=[('get', 'GET'), ('post', 'POST')],
219 values=[('get', 'GET'), ('post', 'POST')],
197 inline=True
220 inline=True
198 ),
221 ),
199 )
222 )
200
223
201
224
202 class WebhookIntegrationType(IntegrationTypeBase):
225 class WebhookIntegrationType(IntegrationTypeBase):
203 key = 'webhook'
226 key = 'webhook'
204 display_name = _('Webhook')
227 display_name = _('Webhook')
205 description = _('Post json events to a webhook endpoint')
228 description = _('Post json events to a webhook endpoint')
206 icon = '''<?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>'''
229 icon = '''<?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>'''
207
230
208 valid_events = [
231 valid_events = [
209 events.PullRequestCloseEvent,
232 events.PullRequestCloseEvent,
210 events.PullRequestMergeEvent,
233 events.PullRequestMergeEvent,
211 events.PullRequestUpdateEvent,
234 events.PullRequestUpdateEvent,
212 events.PullRequestCommentEvent,
235 events.PullRequestCommentEvent,
213 events.PullRequestReviewEvent,
236 events.PullRequestReviewEvent,
214 events.PullRequestCreateEvent,
237 events.PullRequestCreateEvent,
215 events.RepoPushEvent,
238 events.RepoPushEvent,
216 events.RepoCreateEvent,
239 events.RepoCreateEvent,
217 ]
240 ]
218
241
219 def settings_schema(self):
242 def settings_schema(self):
220 schema = WebhookSettingsSchema()
243 schema = WebhookSettingsSchema()
221 schema.add(colander.SchemaNode(
244 schema.add(colander.SchemaNode(
222 colander.Set(),
245 colander.Set(),
223 widget=deform.widget.CheckboxChoiceWidget(
246 widget=deform.widget.CheckboxChoiceWidget(
224 values=sorted(
247 values=sorted(
225 [(e.name, e.display_name) for e in self.valid_events]
248 [(e.name, e.display_name) for e in self.valid_events]
226 )
249 )
227 ),
250 ),
228 description="Events activated for this integration",
251 description="Events activated for this integration",
229 name='events'
252 name='events'
230 ))
253 ))
231 return schema
254 return schema
232
255
233 def send_event(self, event):
256 def send_event(self, event):
234 log.debug('handling event %s with webhook integration %s',
257 log.debug('handling event %s with webhook integration %s',
235 event.name, self)
258 event.name, self)
236
259
237 if event.__class__ not in self.valid_events:
260 if event.__class__ not in self.valid_events:
238 log.debug('event not valid: %r' % event)
261 log.debug('event not valid: %r' % event)
239 return
262 return
240
263
241 if event.name not in self.settings['events']:
264 if event.name not in self.settings['events']:
242 log.debug('event ignored: %r' % event)
265 log.debug('event ignored: %r' % event)
243 return
266 return
244
267
245 data = event.as_dict()
268 data = event.as_dict()
246 template_url = self.settings['url']
269 template_url = self.settings['url']
247
270
248 handler = WebhookHandler(template_url, self.settings['secret_token'])
271 headers = {}
272 head_key = self.settings['custom_header_key']
273 head_val = self.settings['custom_header_val']
274 if head_key and head_val:
275 headers = {head_key: head_val}
276
277 handler = WebhookHandler(
278 template_url, self.settings['secret_token'], headers)
279
249 url_calls = handler(event, data)
280 url_calls = handler(event, data)
250 log.debug('webhook: calling following urls: %s',
281 log.debug('webhook: calling following urls: %s',
251 [x[0] for x in url_calls])
282 [x[0] for x in url_calls])
252 post_to_webhook(url_calls, self.settings)
283 post_to_webhook(url_calls, self.settings)
253
284
254
285
255 @task(ignore_result=True)
286 @task(ignore_result=True)
256 def post_to_webhook(url_calls, settings):
287 def post_to_webhook(url_calls, settings):
257 max_retries = 3
288 max_retries = 3
258 retries = Retry(
289 retries = Retry(
259 total=max_retries,
290 total=max_retries,
260 backoff_factor=0.15,
291 backoff_factor=0.15,
261 status_forcelist=[500, 502, 503, 504])
292 status_forcelist=[500, 502, 503, 504])
262 for url, token, data in url_calls:
293 call_headers = {
294 'User-Agent': 'RhodeCode-webhook-caller/{}'.format(
295 rhodecode.__version__)
296 } # updated below with custom ones, allows override
297
298 for url, token, headers, data in url_calls:
263 req_session = requests.Session()
299 req_session = requests.Session()
264 req_session.mount( # retry max N times
300 req_session.mount( # retry max N times
265 'http://', requests.adapters.HTTPAdapter(max_retries=retries))
301 'http://', requests.adapters.HTTPAdapter(max_retries=retries))
266
302
267 method = settings.get('method_type') or 'post'
303 method = settings.get('method_type') or 'post'
268 call_method = getattr(req_session, method)
304 call_method = getattr(req_session, method)
269
305
306 headers = headers or {}
307 call_headers.update(headers)
308
270 log.debug('calling WEBHOOK with method: %s', call_method)
309 log.debug('calling WEBHOOK with method: %s', call_method)
271 resp = call_method(url, json={
310 resp = call_method(url, json={
272 'token': token,
311 'token': token,
273 'event': data
312 'event': data
274 })
313 }, headers=call_headers)
275 log.debug('Got WEBHOOK response: %s', resp)
314 log.debug('Got WEBHOOK response: %s', resp)
315
276 resp.raise_for_status() # raise exception on a failed request
316 resp.raise_for_status() # raise exception on a failed request
@@ -1,98 +1,111 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 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 import pytest
21 import pytest
22
22
23 from rhodecode import events
23 from rhodecode import events
24 from rhodecode.lib.utils2 import AttributeDict
24 from rhodecode.lib.utils2 import AttributeDict
25 from rhodecode.integrations.types.webhook import WebhookHandler
25 from rhodecode.integrations.types.webhook import WebhookHandler
26
26
27
27
28 @pytest.fixture
28 @pytest.fixture
29 def base_data():
29 def base_data():
30 return {
30 return {
31 'repo': {
31 'repo': {
32 'repo_name': 'foo',
32 'repo_name': 'foo',
33 'repo_type': 'hg',
33 'repo_type': 'hg',
34 'repo_id': '12',
34 'repo_id': '12',
35 'url': 'http://repo.url/foo',
35 'url': 'http://repo.url/foo',
36 'extra_fields': {},
36 'extra_fields': {},
37 },
37 },
38 'actor': {
38 'actor': {
39 'username': 'actor_name',
39 'username': 'actor_name',
40 'user_id': 1
40 'user_id': 1
41 }
41 }
42 }
42 }
43
43
44
44
45 def test_webhook_parse_url_invalid_event():
45 def test_webhook_parse_url_invalid_event():
46 template_url = 'http://server.com/${repo_name}/build'
46 template_url = 'http://server.com/${repo_name}/build'
47 handler = WebhookHandler(template_url, 'secret_token')
47 handler = WebhookHandler(
48 template_url, 'secret_token', {'exmaple-header':'header-values'})
48 with pytest.raises(ValueError) as err:
49 with pytest.raises(ValueError) as err:
49 handler(events.RepoDeleteEvent(''), {})
50 handler(events.RepoDeleteEvent(''), {})
50 assert str(err.value).startswith('event type not supported')
51 assert str(err.value).startswith('event type not supported')
51
52
52
53
53 @pytest.mark.parametrize('template,expected_urls', [
54 @pytest.mark.parametrize('template,expected_urls', [
54 ('http://server.com/${repo_name}/build', ['http://server.com/foo/build']),
55 ('http://server.com/${repo_name}/build', ['http://server.com/foo/build']),
55 ('http://server.com/${repo_name}/${repo_type}', ['http://server.com/foo/hg']),
56 ('http://server.com/${repo_name}/${repo_type}', ['http://server.com/foo/hg']),
56 ('http://${server}.com/${repo_name}/${repo_id}', ['http://${server}.com/foo/12']),
57 ('http://${server}.com/${repo_name}/${repo_id}', ['http://${server}.com/foo/12']),
57 ('http://server.com/${branch}/build', ['http://server.com/${branch}/build']),
58 ('http://server.com/${branch}/build', ['http://server.com/${branch}/build']),
58 ])
59 ])
59 def test_webook_parse_url_for_create_event(base_data, template, expected_urls):
60 def test_webook_parse_url_for_create_event(base_data, template, expected_urls):
60 handler = WebhookHandler(template, 'secret_token')
61 headers = {'exmaple-header': 'header-values'}
62 handler = WebhookHandler(
63 template, 'secret_token', headers)
61 urls = handler(events.RepoCreateEvent(''), base_data)
64 urls = handler(events.RepoCreateEvent(''), base_data)
62 assert urls == [(url, 'secret_token', base_data) for url in expected_urls]
65 assert urls == [
66 (url, 'secret_token', headers, base_data) for url in expected_urls]
63
67
64
68
65 @pytest.mark.parametrize('template,expected_urls', [
69 @pytest.mark.parametrize('template,expected_urls', [
66 ('http://server.com/${repo_name}/${pull_request_id}', ['http://server.com/foo/999']),
70 ('http://server.com/${repo_name}/${pull_request_id}', ['http://server.com/foo/999']),
67 ('http://server.com/${repo_name}/${pull_request_url}', ['http://server.com/foo/http://pr-url.com']),
71 ('http://server.com/${repo_name}/${pull_request_url}', ['http://server.com/foo/http://pr-url.com']),
68 ])
72 ])
69 def test_webook_parse_url_for_pull_request_event(base_data, template, expected_urls):
73 def test_webook_parse_url_for_pull_request_event(
74 base_data, template, expected_urls):
75
70 base_data['pullrequest'] = {
76 base_data['pullrequest'] = {
71 'pull_request_id': 999,
77 'pull_request_id': 999,
72 'url': 'http://pr-url.com',
78 'url': 'http://pr-url.com',
73 }
79 }
74 handler = WebhookHandler(template, 'secret_token')
80 headers = {'exmaple-header': 'header-values'}
81 handler = WebhookHandler(
82 template, 'secret_token', headers)
75 urls = handler(events.PullRequestCreateEvent(
83 urls = handler(events.PullRequestCreateEvent(
76 AttributeDict({'target_repo': 'foo'})), base_data)
84 AttributeDict({'target_repo': 'foo'})), base_data)
77 assert urls == [(url, 'secret_token', base_data) for url in expected_urls]
85 assert urls == [
86 (url, 'secret_token', headers, base_data) for url in expected_urls]
78
87
79
88
80 @pytest.mark.parametrize('template,expected_urls', [
89 @pytest.mark.parametrize('template,expected_urls', [
81 ('http://server.com/${branch}/build', ['http://server.com/stable/build',
90 ('http://server.com/${branch}/build', ['http://server.com/stable/build',
82 'http://server.com/dev/build']),
91 'http://server.com/dev/build']),
83 ('http://server.com/${branch}/${commit_id}', ['http://server.com/stable/stable-xxx',
92 ('http://server.com/${branch}/${commit_id}', ['http://server.com/stable/stable-xxx',
84 'http://server.com/stable/stable-yyy',
93 'http://server.com/stable/stable-yyy',
85 'http://server.com/dev/dev-xxx',
94 'http://server.com/dev/dev-xxx',
86 'http://server.com/dev/dev-yyy']),
95 'http://server.com/dev/dev-yyy']),
87 ])
96 ])
88 def test_webook_parse_url_for_push_event(pylonsapp, repo_push_event, base_data, template, expected_urls):
97 def test_webook_parse_url_for_push_event(
98 pylonsapp, repo_push_event, base_data, template, expected_urls):
89 base_data['push'] = {
99 base_data['push'] = {
90 'branches': [{'name': 'stable'}, {'name': 'dev'}],
100 'branches': [{'name': 'stable'}, {'name': 'dev'}],
91 'commits': [{'branch': 'stable', 'raw_id': 'stable-xxx'},
101 'commits': [{'branch': 'stable', 'raw_id': 'stable-xxx'},
92 {'branch': 'stable', 'raw_id': 'stable-yyy'},
102 {'branch': 'stable', 'raw_id': 'stable-yyy'},
93 {'branch': 'dev', 'raw_id': 'dev-xxx'},
103 {'branch': 'dev', 'raw_id': 'dev-xxx'},
94 {'branch': 'dev', 'raw_id': 'dev-yyy'}]
104 {'branch': 'dev', 'raw_id': 'dev-yyy'}]
95 }
105 }
96 handler = WebhookHandler(template, 'secret_token')
106 headers = {'exmaple-header': 'header-values'}
107 handler = WebhookHandler(
108 template, 'secret_token', headers)
97 urls = handler(repo_push_event, base_data)
109 urls = handler(repo_push_event, base_data)
98 assert urls == [(url, 'secret_token', base_data) for url in expected_urls]
110 assert urls == [
111 (url, 'secret_token', headers, base_data) for url in expected_urls]
General Comments 0
You need to be logged in to leave comments. Login now