Debian Codegraph @

ansible_collections/community/rabbitmq/plugins/lookup/rabbitmq.py

raw
1 # (c) 2018, John Imison <[email protected]>
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import (absolute_import, division, print_function)
5 __metaclass__ = type
6
7 DOCUMENTATION = '''
8 name: rabbitmq
9 author: John Imison (@Im0)
10 short_description: Retrieve messages from an AMQP/AMQPS RabbitMQ queue.
11 description:
12 - This lookup uses a basic get to retrieve all, or a limited number C(count), messages from a RabbitMQ queue.
13 options:
14 url:
15 description:
16 - An URI connection string to connect to the AMQP/AMQPS RabbitMQ server.
17 - For more information refer to the URI spec U(https://www.rabbitmq.com/uri-spec.html).
18 required: True
19 queue:
20 description:
21 - The queue to get messages from.
22 required: True
23 count:
24 description:
25 - How many messages to collect from the queue.
26 - If not set, defaults to retrieving all the messages from the queue.
27 requirements:
28 - The python pika package U(https://pypi.org/project/pika/).
29 notes:
30 - This lookup implements BlockingChannel.basic_get to get messages from a RabbitMQ server.
31 - After retrieving a message from the server, receipt of the message is acknowledged and the message on the server is deleted.
32 - Pika is a pure-Python implementation of the AMQP 0-9-1 protocol that tries to stay fairly independent of the underlying network support library.
33 - More information about pika can be found at U(https://pika.readthedocs.io/en/stable/).
34 - This plugin is tested against RabbitMQ. Other AMQP 0.9.1 protocol based servers may work but not tested/guaranteed.
35 - Assigning the return messages to a variable under C(vars) may result in unexpected results as the lookup is evaluated every time the
36 variable is referenced.
37 - Currently this plugin only handles text based messages from a queue. Unexpected results may occur when retrieving binary data.
38 '''
39
40
41 EXAMPLES = """
42 - name: Get all messages off a queue
43 debug:
44 msg: "{{ lookup('community.rabbitmq.rabbitmq', url='amqp://guest:[email protected]:5672/%2F', queue='hello') }}"
45
46
47 # If you are intending on using the returned messages as a variable in more than
48 # one task (eg. debug, template), it is recommended to set_fact.
49
50 - name: Get 2 messages off a queue and set a fact for re-use
51 set_fact:
52 messages: "{{ lookup('community.rabbitmq.rabbiotmq', url='amqp://guest:[email protected]:5672/%2F', queue='hello', count=2) }}"
53
54 - name: Dump out contents of the messages
55 debug:
56 var: messages
57
58 """
59
60 RETURN = """
61 _list:
62 description:
63 - A list of dictionaries with keys and value from the queue.
64 type: list
65 contains:
66 content_type:
67 description: The content_type on the message in the queue.
68 type: str
69 delivery_mode:
70 description: The delivery_mode on the message in the queue.
71 type: str
72 delivery_tag:
73 description: The delivery_tag on the message in the queue.
74 type: str
75 exchange:
76 description: The exchange the message came from.
77 type: str
78 message_count:
79 description: The message_count for the message on the queue.
80 type: str
81 msg:
82 description: The content of the message.
83 type: str
84 redelivered:
85 description: The redelivered flag. True if the message has been delivered before.
86 type: bool
87 routing_key:
88 description: The routing_key on the message in the queue.
89 type: str
90 headers:
91 description: The headers for the message returned from the queue.
92 type: dict
93 json:
94 description: If application/json is specified in content_type, json will be loaded into variables.
95 type: dict
96
97 """
98
99 import json
100
101 from ansible.errors import AnsibleError
102 from ansible.plugins.lookup import LookupBase
103 from ansible.module_utils._text import to_native, to_text
104 from ansible.utils.display import Display
105
106 try:
107 import pika
108 HAS_PIKA = True
109 except ImportError:
110 HAS_PIKA = False
111
112 display = Display()
113
114
115 class LookupModule(LookupBase):
116
117 def run(self, terms, variables=None, url=None, queue=None, count=None):
118 if not HAS_PIKA:
119 raise AnsibleError('pika python package is required for rabbitmq lookup.')
120 if not url:
121 raise AnsibleError('URL is required for rabbitmq lookup.')
122 if not queue:
123 raise AnsibleError('Queue is required for rabbitmq lookup.')
124
125 display.vvv(u"terms:%s : variables:%s url:%s queue:%s count:%s" % (terms, variables, url, queue, count))
126
127 try:
128 parameters = pika.URLParameters(url)
129 except Exception as e:
130 raise AnsibleError("URL malformed: %s" % to_native(e))
131
132 try:
133 connection = pika.BlockingConnection(parameters)
134 except Exception as e:
135 raise AnsibleError("Connection issue: %s" % to_native(e))
136
137 try:
138 conn_channel = connection.channel()
139 except pika.exceptions.AMQPChannelError as e:
140 try:
141 connection.close()
142 except pika.exceptions.AMQPConnectionError as ie:
143 raise AnsibleError("Channel and connection closing issues: %s / %s" % to_native(e), to_native(ie))
144 raise AnsibleError("Channel issue: %s" % to_native(e))
145
146 ret = []
147 idx = 0
148
149 while True:
150 method_frame, properties, body = conn_channel.basic_get(queue=queue)
151 if method_frame:
152 display.vvv(u"%s, %s, %s " % (method_frame, properties, to_text(body)))
153
154 # TODO: In the future consider checking content_type and handle text/binary data differently.
155 msg_details = dict({
156 'msg': to_text(body),
157 'message_count': method_frame.message_count,
158 'routing_key': method_frame.routing_key,
159 'delivery_tag': method_frame.delivery_tag,
160 'redelivered': method_frame.redelivered,
161 'exchange': method_frame.exchange,
162 'delivery_mode': properties.delivery_mode,
163 'content_type': properties.content_type,
164 'headers': properties.headers
165 })
166 if properties.content_type == 'application/json':
167 try:
168 msg_details['json'] = json.loads(msg_details['msg'])
169 except ValueError as e:
170 raise AnsibleError("Unable to decode JSON for message %s: %s" % (method_frame.delivery_tag, to_native(e)))
171
172 ret.append(msg_details)
173 conn_channel.basic_ack(method_frame.delivery_tag)
174 idx += 1
175 if method_frame.message_count == 0 or idx == count:
176 break
177 # If we didn't get a method_frame, exit.
178 else:
179 break
180
181 if connection.is_closed:
182 return [ret]
183 else:
184 try:
185 connection.close()
186 except pika.exceptions.AMQPConnectionError:
187 pass
188 return [ret]