Debian Codegraph @

ansible_collections/community/rabbitmq/plugins/modules/rabbitmq_binding.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2015, Manuel Sousa <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = r'''
12 ---
13 module: rabbitmq_binding
14 author: Manuel Sousa (@manuel-sousa)
15
16 short_description: Manage rabbitMQ bindings
17 description:
18 - This module uses rabbitMQ REST APIs to create / delete bindings.
19 requirements: [ "requests >= 1.0.0" ]
20 options:
21 state:
22 description:
23 - Whether the bindings should be present or absent.
24 type: str
25 choices: [ "present", "absent" ]
26 default: present
27 name:
28 description:
29 - source exchange to create binding on.
30 type: str
31 required: true
32 aliases: [ "src", "source" ]
33 destination:
34 description:
35 - destination exchange or queue for the binding.
36 type: str
37 required: true
38 aliases: [ "dst", "dest" ]
39 destination_type:
40 description:
41 - Either queue or exchange.
42 type: str
43 required: true
44 choices: [ "queue", "exchange" ]
45 aliases: [ "type", "dest_type" ]
46 routing_key:
47 description:
48 - routing key for the binding.
49 type: str
50 default: "#"
51 arguments:
52 description:
53 - extra arguments for exchange. If defined this argument is a key/value dictionary
54 type: dict
55 required: false
56 default: {}
57 extends_documentation_fragment:
58 - community.rabbitmq.rabbitmq
59
60 '''
61
62 EXAMPLES = r'''
63 - name: Bind myQueue to directExchange with routing key info
64 community.rabbitmq.rabbitmq_binding:
65 name: directExchange
66 destination: myQueue
67 type: queue
68 routing_key: info
69
70 - name: Bind directExchange to topicExchange with routing key *.info
71 community.rabbitmq.rabbitmq_binding:
72 name: topicExchange
73 destination: topicExchange
74 type: exchange
75 routing_key: '*.info'
76 '''
77
78 import json
79 import traceback
80
81 REQUESTS_IMP_ERR = None
82 try:
83 import requests
84 HAS_REQUESTS = True
85 except ImportError:
86 REQUESTS_IMP_ERR = traceback.format_exc()
87 HAS_REQUESTS = False
88
89 from ansible.module_utils.six.moves.urllib import parse as urllib_parse
90 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
91 from ansible_collections.community.rabbitmq.plugins.module_utils.rabbitmq import rabbitmq_argument_spec
92
93
94 class RabbitMqBinding(object):
95 def __init__(self, module):
96 """
97 :param module:
98 """
99 self.module = module
100 self.name = self.module.params['name']
101 self.login_user = self.module.params['login_user']
102 self.login_password = self.module.params['login_password']
103 self.login_host = self.module.params['login_host']
104 self.login_port = self.module.params['login_port']
105 self.login_protocol = self.module.params['login_protocol']
106 self.vhost = self.module.params['vhost']
107 self.destination = self.module.params['destination']
108 self.destination_type = 'q' if self.module.params['destination_type'] == 'queue' else 'e'
109 self.routing_key = self.module.params['routing_key']
110 self.arguments = self.module.params['arguments']
111 self.verify = self.module.params['ca_cert']
112 self.cert = self.module.params['client_cert']
113 self.key = self.module.params['client_key']
114 self.base_url = '{0}://{1}:{2}/api/bindings'.format(self.login_protocol,
115 self.login_host,
116 self.login_port)
117 # Ensure provided data is safe to use in a URL.
118 # https://docs.python.org/3/library/urllib.parse.html#url-quoting
119 # NOTE: This will also encode '/' characters, as they are required
120 # to be percent encoded in the RabbitMQ management API.
121 self.url = '{0}/{1}/e/{2}/{3}/{4}'.format(self.base_url,
122 urllib_parse.quote(self.vhost, safe=''),
123 urllib_parse.quote(self.name, safe=''),
124 self.destination_type,
125 urllib_parse.quote(self.destination, safe=''))
126 self.result = {
127 'changed': False,
128 'name': self.module.params['name'],
129 }
130 self.authentication = (
131 self.login_user,
132 self.login_password
133 )
134 self.request = requests
135 self.http_check_states = {
136 200: True,
137 404: False,
138 }
139 self.http_actionable_states = {
140 201: True,
141 204: True,
142 }
143 self.api_result = self.request.get(self.url, auth=self.authentication, verify=self.verify, cert=(self.cert, self.key))
144
145 def run(self):
146 """
147 :return:
148 """
149 self.check_presence()
150 self.check_mode()
151 self.action_mode()
152
153 def check_presence(self):
154 """
155 :return:
156 """
157 if self.check_should_throw_fail():
158 self.fail()
159
160 def change_required(self):
161 """
162 :return:
163 """
164 if self.module.params['state'] == 'present':
165 if not self.is_present():
166 return True
167 elif self.module.params['state'] == 'absent':
168 if self.is_present():
169 return True
170 return False
171
172 def is_present(self):
173 """
174 :return:
175 """
176 for binding in self.api_result.json():
177 if binding["arguments"] == self.arguments and binding["routing_key"] == self.routing_key:
178 return True
179 return False
180
181 def check_mode(self):
182 """
183 :return:
184 """
185 if self.module.check_mode:
186 result = self.result
187 result['changed'] = self.change_required()
188 result['details'] = self.api_result.json() if self.is_present() else self.api_result.text
189 result['arguments'] = self.module.params['arguments']
190 self.module.exit_json(**result)
191
192 def check_reply_is_correct(self):
193 """
194 :return:
195 """
196 if self.api_result.status_code in self.http_check_states:
197 return True
198 return False
199
200 def check_should_throw_fail(self):
201 """
202 :return:
203 """
204 if not self.is_present():
205 if not self.check_reply_is_correct():
206 return True
207 return False
208
209 def action_mode(self):
210 """
211 :return:
212 """
213 result = self.result
214 if self.change_required():
215 if self.module.params['state'] == 'present':
216 self.create()
217 if self.module.params['state'] == 'absent':
218 self.remove()
219 if self.action_should_throw_fail():
220 self.fail()
221 result['changed'] = True
222 result['destination'] = self.module.params['destination']
223 self.module.exit_json(**result)
224 else:
225 result['changed'] = False
226 self.module.exit_json(**result)
227
228 def action_reply_is_correct(self):
229 """
230 :return:
231 """
232 if self.api_result.status_code in self.http_actionable_states:
233 return True
234 return False
235
236 def action_should_throw_fail(self):
237 """
238 :return:
239 """
240 if not self.action_reply_is_correct():
241 return True
242 return False
243
244 def create(self):
245 """
246 :return:
247 """
248 self.api_result = self.request.post(self.url,
249 auth=self.authentication,
250 verify=self.verify,
251 cert=(self.cert, self.key),
252 headers={"content-type": "application/json"},
253 data=json.dumps({
254 'routing_key': self.routing_key,
255 'arguments': self.arguments
256 }))
257
258 def get_properties_key(self):
259 """
260 :return:
261 """
262 for binding in self.api_result.json():
263 if binding["arguments"] == self.arguments and binding["routing_key"] == self.routing_key:
264 return binding["properties_key"]
265 return None
266
267 def remove(self):
268 """
269 :return:
270 """
271 properties_key = self.get_properties_key()
272 url = '{0}/{1}'.format(self.url, properties_key)
273 self.api_result = self.request.delete(url, auth=self.authentication, verify=self.verify, cert=(self.cert, self.key))
274
275 def fail(self):
276 """
277 :return:
278 """
279 self.module.fail_json(
280 msg="Unexpected reply from API",
281 status=self.api_result.status_code,
282 details=self.api_result.text
283 )
284
285
286 def main():
287
288 argument_spec = rabbitmq_argument_spec()
289 argument_spec.update(
290 dict(
291 state=dict(default='present', choices=['present', 'absent'], type='str'),
292 name=dict(required=True, aliases=["src", "source"], type='str'),
293 destination=dict(required=True, aliases=["dst", "dest"], type='str'),
294 destination_type=dict(required=True, aliases=["type", "dest_type"], choices=["queue", "exchange"],
295 type='str'),
296 routing_key=dict(default='#', type='str', no_log=False),
297 arguments=dict(default=dict(), type='dict')
298 )
299 )
300 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
301
302 if not HAS_REQUESTS:
303 module.fail_json(msg=missing_required_lib("requests"), exception=REQUESTS_IMP_ERR)
304
305 RabbitMqBinding(module).run()
306
307
308 if __name__ == '__main__':
309 main()