| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2014, Ravi Bhure <[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: haproxy |
| 11 |
short_description: Enable, disable, and set weights for HAProxy backend servers using socket commands |
| 12 |
author: |
| 13 |
- Ravi Bhure (@ravibhure) |
| 14 |
description: |
| 15 |
- Enable, disable, drain and set weights for HAProxy backend servers using socket commands. |
| 16 |
notes: |
| 17 |
- Enable, disable and drain commands are restricted and can only be issued on sockets configured for level C(admin). For |
| 18 |
example, you can add the line C(stats socket /var/run/haproxy.sock level admin) to the general section of C(haproxy.cfg). |
| 19 |
See U(http://haproxy.1wt.eu/download/1.5/doc/configuration.txt). |
| 20 |
- Depends on netcat (C(nc)) being available; you need to install the appropriate package for your operating system before |
| 21 |
this module can be used. |
| 22 |
extends_documentation_fragment: |
| 23 |
- community.general._attributes |
| 24 |
attributes: |
| 25 |
check_mode: |
| 26 |
support: none |
| 27 |
diff_mode: |
| 28 |
support: none |
| 29 |
options: |
| 30 |
backend: |
| 31 |
description: |
| 32 |
- Name of the HAProxy backend pool. |
| 33 |
- If this parameter is unset, it is auto-detected. |
| 34 |
type: str |
| 35 |
drain: |
| 36 |
description: |
| 37 |
- Wait until the server has no active connections or until the timeout determined by O(wait_interval) and O(wait_retries) |
| 38 |
is reached. |
| 39 |
- Continue only after the status changes to C(MAINT). |
| 40 |
- This overrides the shutdown_sessions option. |
| 41 |
type: bool |
| 42 |
default: false |
| 43 |
host: |
| 44 |
description: |
| 45 |
- Name of the backend host to change. |
| 46 |
type: str |
| 47 |
required: true |
| 48 |
shutdown_sessions: |
| 49 |
description: |
| 50 |
- When disabling a server, immediately terminate all the sessions attached to the specified server. |
| 51 |
- This can be used to terminate long-running sessions after a server is put into maintenance mode. Overridden by the |
| 52 |
drain option. |
| 53 |
type: bool |
| 54 |
default: false |
| 55 |
socket: |
| 56 |
description: |
| 57 |
- Path to the HAProxy socket file. |
| 58 |
type: path |
| 59 |
default: /var/run/haproxy.sock |
| 60 |
state: |
| 61 |
description: |
| 62 |
- Desired state of the provided backend host. |
| 63 |
- Note that V(drain) state is supported only by HAProxy version 1.5 or later. When used on versions < 1.5, it is ignored. |
| 64 |
type: str |
| 65 |
required: true |
| 66 |
choices: [disabled, drain, enabled] |
| 67 |
agent: |
| 68 |
description: |
| 69 |
- Disable/enable agent checks (depending on O(state) value). |
| 70 |
type: bool |
| 71 |
default: false |
| 72 |
version_added: 1.0.0 |
| 73 |
health: |
| 74 |
description: |
| 75 |
- Disable/enable health checks (depending on O(state) value). |
| 76 |
type: bool |
| 77 |
default: false |
| 78 |
version_added: "1.0.0" |
| 79 |
fail_on_not_found: |
| 80 |
description: |
| 81 |
- Fail whenever trying to enable/disable a backend host that does not exist. |
| 82 |
type: bool |
| 83 |
default: false |
| 84 |
wait: |
| 85 |
description: |
| 86 |
- Wait until the server reports a status of C(UP) when O(state=enabled), status of C(MAINT) when O(state=disabled) or |
| 87 |
status of C(DRAIN) when O(state=drain). |
| 88 |
type: bool |
| 89 |
default: false |
| 90 |
wait_interval: |
| 91 |
description: |
| 92 |
- Number of seconds to wait between retries. |
| 93 |
type: int |
| 94 |
default: 5 |
| 95 |
wait_retries: |
| 96 |
description: |
| 97 |
- Number of times to check for status after changing the state. |
| 98 |
type: int |
| 99 |
default: 25 |
| 100 |
weight: |
| 101 |
description: |
| 102 |
- The value passed in argument. |
| 103 |
- If the value ends with the V(%) sign, then the new weight is relative to the initially configured weight. |
| 104 |
- Relative weights are only permitted between 0 and 100% and absolute weights are permitted between 0 and 256. |
| 105 |
type: str |
| 106 |
""" |
| 107 |
|
| 108 |
EXAMPLES = r""" |
| 109 |
- name: Disable server in 'www' backend pool |
| 110 |
community.general.haproxy: |
| 111 |
state: disabled |
| 112 |
host: '{{ inventory_hostname }}' |
| 113 |
backend: www |
| 114 |
|
| 115 |
- name: Disable server in 'www' backend pool, also stop health/agent checks |
| 116 |
community.general.haproxy: |
| 117 |
state: disabled |
| 118 |
host: '{{ inventory_hostname }}' |
| 119 |
health: true |
| 120 |
agent: true |
| 121 |
|
| 122 |
- name: Disable server without backend pool name (apply to all available backend pool) |
| 123 |
community.general.haproxy: |
| 124 |
state: disabled |
| 125 |
host: '{{ inventory_hostname }}' |
| 126 |
|
| 127 |
- name: Disable server, provide socket file |
| 128 |
community.general.haproxy: |
| 129 |
state: disabled |
| 130 |
host: '{{ inventory_hostname }}' |
| 131 |
socket: /var/run/haproxy.sock |
| 132 |
backend: www |
| 133 |
|
| 134 |
- name: Disable server, provide socket file, wait until status reports in maintenance |
| 135 |
community.general.haproxy: |
| 136 |
state: disabled |
| 137 |
host: '{{ inventory_hostname }}' |
| 138 |
socket: /var/run/haproxy.sock |
| 139 |
backend: www |
| 140 |
wait: true |
| 141 |
|
| 142 |
# Place server in drain mode, providing a socket file. Then check the server's |
| 143 |
# status every minute to see if it changes to maintenance mode, continuing if it |
| 144 |
# does in an hour and failing otherwise. |
| 145 |
- community.general.haproxy: |
| 146 |
state: disabled |
| 147 |
host: '{{ inventory_hostname }}' |
| 148 |
socket: /var/run/haproxy.sock |
| 149 |
backend: www |
| 150 |
wait: true |
| 151 |
drain: true |
| 152 |
wait_interval: 60 |
| 153 |
wait_retries: 60 |
| 154 |
|
| 155 |
- name: Disable backend server in 'www' backend pool and drop open sessions to it |
| 156 |
community.general.haproxy: |
| 157 |
state: disabled |
| 158 |
host: '{{ inventory_hostname }}' |
| 159 |
backend: www |
| 160 |
socket: /var/run/haproxy.sock |
| 161 |
shutdown_sessions: true |
| 162 |
|
| 163 |
- name: Disable server without backend pool name (apply to all available backend pool) but fail when the backend host is |
| 164 |
not found |
| 165 |
community.general.haproxy: |
| 166 |
state: disabled |
| 167 |
host: '{{ inventory_hostname }}' |
| 168 |
fail_on_not_found: true |
| 169 |
|
| 170 |
- name: Enable server in 'www' backend pool |
| 171 |
community.general.haproxy: |
| 172 |
state: enabled |
| 173 |
host: '{{ inventory_hostname }}' |
| 174 |
backend: www |
| 175 |
|
| 176 |
- name: Enable server in 'www' backend pool wait until healthy |
| 177 |
community.general.haproxy: |
| 178 |
state: enabled |
| 179 |
host: '{{ inventory_hostname }}' |
| 180 |
backend: www |
| 181 |
wait: true |
| 182 |
|
| 183 |
- name: Enable server in 'www' backend pool wait until healthy. Retry 10 times with intervals of 5 seconds to retrieve the |
| 184 |
health |
| 185 |
community.general.haproxy: |
| 186 |
state: enabled |
| 187 |
host: '{{ inventory_hostname }}' |
| 188 |
backend: www |
| 189 |
wait: true |
| 190 |
wait_retries: 10 |
| 191 |
wait_interval: 5 |
| 192 |
|
| 193 |
- name: Enable server in 'www' backend pool with change server(s) weight |
| 194 |
community.general.haproxy: |
| 195 |
state: enabled |
| 196 |
host: '{{ inventory_hostname }}' |
| 197 |
socket: /var/run/haproxy.sock |
| 198 |
weight: 10 |
| 199 |
backend: www |
| 200 |
|
| 201 |
- name: Set the server in 'www' backend pool to drain mode |
| 202 |
community.general.haproxy: |
| 203 |
state: drain |
| 204 |
host: '{{ inventory_hostname }}' |
| 205 |
socket: /var/run/haproxy.sock |
| 206 |
backend: www |
| 207 |
""" |
| 208 |
|
| 209 |
import csv |
| 210 |
import socket |
| 211 |
import time |
| 212 |
from string import Template |
| 213 |
|
| 214 |
from ansible.module_utils.basic import AnsibleModule |
| 215 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 216 |
|
| 217 |
DEFAULT_SOCKET_LOCATION = "/var/run/haproxy.sock" |
| 218 |
RECV_SIZE = 1024 |
| 219 |
ACTION_CHOICES = ["enabled", "disabled", "drain"] |
| 220 |
WAIT_RETRIES = 25 |
| 221 |
WAIT_INTERVAL = 5 |
| 222 |
|
| 223 |
|
| 224 |
###################################################################### |
| 225 |
class TimeoutException(Exception): |
| 226 |
pass |
| 227 |
|
| 228 |
|
| 229 |
class HAProxy: |
| 230 |
""" |
| 231 |
Used for communicating with HAProxy through its local UNIX socket interface. |
| 232 |
Perform common tasks in Haproxy related to enable server and |
| 233 |
disable server. |
| 234 |
|
| 235 |
The complete set of external commands Haproxy handles is documented |
| 236 |
on their website: |
| 237 |
|
| 238 |
http://haproxy.1wt.eu/download/1.5/doc/configuration.txt#Unix Socket commands |
| 239 |
""" |
| 240 |
|
| 241 |
def __init__(self, module): |
| 242 |
self.module = module |
| 243 |
|
| 244 |
self.state = self.module.params["state"] |
| 245 |
self.host = self.module.params["host"] |
| 246 |
self.backend = self.module.params["backend"] |
| 247 |
self.weight = self.module.params["weight"] |
| 248 |
self.socket = self.module.params["socket"] |
| 249 |
self.shutdown_sessions = self.module.params["shutdown_sessions"] |
| 250 |
self.fail_on_not_found = self.module.params["fail_on_not_found"] |
| 251 |
self.agent = self.module.params["agent"] |
| 252 |
self.health = self.module.params["health"] |
| 253 |
self.wait = self.module.params["wait"] |
| 254 |
self.wait_retries = self.module.params["wait_retries"] |
| 255 |
self.wait_interval = self.module.params["wait_interval"] |
| 256 |
self._drain = self.module.params["drain"] |
| 257 |
self.command_results = {} |
| 258 |
|
| 259 |
def execute(self, cmd, timeout=200, capture_output=True): |
| 260 |
""" |
| 261 |
Executes a HAProxy command by sending a message to a HAProxy's local |
| 262 |
UNIX socket and waiting up to 'timeout' milliseconds for the response. |
| 263 |
""" |
| 264 |
self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 265 |
self.client.connect(self.socket) |
| 266 |
self.client.sendall(to_bytes(f"{cmd}\n")) |
| 267 |
|
| 268 |
result = b"" |
| 269 |
buf = b"" |
| 270 |
buf = self.client.recv(RECV_SIZE) |
| 271 |
while buf: |
| 272 |
result += buf |
| 273 |
buf = self.client.recv(RECV_SIZE) |
| 274 |
result = to_text(result, errors="surrogate_or_strict") |
| 275 |
|
| 276 |
if capture_output: |
| 277 |
self.capture_command_output(cmd, result.strip()) |
| 278 |
self.client.close() |
| 279 |
return result |
| 280 |
|
| 281 |
def capture_command_output(self, cmd, output): |
| 282 |
""" |
| 283 |
Capture the output for a command |
| 284 |
""" |
| 285 |
if "command" not in self.command_results: |
| 286 |
self.command_results["command"] = [] |
| 287 |
self.command_results["command"].append(cmd) |
| 288 |
if "output" not in self.command_results: |
| 289 |
self.command_results["output"] = [] |
| 290 |
self.command_results["output"].append(output) |
| 291 |
|
| 292 |
def discover_all_backends(self): |
| 293 |
""" |
| 294 |
Discover all entries with svname = 'BACKEND' and return a list of their corresponding |
| 295 |
pxnames |
| 296 |
""" |
| 297 |
data = self.execute("show stat", 200, False).lstrip("# ") |
| 298 |
r = csv.DictReader(data.splitlines()) |
| 299 |
return tuple(d["pxname"] for d in r if d["svname"] == "BACKEND") |
| 300 |
|
| 301 |
def discover_version(self): |
| 302 |
""" |
| 303 |
Attempt to extract the haproxy version. |
| 304 |
Return a tuple containing major and minor version. |
| 305 |
""" |
| 306 |
data = self.execute("show info", 200, False) |
| 307 |
lines = data.splitlines() |
| 308 |
line = [x for x in lines if "Version:" in x] |
| 309 |
try: |
| 310 |
version_values = line[0].partition(":")[2].strip().split(".", 3) |
| 311 |
version = (int(version_values[0]), int(version_values[1])) |
| 312 |
except (ValueError, TypeError, IndexError): |
| 313 |
version = None |
| 314 |
|
| 315 |
return version |
| 316 |
|
| 317 |
def execute_for_backends(self, cmd, pxname, svname, wait_for_status=None): |
| 318 |
""" |
| 319 |
Run some command on the specified backends. If no backends are provided they will |
| 320 |
be discovered automatically (all backends) |
| 321 |
""" |
| 322 |
# Discover backends if none are given |
| 323 |
if pxname is None: |
| 324 |
backends = self.discover_all_backends() |
| 325 |
else: |
| 326 |
backends = [pxname] |
| 327 |
|
| 328 |
# Run the command for each requested backend |
| 329 |
for backend in backends: |
| 330 |
# Fail when backends were not found |
| 331 |
state = self.get_state_for(backend, svname) |
| 332 |
if (self.fail_on_not_found) and state is None: |
| 333 |
self.module.fail_json(msg=f"The specified backend '{backend}/{svname}' was not found!") |
| 334 |
|
| 335 |
if state is not None: |
| 336 |
self.execute(Template(cmd).substitute(pxname=backend, svname=svname)) |
| 337 |
if self.wait and not (wait_for_status == "DRAIN" and state == "DOWN"): |
| 338 |
self.wait_until_status(backend, svname, wait_for_status) |
| 339 |
|
| 340 |
def get_state_for(self, pxname, svname): |
| 341 |
""" |
| 342 |
Find the state of specific services. When pxname is not set, get all backends for a specific host. |
| 343 |
Returns a list of dictionaries containing the status and weight for those services. |
| 344 |
""" |
| 345 |
data = self.execute("show stat", 200, False).lstrip("# ") |
| 346 |
r = csv.DictReader(data.splitlines()) |
| 347 |
|
| 348 |
def unpack_state(d): |
| 349 |
return {"status": d["status"], "weight": d["weight"], "scur": d["scur"]} |
| 350 |
|
| 351 |
state = tuple(unpack_state(d) for d in r if (pxname is None or d["pxname"] == pxname) and d["svname"] == svname) |
| 352 |
return state or None |
| 353 |
|
| 354 |
def wait_until_status(self, pxname, svname, status): |
| 355 |
""" |
| 356 |
Wait for a service to reach the specified status. Try RETRIES times |
| 357 |
with INTERVAL seconds of sleep in between. If the service has not reached |
| 358 |
the expected status in that time, the module will fail. If the service was |
| 359 |
not found, the module will fail. |
| 360 |
""" |
| 361 |
for _i in range(1, self.wait_retries): |
| 362 |
state = self.get_state_for(pxname, svname) |
| 363 |
|
| 364 |
# We can assume there will only be 1 element in state because both svname and pxname are always set when we get here |
| 365 |
# When using track we get a status like this: MAINT (via pxname/svname) so we need to do substring matching |
| 366 |
if status in state[0]["status"]: |
| 367 |
if not self._drain or state[0]["scur"] == "0": |
| 368 |
return True |
| 369 |
time.sleep(self.wait_interval) |
| 370 |
|
| 371 |
self.module.fail_json( |
| 372 |
msg=f"server {pxname}/{svname} not status '{status}' after {self.wait_retries} retries. Aborting." |
| 373 |
) |
| 374 |
|
| 375 |
def enabled(self, host, backend, weight): |
| 376 |
""" |
| 377 |
Enabled action, marks server to UP and checks are re-enabled, |
| 378 |
also supports to get current weight for server (default) and |
| 379 |
set the weight for haproxy backend server when provides. |
| 380 |
""" |
| 381 |
cmd = "get weight $pxname/$svname; enable server $pxname/$svname" |
| 382 |
if self.agent: |
| 383 |
cmd += "; enable agent $pxname/$svname" |
| 384 |
if self.health: |
| 385 |
cmd += "; enable health $pxname/$svname" |
| 386 |
if weight: |
| 387 |
cmd += f"; set weight $pxname/$svname {weight}" |
| 388 |
self.execute_for_backends(cmd, backend, host, "UP") |
| 389 |
|
| 390 |
def disabled(self, host, backend, shutdown_sessions): |
| 391 |
""" |
| 392 |
Disabled action, marks server to DOWN for maintenance. In this mode, no more checks will be |
| 393 |
performed on the server until it leaves maintenance, |
| 394 |
also it shutdown sessions while disabling backend host server. |
| 395 |
""" |
| 396 |
cmd = "get weight $pxname/$svname" |
| 397 |
if self.agent: |
| 398 |
cmd += "; disable agent $pxname/$svname" |
| 399 |
if self.health: |
| 400 |
cmd += "; disable health $pxname/$svname" |
| 401 |
cmd += "; disable server $pxname/$svname" |
| 402 |
if shutdown_sessions: |
| 403 |
cmd += "; shutdown sessions server $pxname/$svname" |
| 404 |
self.execute_for_backends(cmd, backend, host, "MAINT") |
| 405 |
|
| 406 |
def drain(self, host, backend, status="DRAIN"): |
| 407 |
""" |
| 408 |
Drain action, sets the server to DRAIN mode. |
| 409 |
In this mode, the server will not accept any new connections |
| 410 |
other than those that are accepted via persistence. |
| 411 |
""" |
| 412 |
haproxy_version = self.discover_version() |
| 413 |
|
| 414 |
# check if haproxy version supports DRAIN state (starting with 1.5) |
| 415 |
if haproxy_version and haproxy_version >= (1, 5): |
| 416 |
cmd = "set server $pxname/$svname state drain" |
| 417 |
self.execute_for_backends(cmd, backend, host, "DRAIN") |
| 418 |
if status == "MAINT": |
| 419 |
self.disabled(host, backend, self.shutdown_sessions) |
| 420 |
|
| 421 |
def act(self): |
| 422 |
""" |
| 423 |
Figure out what you want to do from ansible, and then do it. |
| 424 |
""" |
| 425 |
# Get the state before the run |
| 426 |
self.command_results["state_before"] = self.get_state_for(self.backend, self.host) |
| 427 |
|
| 428 |
# toggle enable/disable server |
| 429 |
if self.state == "enabled": |
| 430 |
self.enabled(self.host, self.backend, self.weight) |
| 431 |
elif self.state == "disabled" and self._drain: |
| 432 |
self.drain(self.host, self.backend, status="MAINT") |
| 433 |
elif self.state == "disabled": |
| 434 |
self.disabled(self.host, self.backend, self.shutdown_sessions) |
| 435 |
elif self.state == "drain": |
| 436 |
self.drain(self.host, self.backend) |
| 437 |
else: |
| 438 |
self.module.fail_json(msg=f"unknown state specified: '{self.state}'") |
| 439 |
|
| 440 |
# Get the state after the run |
| 441 |
self.command_results["state_after"] = self.get_state_for(self.backend, self.host) |
| 442 |
|
| 443 |
# Report change status |
| 444 |
self.command_results["changed"] = self.command_results["state_before"] != self.command_results["state_after"] |
| 445 |
|
| 446 |
self.module.exit_json(**self.command_results) |
| 447 |
|
| 448 |
|
| 449 |
def main(): |
| 450 |
# load ansible module object |
| 451 |
module = AnsibleModule( |
| 452 |
argument_spec=dict( |
| 453 |
state=dict(type="str", required=True, choices=ACTION_CHOICES), |
| 454 |
host=dict(type="str", required=True), |
| 455 |
backend=dict(type="str"), |
| 456 |
weight=dict(type="str"), |
| 457 |
socket=dict(type="path", default=DEFAULT_SOCKET_LOCATION), |
| 458 |
shutdown_sessions=dict(type="bool", default=False), |
| 459 |
fail_on_not_found=dict(type="bool", default=False), |
| 460 |
health=dict(type="bool", default=False), |
| 461 |
agent=dict(type="bool", default=False), |
| 462 |
wait=dict(type="bool", default=False), |
| 463 |
wait_retries=dict(type="int", default=WAIT_RETRIES), |
| 464 |
wait_interval=dict(type="int", default=WAIT_INTERVAL), |
| 465 |
drain=dict(type="bool", default=False), |
| 466 |
), |
| 467 |
) |
| 468 |
|
| 469 |
if not socket: |
| 470 |
module.fail_json(msg="unable to locate haproxy socket") |
| 471 |
|
| 472 |
ansible_haproxy = HAProxy(module) |
| 473 |
ansible_haproxy.act() |
| 474 |
|
| 475 |
|
| 476 |
if __name__ == "__main__": |
| 477 |
main() |