mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-03-27 07:27:33 +00:00
Reformat everything.
This commit is contained in:
parent
3f2213791a
commit
340ff8586d
1008 changed files with 61301 additions and 58309 deletions
|
|
@ -218,7 +218,9 @@ with deps.declare("beautifulsoup4"):
|
|||
from bs4 import BeautifulSoup
|
||||
|
||||
# balancer member attributes extraction regexp:
|
||||
EXPRESSION = re.compile(to_text(r"(b=([\w\.\-]+)&w=(https?|ajp|wss?|ftp|[sf]cgi)://([\w\.\-]+):?(\d*)([/\w\.\-]*)&?[\w\-\=]*)"))
|
||||
EXPRESSION = re.compile(
|
||||
to_text(r"(b=([\w\.\-]+)&w=(https?|ajp|wss?|ftp|[sf]cgi)://([\w\.\-]+):?(\d*)([/\w\.\-]*)&?[\w\-\=]*)")
|
||||
)
|
||||
# Apache2 server version extraction regexp:
|
||||
APACHE_VERSION_EXPRESSION = re.compile(to_text(r"SERVER VERSION: APACHE/([\d.]+)"))
|
||||
|
||||
|
|
@ -228,16 +230,16 @@ def find_all(where, what):
|
|||
|
||||
|
||||
def regexp_extraction(string, _regexp, groups=1):
|
||||
""" Returns the capture group (default=1) specified in the regexp, applied to the string """
|
||||
"""Returns the capture group (default=1) specified in the regexp, applied to the string"""
|
||||
regexp_search = _regexp.search(string)
|
||||
if regexp_search:
|
||||
if regexp_search.group(groups) != '':
|
||||
if regexp_search.group(groups) != "":
|
||||
return regexp_search.group(groups)
|
||||
return None
|
||||
|
||||
|
||||
class BalancerMember:
|
||||
""" Apache 2.4 mod_proxy LB balancer member.
|
||||
"""Apache 2.4 mod_proxy LB balancer member.
|
||||
attributes:
|
||||
read-only:
|
||||
host -> member host (string),
|
||||
|
|
@ -262,11 +264,11 @@ class BalancerMember:
|
|||
self.module = module
|
||||
|
||||
def get_member_attributes(self):
|
||||
""" Returns a dictionary of a balancer member's attributes."""
|
||||
"""Returns a dictionary of a balancer member's attributes."""
|
||||
|
||||
resp, info = fetch_url(self.module, self.management_url, headers={'Referer': self.management_url})
|
||||
resp, info = fetch_url(self.module, self.management_url, headers={"Referer": self.management_url})
|
||||
|
||||
if info['status'] != 200:
|
||||
if info["status"] != 200:
|
||||
raise ModuleHelperException(f"Could not get balancer_member_page, check for connectivity! {info}")
|
||||
|
||||
try:
|
||||
|
|
@ -274,36 +276,37 @@ class BalancerMember:
|
|||
except TypeError as exc:
|
||||
raise ModuleHelperException(f"Cannot parse balancer_member_page HTML! {exc}") from exc
|
||||
|
||||
subsoup = find_all(find_all(soup, 'table')[1], 'tr')
|
||||
keys = find_all(subsoup[0], 'th')
|
||||
subsoup = find_all(find_all(soup, "table")[1], "tr")
|
||||
keys = find_all(subsoup[0], "th")
|
||||
for valuesset in subsoup[1::1]:
|
||||
if re.search(pattern=self.host, string=str(valuesset)):
|
||||
values = find_all(valuesset, 'td')
|
||||
values = find_all(valuesset, "td")
|
||||
return {keys[x].string: values[x].string for x in range(0, len(keys))}
|
||||
|
||||
def get_member_status(self):
|
||||
""" Returns a dictionary of a balancer member's status attributes."""
|
||||
status_mapping = {'disabled': 'Dis',
|
||||
'drained': 'Drn',
|
||||
'hot_standby': 'Stby',
|
||||
'ignore_errors': 'Ign'}
|
||||
actual_status = self.attributes['Status']
|
||||
"""Returns a dictionary of a balancer member's status attributes."""
|
||||
status_mapping = {"disabled": "Dis", "drained": "Drn", "hot_standby": "Stby", "ignore_errors": "Ign"}
|
||||
actual_status = self.attributes["Status"]
|
||||
status = {mode: patt in actual_status for mode, patt in status_mapping.items()}
|
||||
return status
|
||||
|
||||
def set_member_status(self, values):
|
||||
""" Sets a balancer member's status attributes amongst pre-mapped values."""
|
||||
values_mapping = {'disabled': '&w_status_D',
|
||||
'drained': '&w_status_N',
|
||||
'hot_standby': '&w_status_H',
|
||||
'ignore_errors': '&w_status_I'}
|
||||
"""Sets a balancer member's status attributes amongst pre-mapped values."""
|
||||
values_mapping = {
|
||||
"disabled": "&w_status_D",
|
||||
"drained": "&w_status_N",
|
||||
"hot_standby": "&w_status_H",
|
||||
"ignore_errors": "&w_status_I",
|
||||
}
|
||||
|
||||
request_body = regexp_extraction(self.management_url, EXPRESSION, 1)
|
||||
values_url = "".join(f"{url_param}={1 if values[mode] else 0}" for mode, url_param in values_mapping.items())
|
||||
request_body = f"{request_body}{values_url}"
|
||||
|
||||
response, info = fetch_url(self.module, self.management_url, data=request_body, headers={'Referer': self.management_url})
|
||||
if info['status'] != 200:
|
||||
response, info = fetch_url(
|
||||
self.module, self.management_url, data=request_body, headers={"Referer": self.management_url}
|
||||
)
|
||||
if info["status"] != 200:
|
||||
raise ModuleHelperException(f"Could not set the member status! {self.host} {info['status']}")
|
||||
|
||||
attributes = property(get_member_attributes)
|
||||
|
|
@ -318,24 +321,24 @@ class BalancerMember:
|
|||
"path": self.path,
|
||||
"attributes": self.attributes,
|
||||
"management_url": self.management_url,
|
||||
"balancer_url": self.balancer_url
|
||||
"balancer_url": self.balancer_url,
|
||||
}
|
||||
|
||||
|
||||
class Balancer:
|
||||
""" Apache httpd 2.4 mod_proxy balancer object"""
|
||||
"""Apache httpd 2.4 mod_proxy balancer object"""
|
||||
|
||||
def __init__(self, module, host, suffix, tls=False):
|
||||
proto = "https" if tls else "http"
|
||||
self.base_url = f'{proto}://{host}'
|
||||
self.url = f'{proto}://{host}{suffix}'
|
||||
self.base_url = f"{proto}://{host}"
|
||||
self.url = f"{proto}://{host}{suffix}"
|
||||
self.module = module
|
||||
self.page = self.fetch_balancer_page()
|
||||
|
||||
def fetch_balancer_page(self):
|
||||
""" Returns the balancer management html page as a string for later parsing."""
|
||||
"""Returns the balancer management html page as a string for later parsing."""
|
||||
resp, info = fetch_url(self.module, self.url)
|
||||
if info['status'] != 200:
|
||||
if info["status"] != 200:
|
||||
raise ModuleHelperException(f"Could not get balancer page! HTTP status response: {info['status']}")
|
||||
|
||||
content = to_text(resp.read())
|
||||
|
|
@ -344,19 +347,21 @@ class Balancer:
|
|||
raise ModuleHelperException("Could not get the Apache server version from the balancer-manager")
|
||||
|
||||
if not re.search(pattern=r"2\.4\.[\d]*", string=apache_version):
|
||||
raise ModuleHelperException(f"This module only acts on an Apache2 2.4+ instance, current Apache2 version: {apache_version}")
|
||||
raise ModuleHelperException(
|
||||
f"This module only acts on an Apache2 2.4+ instance, current Apache2 version: {apache_version}"
|
||||
)
|
||||
return content
|
||||
|
||||
def get_balancer_members(self):
|
||||
""" Returns members of the balancer as a generator object for later iteration."""
|
||||
"""Returns members of the balancer as a generator object for later iteration."""
|
||||
try:
|
||||
soup = BeautifulSoup(self.page)
|
||||
except TypeError as e:
|
||||
raise ModuleHelperException(f"Cannot parse balancer page HTML! {self.page}") from e
|
||||
|
||||
elements = find_all(soup, 'a')
|
||||
elements = find_all(soup, "a")
|
||||
for element in elements[1::1]:
|
||||
balancer_member_suffix = element.get('href')
|
||||
balancer_member_suffix = element.get("href")
|
||||
if not balancer_member_suffix:
|
||||
raise ModuleHelperException("Argument 'balancer_member_suffix' is empty!")
|
||||
|
||||
|
|
@ -366,17 +371,22 @@ class Balancer:
|
|||
|
||||
|
||||
class ApacheModProxy(ModuleHelper):
|
||||
""" Initiates module."""
|
||||
"""Initiates module."""
|
||||
|
||||
module = dict(
|
||||
argument_spec=dict(
|
||||
balancer_vhost=dict(required=True, type='str'),
|
||||
balancer_url_suffix=dict(default="/balancer-manager/", type='str'),
|
||||
member_host=dict(type='str'),
|
||||
state=dict(type='list', elements='str', choices=['present', 'absent', 'enabled', 'disabled', 'drained', 'hot_standby', 'ignore_errors']),
|
||||
tls=dict(default=False, type='bool'),
|
||||
validate_certs=dict(default=True, type='bool')
|
||||
balancer_vhost=dict(required=True, type="str"),
|
||||
balancer_url_suffix=dict(default="/balancer-manager/", type="str"),
|
||||
member_host=dict(type="str"),
|
||||
state=dict(
|
||||
type="list",
|
||||
elements="str",
|
||||
choices=["present", "absent", "enabled", "disabled", "drained", "hot_standby", "ignore_errors"],
|
||||
),
|
||||
tls=dict(default=False, type="bool"),
|
||||
validate_certs=dict(default=True, type="bool"),
|
||||
),
|
||||
supports_check_mode=True
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
def __init_module__(self):
|
||||
|
|
@ -385,19 +395,21 @@ class ApacheModProxy(ModuleHelper):
|
|||
if len(self.vars.state or []) > 1 and ("present" in self.vars.state or "enabled" in self.vars.state):
|
||||
self.do_raise(msg="states present/enabled are mutually exclusive with other states!")
|
||||
|
||||
self.mybalancer = Balancer(self.module, self.vars.balancer_vhost, self.vars.balancer_url_suffix, tls=self.vars.tls)
|
||||
self.mybalancer = Balancer(
|
||||
self.module, self.vars.balancer_vhost, self.vars.balancer_url_suffix, tls=self.vars.tls
|
||||
)
|
||||
|
||||
def __run__(self):
|
||||
if self.vars.member_host is None:
|
||||
self.vars.members = [member.as_dict() for member in self.mybalancer.members]
|
||||
else:
|
||||
member_exists = False
|
||||
member_status = {'disabled': False, 'drained': False, 'hot_standby': False, 'ignore_errors': False}
|
||||
member_status = {"disabled": False, "drained": False, "hot_standby": False, "ignore_errors": False}
|
||||
for mode in member_status:
|
||||
for state in self.vars.state or []:
|
||||
if mode == state:
|
||||
member_status[mode] = True
|
||||
elif mode == 'disabled' and state == 'absent':
|
||||
elif mode == "disabled" and state == "absent":
|
||||
member_status[mode] = True
|
||||
|
||||
for member in self.mybalancer.members:
|
||||
|
|
@ -409,16 +421,18 @@ class ApacheModProxy(ModuleHelper):
|
|||
member_status_after = member.status = member_status
|
||||
else:
|
||||
member_status_after = member_status
|
||||
self.changed |= (member_status_before != member_status_after)
|
||||
self.changed |= member_status_before != member_status_after
|
||||
self.vars.member = member.as_dict()
|
||||
|
||||
if not member_exists:
|
||||
self.do_raise(msg=f'{self.vars.member_host} is not a member of the balancer {self.vars.balancer_vhost}!')
|
||||
self.do_raise(
|
||||
msg=f"{self.vars.member_host} is not a member of the balancer {self.vars.balancer_vhost}!"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
ApacheModProxy.execute()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue