medic-cli 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- medic/__init__.py +41 -0
- medic/__main__.py +8 -0
- medic/checks/__init__.py +30 -0
- medic/checks/dns.py +60 -0
- medic/checks/exec.py +90 -0
- medic/checks/http.py +181 -0
- medic/checks/ping.py +226 -0
- medic/checks/ssh.py +246 -0
- medic/checks/system.py +469 -0
- medic/checks/tcp.py +184 -0
- medic/checks/tls.py +255 -0
- medic/cli.py +572 -0
- medic/completion.py +46 -0
- medic/config.py +199 -0
- medic/core/__init__.py +18 -0
- medic/core/base.py +48 -0
- medic/core/enums.py +85 -0
- medic/core/models.py +116 -0
- medic/core/runner.py +212 -0
- medic/formatters/__init__.py +48 -0
- medic/formatters/base.py +14 -0
- medic/formatters/json_formatter.py +26 -0
- medic/formatters/junit_formatter.py +52 -0
- medic/formatters/rich_formatter.py +187 -0
- medic/formatters/text_formatter.py +60 -0
- medic/py.typed +0 -0
- medic_cli-0.1.1.dist-info/METADATA +175 -0
- medic_cli-0.1.1.dist-info/RECORD +32 -0
- medic_cli-0.1.1.dist-info/WHEEL +5 -0
- medic_cli-0.1.1.dist-info/entry_points.txt +2 -0
- medic_cli-0.1.1.dist-info/licenses/LICENSE +21 -0
- medic_cli-0.1.1.dist-info/top_level.txt +1 -0
medic/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""medic: Fast, type-safe CLI health check & diagnostic tool."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("medic-cli")
|
|
7
|
+
except PackageNotFoundError: # running from a source tree without install metadata
|
|
8
|
+
__version__ = "0+unknown"
|
|
9
|
+
|
|
10
|
+
from .checks.http import HTTPCheck
|
|
11
|
+
from .checks.ping import PingCheck
|
|
12
|
+
from .checks.ssh import SSHCheck
|
|
13
|
+
from .checks.system import CPUCheck, DiskCheck, MemoryCheck, SwapCheck, SystemCheckGroup, UptimeCheck
|
|
14
|
+
from .checks.tcp import TCPCheck
|
|
15
|
+
from .checks.tls import TLSCheck
|
|
16
|
+
from .core.base import BaseCheck
|
|
17
|
+
from .core.enums import CheckCategory, CheckStatus, OutputFormat
|
|
18
|
+
from .core.models import CheckResult, MedicReport
|
|
19
|
+
from .core.runner import MedicRunner
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"__version__",
|
|
23
|
+
"CheckCategory",
|
|
24
|
+
"CheckStatus",
|
|
25
|
+
"OutputFormat",
|
|
26
|
+
"CheckResult",
|
|
27
|
+
"MedicReport",
|
|
28
|
+
"MedicRunner",
|
|
29
|
+
"BaseCheck",
|
|
30
|
+
"CPUCheck",
|
|
31
|
+
"MemoryCheck",
|
|
32
|
+
"DiskCheck",
|
|
33
|
+
"SwapCheck",
|
|
34
|
+
"UptimeCheck",
|
|
35
|
+
"SystemCheckGroup",
|
|
36
|
+
"PingCheck",
|
|
37
|
+
"TCPCheck",
|
|
38
|
+
"HTTPCheck",
|
|
39
|
+
"TLSCheck",
|
|
40
|
+
"SSHCheck",
|
|
41
|
+
]
|
medic/__main__.py
ADDED
medic/checks/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Health check modules for medic."""
|
|
2
|
+
|
|
3
|
+
from .http import HTTPCheck
|
|
4
|
+
from .ping import PingCheck
|
|
5
|
+
from .ssh import SSHCheck
|
|
6
|
+
from .system import (
|
|
7
|
+
CPUCheck,
|
|
8
|
+
DiskCheck,
|
|
9
|
+
MemoryCheck,
|
|
10
|
+
SwapCheck,
|
|
11
|
+
SystemCheckGroup,
|
|
12
|
+
UptimeCheck,
|
|
13
|
+
)
|
|
14
|
+
from .tcp import TCPCheck, parse_host_port
|
|
15
|
+
from .tls import TLSCheck
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"CPUCheck",
|
|
19
|
+
"MemoryCheck",
|
|
20
|
+
"SwapCheck",
|
|
21
|
+
"DiskCheck",
|
|
22
|
+
"UptimeCheck",
|
|
23
|
+
"SystemCheckGroup",
|
|
24
|
+
"PingCheck",
|
|
25
|
+
"TCPCheck",
|
|
26
|
+
"parse_host_port",
|
|
27
|
+
"HTTPCheck",
|
|
28
|
+
"TLSCheck",
|
|
29
|
+
"SSHCheck",
|
|
30
|
+
]
|
medic/checks/dns.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""DNS resolution check."""
|
|
2
|
+
|
|
3
|
+
import socket
|
|
4
|
+
import time
|
|
5
|
+
from typing import List, Optional, Sequence
|
|
6
|
+
|
|
7
|
+
from medic.core.base import BaseCheck
|
|
8
|
+
from medic.core.enums import CheckCategory, CheckStatus
|
|
9
|
+
from medic.core.models import CheckResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DNSCheck(BaseCheck):
|
|
13
|
+
"""Resolves a hostname via the system resolver, optionally requiring specific addresses."""
|
|
14
|
+
|
|
15
|
+
category = CheckCategory.DNS
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
host: str,
|
|
20
|
+
name: Optional[str] = None,
|
|
21
|
+
expect: Optional[Sequence[str]] = None,
|
|
22
|
+
warn_latency_ms: float = 500.0,
|
|
23
|
+
timeout: float = 5.0,
|
|
24
|
+
enabled: bool = True,
|
|
25
|
+
) -> None:
|
|
26
|
+
super().__init__(name=name or f"DNS {host}", timeout=timeout, enabled=enabled)
|
|
27
|
+
self.host = host.strip()
|
|
28
|
+
self.expect = list(expect) if expect else []
|
|
29
|
+
self.warn_latency_ms = warn_latency_ms
|
|
30
|
+
|
|
31
|
+
def run(self) -> CheckResult:
|
|
32
|
+
start = time.perf_counter()
|
|
33
|
+
try:
|
|
34
|
+
infos = socket.getaddrinfo(self.host, None, proto=socket.IPPROTO_TCP)
|
|
35
|
+
except socket.gaierror as exc:
|
|
36
|
+
return self._result(CheckStatus.FAILED, f"Resolution failed: {exc.strerror or exc}", start, [])
|
|
37
|
+
|
|
38
|
+
addrs: List[str] = sorted({str(i[4][0]) for i in infos})
|
|
39
|
+
missing = [a for a in self.expect if a not in addrs]
|
|
40
|
+
if missing:
|
|
41
|
+
return self._result(
|
|
42
|
+
CheckStatus.FAILED, f"Missing expected address(es): {', '.join(missing)}", start, addrs
|
|
43
|
+
)
|
|
44
|
+
elapsed = (time.perf_counter() - start) * 1000.0
|
|
45
|
+
status = CheckStatus.WARNING if elapsed > self.warn_latency_ms else CheckStatus.PASSED
|
|
46
|
+
return self._result(status, f"Resolved to {', '.join(addrs)}", start, addrs)
|
|
47
|
+
|
|
48
|
+
def _result(self, status: CheckStatus, message: str, start: float, addrs: List[str]) -> CheckResult:
|
|
49
|
+
return CheckResult(
|
|
50
|
+
name=self.name,
|
|
51
|
+
category=self.category,
|
|
52
|
+
status=status,
|
|
53
|
+
message=message,
|
|
54
|
+
target=self.host,
|
|
55
|
+
latency_ms=(time.perf_counter() - start) * 1000.0,
|
|
56
|
+
details={"addresses": addrs},
|
|
57
|
+
remediation="Check resolver configuration (/etc/resolv.conf) and the DNS record."
|
|
58
|
+
if status == CheckStatus.FAILED
|
|
59
|
+
else None,
|
|
60
|
+
)
|
medic/checks/exec.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Run an arbitrary command and judge it by exit code and output."""
|
|
2
|
+
|
|
3
|
+
import shlex
|
|
4
|
+
import subprocess
|
|
5
|
+
import time
|
|
6
|
+
from typing import List, Optional, Sequence, Union
|
|
7
|
+
|
|
8
|
+
from medic.core.base import BaseCheck
|
|
9
|
+
from medic.core.enums import CheckCategory, CheckStatus
|
|
10
|
+
from medic.core.models import CheckResult
|
|
11
|
+
|
|
12
|
+
_OUTPUT_TAIL = 500
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ExecCheck(BaseCheck):
|
|
16
|
+
"""Passes when a command exits with the expected code (and optional output match).
|
|
17
|
+
|
|
18
|
+
The command is run without a shell unless ``shell=True``.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
category = CheckCategory.EXEC
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
command: Union[str, Sequence[str]],
|
|
26
|
+
name: Optional[str] = None,
|
|
27
|
+
expect_exit: int = 0,
|
|
28
|
+
contains_text: Optional[str] = None,
|
|
29
|
+
shell: bool = False,
|
|
30
|
+
cwd: Optional[str] = None,
|
|
31
|
+
timeout: float = 10.0,
|
|
32
|
+
enabled: bool = True,
|
|
33
|
+
) -> None:
|
|
34
|
+
self.argv: Union[str, List[str]]
|
|
35
|
+
if isinstance(command, str):
|
|
36
|
+
self.argv = command if shell else shlex.split(command)
|
|
37
|
+
else:
|
|
38
|
+
self.argv = list(command)
|
|
39
|
+
display = command if isinstance(command, str) else shlex.join(command)
|
|
40
|
+
super().__init__(name=name or f"Exec {display}", timeout=timeout, enabled=enabled)
|
|
41
|
+
self.display = display
|
|
42
|
+
self.expect_exit = expect_exit
|
|
43
|
+
self.contains_text = contains_text
|
|
44
|
+
self.shell = shell
|
|
45
|
+
self.cwd = cwd
|
|
46
|
+
|
|
47
|
+
def run(self) -> CheckResult:
|
|
48
|
+
start = time.perf_counter()
|
|
49
|
+
try:
|
|
50
|
+
proc = subprocess.run(
|
|
51
|
+
self.argv,
|
|
52
|
+
shell=self.shell,
|
|
53
|
+
cwd=self.cwd,
|
|
54
|
+
capture_output=True,
|
|
55
|
+
text=True,
|
|
56
|
+
timeout=self.timeout,
|
|
57
|
+
)
|
|
58
|
+
except subprocess.TimeoutExpired:
|
|
59
|
+
return self._result(CheckStatus.FAILED, f"Command timed out after {self.timeout:.1f}s", start)
|
|
60
|
+
except (OSError, ValueError) as exc:
|
|
61
|
+
return self._result(CheckStatus.FAILED, f"Could not run command: {exc}", start)
|
|
62
|
+
|
|
63
|
+
out = (proc.stdout or "").strip()
|
|
64
|
+
err = (proc.stderr or "").strip()
|
|
65
|
+
details = {
|
|
66
|
+
"command": self.display,
|
|
67
|
+
"exit_code": proc.returncode,
|
|
68
|
+
"stdout": out[-_OUTPUT_TAIL:],
|
|
69
|
+
"stderr": err[-_OUTPUT_TAIL:],
|
|
70
|
+
}
|
|
71
|
+
if proc.returncode != self.expect_exit:
|
|
72
|
+
tail = (err or out).splitlines()[-1:] or [""]
|
|
73
|
+
msg = f"Exit code {proc.returncode} (expected {self.expect_exit})"
|
|
74
|
+
if tail[0]:
|
|
75
|
+
msg += f": {tail[0][:200]}"
|
|
76
|
+
return self._result(CheckStatus.FAILED, msg, start, details)
|
|
77
|
+
if self.contains_text is not None and self.contains_text not in out:
|
|
78
|
+
return self._result(CheckStatus.FAILED, f"Output does not contain {self.contains_text!r}", start, details)
|
|
79
|
+
return self._result(CheckStatus.PASSED, f"Exit code {proc.returncode}", start, details)
|
|
80
|
+
|
|
81
|
+
def _result(self, status: CheckStatus, message: str, start: float, details: Optional[dict] = None) -> CheckResult:
|
|
82
|
+
return CheckResult(
|
|
83
|
+
name=self.name,
|
|
84
|
+
category=self.category,
|
|
85
|
+
status=status,
|
|
86
|
+
message=message,
|
|
87
|
+
target=self.display,
|
|
88
|
+
latency_ms=(time.perf_counter() - start) * 1000.0,
|
|
89
|
+
details=details or {},
|
|
90
|
+
)
|
medic/checks/http.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""HTTP and HTTPS endpoint health checks."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import time
|
|
5
|
+
import urllib.parse
|
|
6
|
+
from typing import Any, Dict, Optional, Sequence, Union
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
from requests.exceptions import ConnectionError, SSLError, Timeout
|
|
10
|
+
|
|
11
|
+
from medic.core.base import BaseCheck, timed_execution
|
|
12
|
+
from medic.core.enums import CheckCategory, CheckStatus
|
|
13
|
+
from medic.core.models import CheckResult
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def normalize_url(url: str, default_scheme: str = "https") -> str:
|
|
17
|
+
"""Ensure URL has a valid scheme."""
|
|
18
|
+
url = url.strip()
|
|
19
|
+
if not re.match(r"^[a-zA-Z][a-zA-Z0-9\+\-\.]*://", url):
|
|
20
|
+
url = f"{default_scheme}://{url}"
|
|
21
|
+
return url
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class HTTPCheck(BaseCheck):
|
|
25
|
+
"""Checks HTTP/HTTPS endpoint availability, response code, latency, and content."""
|
|
26
|
+
|
|
27
|
+
category = CheckCategory.HTTP
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
url: str,
|
|
32
|
+
name: Optional[str] = None,
|
|
33
|
+
method: str = "GET",
|
|
34
|
+
expected_status: Union[int, Sequence[int]] = (200, 201, 204, 301, 302, 307, 308),
|
|
35
|
+
follow_redirects: bool = True,
|
|
36
|
+
verify_ssl: bool = True,
|
|
37
|
+
contains_text: Optional[str] = None,
|
|
38
|
+
headers: Optional[Dict[str, str]] = None,
|
|
39
|
+
timeout: float = 10.0,
|
|
40
|
+
warn_latency_ms: float = 1000.0,
|
|
41
|
+
crit_latency_ms: float = 3000.0,
|
|
42
|
+
enabled: bool = True,
|
|
43
|
+
) -> None:
|
|
44
|
+
self.raw_url = url
|
|
45
|
+
self.url = normalize_url(url)
|
|
46
|
+
parsed = urllib.parse.urlparse(self.url)
|
|
47
|
+
display_target = f"{parsed.scheme}://{parsed.netloc}{parsed.path or '/'}"
|
|
48
|
+
chk_name = name or f"HTTP {display_target}"
|
|
49
|
+
super().__init__(name=chk_name, timeout=timeout, enabled=enabled)
|
|
50
|
+
|
|
51
|
+
self.method = method.upper()
|
|
52
|
+
if isinstance(expected_status, int):
|
|
53
|
+
self.expected_status: Sequence[int] = [expected_status]
|
|
54
|
+
else:
|
|
55
|
+
self.expected_status = expected_status
|
|
56
|
+
self.follow_redirects = follow_redirects
|
|
57
|
+
self.verify_ssl = verify_ssl
|
|
58
|
+
self.contains_text = contains_text
|
|
59
|
+
self.headers = headers or {
|
|
60
|
+
"User-Agent": "Medic-HealthCheck/0.1.0 (Python)",
|
|
61
|
+
"Accept": "*/*",
|
|
62
|
+
}
|
|
63
|
+
self.warn_latency_ms = warn_latency_ms
|
|
64
|
+
self.crit_latency_ms = crit_latency_ms
|
|
65
|
+
|
|
66
|
+
def run(self) -> CheckResult:
|
|
67
|
+
with timed_execution() as timer:
|
|
68
|
+
try:
|
|
69
|
+
session = requests.Session()
|
|
70
|
+
req_start = time.perf_counter()
|
|
71
|
+
resp = session.request(
|
|
72
|
+
method=self.method,
|
|
73
|
+
url=self.url,
|
|
74
|
+
headers=self.headers,
|
|
75
|
+
timeout=self.timeout,
|
|
76
|
+
allow_redirects=self.follow_redirects,
|
|
77
|
+
verify=self.verify_ssl,
|
|
78
|
+
)
|
|
79
|
+
req_ms = (time.perf_counter() - req_start) * 1000.0
|
|
80
|
+
|
|
81
|
+
except SSLError as e:
|
|
82
|
+
return CheckResult(
|
|
83
|
+
name=self.name,
|
|
84
|
+
category=self.category,
|
|
85
|
+
status=CheckStatus.FAILED,
|
|
86
|
+
message=f"SSL certificate verification failed: {e}",
|
|
87
|
+
target=self.url,
|
|
88
|
+
latency_ms=timer["elapsed_ms"],
|
|
89
|
+
remediation="Verify SSL certificate expiration, SANs, or CA trust bundle (use --no-verify-ssl to bypass).",
|
|
90
|
+
)
|
|
91
|
+
except Timeout:
|
|
92
|
+
return CheckResult(
|
|
93
|
+
name=self.name,
|
|
94
|
+
category=self.category,
|
|
95
|
+
status=CheckStatus.FAILED,
|
|
96
|
+
message=f"HTTP request timed out after {self.timeout:.1f}s",
|
|
97
|
+
target=self.url,
|
|
98
|
+
latency_ms=timer["elapsed_ms"],
|
|
99
|
+
remediation="Endpoint took too long to respond. Check server load, slow database queries, or upstream reverse proxy.",
|
|
100
|
+
)
|
|
101
|
+
except ConnectionError as e:
|
|
102
|
+
return CheckResult(
|
|
103
|
+
name=self.name,
|
|
104
|
+
category=self.category,
|
|
105
|
+
status=CheckStatus.FAILED,
|
|
106
|
+
message=f"Connection failed: {e}",
|
|
107
|
+
target=self.url,
|
|
108
|
+
latency_ms=timer["elapsed_ms"],
|
|
109
|
+
remediation=f"Could not establish connection to {self.url}. Ensure host is up and web server is running.",
|
|
110
|
+
)
|
|
111
|
+
except Exception as e:
|
|
112
|
+
return CheckResult(
|
|
113
|
+
name=self.name,
|
|
114
|
+
category=self.category,
|
|
115
|
+
status=CheckStatus.ERROR,
|
|
116
|
+
message=f"HTTP error: {e}",
|
|
117
|
+
target=self.url,
|
|
118
|
+
latency_ms=timer["elapsed_ms"],
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
status_code = resp.status_code
|
|
122
|
+
status = CheckStatus.PASSED
|
|
123
|
+
remediation = None
|
|
124
|
+
|
|
125
|
+
# Verify status code
|
|
126
|
+
if status_code not in self.expected_status:
|
|
127
|
+
if 500 <= status_code < 600:
|
|
128
|
+
status = CheckStatus.FAILED
|
|
129
|
+
remediation = f"Server returned 5xx error ({status_code}). Check application logs and backend services."
|
|
130
|
+
elif 400 <= status_code < 500:
|
|
131
|
+
status = CheckStatus.FAILED
|
|
132
|
+
remediation = f"Client error ({status_code}). Check route path, authentication headers, or permissions."
|
|
133
|
+
else:
|
|
134
|
+
status = CheckStatus.FAILED
|
|
135
|
+
remediation = f"Unexpected HTTP status code {status_code} (expected: {list(self.expected_status)})."
|
|
136
|
+
|
|
137
|
+
# Verify body content if requested
|
|
138
|
+
body_text = resp.text
|
|
139
|
+
if self.contains_text and status == CheckStatus.PASSED:
|
|
140
|
+
if self.contains_text not in body_text:
|
|
141
|
+
status = CheckStatus.FAILED
|
|
142
|
+
remediation = f"Response body does not contain expected substring '{self.contains_text}'."
|
|
143
|
+
|
|
144
|
+
# Verify latency
|
|
145
|
+
if status == CheckStatus.PASSED:
|
|
146
|
+
if req_ms >= self.crit_latency_ms:
|
|
147
|
+
status = CheckStatus.FAILED
|
|
148
|
+
remediation = f"HTTP response time ({req_ms:.1f}ms) is critically slow."
|
|
149
|
+
elif req_ms >= self.warn_latency_ms:
|
|
150
|
+
status = CheckStatus.WARNING
|
|
151
|
+
remediation = f"HTTP response time ({req_ms:.1f}ms) exceeds warning threshold."
|
|
152
|
+
|
|
153
|
+
redirect_info = ""
|
|
154
|
+
if resp.history:
|
|
155
|
+
redirect_count = len(resp.history)
|
|
156
|
+
redirect_info = f" ({redirect_count} redirect{'s' if redirect_count > 1 else ''} -> {resp.url})"
|
|
157
|
+
|
|
158
|
+
msg = f"HTTP {self.method} {status_code} in {req_ms:.1f}ms{redirect_info}"
|
|
159
|
+
|
|
160
|
+
details: Dict[str, Any] = {
|
|
161
|
+
"url": self.url,
|
|
162
|
+
"final_url": str(resp.url),
|
|
163
|
+
"status_code": status_code,
|
|
164
|
+
"reason": resp.reason,
|
|
165
|
+
"latency_ms": round(req_ms, 2),
|
|
166
|
+
"headers": dict(resp.headers),
|
|
167
|
+
"redirect_count": len(resp.history),
|
|
168
|
+
"content_length": len(resp.content),
|
|
169
|
+
"content_type": resp.headers.get("Content-Type"),
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return CheckResult(
|
|
173
|
+
name=self.name,
|
|
174
|
+
category=self.category,
|
|
175
|
+
status=status,
|
|
176
|
+
message=msg,
|
|
177
|
+
target=self.url,
|
|
178
|
+
latency_ms=req_ms,
|
|
179
|
+
details=details,
|
|
180
|
+
remediation=remediation,
|
|
181
|
+
)
|
medic/checks/ping.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""ICMP ping reachability and latency health checks."""
|
|
2
|
+
|
|
3
|
+
import platform
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from typing import Any, Dict, Optional
|
|
8
|
+
|
|
9
|
+
from medic.core.base import BaseCheck, timed_execution
|
|
10
|
+
from medic.core.enums import CheckCategory, CheckStatus
|
|
11
|
+
from medic.core.models import CheckResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PingCheck(BaseCheck):
|
|
15
|
+
"""Performs ICMP ping check to assess network reachability, packet loss, and latency."""
|
|
16
|
+
|
|
17
|
+
category = CheckCategory.PING
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
host: str,
|
|
22
|
+
name: Optional[str] = None,
|
|
23
|
+
count: int = 3,
|
|
24
|
+
timeout_sec: float = 2.0,
|
|
25
|
+
warn_latency_ms: float = 150.0,
|
|
26
|
+
crit_latency_ms: float = 500.0,
|
|
27
|
+
warn_loss_pct: float = 0.0,
|
|
28
|
+
enabled: bool = True,
|
|
29
|
+
) -> None:
|
|
30
|
+
chk_name = name or f"Ping {host}"
|
|
31
|
+
super().__init__(name=chk_name, timeout=timeout_sec * count + 2.0, enabled=enabled)
|
|
32
|
+
self.host = host.strip()
|
|
33
|
+
self.count = max(1, count)
|
|
34
|
+
self.timeout_sec = max(0.5, timeout_sec)
|
|
35
|
+
self.warn_latency_ms = warn_latency_ms
|
|
36
|
+
self.crit_latency_ms = crit_latency_ms
|
|
37
|
+
self.warn_loss_pct = warn_loss_pct
|
|
38
|
+
|
|
39
|
+
def _build_command(self) -> list[str]:
|
|
40
|
+
"""Construct the ping CLI command for the current operating system."""
|
|
41
|
+
sys_name = platform.system().lower()
|
|
42
|
+
ping_bin = shutil.which("ping") or "ping"
|
|
43
|
+
|
|
44
|
+
if sys_name == "windows":
|
|
45
|
+
# -n count, -w timeout in ms
|
|
46
|
+
return [ping_bin, "-n", str(self.count), "-w", str(int(self.timeout_sec * 1000)), self.host]
|
|
47
|
+
elif sys_name == "darwin":
|
|
48
|
+
# macOS: -c count, -W timeout in ms (or -t in secs)
|
|
49
|
+
return [ping_bin, "-c", str(self.count), "-W", str(int(self.timeout_sec * 1000)), self.host]
|
|
50
|
+
else:
|
|
51
|
+
# Linux & others: -c count, -W timeout in seconds
|
|
52
|
+
return [ping_bin, "-c", str(self.count), "-W", str(int(self.timeout_sec)), self.host]
|
|
53
|
+
|
|
54
|
+
def _parse_output(self, stdout: str) -> Dict[str, Any]:
|
|
55
|
+
"""Parse packet loss and RTT statistics from ping output."""
|
|
56
|
+
data: Dict[str, Any] = {
|
|
57
|
+
"transmitted": None,
|
|
58
|
+
"received": None,
|
|
59
|
+
"packet_loss_pct": None,
|
|
60
|
+
"min_rtt_ms": None,
|
|
61
|
+
"avg_rtt_ms": None,
|
|
62
|
+
"max_rtt_ms": None,
|
|
63
|
+
"mdev_rtt_ms": None,
|
|
64
|
+
"resolved_ip": None,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# IP resolution (e.g. PING google.com (142.250.190.46))
|
|
68
|
+
ip_match = re.search(r"\(([\d\.:a-fA-F]+)\)", stdout)
|
|
69
|
+
if ip_match:
|
|
70
|
+
data["resolved_ip"] = ip_match.group(1)
|
|
71
|
+
|
|
72
|
+
# Packet loss parsing
|
|
73
|
+
# Matches: "3 packets transmitted, 3 received, 0% packet loss"
|
|
74
|
+
loss_match = re.search(
|
|
75
|
+
r"(\d+)\s+packets transmitted,\s+(\d+)\s+(?:packets\s+)?received.*?(?:([0-9\.]+)%\s+packet loss)",
|
|
76
|
+
stdout,
|
|
77
|
+
re.IGNORECASE,
|
|
78
|
+
)
|
|
79
|
+
if loss_match:
|
|
80
|
+
data["transmitted"] = int(loss_match.group(1))
|
|
81
|
+
data["received"] = int(loss_match.group(2))
|
|
82
|
+
data["packet_loss_pct"] = float(loss_match.group(3))
|
|
83
|
+
else:
|
|
84
|
+
# Windows fallback: "Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)"
|
|
85
|
+
win_match = re.search(
|
|
86
|
+
r"Sent\s*=\s*(\d+),\s*Received\s*=\s*(\d+),\s*Lost\s*=\s*\d+\s*\(([\d\.]+)%\s*loss\)",
|
|
87
|
+
stdout,
|
|
88
|
+
re.IGNORECASE,
|
|
89
|
+
)
|
|
90
|
+
if win_match:
|
|
91
|
+
data["transmitted"] = int(win_match.group(1))
|
|
92
|
+
data["received"] = int(win_match.group(2))
|
|
93
|
+
data["packet_loss_pct"] = float(win_match.group(3))
|
|
94
|
+
|
|
95
|
+
# Latency / RTT parsing
|
|
96
|
+
# Matches: "rtt min/avg/max/mdev = 0.075/0.077/0.079/0.002 ms"
|
|
97
|
+
# or "round-trip min/avg/max/stddev = 12.3/14.5/16.7/1.2 ms"
|
|
98
|
+
rtt_match = re.search(
|
|
99
|
+
r"(?:rtt|round-trip)\s+min/avg/max/(?:mdev|stddev)\s*=\s*([\d\.]+)/([\d\.]+)/([\d\.]+)/([\d\.]+)\s*ms",
|
|
100
|
+
stdout,
|
|
101
|
+
re.IGNORECASE,
|
|
102
|
+
)
|
|
103
|
+
if rtt_match:
|
|
104
|
+
data["min_rtt_ms"] = float(rtt_match.group(1))
|
|
105
|
+
data["avg_rtt_ms"] = float(rtt_match.group(2))
|
|
106
|
+
data["max_rtt_ms"] = float(rtt_match.group(3))
|
|
107
|
+
data["mdev_rtt_ms"] = float(rtt_match.group(4))
|
|
108
|
+
else:
|
|
109
|
+
# Windows fallback: "Minimum = 12ms, Maximum = 15ms, Average = 13ms"
|
|
110
|
+
win_rtt = re.search(
|
|
111
|
+
r"Minimum\s*=\s*(\d+)ms,\s*Maximum\s*=\s*(\d+)ms,\s*Average\s*=\s*(\d+)ms",
|
|
112
|
+
stdout,
|
|
113
|
+
re.IGNORECASE,
|
|
114
|
+
)
|
|
115
|
+
if win_rtt:
|
|
116
|
+
data["min_rtt_ms"] = float(win_rtt.group(1))
|
|
117
|
+
data["max_rtt_ms"] = float(win_rtt.group(2))
|
|
118
|
+
data["avg_rtt_ms"] = float(win_rtt.group(3))
|
|
119
|
+
|
|
120
|
+
return data
|
|
121
|
+
|
|
122
|
+
def run(self) -> CheckResult:
|
|
123
|
+
cmd = self._build_command()
|
|
124
|
+
with timed_execution() as timer:
|
|
125
|
+
try:
|
|
126
|
+
proc = subprocess.run(
|
|
127
|
+
cmd,
|
|
128
|
+
capture_output=True,
|
|
129
|
+
text=True,
|
|
130
|
+
timeout=self.timeout,
|
|
131
|
+
)
|
|
132
|
+
stdout = proc.stdout
|
|
133
|
+
parsed = self._parse_output(stdout)
|
|
134
|
+
except subprocess.TimeoutExpired:
|
|
135
|
+
return CheckResult(
|
|
136
|
+
name=self.name,
|
|
137
|
+
category=self.category,
|
|
138
|
+
status=CheckStatus.FAILED,
|
|
139
|
+
message=f"Ping timed out after {self.timeout:.1f}s for {self.host}",
|
|
140
|
+
target=self.host,
|
|
141
|
+
latency_ms=timer["elapsed_ms"],
|
|
142
|
+
remediation=f"Host {self.host} did not respond to ICMP. Check firewall/ICMP blocking or DNS resolution.",
|
|
143
|
+
)
|
|
144
|
+
except FileNotFoundError:
|
|
145
|
+
return CheckResult(
|
|
146
|
+
name=self.name,
|
|
147
|
+
category=self.category,
|
|
148
|
+
status=CheckStatus.ERROR,
|
|
149
|
+
message="ping executable not found in PATH",
|
|
150
|
+
target=self.host,
|
|
151
|
+
latency_ms=timer["elapsed_ms"],
|
|
152
|
+
)
|
|
153
|
+
except Exception as exc:
|
|
154
|
+
return CheckResult(
|
|
155
|
+
name=self.name,
|
|
156
|
+
category=self.category,
|
|
157
|
+
status=CheckStatus.ERROR,
|
|
158
|
+
message=f"Failed to execute ping: {exc}",
|
|
159
|
+
target=self.host,
|
|
160
|
+
latency_ms=timer["elapsed_ms"],
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
loss_pct = parsed["packet_loss_pct"]
|
|
164
|
+
avg_rtt = parsed["avg_rtt_ms"]
|
|
165
|
+
|
|
166
|
+
if loss_pct is None and proc.returncode != 0:
|
|
167
|
+
return CheckResult(
|
|
168
|
+
name=self.name,
|
|
169
|
+
category=self.category,
|
|
170
|
+
status=CheckStatus.FAILED,
|
|
171
|
+
message=f"Host unreachable: {self.host}",
|
|
172
|
+
target=self.host,
|
|
173
|
+
latency_ms=timer["elapsed_ms"],
|
|
174
|
+
details={"raw_output": stdout, "exit_code": proc.returncode},
|
|
175
|
+
remediation=f"Verify network connectivity and DNS resolution for {self.host}.",
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# Evaluate status
|
|
179
|
+
status = CheckStatus.PASSED
|
|
180
|
+
remediation = None
|
|
181
|
+
latency_for_result = avg_rtt if avg_rtt is not None else timer["elapsed_ms"]
|
|
182
|
+
|
|
183
|
+
if loss_pct is not None and loss_pct >= 100.0:
|
|
184
|
+
status = CheckStatus.FAILED
|
|
185
|
+
msg = f"Host unreachable (100% packet loss): {self.host}"
|
|
186
|
+
remediation = f"Host {self.host} is down or ICMP packets are filtered by security groups/firewall."
|
|
187
|
+
elif loss_pct is not None and loss_pct > self.warn_loss_pct:
|
|
188
|
+
status = CheckStatus.WARNING
|
|
189
|
+
msg = f"Packet loss: {loss_pct:.1f}% ({parsed['received']}/{parsed['transmitted']} packets) - avg: {avg_rtt or 0:.2f}ms"
|
|
190
|
+
remediation = "Intermittent packet loss detected. Check for network congestion or flaky link."
|
|
191
|
+
elif avg_rtt is not None and avg_rtt >= self.crit_latency_ms:
|
|
192
|
+
status = CheckStatus.FAILED
|
|
193
|
+
msg = f"Critical latency: {avg_rtt:.1f}ms (loss: {loss_pct or 0:.0f}%)"
|
|
194
|
+
remediation = "Excessive latency detected. Investigate network routing or path MTU."
|
|
195
|
+
elif avg_rtt is not None and avg_rtt >= self.warn_latency_ms:
|
|
196
|
+
status = CheckStatus.WARNING
|
|
197
|
+
msg = f"High latency: {avg_rtt:.1f}ms (loss: {loss_pct or 0:.0f}%)"
|
|
198
|
+
remediation = f"Latency to {self.host} exceeds threshold ({self.warn_latency_ms}ms)."
|
|
199
|
+
else:
|
|
200
|
+
rtt_text = f"{avg_rtt:.2f}ms" if avg_rtt is not None else "OK"
|
|
201
|
+
loss_text = f"loss: {loss_pct:.0f}%" if loss_pct is not None else "0% loss"
|
|
202
|
+
resolved = f" ({parsed['resolved_ip']})" if parsed["resolved_ip"] else ""
|
|
203
|
+
msg = f"Reachable{resolved} - RTT avg: {rtt_text}, {loss_text}"
|
|
204
|
+
|
|
205
|
+
details: Dict[str, Any] = {
|
|
206
|
+
"host": self.host,
|
|
207
|
+
"resolved_ip": parsed["resolved_ip"],
|
|
208
|
+
"packet_loss_pct": loss_pct,
|
|
209
|
+
"min_rtt_ms": parsed["min_rtt_ms"],
|
|
210
|
+
"avg_rtt_ms": parsed["avg_rtt_ms"],
|
|
211
|
+
"max_rtt_ms": parsed["max_rtt_ms"],
|
|
212
|
+
"mdev_rtt_ms": parsed["mdev_rtt_ms"],
|
|
213
|
+
"transmitted": parsed["transmitted"],
|
|
214
|
+
"received": parsed["received"],
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return CheckResult(
|
|
218
|
+
name=self.name,
|
|
219
|
+
category=self.category,
|
|
220
|
+
status=status,
|
|
221
|
+
message=msg,
|
|
222
|
+
target=self.host,
|
|
223
|
+
latency_ms=latency_for_result,
|
|
224
|
+
details=details,
|
|
225
|
+
remediation=remediation,
|
|
226
|
+
)
|