| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2013, Darryl Stoflet <[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: monit |
| 11 |
short_description: Manage the state of a program monitored using Monit |
| 12 |
description: |
| 13 |
- Manage the state of a program monitored using Monit. |
| 14 |
extends_documentation_fragment: |
| 15 |
- community.general._attributes |
| 16 |
attributes: |
| 17 |
check_mode: |
| 18 |
support: full |
| 19 |
diff_mode: |
| 20 |
support: none |
| 21 |
options: |
| 22 |
name: |
| 23 |
description: |
| 24 |
- The name of the C(monit) program/process to manage. |
| 25 |
required: true |
| 26 |
type: str |
| 27 |
state: |
| 28 |
description: |
| 29 |
- The state of service. |
| 30 |
required: true |
| 31 |
choices: ["present", "started", "stopped", "restarted", "monitored", "unmonitored", "reloaded"] |
| 32 |
type: str |
| 33 |
timeout: |
| 34 |
description: |
| 35 |
- If there are pending actions for the service monitored by monit, then it checks for up to this many seconds to verify |
| 36 |
the requested action has been performed. The module sleeps for five seconds between each check. |
| 37 |
default: 300 |
| 38 |
type: int |
| 39 |
author: |
| 40 |
- Darryl Stoflet (@dstoflet) |
| 41 |
- Simon Kelly (@snopoke) |
| 42 |
requirements: |
| 43 |
- Monit. Support for versions 5.18 and older is deprecated and will be removed in community.general 14.0.0. |
| 44 |
""" |
| 45 |
|
| 46 |
EXAMPLES = r""" |
| 47 |
- name: Manage the state of program httpd to be in started state |
| 48 |
community.general.monit: |
| 49 |
name: httpd |
| 50 |
state: started |
| 51 |
""" |
| 52 |
|
| 53 |
import re |
| 54 |
import time |
| 55 |
from enum import Enum |
| 56 |
|
| 57 |
from ansible.module_utils.basic import AnsibleModule |
| 58 |
|
| 59 |
STATE_COMMAND_MAP = { |
| 60 |
"stopped": "stop", |
| 61 |
"started": "start", |
| 62 |
"monitored": "monitor", |
| 63 |
"unmonitored": "unmonitor", |
| 64 |
"restarted": "restart", |
| 65 |
} |
| 66 |
|
| 67 |
MONIT_SERVICES = ["Process", "File", "Fifo", "Filesystem", "Directory", "Remote host", "System", "Program", "Network"] |
| 68 |
|
| 69 |
|
| 70 |
class StatusValue(Enum): |
| 71 |
MISSING = "missing" |
| 72 |
OK = "ok" |
| 73 |
NOT_MONITORED = "not_monitored" |
| 74 |
INITIALIZING = "initializing" |
| 75 |
DOES_NOT_EXIST = "does_not_exist" |
| 76 |
EXECUTION_FAILED = "execution_failed" |
| 77 |
|
| 78 |
|
| 79 |
class Status: |
| 80 |
"""Represents a monit status with optional pending state.""" |
| 81 |
|
| 82 |
def __init__(self, status_val: str | StatusValue, is_pending: bool = False): |
| 83 |
if isinstance(status_val, StatusValue): |
| 84 |
self.state = status_val |
| 85 |
else: |
| 86 |
self.state = getattr(StatusValue, status_val) |
| 87 |
self.is_pending = is_pending |
| 88 |
|
| 89 |
@property |
| 90 |
def value(self): |
| 91 |
return self.state.value |
| 92 |
|
| 93 |
def pending(self): |
| 94 |
"""Return a new Status instance with is_pending=True.""" |
| 95 |
return Status(self.state, is_pending=True) |
| 96 |
|
| 97 |
def __getattr__(self, item): |
| 98 |
if item.startswith("is_"): |
| 99 |
status_name = item[3:].upper() |
| 100 |
if hasattr(StatusValue, status_name): |
| 101 |
return self.value == getattr(StatusValue, status_name).value |
| 102 |
raise AttributeError(item) |
| 103 |
|
| 104 |
def __eq__(self, other): |
| 105 |
if not isinstance(other, Status): |
| 106 |
return False |
| 107 |
return self.state == other.state and self.is_pending == other.is_pending |
| 108 |
|
| 109 |
def __str__(self): |
| 110 |
return f"{self.value}{' (pending)' if self.is_pending else ''}" |
| 111 |
|
| 112 |
def __repr__(self): |
| 113 |
return f"<{self}>" |
| 114 |
|
| 115 |
|
| 116 |
# Initialize convenience class attributes |
| 117 |
|
| 118 |
|
| 119 |
class Monit: |
| 120 |
def __init__(self, module, monit_bin_path, service_name, timeout): |
| 121 |
self.module = module |
| 122 |
self.monit_bin_path = monit_bin_path |
| 123 |
self.process_name = service_name |
| 124 |
self.timeout = timeout |
| 125 |
|
| 126 |
self._monit_version = None |
| 127 |
self._raw_version = None |
| 128 |
self._status_change_retry_count = 6 |
| 129 |
|
| 130 |
if self.monit_version() <= (5, 18): |
| 131 |
module.deprecate( |
| 132 |
"Support for monit 5.18 and older is deprecated and will be removed in community.general 14.0.0.", |
| 133 |
version="14.0.0", |
| 134 |
collection_name="community.general", |
| 135 |
) |
| 136 |
|
| 137 |
def monit_version(self): |
| 138 |
if self._monit_version is None: |
| 139 |
self._raw_version, version = self._get_monit_version() |
| 140 |
# Use only major and minor even if there are more these should be enough |
| 141 |
self._monit_version = version[0], version[1] |
| 142 |
return self._monit_version |
| 143 |
|
| 144 |
def _get_monit_version(self): |
| 145 |
rc, out, err = self.module.run_command([self.monit_bin_path, "-V"], check_rc=True) |
| 146 |
version_line = out.split("\n")[0] |
| 147 |
raw_version = re.search(r"([0-9]+\.){1,2}([0-9]+)?", version_line).group() |
| 148 |
return raw_version, tuple(map(int, raw_version.split("."))) |
| 149 |
|
| 150 |
def exit_fail(self, msg, status=None, **kwargs): |
| 151 |
kwargs.update( |
| 152 |
{ |
| 153 |
"msg": msg, |
| 154 |
"monit_version": self._raw_version, |
| 155 |
"process_status": str(status) if status else None, |
| 156 |
} |
| 157 |
) |
| 158 |
self.module.fail_json(**kwargs) |
| 159 |
|
| 160 |
def exit_success(self, state): |
| 161 |
self.module.exit_json( |
| 162 |
changed=True, |
| 163 |
name=self.process_name, |
| 164 |
monit_version=self._raw_version, |
| 165 |
state=state, |
| 166 |
) |
| 167 |
|
| 168 |
@property |
| 169 |
def command_args(self): |
| 170 |
return ["-B"] if self.monit_version() > (5, 18) else [] |
| 171 |
|
| 172 |
def get_status(self, validate=False) -> Status: |
| 173 |
"""Return the status of the process in monit. |
| 174 |
|
| 175 |
:@param validate: Force monit to re-check the status of the process |
| 176 |
""" |
| 177 |
monit_command = "validate" if validate else "status" |
| 178 |
check_rc = not validate # 'validate' always has rc = 1 |
| 179 |
command = [self.monit_bin_path, monit_command] + self.command_args + [self.process_name] |
| 180 |
rc, out, err = self.module.run_command(command, check_rc=check_rc) |
| 181 |
return self._parse_status(out, err) |
| 182 |
|
| 183 |
def _parse_status(self, output, err) -> Status: |
| 184 |
escaped_monit_services = "|".join([re.escape(x) for x in MONIT_SERVICES]) |
| 185 |
pattern = f"({escaped_monit_services}) '{re.escape(self.process_name)}'" |
| 186 |
if not re.search(pattern, output, re.IGNORECASE): |
| 187 |
return Status("MISSING") |
| 188 |
|
| 189 |
status_val_find = re.findall(r"^\s*status\s*([\w\- ]+)", output, re.MULTILINE) |
| 190 |
if not status_val_find: |
| 191 |
self.exit_fail("Unable to find process status", stdout=output, stderr=err) |
| 192 |
|
| 193 |
status_val = status_val_find[0].strip().upper() |
| 194 |
if " | " in status_val: |
| 195 |
status_val = status_val.split(" | ")[0] |
| 196 |
if " - " not in status_val: |
| 197 |
status_val = status_val.replace(" ", "_") |
| 198 |
# Normalize RUNNING to OK (monit reports both, they mean the same thing) |
| 199 |
if status_val == "RUNNING": |
| 200 |
status_val = "OK" |
| 201 |
try: |
| 202 |
return Status(status_val) |
| 203 |
except AttributeError: |
| 204 |
self.module.warn(f"Unknown monit status '{status_val}', treating as execution failed") |
| 205 |
return Status("EXECUTION_FAILED") |
| 206 |
else: |
| 207 |
status_val, substatus = status_val.split(" - ") |
| 208 |
action, state = substatus.split() |
| 209 |
if action in ["START", "INITIALIZING", "RESTART", "MONITOR"]: |
| 210 |
status = Status("OK") |
| 211 |
else: |
| 212 |
status = Status("NOT_MONITORED") |
| 213 |
|
| 214 |
if state == "PENDING": |
| 215 |
status = status.pending() |
| 216 |
return status |
| 217 |
|
| 218 |
def is_process_present(self): |
| 219 |
command = [self.monit_bin_path, "summary"] + self.command_args |
| 220 |
rc, out, err = self.module.run_command(command, check_rc=True) |
| 221 |
return bool(re.findall(rf"\b{self.process_name}\b", out)) |
| 222 |
|
| 223 |
def is_process_running(self): |
| 224 |
return self.get_status().is_ok |
| 225 |
|
| 226 |
def run_command(self, command): |
| 227 |
"""Runs a monit command, and returns the new status.""" |
| 228 |
return self.module.run_command([self.monit_bin_path, command, self.process_name], check_rc=True) |
| 229 |
|
| 230 |
def wait_for_status_change(self, current_status): |
| 231 |
running_status = self.get_status() |
| 232 |
if running_status.value != current_status.value or current_status.value == StatusValue.EXECUTION_FAILED: |
| 233 |
return running_status |
| 234 |
|
| 235 |
loop_count = 0 |
| 236 |
while running_status.value == current_status.value: |
| 237 |
if loop_count >= self._status_change_retry_count: |
| 238 |
self.exit_fail("waited too long for monit to change state", running_status) |
| 239 |
|
| 240 |
loop_count += 1 |
| 241 |
time.sleep(0.5) |
| 242 |
validate = loop_count % 2 == 0 # force recheck of status every second try |
| 243 |
running_status = self.get_status(validate) |
| 244 |
return running_status |
| 245 |
|
| 246 |
def wait_for_monit_to_stop_pending(self, current_status=None): |
| 247 |
"""Fails this run if there is no status or it is pending/initializing for timeout""" |
| 248 |
timeout_time = time.time() + self.timeout |
| 249 |
|
| 250 |
if not current_status: |
| 251 |
current_status = self.get_status() |
| 252 |
waiting_status = [ |
| 253 |
StatusValue.MISSING, |
| 254 |
StatusValue.INITIALIZING, |
| 255 |
StatusValue.DOES_NOT_EXIST, |
| 256 |
] |
| 257 |
while current_status.is_pending or (current_status.state in waiting_status): |
| 258 |
if time.time() >= timeout_time: |
| 259 |
self.exit_fail('waited too long for "pending", or "initiating" status to go away', current_status) |
| 260 |
|
| 261 |
time.sleep(5) |
| 262 |
current_status = self.get_status(validate=True) |
| 263 |
return current_status |
| 264 |
|
| 265 |
def reload(self): |
| 266 |
rc, out, err = self.module.run_command([self.monit_bin_path, "reload"]) |
| 267 |
if rc != 0: |
| 268 |
self.exit_fail("monit reload failed", stdout=out, stderr=err) |
| 269 |
self.exit_success(state="reloaded") |
| 270 |
|
| 271 |
def present(self): |
| 272 |
self.run_command("reload") |
| 273 |
|
| 274 |
timeout_time = time.time() + self.timeout |
| 275 |
while not self.is_process_present(): |
| 276 |
if time.time() >= timeout_time: |
| 277 |
self.exit_fail('waited too long for process to become "present"') |
| 278 |
|
| 279 |
time.sleep(5) |
| 280 |
|
| 281 |
self.exit_success(state="present") |
| 282 |
|
| 283 |
def change_state(self, state: str, expected_status: StatusValue, invert_expected: bool | None = None): |
| 284 |
current_status = self.get_status() |
| 285 |
self.run_command(STATE_COMMAND_MAP[state]) |
| 286 |
# Give monit daemon a moment to process the command before checking status |
| 287 |
# to avoid race condition where HTTP interface may be temporarily unresponsive |
| 288 |
time.sleep(0.5) |
| 289 |
status = self.wait_for_status_change(current_status) |
| 290 |
status = self.wait_for_monit_to_stop_pending(status) |
| 291 |
status_match = status.state == expected_status |
| 292 |
if invert_expected: |
| 293 |
status_match = not status_match |
| 294 |
if status_match: |
| 295 |
self.exit_success(state=state) |
| 296 |
self.exit_fail(f"{self.process_name} process not {state}", status) |
| 297 |
|
| 298 |
def stop(self): |
| 299 |
self.change_state("stopped", expected_status=StatusValue.NOT_MONITORED) |
| 300 |
|
| 301 |
def unmonitor(self): |
| 302 |
self.change_state("unmonitored", expected_status=StatusValue.NOT_MONITORED) |
| 303 |
|
| 304 |
def restart(self): |
| 305 |
self.change_state("restarted", expected_status=StatusValue.OK) |
| 306 |
|
| 307 |
def start(self): |
| 308 |
self.change_state("started", expected_status=StatusValue.OK) |
| 309 |
|
| 310 |
def monitor(self): |
| 311 |
self.change_state("monitored", expected_status=StatusValue.NOT_MONITORED, invert_expected=True) |
| 312 |
|
| 313 |
|
| 314 |
def main(): |
| 315 |
arg_spec = dict( |
| 316 |
name=dict(required=True), |
| 317 |
timeout=dict(default=300, type="int"), |
| 318 |
state=dict( |
| 319 |
required=True, |
| 320 |
choices=["present", "started", "restarted", "stopped", "monitored", "unmonitored", "reloaded"], |
| 321 |
), |
| 322 |
) |
| 323 |
|
| 324 |
module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True) |
| 325 |
module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"} |
| 326 |
|
| 327 |
name = module.params["name"] |
| 328 |
state = module.params["state"] |
| 329 |
timeout = module.params["timeout"] |
| 330 |
|
| 331 |
monit = Monit(module, module.get_bin_path("monit", True), name, timeout) |
| 332 |
|
| 333 |
def exit_if_check_mode(): |
| 334 |
if module.check_mode: |
| 335 |
module.exit_json(changed=True) |
| 336 |
|
| 337 |
if state == "reloaded": |
| 338 |
exit_if_check_mode() |
| 339 |
monit.reload() |
| 340 |
|
| 341 |
present = monit.is_process_present() |
| 342 |
|
| 343 |
if not present and state != "present": |
| 344 |
module.fail_json(msg=f"{name} process not presently configured with monit", name=name) |
| 345 |
|
| 346 |
if state == "present": |
| 347 |
if present: |
| 348 |
module.exit_json(changed=False, name=name, state=state) |
| 349 |
exit_if_check_mode() |
| 350 |
monit.present() |
| 351 |
|
| 352 |
monit.wait_for_monit_to_stop_pending() |
| 353 |
running = monit.is_process_running() |
| 354 |
|
| 355 |
if running and state in ["started", "monitored"]: |
| 356 |
module.exit_json(changed=False, name=name, state=state) |
| 357 |
|
| 358 |
if running and state == "stopped": |
| 359 |
exit_if_check_mode() |
| 360 |
monit.stop() |
| 361 |
|
| 362 |
if running and state == "unmonitored": |
| 363 |
exit_if_check_mode() |
| 364 |
monit.unmonitor() |
| 365 |
|
| 366 |
elif state == "restarted": |
| 367 |
exit_if_check_mode() |
| 368 |
monit.restart() |
| 369 |
|
| 370 |
elif not running and state == "started": |
| 371 |
exit_if_check_mode() |
| 372 |
monit.start() |
| 373 |
|
| 374 |
elif not running and state == "monitored": |
| 375 |
exit_if_check_mode() |
| 376 |
monit.monitor() |
| 377 |
|
| 378 |
module.exit_json(changed=False, name=name, state=state) |
| 379 |
|
| 380 |
|
| 381 |
if __name__ == "__main__": |
| 382 |
main() |