Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Olivier Boukili <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: apache2_mod_proxy
11 author: Olivier Boukili (@oboukili)
12 short_description: Set and/or get members' attributes of an Apache httpd 2.4 mod_proxy balancer pool
13 description:
14 - Set and/or get members' attributes of an Apache httpd 2.4 mod_proxy balancer pool, using HTTP POST and GET requests. The
15 httpd mod_proxy balancer-member status page has to be enabled and accessible, as this module relies on parsing this page.
16 extends_documentation_fragment:
17 - community.general._attributes
18 requirements:
19 - Python package C(beautifulsoup4)
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: none
25 options:
26 balancer_url_suffix:
27 type: str
28 description:
29 - Suffix of the balancer pool URL required to access the balancer pool status page (for example V(balancer_vhost[:port]/balancer_url_suffix)).
30 default: /balancer-manager/
31 balancer_vhost:
32 type: str
33 description:
34 - (IPv4|IPv6|FQDN):port of the Apache httpd 2.4 mod_proxy balancer pool.
35 required: true
36 member_host:
37 type: str
38 description:
39 - (IPv4|IPv6|FQDN) of the balancer member to get or to set attributes to. Port number is autodetected and should not
40 be specified here.
41 - If undefined, the M(community.general.apache2_mod_proxy) module returns a members list of dictionaries of all the
42 current balancer pool members' attributes.
43 state:
44 type: list
45 elements: str
46 choices: [present, absent, enabled, disabled, drained, hot_standby, ignore_errors]
47 description:
48 - Desired state of the member host.
49 - States can be simultaneously invoked by separating them with a comma (for example V(state=drained,ignore_errors)),
50 but it is recommended to specify them as a proper YAML list.
51 - States V(present) and V(absent) must be used without any other state.
52 tls:
53 description:
54 - Use https to access balancer management page.
55 type: bool
56 default: false
57 validate_certs:
58 description:
59 - Validate ssl/tls certificates.
60 type: bool
61 default: true
62 """
63
64 EXAMPLES = r"""
65 - name: Get all current balancer pool members attributes
66 community.general.apache2_mod_proxy:
67 balancer_vhost: 10.0.0.2
68
69 - name: Get a specific member attributes
70 community.general.apache2_mod_proxy:
71 balancer_vhost: myws.mydomain.org
72 balancer_suffix: /lb/
73 member_host: node1.myws.mydomain.org
74
75 # Enable all balancer pool members:
76 - name: Get attributes
77 community.general.apache2_mod_proxy:
78 balancer_vhost: '{{ myloadbalancer_host }}'
79 register: result
80
81 - name: Enable all balancer pool members
82 community.general.apache2_mod_proxy:
83 balancer_vhost: '{{ myloadbalancer_host }}'
84 member_host: '{{ item.host }}'
85 state: present
86 with_items: '{{ result.members }}'
87
88 # Gracefully disable a member from a loadbalancer node:
89 - name: Step 1
90 community.general.apache2_mod_proxy:
91 balancer_vhost: '{{ vhost_host }}'
92 member_host: '{{ member.host }}'
93 state: drained
94 delegate_to: myloadbalancernode
95
96 - name: Step 2
97 ansible.builtin.wait_for:
98 host: '{{ member.host }}'
99 port: '{{ member.port }}'
100 state: drained
101 delegate_to: myloadbalancernode
102
103 - name: Step 3
104 community.general.apache2_mod_proxy:
105 balancer_vhost: '{{ vhost_host }}'
106 member_host: '{{ member.host }}'
107 state: absent
108 delegate_to: myloadbalancernode
109 """
110
111 RETURN = r"""
112 member:
113 description: Specific balancer member information dictionary, returned when the module is invoked with O(member_host) parameter.
114 type: dict
115 returned: success
116 sample:
117 {
118 "attributes": {
119 "Busy": "0",
120 "Elected": "42",
121 "Factor": "1",
122 "From": "136K",
123 "Load": "0",
124 "Route": null,
125 "RouteRedir": null,
126 "Set": "0",
127 "Status": "Init Ok ",
128 "To": " 47K",
129 "Worker URL": null
130 },
131 "balancer_url": "http://10.10.0.2/balancer-manager/",
132 "host": "10.10.0.20",
133 "management_url": "http://10.10.0.2/lb/?b=mywsbalancer&w=http://10.10.0.20:8080/ws&nonce=8925436c-79c6-4841-8936-e7d13b79239b",
134 "path": "/ws",
135 "port": 8080,
136 "protocol": "http",
137 "status": {
138 "disabled": false,
139 "drained": false,
140 "hot_standby": false,
141 "ignore_errors": false
142 }
143 }
144 members:
145 description: List of member (defined above) dictionaries, returned when the module is invoked with no O(member_host) and
146 O(state) args.
147 returned: success
148 type: list
149 sample:
150 [
151 {
152 "attributes": {
153 "Busy": "0",
154 "Elected": "42",
155 "Factor": "1",
156 "From": "136K",
157 "Load": "0",
158 "Route": null,
159 "RouteRedir": null,
160 "Set": "0",
161 "Status": "Init Ok ",
162 "To": " 47K",
163 "Worker URL": null
164 },
165 "balancer_url": "http://10.10.0.2/balancer-manager/",
166 "host": "10.10.0.20",
167 "management_url": "http://10.10.0.2/lb/?b=mywsbalancer&w=http://10.10.0.20:8080/ws&nonce=8925436c-79c6-4841-8936-e7d13b79239b",
168 "path": "/ws",
169 "port": 8080,
170 "protocol": "http",
171 "status": {
172 "disabled": false,
173 "drained": false,
174 "hot_standby": false,
175 "ignore_errors": false
176 }
177 },
178 {
179 "attributes": {
180 "Busy": "0",
181 "Elected": "42",
182 "Factor": "1",
183 "From": "136K",
184 "Load": "0",
185 "Route": null,
186 "RouteRedir": null,
187 "Set": "0",
188 "Status": "Init Ok ",
189 "To": " 47K",
190 "Worker URL": null
191 },
192 "balancer_url": "http://10.10.0.2/balancer-manager/",
193 "host": "10.10.0.21",
194 "management_url": "http://10.10.0.2/lb/?b=mywsbalancer&w=http://10.10.0.21:8080/ws&nonce=8925436c-79c6-4841-8936-e7d13b79239b",
195 "path": "/ws",
196 "port": 8080,
197 "protocol": "http",
198 "status": {
199 "disabled": false,
200 "drained": false,
201 "hot_standby": false,
202 "ignore_errors": false
203 }
204 }
205 ]
206 """
207
208 import re
209
210 from ansible.module_utils.common.text.converters import to_text
211 from ansible.module_utils.urls import fetch_url
212
213 from ansible_collections.community.general.plugins.module_utils import _deps as deps
214 from ansible_collections.community.general.plugins.module_utils._module_helper import (
215 ModuleHelper,
216 ModuleHelperException,
217 )
218
219 with deps.declare("beautifulsoup4"):
220 from bs4 import BeautifulSoup
221
222 # balancer member attributes extraction regexp:
223 EXPRESSION = re.compile(
224 to_text(r"(b=([\w\.\-]+)&w=(https?|ajp|wss?|ftp|[sf]cgi)://([\w\.\-]+):?(\d*)([/\w\.\-]*)&?[\w\-\=]*)")
225 )
226 # Apache2 server version extraction regexp:
227 APACHE_VERSION_EXPRESSION = re.compile(to_text(r"SERVER VERSION: APACHE/([\d.]+)"))
228
229
230 def find_all(where, what):
231 return where.find_all(what)
232
233
234 def regexp_extraction(string, _regexp, groups=1):
235 """Returns the capture group (default=1) specified in the regexp, applied to the string"""
236 regexp_search = _regexp.search(string)
237 if regexp_search:
238 if regexp_search.group(groups) != "":
239 return regexp_search.group(groups)
240 return None
241
242
243 class BalancerMember:
244 """Apache 2.4 mod_proxy LB balancer member.
245 attributes:
246 read-only:
247 host -> member host (string),
248 management_url -> member management url (string),
249 protocol -> member protocol (string)
250 port -> member port (string),
251 path -> member location (string),
252 balancer_url -> url of this member's parent balancer (string),
253 attributes -> whole member attributes (dictionary)
254 module -> ansible module instance (AnsibleModule object).
255 writable:
256 status -> status of the member (dictionary)
257 """
258
259 def __init__(self, management_url, balancer_url, module):
260 self.host = regexp_extraction(management_url, EXPRESSION, 4)
261 self.management_url = management_url
262 self.protocol = regexp_extraction(management_url, EXPRESSION, 3)
263 self.port = regexp_extraction(management_url, EXPRESSION, 5)
264 self.path = regexp_extraction(management_url, EXPRESSION, 6)
265 self.balancer_url = balancer_url
266 self.module = module
267
268 def get_member_attributes(self):
269 """Returns a dictionary of a balancer member's attributes."""
270
271 resp, info = fetch_url(self.module, self.management_url, headers={"Referer": self.management_url})
272
273 if info["status"] != 200:
274 raise ModuleHelperException(f"Could not get balancer_member_page, check for connectivity! {info}")
275
276 try:
277 soup = BeautifulSoup(resp)
278 except TypeError as exc:
279 raise ModuleHelperException(f"Cannot parse balancer_member_page HTML! {exc}") from exc
280
281 subsoup = find_all(find_all(soup, "table")[1], "tr")
282 keys = find_all(subsoup[0], "th")
283 for valuesset in subsoup[1::1]:
284 if re.search(pattern=self.host, string=str(valuesset)):
285 values = find_all(valuesset, "td")
286 return {keys[x].string: values[x].string for x in range(0, len(keys))}
287
288 def get_member_status(self):
289 """Returns a dictionary of a balancer member's status attributes."""
290 status_mapping = {"disabled": "Dis", "drained": "Drn", "hot_standby": "Stby", "ignore_errors": "Ign"}
291 actual_status = self.attributes["Status"]
292 status = {mode: patt in actual_status for mode, patt in status_mapping.items()}
293 return status
294
295 def set_member_status(self, values):
296 """Sets a balancer member's status attributes amongst pre-mapped values."""
297 values_mapping = {
298 "disabled": "&w_status_D",
299 "drained": "&w_status_N",
300 "hot_standby": "&w_status_H",
301 "ignore_errors": "&w_status_I",
302 }
303
304 request_body = regexp_extraction(self.management_url, EXPRESSION, 1)
305 values_url = "".join(f"{url_param}={1 if values[mode] else 0}" for mode, url_param in values_mapping.items())
306 request_body = f"{request_body}{values_url}"
307
308 response, info = fetch_url(
309 self.module, self.management_url, data=request_body, headers={"Referer": self.management_url}
310 )
311 if info["status"] != 200:
312 raise ModuleHelperException(f"Could not set the member status! {self.host} {info['status']}")
313
314 attributes = property(get_member_attributes)
315 status = property(get_member_status, set_member_status)
316
317 def as_dict(self):
318 return {
319 "host": self.host,
320 "status": self.status,
321 "protocol": self.protocol,
322 "port": self.port,
323 "path": self.path,
324 "attributes": self.attributes,
325 "management_url": self.management_url,
326 "balancer_url": self.balancer_url,
327 }
328
329
330 class Balancer:
331 """Apache httpd 2.4 mod_proxy balancer object"""
332
333 def __init__(self, module, host, suffix, tls=False):
334 proto = "https" if tls else "http"
335 self.base_url = f"{proto}://{host}"
336 self.url = f"{proto}://{host}{suffix}"
337 self.module = module
338 self.page = self.fetch_balancer_page()
339
340 def fetch_balancer_page(self):
341 """Returns the balancer management html page as a string for later parsing."""
342 resp, info = fetch_url(self.module, self.url)
343 if info["status"] != 200:
344 raise ModuleHelperException(f"Could not get balancer page! HTTP status response: {info['status']}")
345
346 content = to_text(resp.read())
347 apache_version = regexp_extraction(content.upper(), APACHE_VERSION_EXPRESSION, 1)
348 if not apache_version:
349 raise ModuleHelperException("Could not get the Apache server version from the balancer-manager")
350
351 if not re.search(pattern=r"2\.4\.[\d]*", string=apache_version):
352 raise ModuleHelperException(
353 f"This module only acts on an Apache2 2.4+ instance, current Apache2 version: {apache_version}"
354 )
355 return content
356
357 def get_balancer_members(self):
358 """Returns members of the balancer as a generator object for later iteration."""
359 try:
360 soup = BeautifulSoup(self.page)
361 except TypeError as e:
362 raise ModuleHelperException(f"Cannot parse balancer page HTML! {self.page}") from e
363
364 elements = find_all(soup, "a")
365 for element in elements[1::1]:
366 balancer_member_suffix = element.get("href")
367 if not balancer_member_suffix:
368 raise ModuleHelperException("Argument 'balancer_member_suffix' is empty!")
369
370 yield BalancerMember(self.base_url + balancer_member_suffix, self.url, self.module)
371
372 members = property(get_balancer_members)
373
374
375 class ApacheModProxy(ModuleHelper):
376 """Initiates module."""
377
378 module = dict(
379 argument_spec=dict(
380 balancer_vhost=dict(required=True, type="str"),
381 balancer_url_suffix=dict(default="/balancer-manager/", type="str"),
382 member_host=dict(type="str"),
383 state=dict(
384 type="list",
385 elements="str",
386 choices=["present", "absent", "enabled", "disabled", "drained", "hot_standby", "ignore_errors"],
387 ),
388 tls=dict(default=False, type="bool"),
389 validate_certs=dict(default=True, type="bool"),
390 ),
391 supports_check_mode=True,
392 )
393
394 def __init_module__(self):
395 deps.validate(self.module)
396
397 if len(self.vars.state or []) > 1 and ("present" in self.vars.state or "enabled" in self.vars.state):
398 self.do_raise(msg="states present/enabled are mutually exclusive with other states!")
399
400 self.mybalancer = Balancer(
401 self.module, self.vars.balancer_vhost, self.vars.balancer_url_suffix, tls=self.vars.tls
402 )
403
404 def __run__(self):
405 if self.vars.member_host is None:
406 self.vars.members = [member.as_dict() for member in self.mybalancer.members]
407 else:
408 member_exists = False
409 member_status = {"disabled": False, "drained": False, "hot_standby": False, "ignore_errors": False}
410 for mode in member_status:
411 for state in self.vars.state or []:
412 if mode == state:
413 member_status[mode] = True
414 elif mode == "disabled" and state == "absent":
415 member_status[mode] = True
416
417 for member in self.mybalancer.members:
418 if str(member.host) == self.vars.member_host:
419 member_exists = True
420 if self.vars.state is not None:
421 member_status_before = member.status
422 if not self.check_mode:
423 member_status_after = member.status = member_status
424 else:
425 member_status_after = member_status
426 self.changed |= member_status_before != member_status_after
427 self.vars.member = member.as_dict()
428
429 if not member_exists:
430 self.do_raise(
431 msg=f"{self.vars.member_host} is not a member of the balancer {self.vars.balancer_vhost}!"
432 )
433
434
435 def main():
436 ApacheModProxy.execute()
437
438
439 if __name__ == "__main__":
440 main()