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/checks/system.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
"""System resource health checks (CPU, Memory, Disk, Swap, Uptime)."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import time
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import psutil
|
|
11
|
+
HAS_PSUTIL = True
|
|
12
|
+
except ImportError:
|
|
13
|
+
HAS_PSUTIL = False
|
|
14
|
+
|
|
15
|
+
from medic.core.base import BaseCheck, timed_execution
|
|
16
|
+
from medic.core.enums import CheckCategory, CheckStatus
|
|
17
|
+
from medic.core.models import CheckResult
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _format_bytes(bytes_val: float) -> str:
|
|
21
|
+
"""Format bytes into human-readable string (KB, MB, GB, TB)."""
|
|
22
|
+
for unit in ["B", "KB", "MB", "GB", "TB", "PB"]:
|
|
23
|
+
if bytes_val < 1024.0:
|
|
24
|
+
return f"{bytes_val:.1f} {unit}"
|
|
25
|
+
bytes_val /= 1024.0
|
|
26
|
+
return f"{bytes_val:.1f} PB"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _format_seconds(seconds: float) -> str:
|
|
30
|
+
"""Format seconds into readable days, hours, minutes."""
|
|
31
|
+
days, rem = divmod(int(seconds), 86400)
|
|
32
|
+
hours, rem = divmod(rem, 3600)
|
|
33
|
+
minutes, secs = divmod(rem, 60)
|
|
34
|
+
parts = []
|
|
35
|
+
if days > 0:
|
|
36
|
+
parts.append(f"{days}d")
|
|
37
|
+
if hours > 0:
|
|
38
|
+
parts.append(f"{hours}h")
|
|
39
|
+
if minutes > 0:
|
|
40
|
+
parts.append(f"{minutes}m")
|
|
41
|
+
if secs > 0 or not parts:
|
|
42
|
+
parts.append(f"{secs}s")
|
|
43
|
+
return " ".join(parts)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CPUCheck(BaseCheck):
|
|
47
|
+
"""Checks CPU utilization and system load average."""
|
|
48
|
+
|
|
49
|
+
category = CheckCategory.SYSTEM
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
name: str = "System CPU",
|
|
54
|
+
warn_percent: float = 80.0,
|
|
55
|
+
crit_percent: float = 95.0,
|
|
56
|
+
interval: float = 0.2,
|
|
57
|
+
timeout: float = 5.0,
|
|
58
|
+
enabled: bool = True,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__(name=name, timeout=timeout, enabled=enabled)
|
|
61
|
+
self.warn_percent = warn_percent
|
|
62
|
+
self.crit_percent = crit_percent
|
|
63
|
+
self.interval = interval
|
|
64
|
+
|
|
65
|
+
def run(self) -> CheckResult:
|
|
66
|
+
with timed_execution() as timer:
|
|
67
|
+
if not HAS_PSUTIL:
|
|
68
|
+
return CheckResult(
|
|
69
|
+
name=self.name,
|
|
70
|
+
category=self.category,
|
|
71
|
+
status=CheckStatus.ERROR,
|
|
72
|
+
message="psutil library is required for CPU checks",
|
|
73
|
+
target="cpu",
|
|
74
|
+
latency_ms=timer["elapsed_ms"],
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
cpu_pct = psutil.cpu_percent(interval=self.interval)
|
|
78
|
+
cpu_count = psutil.cpu_count(logical=True) or 1
|
|
79
|
+
cpu_count_phys = psutil.cpu_count(logical=False) or cpu_count
|
|
80
|
+
|
|
81
|
+
# Load averages
|
|
82
|
+
load_avg: Tuple[float, float, float]
|
|
83
|
+
try:
|
|
84
|
+
load_avg = os.getloadavg()
|
|
85
|
+
except (AttributeError, OSError):
|
|
86
|
+
load_avg = (0.0, 0.0, 0.0)
|
|
87
|
+
|
|
88
|
+
# Determine status
|
|
89
|
+
status = CheckStatus.PASSED
|
|
90
|
+
remediation = None
|
|
91
|
+
|
|
92
|
+
if cpu_pct >= self.crit_percent:
|
|
93
|
+
status = CheckStatus.FAILED
|
|
94
|
+
remediation = "High CPU load. Identify heavy processes with: ps aux --sort=-%cpu | head -n 10"
|
|
95
|
+
elif cpu_pct >= self.warn_percent:
|
|
96
|
+
status = CheckStatus.WARNING
|
|
97
|
+
remediation = "Elevated CPU usage. Monitor system activity with: top -b -n 1 | head -n 20"
|
|
98
|
+
|
|
99
|
+
msg = f"CPU Usage: {cpu_pct:.1f}% (Load: {load_avg[0]:.2f}, {load_avg[1]:.2f}, {load_avg[2]:.2f})"
|
|
100
|
+
|
|
101
|
+
details: Dict[str, Any] = {
|
|
102
|
+
"cpu_percent": cpu_pct,
|
|
103
|
+
"logical_cores": cpu_count,
|
|
104
|
+
"physical_cores": cpu_count_phys,
|
|
105
|
+
"load_1m": load_avg[0],
|
|
106
|
+
"load_5m": load_avg[1],
|
|
107
|
+
"load_15m": load_avg[2],
|
|
108
|
+
"warn_threshold": self.warn_percent,
|
|
109
|
+
"crit_threshold": self.crit_percent,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return CheckResult(
|
|
113
|
+
name=self.name,
|
|
114
|
+
category=self.category,
|
|
115
|
+
status=status,
|
|
116
|
+
message=msg,
|
|
117
|
+
target="cpu",
|
|
118
|
+
latency_ms=timer["elapsed_ms"],
|
|
119
|
+
details=details,
|
|
120
|
+
remediation=remediation,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class MemoryCheck(BaseCheck):
|
|
125
|
+
"""Checks RAM (virtual memory) utilization."""
|
|
126
|
+
|
|
127
|
+
category = CheckCategory.SYSTEM
|
|
128
|
+
|
|
129
|
+
def __init__(
|
|
130
|
+
self,
|
|
131
|
+
name: str = "System Memory",
|
|
132
|
+
warn_percent: float = 85.0,
|
|
133
|
+
crit_percent: float = 95.0,
|
|
134
|
+
timeout: float = 5.0,
|
|
135
|
+
enabled: bool = True,
|
|
136
|
+
) -> None:
|
|
137
|
+
super().__init__(name=name, timeout=timeout, enabled=enabled)
|
|
138
|
+
self.warn_percent = warn_percent
|
|
139
|
+
self.crit_percent = crit_percent
|
|
140
|
+
|
|
141
|
+
def run(self) -> CheckResult:
|
|
142
|
+
with timed_execution() as timer:
|
|
143
|
+
if not HAS_PSUTIL:
|
|
144
|
+
return CheckResult(
|
|
145
|
+
name=self.name,
|
|
146
|
+
category=self.category,
|
|
147
|
+
status=CheckStatus.ERROR,
|
|
148
|
+
message="psutil library is required for Memory checks",
|
|
149
|
+
target="memory",
|
|
150
|
+
latency_ms=timer["elapsed_ms"],
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
vm = psutil.virtual_memory()
|
|
154
|
+
used_pct = vm.percent
|
|
155
|
+
used_str = _format_bytes(vm.used)
|
|
156
|
+
total_str = _format_bytes(vm.total)
|
|
157
|
+
avail_str = _format_bytes(vm.available)
|
|
158
|
+
|
|
159
|
+
status = CheckStatus.PASSED
|
|
160
|
+
remediation = None
|
|
161
|
+
|
|
162
|
+
if used_pct >= self.crit_percent:
|
|
163
|
+
status = CheckStatus.FAILED
|
|
164
|
+
remediation = "Critical RAM usage. Check memory leaks with: ps aux --sort=-%mem | head -n 10"
|
|
165
|
+
elif used_pct >= self.warn_percent:
|
|
166
|
+
status = CheckStatus.WARNING
|
|
167
|
+
remediation = "Elevated RAM usage. Consider clearing caches or freeing unused buffers."
|
|
168
|
+
|
|
169
|
+
msg = f"RAM: {used_pct:.1f}% used ({used_str} / {total_str}, {avail_str} available)"
|
|
170
|
+
|
|
171
|
+
details: Dict[str, Any] = {
|
|
172
|
+
"used_percent": used_pct,
|
|
173
|
+
"used_bytes": vm.used,
|
|
174
|
+
"total_bytes": vm.total,
|
|
175
|
+
"available_bytes": vm.available,
|
|
176
|
+
"used_human": used_str,
|
|
177
|
+
"total_human": total_str,
|
|
178
|
+
"available_human": avail_str,
|
|
179
|
+
"warn_threshold": self.warn_percent,
|
|
180
|
+
"crit_threshold": self.crit_percent,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return CheckResult(
|
|
184
|
+
name=self.name,
|
|
185
|
+
category=self.category,
|
|
186
|
+
status=status,
|
|
187
|
+
message=msg,
|
|
188
|
+
target="memory",
|
|
189
|
+
latency_ms=timer["elapsed_ms"],
|
|
190
|
+
details=details,
|
|
191
|
+
remediation=remediation,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class SwapCheck(BaseCheck):
|
|
196
|
+
"""Checks Swap space utilization."""
|
|
197
|
+
|
|
198
|
+
category = CheckCategory.SYSTEM
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
name: str = "System Swap",
|
|
203
|
+
warn_percent: float = 75.0,
|
|
204
|
+
crit_percent: float = 90.0,
|
|
205
|
+
timeout: float = 5.0,
|
|
206
|
+
enabled: bool = True,
|
|
207
|
+
) -> None:
|
|
208
|
+
super().__init__(name=name, timeout=timeout, enabled=enabled)
|
|
209
|
+
self.warn_percent = warn_percent
|
|
210
|
+
self.crit_percent = crit_percent
|
|
211
|
+
|
|
212
|
+
def run(self) -> CheckResult:
|
|
213
|
+
with timed_execution() as timer:
|
|
214
|
+
if not HAS_PSUTIL:
|
|
215
|
+
return CheckResult(
|
|
216
|
+
name=self.name,
|
|
217
|
+
category=self.category,
|
|
218
|
+
status=CheckStatus.ERROR,
|
|
219
|
+
message="psutil library is required for Swap checks",
|
|
220
|
+
target="swap",
|
|
221
|
+
latency_ms=timer["elapsed_ms"],
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
sw = psutil.swap_memory()
|
|
225
|
+
if sw.total == 0:
|
|
226
|
+
return CheckResult(
|
|
227
|
+
name=self.name,
|
|
228
|
+
category=self.category,
|
|
229
|
+
status=CheckStatus.PASSED,
|
|
230
|
+
message="Swap: disabled / 0 B configured",
|
|
231
|
+
target="swap",
|
|
232
|
+
latency_ms=timer["elapsed_ms"],
|
|
233
|
+
details={"total_bytes": 0, "used_bytes": 0, "used_percent": 0.0},
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
used_pct = sw.percent
|
|
237
|
+
used_str = _format_bytes(sw.used)
|
|
238
|
+
total_str = _format_bytes(sw.total)
|
|
239
|
+
free_str = _format_bytes(sw.free)
|
|
240
|
+
|
|
241
|
+
status = CheckStatus.PASSED
|
|
242
|
+
remediation = None
|
|
243
|
+
|
|
244
|
+
if used_pct >= self.crit_percent:
|
|
245
|
+
status = CheckStatus.FAILED
|
|
246
|
+
remediation = "Swap space almost exhausted. System may face OOM kills."
|
|
247
|
+
elif used_pct >= self.warn_percent:
|
|
248
|
+
status = CheckStatus.WARNING
|
|
249
|
+
remediation = "High swap activity indicates memory pressure."
|
|
250
|
+
|
|
251
|
+
msg = f"Swap: {used_pct:.1f}% used ({used_str} / {total_str}, {free_str} free)"
|
|
252
|
+
|
|
253
|
+
details = {
|
|
254
|
+
"used_percent": used_pct,
|
|
255
|
+
"used_bytes": sw.used,
|
|
256
|
+
"total_bytes": sw.total,
|
|
257
|
+
"free_bytes": sw.free,
|
|
258
|
+
"used_human": used_str,
|
|
259
|
+
"total_human": total_str,
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return CheckResult(
|
|
263
|
+
name=self.name,
|
|
264
|
+
category=self.category,
|
|
265
|
+
status=status,
|
|
266
|
+
message=msg,
|
|
267
|
+
target="swap",
|
|
268
|
+
latency_ms=timer["elapsed_ms"],
|
|
269
|
+
details=details,
|
|
270
|
+
remediation=remediation,
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class DiskCheck(BaseCheck):
|
|
275
|
+
"""Checks disk space usage for a given path or mount point."""
|
|
276
|
+
|
|
277
|
+
category = CheckCategory.SYSTEM
|
|
278
|
+
|
|
279
|
+
def __init__(
|
|
280
|
+
self,
|
|
281
|
+
path: str = "/",
|
|
282
|
+
name: Optional[str] = None,
|
|
283
|
+
warn_percent: float = 85.0,
|
|
284
|
+
crit_percent: float = 92.0,
|
|
285
|
+
timeout: float = 5.0,
|
|
286
|
+
enabled: bool = True,
|
|
287
|
+
) -> None:
|
|
288
|
+
chk_name = name or f"Disk ({path})"
|
|
289
|
+
super().__init__(name=chk_name, timeout=timeout, enabled=enabled)
|
|
290
|
+
self.path = path
|
|
291
|
+
self.warn_percent = warn_percent
|
|
292
|
+
self.crit_percent = crit_percent
|
|
293
|
+
|
|
294
|
+
def run(self) -> CheckResult:
|
|
295
|
+
with timed_execution() as timer:
|
|
296
|
+
if not os.path.exists(self.path):
|
|
297
|
+
return CheckResult(
|
|
298
|
+
name=self.name,
|
|
299
|
+
category=self.category,
|
|
300
|
+
status=CheckStatus.FAILED,
|
|
301
|
+
message=f"Disk path does not exist: {self.path}",
|
|
302
|
+
target=self.path,
|
|
303
|
+
latency_ms=timer["elapsed_ms"],
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
if HAS_PSUTIL:
|
|
307
|
+
usage = psutil.disk_usage(self.path)
|
|
308
|
+
total = usage.total
|
|
309
|
+
used = usage.used
|
|
310
|
+
free = usage.free
|
|
311
|
+
pct = usage.percent
|
|
312
|
+
else:
|
|
313
|
+
usage_sh = shutil.disk_usage(self.path)
|
|
314
|
+
total = usage_sh.total
|
|
315
|
+
used = usage_sh.used
|
|
316
|
+
free = usage_sh.free
|
|
317
|
+
pct = (used / total * 100.0) if total > 0 else 0.0
|
|
318
|
+
|
|
319
|
+
total_str = _format_bytes(total)
|
|
320
|
+
used_str = _format_bytes(used)
|
|
321
|
+
free_str = _format_bytes(free)
|
|
322
|
+
|
|
323
|
+
status = CheckStatus.PASSED
|
|
324
|
+
remediation = None
|
|
325
|
+
|
|
326
|
+
if pct >= self.crit_percent:
|
|
327
|
+
status = CheckStatus.FAILED
|
|
328
|
+
remediation = f"Critically low disk space on {self.path}. Clean logs and temporary files: du -sh {self.path}/* 2>/dev/null | sort -hr | head -n 10"
|
|
329
|
+
elif pct >= self.warn_percent:
|
|
330
|
+
status = CheckStatus.WARNING
|
|
331
|
+
remediation = f"Disk {self.path} is filling up ({pct:.1f}%). Check large files."
|
|
332
|
+
|
|
333
|
+
msg = f"Disk ({self.path}): {pct:.1f}% used ({used_str} / {total_str}, {free_str} free)"
|
|
334
|
+
|
|
335
|
+
details: Dict[str, Any] = {
|
|
336
|
+
"path": self.path,
|
|
337
|
+
"used_percent": pct,
|
|
338
|
+
"used_bytes": used,
|
|
339
|
+
"total_bytes": total,
|
|
340
|
+
"free_bytes": free,
|
|
341
|
+
"used_human": used_str,
|
|
342
|
+
"total_human": total_str,
|
|
343
|
+
"free_human": free_str,
|
|
344
|
+
"warn_threshold": self.warn_percent,
|
|
345
|
+
"crit_threshold": self.crit_percent,
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
return CheckResult(
|
|
349
|
+
name=self.name,
|
|
350
|
+
category=self.category,
|
|
351
|
+
status=status,
|
|
352
|
+
message=msg,
|
|
353
|
+
target=self.path,
|
|
354
|
+
latency_ms=timer["elapsed_ms"],
|
|
355
|
+
details=details,
|
|
356
|
+
remediation=remediation,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
class UptimeCheck(BaseCheck):
|
|
361
|
+
"""Checks system uptime and boot timestamp."""
|
|
362
|
+
|
|
363
|
+
category = CheckCategory.SYSTEM
|
|
364
|
+
|
|
365
|
+
def __init__(
|
|
366
|
+
self,
|
|
367
|
+
name: str = "System Uptime",
|
|
368
|
+
min_uptime_seconds: float = 60.0,
|
|
369
|
+
timeout: float = 5.0,
|
|
370
|
+
enabled: bool = True,
|
|
371
|
+
) -> None:
|
|
372
|
+
super().__init__(name=name, timeout=timeout, enabled=enabled)
|
|
373
|
+
self.min_uptime_seconds = min_uptime_seconds
|
|
374
|
+
|
|
375
|
+
def run(self) -> CheckResult:
|
|
376
|
+
with timed_execution() as timer:
|
|
377
|
+
if not HAS_PSUTIL:
|
|
378
|
+
return CheckResult(
|
|
379
|
+
name=self.name,
|
|
380
|
+
category=self.category,
|
|
381
|
+
status=CheckStatus.ERROR,
|
|
382
|
+
message="psutil library is required for Uptime check",
|
|
383
|
+
target="system",
|
|
384
|
+
latency_ms=timer["elapsed_ms"],
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
boot_time = psutil.boot_time()
|
|
388
|
+
now = time.time()
|
|
389
|
+
uptime_secs = max(0.0, now - boot_time)
|
|
390
|
+
uptime_str = _format_seconds(uptime_secs)
|
|
391
|
+
boot_dt = datetime.fromtimestamp(boot_time, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
|
392
|
+
|
|
393
|
+
proc_count = len(psutil.pids())
|
|
394
|
+
|
|
395
|
+
status = CheckStatus.PASSED
|
|
396
|
+
remediation = None
|
|
397
|
+
|
|
398
|
+
if uptime_secs < self.min_uptime_seconds:
|
|
399
|
+
status = CheckStatus.WARNING
|
|
400
|
+
remediation = f"System was rebooted recently ({uptime_str} ago). Check dmesg or system logs."
|
|
401
|
+
|
|
402
|
+
msg = f"Uptime: {uptime_str} (Booted: {boot_dt}, Processes: {proc_count})"
|
|
403
|
+
|
|
404
|
+
details: Dict[str, Any] = {
|
|
405
|
+
"uptime_seconds": uptime_secs,
|
|
406
|
+
"uptime_human": uptime_str,
|
|
407
|
+
"boot_time": boot_dt,
|
|
408
|
+
"process_count": proc_count,
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
return CheckResult(
|
|
412
|
+
name=self.name,
|
|
413
|
+
category=self.category,
|
|
414
|
+
status=status,
|
|
415
|
+
message=msg,
|
|
416
|
+
target="system",
|
|
417
|
+
latency_ms=timer["elapsed_ms"],
|
|
418
|
+
details=details,
|
|
419
|
+
remediation=remediation,
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
class SystemCheckGroup(BaseCheck):
|
|
424
|
+
"""Composite check that gathers all standard system health metrics."""
|
|
425
|
+
|
|
426
|
+
category = CheckCategory.SYSTEM
|
|
427
|
+
|
|
428
|
+
def __init__(
|
|
429
|
+
self,
|
|
430
|
+
name: str = "System Health",
|
|
431
|
+
disk_paths: Optional[List[str]] = None,
|
|
432
|
+
cpu_warn: float = 80.0,
|
|
433
|
+
cpu_crit: float = 95.0,
|
|
434
|
+
ram_warn: float = 85.0,
|
|
435
|
+
ram_crit: float = 95.0,
|
|
436
|
+
disk_warn: float = 85.0,
|
|
437
|
+
disk_crit: float = 92.0,
|
|
438
|
+
timeout: float = 10.0,
|
|
439
|
+
enabled: bool = True,
|
|
440
|
+
) -> None:
|
|
441
|
+
super().__init__(name=name, timeout=timeout, enabled=enabled)
|
|
442
|
+
self.disk_paths = disk_paths or ["/"]
|
|
443
|
+
self.cpu_warn = cpu_warn
|
|
444
|
+
self.cpu_crit = cpu_crit
|
|
445
|
+
self.ram_warn = ram_warn
|
|
446
|
+
self.ram_crit = ram_crit
|
|
447
|
+
self.disk_warn = disk_warn
|
|
448
|
+
self.disk_crit = disk_crit
|
|
449
|
+
|
|
450
|
+
def run(self) -> List[CheckResult]:
|
|
451
|
+
sub_checks: List[BaseCheck] = [
|
|
452
|
+
CPUCheck(warn_percent=self.cpu_warn, crit_percent=self.cpu_crit),
|
|
453
|
+
MemoryCheck(warn_percent=self.ram_warn, crit_percent=self.ram_crit),
|
|
454
|
+
SwapCheck(),
|
|
455
|
+
]
|
|
456
|
+
for path in self.disk_paths:
|
|
457
|
+
sub_checks.append(
|
|
458
|
+
DiskCheck(path=path, warn_percent=self.disk_warn, crit_percent=self.disk_crit)
|
|
459
|
+
)
|
|
460
|
+
sub_checks.append(UptimeCheck())
|
|
461
|
+
|
|
462
|
+
results: List[CheckResult] = []
|
|
463
|
+
for chk in sub_checks:
|
|
464
|
+
res = chk.run()
|
|
465
|
+
if isinstance(res, list):
|
|
466
|
+
results.extend(res)
|
|
467
|
+
else:
|
|
468
|
+
results.append(res)
|
|
469
|
+
return results
|
medic/checks/tcp.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""TCP socket connectivity, latency, and banner check."""
|
|
2
|
+
|
|
3
|
+
import socket
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Dict, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
from medic.core.base import BaseCheck, timed_execution
|
|
8
|
+
from medic.core.enums import CheckCategory, CheckStatus
|
|
9
|
+
from medic.core.models import CheckResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_host_port(target: str, default_port: int = 80) -> Tuple[str, int]:
|
|
13
|
+
"""Parse host and port from strings like 'example.com:443', '[::1]:80', or 'localhost'."""
|
|
14
|
+
target = target.strip()
|
|
15
|
+
if target.startswith("["):
|
|
16
|
+
# IPv6 with brackets, e.g. [::1]:8080 or [::1]
|
|
17
|
+
end_bracket = target.find("]")
|
|
18
|
+
if end_bracket != -1:
|
|
19
|
+
host = target[1:end_bracket]
|
|
20
|
+
rem = target[end_bracket + 1 :]
|
|
21
|
+
if rem.startswith(":"):
|
|
22
|
+
port = int(rem[1:])
|
|
23
|
+
return host, port
|
|
24
|
+
return host, default_port
|
|
25
|
+
|
|
26
|
+
if ":" in target:
|
|
27
|
+
parts = target.rsplit(":", 1)
|
|
28
|
+
try:
|
|
29
|
+
return parts[0], int(parts[1])
|
|
30
|
+
except ValueError:
|
|
31
|
+
return parts[0], default_port
|
|
32
|
+
|
|
33
|
+
return target, default_port
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TCPCheck(BaseCheck):
|
|
37
|
+
"""Checks TCP socket connectivity to a specified host:port."""
|
|
38
|
+
|
|
39
|
+
category = CheckCategory.TCP
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
host: str,
|
|
44
|
+
port: int = 80,
|
|
45
|
+
name: Optional[str] = None,
|
|
46
|
+
timeout: float = 5.0,
|
|
47
|
+
warn_latency_ms: float = 200.0,
|
|
48
|
+
crit_latency_ms: float = 1000.0,
|
|
49
|
+
grab_banner: bool = False,
|
|
50
|
+
banner_send_payload: Optional[bytes] = None,
|
|
51
|
+
banner_max_bytes: int = 256,
|
|
52
|
+
enabled: bool = True,
|
|
53
|
+
) -> None:
|
|
54
|
+
chk_name = name or f"TCP {host}:{port}"
|
|
55
|
+
super().__init__(name=chk_name, timeout=timeout, enabled=enabled)
|
|
56
|
+
self.host = host.strip()
|
|
57
|
+
self.port = port
|
|
58
|
+
self.warn_latency_ms = warn_latency_ms
|
|
59
|
+
self.crit_latency_ms = crit_latency_ms
|
|
60
|
+
self.grab_banner = grab_banner
|
|
61
|
+
self.banner_send_payload = banner_send_payload
|
|
62
|
+
self.banner_max_bytes = banner_max_bytes
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def from_target(cls, target: str, default_port: int = 80, **kwargs: Any) -> "TCPCheck":
|
|
66
|
+
"""Factory method to instantiate from 'host:port' string."""
|
|
67
|
+
host, port = parse_host_port(target, default_port=default_port)
|
|
68
|
+
return cls(host=host, port=port, **kwargs)
|
|
69
|
+
|
|
70
|
+
def run(self) -> CheckResult:
|
|
71
|
+
target_str = f"{self.host}:{self.port}"
|
|
72
|
+
with timed_execution() as timer:
|
|
73
|
+
banner_text: Optional[str] = None
|
|
74
|
+
resolved_ip: Optional[str] = None
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
# Resolve host first
|
|
78
|
+
addr_info = socket.getaddrinfo(
|
|
79
|
+
self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM
|
|
80
|
+
)
|
|
81
|
+
if addr_info:
|
|
82
|
+
resolved_ip = str(addr_info[0][4][0])
|
|
83
|
+
except socket.gaierror as e:
|
|
84
|
+
return CheckResult(
|
|
85
|
+
name=self.name,
|
|
86
|
+
category=self.category,
|
|
87
|
+
status=CheckStatus.FAILED,
|
|
88
|
+
message=f"DNS resolution failed: {e}",
|
|
89
|
+
target=target_str,
|
|
90
|
+
latency_ms=timer["elapsed_ms"],
|
|
91
|
+
remediation=f"Check DNS configuration or /etc/hosts for '{self.host}'.",
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# Establish TCP connection
|
|
95
|
+
sock: Optional[socket.socket] = None
|
|
96
|
+
try:
|
|
97
|
+
conn_start = time.perf_counter()
|
|
98
|
+
sock = socket.create_connection((self.host, self.port), timeout=self.timeout)
|
|
99
|
+
conn_ms = (time.perf_counter() - conn_start) * 1000.0
|
|
100
|
+
|
|
101
|
+
# Optional banner grab
|
|
102
|
+
if self.grab_banner:
|
|
103
|
+
sock.settimeout(min(self.timeout, 2.0))
|
|
104
|
+
if self.banner_send_payload:
|
|
105
|
+
sock.sendall(self.banner_send_payload)
|
|
106
|
+
try:
|
|
107
|
+
raw_banner = sock.recv(self.banner_max_bytes)
|
|
108
|
+
banner_text = raw_banner.decode("utf-8", errors="replace").strip()
|
|
109
|
+
except (TimeoutError, OSError):
|
|
110
|
+
banner_text = None
|
|
111
|
+
|
|
112
|
+
except ConnectionRefusedError:
|
|
113
|
+
return CheckResult(
|
|
114
|
+
name=self.name,
|
|
115
|
+
category=self.category,
|
|
116
|
+
status=CheckStatus.FAILED,
|
|
117
|
+
message=f"Connection refused on {target_str}",
|
|
118
|
+
target=target_str,
|
|
119
|
+
latency_ms=timer["elapsed_ms"],
|
|
120
|
+
details={"resolved_ip": resolved_ip, "port": self.port},
|
|
121
|
+
remediation=f"Verify that the service is running and listening on {target_str} (e.g. netstat -tulpn or ss -tulpn).",
|
|
122
|
+
)
|
|
123
|
+
except TimeoutError:
|
|
124
|
+
return CheckResult(
|
|
125
|
+
name=self.name,
|
|
126
|
+
category=self.category,
|
|
127
|
+
status=CheckStatus.FAILED,
|
|
128
|
+
message=f"Connection timed out after {self.timeout:.1f}s to {target_str}",
|
|
129
|
+
target=target_str,
|
|
130
|
+
latency_ms=timer["elapsed_ms"],
|
|
131
|
+
details={"resolved_ip": resolved_ip, "port": self.port},
|
|
132
|
+
remediation=f"Check firewall rules (iptables, ufw, security groups) permitting ingress on port {self.port}.",
|
|
133
|
+
)
|
|
134
|
+
except OSError as e:
|
|
135
|
+
return CheckResult(
|
|
136
|
+
name=self.name,
|
|
137
|
+
category=self.category,
|
|
138
|
+
status=CheckStatus.FAILED,
|
|
139
|
+
message=f"Socket error ({e.strerror or str(e)}) on {target_str}",
|
|
140
|
+
target=target_str,
|
|
141
|
+
latency_ms=timer["elapsed_ms"],
|
|
142
|
+
details={"resolved_ip": resolved_ip, "errno": getattr(e, "errno", None)},
|
|
143
|
+
remediation="Check routing table and network interface status.",
|
|
144
|
+
)
|
|
145
|
+
finally:
|
|
146
|
+
if sock is not None:
|
|
147
|
+
try:
|
|
148
|
+
sock.close()
|
|
149
|
+
except Exception:
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
# Evaluate latency
|
|
153
|
+
status = CheckStatus.PASSED
|
|
154
|
+
remediation = None
|
|
155
|
+
|
|
156
|
+
if conn_ms >= self.crit_latency_ms:
|
|
157
|
+
status = CheckStatus.FAILED
|
|
158
|
+
remediation = f"TCP handshake latency ({conn_ms:.1f}ms) is critically slow."
|
|
159
|
+
elif conn_ms >= self.warn_latency_ms:
|
|
160
|
+
status = CheckStatus.WARNING
|
|
161
|
+
remediation = f"TCP handshake latency ({conn_ms:.1f}ms) is high."
|
|
162
|
+
|
|
163
|
+
banner_info = f" [Banner: {banner_text[:30]}...]" if banner_text else ""
|
|
164
|
+
ip_info = f" ({resolved_ip})" if resolved_ip and resolved_ip != self.host else ""
|
|
165
|
+
msg = f"Connected to {target_str}{ip_info} in {conn_ms:.2f}ms{banner_info}"
|
|
166
|
+
|
|
167
|
+
details: Dict[str, Any] = {
|
|
168
|
+
"host": self.host,
|
|
169
|
+
"port": self.port,
|
|
170
|
+
"resolved_ip": resolved_ip,
|
|
171
|
+
"handshake_ms": round(conn_ms, 2),
|
|
172
|
+
"banner": banner_text,
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return CheckResult(
|
|
176
|
+
name=self.name,
|
|
177
|
+
category=self.category,
|
|
178
|
+
status=status,
|
|
179
|
+
message=msg,
|
|
180
|
+
target=target_str,
|
|
181
|
+
latency_ms=conn_ms,
|
|
182
|
+
details=details,
|
|
183
|
+
remediation=remediation,
|
|
184
|
+
)
|