Debian Codegraph @

ansible_collections/community/rabbitmq/plugins/module_utils/rabbitmq.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright: (c) 2016, Jorge Rodriguez <[email protected]>
4 # Copyright: (c) 2018, John Imison <[email protected]>
5 #
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11 from ansible.module_utils._text import to_native
12 from ansible.module_utils.basic import missing_required_lib
13 from ansible.module_utils.six.moves.urllib import parse as urllib_parse
14 from mimetypes import MimeTypes
15
16 import os
17 import json
18 import traceback
19
20 PIKA_IMP_ERR = None
21 try:
22 import pika
23 import pika.exceptions
24 HAS_PIKA = True
25 except ImportError:
26 PIKA_IMP_ERR = traceback.format_exc()
27 HAS_PIKA = False
28
29
30 def rabbitmq_argument_spec():
31 return dict(
32 login_user=dict(type='str', default='guest'),
33 login_password=dict(type='str', default='guest', no_log=True),
34 login_host=dict(type='str', default='localhost'),
35 login_port=dict(type='str', default='15672'),
36 login_protocol=dict(type='str', default='http', choices=['http', 'https']),
37 ca_cert=dict(type='path', aliases=['cacert']),
38 client_cert=dict(type='path', aliases=['cert']),
39 client_key=dict(type='path', aliases=['key']),
40 vhost=dict(type='str', default='/'),
41 )
42
43
44 # notification/rabbitmq_basic_publish.py
45 class RabbitClient():
46 def __init__(self, module):
47 self.module = module
48 self.params = module.params
49 self.check_required_library()
50 self.check_host_params()
51 self.url = self.params['url']
52 self.proto = self.params['proto']
53 self.username = self.params['username']
54 self.password = self.params['password']
55 self.host = self.params['host']
56 self.port = self.params['port']
57 self.vhost = self.params['vhost']
58 self.queue = self.params['queue']
59 self.exchange = self.params['exchange']
60 self.routing_key = self.params['routing_key']
61 self.headers = self.params['headers']
62 self.cafile = self.params['cafile']
63 self.certfile = self.params['certfile']
64 self.keyfile = self.params['keyfile']
65
66 if self.host is not None:
67 self.build_url()
68
69 if self.cafile is not None:
70 self.append_ssl_certs()
71
72 self.connect_to_rabbitmq()
73
74 def check_required_library(self):
75 if not HAS_PIKA:
76 self.module.fail_json(msg=missing_required_lib("pika"), exception=PIKA_IMP_ERR)
77
78 def check_host_params(self):
79 # Fail if url is specified and other conflicting parameters have been specified
80 if self.params['url'] is not None and any(self.params[k] is not None for k in ['proto', 'host', 'port', 'password', 'username', 'vhost']):
81 self.module.fail_json(msg="url and proto, host, port, vhost, username or password cannot be specified at the same time.")
82
83 # Fail if url not specified and there is a missing parameter to build the url
84 if self.params['url'] is None and any(self.params[k] is None for k in ['proto', 'host', 'port', 'password', 'username', 'vhost']):
85 self.module.fail_json(msg="Connection parameters must be passed via url, or, proto, host, port, vhost, username or password.")
86
87 def append_ssl_certs(self):
88 ssl_options = {}
89 if self.cafile:
90 ssl_options['cafile'] = self.cafile
91 if self.certfile:
92 ssl_options['certfile'] = self.certfile
93 if self.keyfile:
94 ssl_options['keyfile'] = self.keyfile
95
96 self.url = self.url + '?ssl_options=' + urllib_parse.quote(json.dumps(ssl_options))
97
98 @staticmethod
99 def rabbitmq_argument_spec():
100 return dict(
101 url=dict(type='str'),
102 proto=dict(type='str', choices=['amqp', 'amqps']),
103 host=dict(type='str'),
104 port=dict(type='int'),
105 username=dict(type='str'),
106 password=dict(type='str', no_log=True),
107 vhost=dict(type='str'),
108 queue=dict(type='str')
109 )
110
111 ''' Consider some file size limits here '''
112 def _read_file(self, path):
113 try:
114 with open(path, "rb") as file_handle:
115 return file_handle.read()
116 except IOError as e:
117 self.module.fail_json(msg="Unable to open file %s: %s" % (path, to_native(e)))
118
119 @staticmethod
120 def _check_file_mime_type(path):
121 mime = MimeTypes()
122 return mime.guess_type(path)
123
124 def build_url(self):
125 self.url = '{0}://{1}:{2}@{3}:{4}/{5}'.format(self.proto,
126 self.username,
127 self.password,
128 self.host,
129 self.port,
130 self.vhost)
131
132 def connect_to_rabbitmq(self):
133 """
134 Function to connect to rabbitmq using username and password
135 """
136 try:
137 parameters = pika.URLParameters(self.url)
138 except Exception as e:
139 self.module.fail_json(msg="URL malformed: %s" % to_native(e))
140
141 try:
142 self.connection = pika.BlockingConnection(parameters)
143 except Exception as e:
144 self.module.fail_json(msg="Connection issue: %s" % to_native(e))
145
146 try:
147 self.conn_channel = self.connection.channel()
148 except pika.exceptions.AMQPChannelError as e:
149 self.close_connection()
150 self.module.fail_json(msg="Channel issue: %s" % to_native(e))
151
152 def close_connection(self):
153 try:
154 self.connection.close()
155 except pika.exceptions.AMQPConnectionError:
156 pass
157
158 def basic_publish(self):
159 self.content_type = self.params.get("content_type")
160
161 if self.params.get("body") is not None:
162 args = dict(
163 body=self.params.get("body"),
164 properties=pika.BasicProperties(content_type=self.content_type, delivery_mode=1, headers=self.headers))
165
166 # If src (file) is defined and content_type is left as default, do a mime lookup on the file
167 if self.params.get("src") is not None and self.content_type == 'text/plain':
168 self.content_type = RabbitClient._check_file_mime_type(self.params.get("src"))[0]
169 self.headers.update(
170 filename=os.path.basename(self.params.get("src"))
171 )
172
173 args = dict(
174 body=self._read_file(self.params.get("src")),
175 properties=pika.BasicProperties(content_type=self.content_type,
176 delivery_mode=1,
177 headers=self.headers
178 ))
179 elif self.params.get("src") is not None:
180 args = dict(
181 body=self._read_file(self.params.get("src")),
182 properties=pika.BasicProperties(content_type=self.content_type,
183 delivery_mode=1,
184 headers=self.headers
185 ))
186
187 try:
188 # If queue and exchange is not defined post to random queue, RabbitMQ will return the queue name of the automatically generated queue.
189 if self.queue is None and self.exchange is None:
190 result = self.conn_channel.queue_declare(queue='',
191 durable=self.params.get("durable"),
192 exclusive=self.params.get("exclusive"),
193 auto_delete=self.params.get("auto_delete"),
194 arguments=self.params.get("headers"))
195 self.conn_channel.confirm_delivery()
196 self.queue = result.method.queue
197 elif self.queue is not None and self.exchange is None:
198 self.conn_channel.queue_declare(queue=self.queue,
199 durable=self.params.get("durable"),
200 exclusive=self.params.get("exclusive"),
201 auto_delete=self.params.get("auto_delete"),
202 arguments=self.params.get("headers"))
203 self.conn_channel.confirm_delivery()
204 except Exception as e:
205 self.module.fail_json(msg="Queue declare issue: %s" % to_native(e))
206
207 # https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/cloudstack.py#L150
208 # If routing key is not defined, but, the queue is... we will use the queue name as routing_key.
209 if self.routing_key is not None:
210 args['routing_key'] = self.routing_key
211 elif self.routing_key is None and self.queue is not None:
212 args['routing_key'] = self.queue
213 elif self.routing_key is None and self.exchange is not None:
214 args['routing_key'] = self.exchange
215 else:
216 args['routing_key'] = ''
217
218 # If exchange is not specified use the default/nameless exchange
219 if self.exchange is None:
220 args['exchange'] = ''
221 else:
222 args['exchange'] = self.exchange
223 if self.routing_key is None:
224 args['routing_key'] = self.exchange
225
226 # self.module.fail_json(msg="%s %s %s" % (to_native(self.queue), to_native(self.exchange), to_native(self.routing_key)))
227 try:
228 self.conn_channel.basic_publish(**args)
229 return True
230 except pika.exceptions.UnroutableError:
231 return False