Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2013, John Dewey <[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_policy
14 short_description: Manage the state of policies in RabbitMQ
15 description:
16 - Manage the state of a policy in RabbitMQ using rabbitmqctl or REST APIs.
17 author: John Dewey (@retr0h)
18 options:
19 name:
20 description:
21 - The name of the policy to manage.
22 type: str
23 required: true
24 vhost:
25 description:
26 - The name of the vhost to apply to.
27 type: str
28 default: /
29 apply_to:
30 description:
31 - What the policy applies to. Requires RabbitMQ 3.2.0 or later. For classic_queues,
32 quorum_queues and streams RabbitMQ 3.12 or later is required
33 type: str
34 default: all
35 choices: [all, exchanges, queues, classic_queues, quorum_queues, streams]
36 pattern:
37 description:
38 - A regex of queues to apply the policy to. Required when
39 C(state=present). This option is no longer required as of Ansible 2.9.
40 type: str
41 required: false
42 default: null
43 tags:
44 description:
45 - A dict or string describing the policy. Required when
46 C(state=present). This option is no longer required as of Ansible 2.9.
47 type: dict
48 required: false
49 default: null
50 priority:
51 description:
52 - The priority of the policy.
53 type: str
54 default: '0'
55 node:
56 description:
57 - Erlang node name of the rabbit we wish to configure.
58 type: str
59 default: rabbit
60 state:
61 description:
62 - The state of the policy.
63 type: str
64 default: present
65 choices: [present, absent]
66 login_user:
67 description:
68 - RabbitMQ user for connection.
69 type: str
70 version_added: '1.6.0'
71 login_password:
72 description:
73 - RabbitMQ password for connection.
74 type: str
75 version_added: '1.6.0'
76 login_host:
77 description:
78 - RabbitMQ host for connection.
79 type: str
80 version_added: '1.6.0'
81 login_port:
82 description:
83 - RabbitMQ management API port.
84 type: str
85 default: '15672'
86 version_added: '1.6.0'
87 login_protocol:
88 description:
89 - RabbitMQ management API protocol.
90 type: str
91 choices: [ http , https ]
92 default: http
93 version_added: '1.6.0'
94 ca_cert:
95 description:
96 - CA certificate to verify SSL connection to management API.
97 type: path
98 version_added: '1.6.0'
99 client_cert:
100 description:
101 - Client certificate to send on SSL connections to management API.
102 type: path
103 version_added: '1.6.0'
104 client_key:
105 description:
106 - Private key matching the client certificate.
107 type: path
108 version_added: '1.6.0'
109 '''
110
111 EXAMPLES = r'''
112 - name: Ensure the default vhost contains the HA policy via a dict
113 community.rabbitmq.rabbitmq_policy:
114 name: HA
115 pattern: .*
116 args:
117 tags:
118 ha-mode: all
119
120 - name: Ensure the default vhost contains the HA policy
121 community.rabbitmq.rabbitmq_policy:
122 name: HA
123 pattern: .*
124 tags:
125 ha-mode: all
126
127 - name: Ensure the default vhost contains the HA policy using REST APIs.
128 community.rabbitmq.rabbitmq_policy:
129 name: HA
130 pattern: .*
131 login_host: localhost
132 login_user: admin
133 login_password: changeadmin
134 tags:
135 ha-mode: all
136 '''
137
138 import json
139 import re
140 import traceback
141
142 from ansible_collections.community.rabbitmq.plugins.module_utils.version import LooseVersion as Version
143 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
144 from ansible.module_utils.six.moves.urllib import parse as urllib_parse
145
146 REQUESTS_IMP_ERR = None
147 try:
148 import requests
149
150 HAS_REQUESTS = True
151 except ImportError:
152 REQUESTS_IMP_ERR = traceback.format_exc()
153 HAS_REQUESTS = False
154
155
156 class RabbitMqPolicy(object):
157
158 def __init__(self, module, name):
159 self._module = module
160 self._name = name
161 self._vhost = module.params['vhost']
162 self._pattern = module.params['pattern']
163 self._apply_to = module.params['apply_to']
164 self._tags = module.params['tags']
165 self._priority = module.params['priority']
166 self._node = module.params['node']
167
168 # API parameters.
169 self._login_user = module.params['login_user']
170 self._login_password = module.params['login_password']
171 self._login_host = module.params['login_host']
172 self._login_port = module.params['login_port']
173 self._login_protocol = module.params['login_protocol']
174 self._verify = module.params['ca_cert']
175 self._cert = module.params['client_cert']
176 self._key = module.params['client_key']
177
178 require_rabbitmqctl = self._login_host is None
179 self._rabbitmqctl = module.get_bin_path('rabbitmqctl', require_rabbitmqctl)
180 self._version = self._rabbit_version()
181
182 def _exec(self,
183 args,
184 force_exec_in_check_mode=False,
185 split_lines=True,
186 add_vhost=True):
187 if (not self._module.check_mode
188 or (self._module.check_mode and force_exec_in_check_mode)):
189 cmd = [self._rabbitmqctl, '-q', '-n', self._node]
190
191 if add_vhost:
192 args.insert(1, '-p')
193 args.insert(2, self._vhost)
194
195 rc, out, err = self._module.run_command(cmd + args, check_rc=True)
196 if split_lines:
197 return out.splitlines()
198
199 return out
200 return list()
201
202 def _request_policy_api(self, method, vhost=None, name=None, data=None):
203 # Check if the vhost and name should be defined.
204 if method in ['put', 'delete']:
205 if vhost is None:
206 msg = "Error in HTTP request (method %s) for (endpoint policies), user %s. vhost must be defined." % (
207 method,
208 self._login_user,
209 )
210 self._module.fail_json(msg=msg)
211 return None
212 if name is None:
213 msg = "Error in HTTP request (method %s) for (endpoint policies), user %s. name must be defined." % (
214 method,
215 self._login_user,
216 )
217 self._module.fail_json(msg=msg)
218 return None
219
220 policies_endpoint = ['policies']
221 if vhost:
222 # Ensure provided data is safe to use in a URL.
223 # https://docs.python.org/3/library/urllib.parse.html#url-quoting
224 # NOTE: This will also encode '/' characters, as they are required
225 # to be percent encoded in the RabbitMQ management API.
226 policies_endpoint.append(urllib_parse.quote(vhost, safe=''))
227 if name:
228 policies_endpoint.append(name)
229 return self._request_api(method, endpoint='/'.join(policies_endpoint), data=data)
230
231 def _request_overview(self):
232 return self._request_api('get', 'overview')
233
234 def _request_api(self, method, endpoint, data=None):
235 if self._module.check_mode and method != "get":
236 return None
237
238 # TODO: verify the endpoint is supported.
239 try:
240 url = "%s://%s:%s/api/%s" % (
241 self._login_protocol,
242 self._login_host,
243 self._login_port,
244 endpoint,
245 )
246 response = requests.request(
247 method=method,
248 url=url,
249 auth=(self._login_user, self._login_password),
250 verify=self._verify,
251 cert=(self._cert, self._key),
252 json=data,
253 )
254
255 except requests.exceptions.RequestException as exception:
256 msg = "Error in HTTP request (method %s) for endpoint %s, user %s in rabbitmq." % (
257 method,
258 endpoint,
259 self._login_user,
260 )
261 self._module.fail_json(msg=msg, exception=exception)
262
263 return response
264
265 def _rabbit_version(self):
266 if self._login_host is not None:
267 response = self._request_overview()
268
269 if response is not None and not response.ok:
270 msg = (
271 "Error trying to retrieve rabbitmq version. "
272 "Status code '%s'."
273 ) % (response.status_code)
274 self._module.fail_json(msg=msg)
275 return None
276
277 return Version(response.json()['rabbitmq_version'])
278 else:
279 status = self._exec(['status'], True, False, False)
280
281 # 3.7.x erlang style output
282 version_match = re.search('{rabbit,".*","(?P<version>.*)"}', status)
283 if version_match:
284 return Version(version_match.group('version'))
285
286 # 3.8.x style ouput
287 version_match = re.search('RabbitMQ version: (?P<version>.*)', status)
288 if version_match:
289 return Version(version_match.group('version'))
290
291 return None
292
293 def _list_policies(self):
294 if self._login_host is not None:
295 response = self._request_policy_api('get', self._vhost)
296
297 if response is not None and not response.ok:
298 msg = (
299 "Error trying to retrieve policies on vhost %s in rabbitmq. "
300 "Status code '%s'."
301 ) % (self._vhost, response.status_code)
302 self._module.fail_json(msg=msg)
303 return None
304
305 # PARSE THE RESPONSE DATA.
306 # The response data is a json list with field names. The logic of the code expects tab delimited strings.
307 policy_response = response.json()
308 self._module.debug(f'[list_policies] {json.dumps(policy_response)}')
309 policies = []
310 if self._version and self._version >= Version('3.7.0'):
311 for policy in policy_response:
312 policies.append("%s\t%s\t%s\t%s\t%s\t%s" % (
313 policy['vhost'], policy['name'], policy['pattern'], policy['apply-to'], json.dumps(policy['definition']), policy['priority']))
314 else:
315 # Prior to 3.7.0, the apply-to & pattern fields were swapped.
316 for policy in policy_response:
317 policies.append("%s\t%s\t%s\t%s\t%s\t%s" % (
318 policy['vhost'], policy['name'], policy['apply-to'], policy['pattern'], json.dumps(policy['definition']), policy['priority']))
319 return policies
320
321 else:
322 if self._version and self._version >= Version('3.7.9'):
323 # Remove first header line from policies list for version > 3.7.9
324 return self._exec(['list_policies'], True)[1:]
325
326 return self._exec(['list_policies'], True)
327
328 def has_modifications(self):
329 if self._pattern is None or self._tags is None:
330 self._module.fail_json(
331 msg=('pattern and tags are required for '
332 'state=present'))
333
334 if self._version and self._version >= Version('3.7.0'):
335 # Change fields order in rabbitmqctl output in version 3.7
336 return not any(
337 self._policy_check(policy, apply_to_fno=3, pattern_fno=2)
338 for policy in self._list_policies())
339 else:
340 return not any(
341 self._policy_check(policy) for policy in self._list_policies())
342
343 def should_be_deleted(self):
344 return any(
345 self._policy_check_by_name(policy)
346 for policy in self._list_policies())
347
348 def set(self):
349 if self._login_host is not None:
350 policy = {
351 "vhost": self._vhost,
352 "name": self._name,
353 "pattern": self._pattern,
354 "apply-to": self._apply_to,
355 "definition": self._tags,
356 "priority": int(self._priority) # Priority must be a number.
357 }
358 self._module.debug(f'[set_policy] {json.dumps(policy)}')
359 response = self._request_policy_api('put', self._vhost, self._name, data=policy)
360
361 if response is not None and not response.ok:
362 msg = (
363 "Error trying to set policy %s in rabbitmq. "
364 "Response %s\n"
365 ) % (self._name, response.text)
366 self._module.fail_json(msg=msg)
367 else:
368 args = ['set_policy']
369 args.append(self._name)
370 args.append(self._pattern)
371 args.append(json.dumps(self._tags))
372 args.append('--priority')
373 args.append(self._priority)
374 if self._apply_to != 'all':
375 args.append('--apply-to')
376 args.append(self._apply_to)
377 return self._exec(args)
378
379 def clear(self):
380 if self._login_host is not None:
381 response = self._request_policy_api('delete', self._vhost, self._name)
382
383 if response is not None and not response.ok:
384 msg = (
385 "Error trying to remove policy %s in rabbitmq. "
386 "Status code '%s'."
387 ) % (self._name, response.status_code)
388 self._module.fail_json(msg=msg)
389 else:
390 return self._exec(['clear_policy', self._name])
391
392 def _policy_check(self,
393 policy,
394 name_fno=1,
395 apply_to_fno=2,
396 pattern_fno=3,
397 tags_fno=4,
398 priority_fno=5):
399 if not policy:
400 return False
401
402 policy_data = policy.split('\t')
403
404 policy_name = policy_data[name_fno]
405 apply_to = policy_data[apply_to_fno]
406 pattern = policy_data[pattern_fno].replace('\\\\', '\\')
407
408 try:
409 tags = json.loads(policy_data[tags_fno])
410 except json.decoder.JSONDecodeError:
411 tags = policy_data[tags_fno]
412
413 priority = policy_data[priority_fno]
414
415 return (policy_name == self._name and apply_to == self._apply_to
416 and tags == self._tags and priority == self._priority
417 and pattern == self._pattern)
418
419 def _policy_check_by_name(self, policy):
420 if not policy:
421 return False
422
423 policy_name = policy.split('\t')[1]
424
425 return policy_name == self._name
426
427
428 def main():
429 arg_spec = dict(
430 name=dict(required=True),
431 vhost=dict(default='/'),
432 pattern=dict(required=False, default=None),
433 apply_to=dict(default='all', choices=['all', 'exchanges', 'queues', 'classic_queues', 'quorum_queues', 'streams']),
434 tags=dict(type='dict', required=False, default=None),
435 priority=dict(default='0'),
436 node=dict(default='rabbit'),
437 state=dict(default='present', choices=['present', 'absent']),
438 # API Params.
439 login_user=dict(type="str", no_log=True),
440 login_password=dict(type="str", no_log=True),
441 login_host=dict(type="str"),
442 login_port=dict(type="str", default="15672"),
443 login_protocol=dict(type="str", default="http", choices=["http", "https"]),
444 ca_cert=dict(type="path"),
445 client_cert=dict(type="path"),
446 client_key=dict(type="path"),
447 )
448
449 module = AnsibleModule(
450 argument_spec=arg_spec,
451 supports_check_mode=True
452 )
453
454 if not HAS_REQUESTS:
455 module.fail_json(msg=missing_required_lib("requests"), exception=REQUESTS_IMP_ERR)
456
457 name = module.params['name']
458 state = module.params['state']
459 rabbitmq_policy = RabbitMqPolicy(module, name)
460
461 result = dict(changed=False, name=name, state=state)
462
463 if state == 'present' and rabbitmq_policy.has_modifications():
464 rabbitmq_policy.set()
465 result['changed'] = True
466 elif state == 'absent' and rabbitmq_policy.should_be_deleted():
467 rabbitmq_policy.clear()
468 result['changed'] = True
469
470 module.exit_json(**result)
471
472
473 if __name__ == '__main__':
474 main()