Debian Codegraph @

ansible_collections/community/general/plugins/modules/znode.py

raw
1 #!/usr/bin/python
2 # Copyright 2015 WP Engine, Inc. All rights reserved.
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: znode
10 short_description: Create, delete, retrieve, and update znodes using ZooKeeper
11 description:
12 - Create, delete, retrieve, and update znodes using ZooKeeper.
13 attributes:
14 check_mode:
15 support: none
16 diff_mode:
17 support: none
18 extends_documentation_fragment:
19 - community.general._attributes
20 options:
21 hosts:
22 description:
23 - A list of ZooKeeper servers (format V([server]:[port])).
24 required: true
25 type: str
26 name:
27 description:
28 - The path of the znode.
29 required: true
30 type: str
31 value:
32 description:
33 - The value assigned to the znode.
34 type: str
35 op:
36 description:
37 - An operation to perform. Mutually exclusive with state.
38 choices: [get, wait, list]
39 type: str
40 state:
41 description:
42 - The state to enforce. Mutually exclusive with op.
43 choices: [present, absent]
44 type: str
45 timeout:
46 description:
47 - The amount of time to wait for a node to appear.
48 default: 300
49 type: int
50 recursive:
51 description:
52 - Recursively delete node and all its children.
53 type: bool
54 default: false
55 auth_scheme:
56 description:
57 - Authentication scheme.
58 choices: [digest, sasl]
59 type: str
60 default: "digest"
61 version_added: 5.8.0
62 auth_credential:
63 description:
64 - The authentication credential value. Depends on O(auth_scheme).
65 - The format for O(auth_scheme=digest) is C(user:password), and the format for O(auth_scheme=sasl) is C(user:password).
66 type: str
67 version_added: 5.8.0
68 use_tls:
69 description:
70 - Using TLS/SSL or not.
71 type: bool
72 default: false
73 version_added: '6.5.0'
74 requirements:
75 - kazoo >= 2.1
76 author: "Trey Perry (@treyperry)"
77 """
78
79 EXAMPLES = r"""
80 - name: Creating or updating a znode with a given value
81 community.general.znode:
82 hosts: 'localhost:2181'
83 name: /mypath
84 value: myvalue
85 state: present
86
87 - name: Getting the value and stat structure for a znode
88 community.general.znode:
89 hosts: 'localhost:2181'
90 name: /mypath
91 op: get
92
93 - name: Getting the value and stat structure for a znode using digest authentication
94 community.general.znode:
95 hosts: 'localhost:2181'
96 auth_credential: 'user1:s3cr3t'
97 name: /secretmypath
98 op: get
99
100 - name: Listing a particular znode's children
101 community.general.znode:
102 hosts: 'localhost:2181'
103 name: /zookeeper
104 op: list
105
106 - name: Waiting 20 seconds for a znode to appear at path /mypath
107 community.general.znode:
108 hosts: 'localhost:2181'
109 name: /mypath
110 op: wait
111 timeout: 20
112
113 - name: Deleting a znode at path /mypath
114 community.general.znode:
115 hosts: 'localhost:2181'
116 name: /mypath
117 state: absent
118
119 - name: Creating or updating a znode with a given value on a remote Zookeeper
120 community.general.znode:
121 hosts: 'my-zookeeper-node:2181'
122 name: /mypath
123 value: myvalue
124 state: present
125 delegate_to: 127.0.0.1
126 """
127
128 import time
129 import traceback
130
131 KAZOO_IMP_ERR = None
132 try:
133 from kazoo.client import KazooClient
134 from kazoo.handlers.threading import KazooTimeoutError
135
136 KAZOO_INSTALLED = True
137 except ImportError:
138 KAZOO_IMP_ERR = traceback.format_exc()
139 KAZOO_INSTALLED = False
140
141 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
142 from ansible.module_utils.common.text.converters import to_bytes
143
144
145 def main():
146 module = AnsibleModule(
147 argument_spec=dict(
148 hosts=dict(required=True, type="str"),
149 name=dict(required=True, type="str"),
150 value=dict(type="str"),
151 op=dict(choices=["get", "wait", "list"]),
152 state=dict(choices=["present", "absent"]),
153 timeout=dict(default=300, type="int"),
154 recursive=dict(default=False, type="bool"),
155 auth_scheme=dict(default="digest", choices=["digest", "sasl"]),
156 auth_credential=dict(type="str", no_log=True),
157 use_tls=dict(default=False, type="bool"),
158 ),
159 supports_check_mode=False,
160 )
161
162 if not KAZOO_INSTALLED:
163 module.fail_json(msg=missing_required_lib("kazoo >= 2.1"), exception=KAZOO_IMP_ERR)
164
165 check = check_params(module.params)
166 if not check["success"]:
167 module.fail_json(msg=check["msg"])
168
169 zoo = KazooCommandProxy(module)
170 try:
171 zoo.start()
172 except KazooTimeoutError:
173 module.fail_json(msg="The connection to the ZooKeeper ensemble timed out.")
174
175 command_dict = {
176 "op": {"get": zoo.get, "list": zoo.list, "wait": zoo.wait},
177 "state": {"present": zoo.present, "absent": zoo.absent},
178 }
179
180 command_type = "op" if "op" in module.params and module.params["op"] is not None else "state"
181 method = module.params[command_type]
182 result, result_dict = command_dict[command_type][method]()
183 zoo.shutdown()
184
185 if result:
186 module.exit_json(**result_dict)
187 else:
188 module.fail_json(**result_dict)
189
190
191 def check_params(params):
192 if not params["state"] and not params["op"]:
193 return {"success": False, "msg": "Please define an operation (op) or a state."}
194
195 if params["state"] and params["op"]:
196 return {"success": False, "msg": "Please choose an operation (op) or a state, but not both."}
197
198 return {"success": True}
199
200
201 class KazooCommandProxy:
202 def __init__(self, module):
203 self.module = module
204 self.zk = KazooClient(module.params["hosts"], use_ssl=module.params["use_tls"])
205
206 def absent(self):
207 return self._absent(self.module.params["name"])
208
209 def exists(self, znode):
210 return self.zk.exists(znode)
211
212 def list(self):
213 children = self.zk.get_children(self.module.params["name"])
214 return True, {
215 "count": len(children),
216 "items": children,
217 "msg": "Retrieved znodes in path.",
218 "znode": self.module.params["name"],
219 }
220
221 def present(self):
222 return self._present(self.module.params["name"], self.module.params["value"])
223
224 def get(self):
225 return self._get(self.module.params["name"])
226
227 def shutdown(self):
228 self.zk.stop()
229 self.zk.close()
230
231 def start(self):
232 self.zk.start()
233 if self.module.params["auth_credential"]:
234 self.zk.add_auth(self.module.params["auth_scheme"], self.module.params["auth_credential"])
235
236 def wait(self):
237 return self._wait(self.module.params["name"], self.module.params["timeout"])
238
239 def _absent(self, znode):
240 if self.exists(znode):
241 self.zk.delete(znode, recursive=self.module.params["recursive"])
242 return True, {"changed": True, "msg": "The znode was deleted."}
243 else:
244 return True, {"changed": False, "msg": "The znode does not exist."}
245
246 def _get(self, path):
247 if self.exists(path):
248 value, zstat = self.zk.get(path)
249 stat_dict = {}
250 for i in dir(zstat):
251 if not i.startswith("_"):
252 attr = getattr(zstat, i)
253 if isinstance(attr, (int, str)):
254 stat_dict[i] = attr
255 result = True, {"msg": "The node was retrieved.", "znode": path, "value": value, "stat": stat_dict}
256 else:
257 result = False, {"msg": "The requested node does not exist."}
258
259 return result
260
261 def _present(self, path, value):
262 if self.exists(path):
263 (current_value, zstat) = self.zk.get(path)
264 if value != current_value:
265 self.zk.set(path, to_bytes(value))
266 return True, {"changed": True, "msg": "Updated the znode value.", "znode": path, "value": value}
267 else:
268 return True, {"changed": False, "msg": "No changes were necessary.", "znode": path, "value": value}
269 else:
270 self.zk.create(path, to_bytes(value), makepath=True)
271 return True, {"changed": True, "msg": "Created a new znode.", "znode": path, "value": value}
272
273 def _wait(self, path, timeout, interval=5):
274 lim = time.time() + timeout
275
276 while time.time() < lim:
277 if self.exists(path):
278 return True, {
279 "msg": "The node appeared before the configured timeout.",
280 "znode": path,
281 "timeout": timeout,
282 }
283 else:
284 time.sleep(interval)
285
286 return False, {
287 "msg": "The node did not appear before the operation timed out.",
288 "timeout": timeout,
289 "znode": path,
290 }
291
292
293 if __name__ == "__main__":
294 main()