mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-03-30 08:56:18 +00:00
Reformat everything.
This commit is contained in:
parent
3f2213791a
commit
340ff8586d
1008 changed files with 61301 additions and 58309 deletions
|
|
@ -217,7 +217,7 @@ from ansible.module_utils.common.text.converters import to_bytes, to_text
|
|||
|
||||
DEFAULT_SOCKET_LOCATION = "/var/run/haproxy.sock"
|
||||
RECV_SIZE = 1024
|
||||
ACTION_CHOICES = ['enabled', 'disabled', 'drain']
|
||||
ACTION_CHOICES = ["enabled", "disabled", "drain"]
|
||||
WAIT_RETRIES = 25
|
||||
WAIT_INTERVAL = 5
|
||||
|
||||
|
|
@ -242,19 +242,19 @@ class HAProxy:
|
|||
def __init__(self, module):
|
||||
self.module = module
|
||||
|
||||
self.state = self.module.params['state']
|
||||
self.host = self.module.params['host']
|
||||
self.backend = self.module.params['backend']
|
||||
self.weight = self.module.params['weight']
|
||||
self.socket = self.module.params['socket']
|
||||
self.shutdown_sessions = self.module.params['shutdown_sessions']
|
||||
self.fail_on_not_found = self.module.params['fail_on_not_found']
|
||||
self.agent = self.module.params['agent']
|
||||
self.health = self.module.params['health']
|
||||
self.wait = self.module.params['wait']
|
||||
self.wait_retries = self.module.params['wait_retries']
|
||||
self.wait_interval = self.module.params['wait_interval']
|
||||
self._drain = self.module.params['drain']
|
||||
self.state = self.module.params["state"]
|
||||
self.host = self.module.params["host"]
|
||||
self.backend = self.module.params["backend"]
|
||||
self.weight = self.module.params["weight"]
|
||||
self.socket = self.module.params["socket"]
|
||||
self.shutdown_sessions = self.module.params["shutdown_sessions"]
|
||||
self.fail_on_not_found = self.module.params["fail_on_not_found"]
|
||||
self.agent = self.module.params["agent"]
|
||||
self.health = self.module.params["health"]
|
||||
self.wait = self.module.params["wait"]
|
||||
self.wait_retries = self.module.params["wait_retries"]
|
||||
self.wait_interval = self.module.params["wait_interval"]
|
||||
self._drain = self.module.params["drain"]
|
||||
self.command_results = {}
|
||||
|
||||
def execute(self, cmd, timeout=200, capture_output=True):
|
||||
|
|
@ -264,15 +264,15 @@ class HAProxy:
|
|||
"""
|
||||
self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.client.connect(self.socket)
|
||||
self.client.sendall(to_bytes(f'{cmd}\n'))
|
||||
self.client.sendall(to_bytes(f"{cmd}\n"))
|
||||
|
||||
result = b''
|
||||
buf = b''
|
||||
result = b""
|
||||
buf = b""
|
||||
buf = self.client.recv(RECV_SIZE)
|
||||
while buf:
|
||||
result += buf
|
||||
buf = self.client.recv(RECV_SIZE)
|
||||
result = to_text(result, errors='surrogate_or_strict')
|
||||
result = to_text(result, errors="surrogate_or_strict")
|
||||
|
||||
if capture_output:
|
||||
self.capture_command_output(cmd, result.strip())
|
||||
|
|
@ -283,32 +283,32 @@ class HAProxy:
|
|||
"""
|
||||
Capture the output for a command
|
||||
"""
|
||||
if 'command' not in self.command_results:
|
||||
self.command_results['command'] = []
|
||||
self.command_results['command'].append(cmd)
|
||||
if 'output' not in self.command_results:
|
||||
self.command_results['output'] = []
|
||||
self.command_results['output'].append(output)
|
||||
if "command" not in self.command_results:
|
||||
self.command_results["command"] = []
|
||||
self.command_results["command"].append(cmd)
|
||||
if "output" not in self.command_results:
|
||||
self.command_results["output"] = []
|
||||
self.command_results["output"].append(output)
|
||||
|
||||
def discover_all_backends(self):
|
||||
"""
|
||||
Discover all entries with svname = 'BACKEND' and return a list of their corresponding
|
||||
pxnames
|
||||
"""
|
||||
data = self.execute('show stat', 200, False).lstrip('# ')
|
||||
data = self.execute("show stat", 200, False).lstrip("# ")
|
||||
r = csv.DictReader(data.splitlines())
|
||||
return tuple(d['pxname'] for d in r if d['svname'] == 'BACKEND')
|
||||
return tuple(d["pxname"] for d in r if d["svname"] == "BACKEND")
|
||||
|
||||
def discover_version(self):
|
||||
"""
|
||||
Attempt to extract the haproxy version.
|
||||
Return a tuple containing major and minor version.
|
||||
"""
|
||||
data = self.execute('show info', 200, False)
|
||||
data = self.execute("show info", 200, False)
|
||||
lines = data.splitlines()
|
||||
line = [x for x in lines if 'Version:' in x]
|
||||
line = [x for x in lines if "Version:" in x]
|
||||
try:
|
||||
version_values = line[0].partition(':')[2].strip().split('.', 3)
|
||||
version_values = line[0].partition(":")[2].strip().split(".", 3)
|
||||
version = (int(version_values[0]), int(version_values[1]))
|
||||
except (ValueError, TypeError, IndexError):
|
||||
version = None
|
||||
|
|
@ -331,8 +331,7 @@ class HAProxy:
|
|||
# Fail when backends were not found
|
||||
state = self.get_state_for(backend, svname)
|
||||
if (self.fail_on_not_found) and state is None:
|
||||
self.module.fail_json(
|
||||
msg=f"The specified backend '{backend}/{svname}' was not found!")
|
||||
self.module.fail_json(msg=f"The specified backend '{backend}/{svname}' was not found!")
|
||||
|
||||
if state is not None:
|
||||
self.execute(Template(cmd).substitute(pxname=backend, svname=svname))
|
||||
|
|
@ -344,13 +343,13 @@ class HAProxy:
|
|||
Find the state of specific services. When pxname is not set, get all backends for a specific host.
|
||||
Returns a list of dictionaries containing the status and weight for those services.
|
||||
"""
|
||||
data = self.execute('show stat', 200, False).lstrip('# ')
|
||||
data = self.execute("show stat", 200, False).lstrip("# ")
|
||||
r = csv.DictReader(data.splitlines())
|
||||
|
||||
def unpack_state(d):
|
||||
return {'status': d['status'], 'weight': d['weight'], 'scur': d['scur']}
|
||||
return {"status": d["status"], "weight": d["weight"], "scur": d["scur"]}
|
||||
|
||||
state = tuple(unpack_state(d) for d in r if (pxname is None or d['pxname'] == pxname) and d['svname'] == svname)
|
||||
state = tuple(unpack_state(d) for d in r if (pxname is None or d["pxname"] == pxname) and d["svname"] == svname)
|
||||
return state or None
|
||||
|
||||
def wait_until_status(self, pxname, svname, status):
|
||||
|
|
@ -365,12 +364,14 @@ class HAProxy:
|
|||
|
||||
# We can assume there will only be 1 element in state because both svname and pxname are always set when we get here
|
||||
# When using track we get a status like this: MAINT (via pxname/svname) so we need to do substring matching
|
||||
if status in state[0]['status']:
|
||||
if not self._drain or state[0]['scur'] == '0':
|
||||
if status in state[0]["status"]:
|
||||
if not self._drain or state[0]["scur"] == "0":
|
||||
return True
|
||||
time.sleep(self.wait_interval)
|
||||
|
||||
self.module.fail_json(msg=f"server {pxname}/{svname} not status '{status}' after {self.wait_retries} retries. Aborting.")
|
||||
self.module.fail_json(
|
||||
msg=f"server {pxname}/{svname} not status '{status}' after {self.wait_retries} retries. Aborting."
|
||||
)
|
||||
|
||||
def enabled(self, host, backend, weight):
|
||||
"""
|
||||
|
|
@ -385,7 +386,7 @@ class HAProxy:
|
|||
cmd += "; enable health $pxname/$svname"
|
||||
if weight:
|
||||
cmd += f"; set weight $pxname/$svname {weight}"
|
||||
self.execute_for_backends(cmd, backend, host, 'UP')
|
||||
self.execute_for_backends(cmd, backend, host, "UP")
|
||||
|
||||
def disabled(self, host, backend, shutdown_sessions):
|
||||
"""
|
||||
|
|
@ -401,9 +402,9 @@ class HAProxy:
|
|||
cmd += "; disable server $pxname/$svname"
|
||||
if shutdown_sessions:
|
||||
cmd += "; shutdown sessions server $pxname/$svname"
|
||||
self.execute_for_backends(cmd, backend, host, 'MAINT')
|
||||
self.execute_for_backends(cmd, backend, host, "MAINT")
|
||||
|
||||
def drain(self, host, backend, status='DRAIN'):
|
||||
def drain(self, host, backend, status="DRAIN"):
|
||||
"""
|
||||
Drain action, sets the server to DRAIN mode.
|
||||
In this mode, the server will not accept any new connections
|
||||
|
|
@ -423,47 +424,46 @@ class HAProxy:
|
|||
Figure out what you want to do from ansible, and then do it.
|
||||
"""
|
||||
# Get the state before the run
|
||||
self.command_results['state_before'] = self.get_state_for(self.backend, self.host)
|
||||
self.command_results["state_before"] = self.get_state_for(self.backend, self.host)
|
||||
|
||||
# toggle enable/disable server
|
||||
if self.state == 'enabled':
|
||||
if self.state == "enabled":
|
||||
self.enabled(self.host, self.backend, self.weight)
|
||||
elif self.state == 'disabled' and self._drain:
|
||||
self.drain(self.host, self.backend, status='MAINT')
|
||||
elif self.state == 'disabled':
|
||||
elif self.state == "disabled" and self._drain:
|
||||
self.drain(self.host, self.backend, status="MAINT")
|
||||
elif self.state == "disabled":
|
||||
self.disabled(self.host, self.backend, self.shutdown_sessions)
|
||||
elif self.state == 'drain':
|
||||
elif self.state == "drain":
|
||||
self.drain(self.host, self.backend)
|
||||
else:
|
||||
self.module.fail_json(msg=f"unknown state specified: '{self.state}'")
|
||||
|
||||
# Get the state after the run
|
||||
self.command_results['state_after'] = self.get_state_for(self.backend, self.host)
|
||||
self.command_results["state_after"] = self.get_state_for(self.backend, self.host)
|
||||
|
||||
# Report change status
|
||||
self.command_results['changed'] = (self.command_results['state_before'] != self.command_results['state_after'])
|
||||
self.command_results["changed"] = self.command_results["state_before"] != self.command_results["state_after"]
|
||||
|
||||
self.module.exit_json(**self.command_results)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# load ansible module object
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
state=dict(type='str', required=True, choices=ACTION_CHOICES),
|
||||
host=dict(type='str', required=True),
|
||||
backend=dict(type='str'),
|
||||
weight=dict(type='str'),
|
||||
socket=dict(type='path', default=DEFAULT_SOCKET_LOCATION),
|
||||
shutdown_sessions=dict(type='bool', default=False),
|
||||
fail_on_not_found=dict(type='bool', default=False),
|
||||
health=dict(type='bool', default=False),
|
||||
agent=dict(type='bool', default=False),
|
||||
wait=dict(type='bool', default=False),
|
||||
wait_retries=dict(type='int', default=WAIT_RETRIES),
|
||||
wait_interval=dict(type='int', default=WAIT_INTERVAL),
|
||||
drain=dict(type='bool', default=False),
|
||||
state=dict(type="str", required=True, choices=ACTION_CHOICES),
|
||||
host=dict(type="str", required=True),
|
||||
backend=dict(type="str"),
|
||||
weight=dict(type="str"),
|
||||
socket=dict(type="path", default=DEFAULT_SOCKET_LOCATION),
|
||||
shutdown_sessions=dict(type="bool", default=False),
|
||||
fail_on_not_found=dict(type="bool", default=False),
|
||||
health=dict(type="bool", default=False),
|
||||
agent=dict(type="bool", default=False),
|
||||
wait=dict(type="bool", default=False),
|
||||
wait_retries=dict(type="int", default=WAIT_RETRIES),
|
||||
wait_interval=dict(type="int", default=WAIT_INTERVAL),
|
||||
drain=dict(type="bool", default=False),
|
||||
),
|
||||
)
|
||||
|
||||
|
|
@ -474,5 +474,5 @@ def main():
|
|||
ansible_haproxy.act()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue